flipper_http.c 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511
  1. // Description: Flipper HTTP API (For use with Flipper Zero and the FlipperHTTP flash: https://github.com/jblanked/FlipperHTTP)
  2. // License: MIT
  3. // Author: JBlanked
  4. // File: flipper_http.c
  5. #include <flipper_http/flipper_http.h> // change this to where flipper_http.h is located
  6. FlipperHTTP fhttp = {0};
  7. // Function to append received data to file
  8. // make sure to initialize the file path before calling this function
  9. bool flipper_http_append_to_file(
  10. const void *data,
  11. size_t data_size,
  12. bool start_new_file,
  13. char *file_path)
  14. {
  15. Storage *storage = furi_record_open(RECORD_STORAGE);
  16. File *file = storage_file_alloc(storage);
  17. if (start_new_file)
  18. {
  19. // Delete the file if it already exists
  20. if (storage_file_exists(storage, file_path))
  21. {
  22. if (!storage_simply_remove_recursive(storage, file_path))
  23. {
  24. FURI_LOG_E(HTTP_TAG, "Failed to delete file: %s", file_path);
  25. storage_file_free(file);
  26. furi_record_close(RECORD_STORAGE);
  27. return false;
  28. }
  29. }
  30. // Open the file in write mode
  31. if (!storage_file_open(file, file_path, FSAM_WRITE, FSOM_CREATE_ALWAYS))
  32. {
  33. FURI_LOG_E(HTTP_TAG, "Failed to open file for writing: %s", file_path);
  34. storage_file_free(file);
  35. furi_record_close(RECORD_STORAGE);
  36. return false;
  37. }
  38. }
  39. else
  40. {
  41. // Open the file in append mode
  42. if (!storage_file_open(file, file_path, FSAM_WRITE, FSOM_OPEN_APPEND))
  43. {
  44. FURI_LOG_E(HTTP_TAG, "Failed to open file for appending: %s", file_path);
  45. storage_file_free(file);
  46. furi_record_close(RECORD_STORAGE);
  47. return false;
  48. }
  49. }
  50. // Write the data to the file
  51. if (storage_file_write(file, data, data_size) != data_size)
  52. {
  53. FURI_LOG_E(HTTP_TAG, "Failed to append data to file");
  54. storage_file_close(file);
  55. storage_file_free(file);
  56. furi_record_close(RECORD_STORAGE);
  57. return false;
  58. }
  59. storage_file_close(file);
  60. storage_file_free(file);
  61. furi_record_close(RECORD_STORAGE);
  62. return true;
  63. }
  64. FuriString *flipper_http_load_from_file(char *file_path)
  65. {
  66. // Open the storage record
  67. Storage *storage = furi_record_open(RECORD_STORAGE);
  68. if (!storage)
  69. {
  70. FURI_LOG_E(HTTP_TAG, "Failed to open storage record");
  71. return NULL;
  72. }
  73. // Allocate a file handle
  74. File *file = storage_file_alloc(storage);
  75. if (!file)
  76. {
  77. FURI_LOG_E(HTTP_TAG, "Failed to allocate storage file");
  78. furi_record_close(RECORD_STORAGE);
  79. return NULL;
  80. }
  81. // Open the file for reading
  82. if (!storage_file_open(file, file_path, FSAM_READ, FSOM_OPEN_EXISTING))
  83. {
  84. storage_file_free(file);
  85. furi_record_close(RECORD_STORAGE);
  86. FURI_LOG_E(HTTP_TAG, "Failed to open file for reading: %s", file_path);
  87. return NULL;
  88. }
  89. // Allocate a FuriString to hold the received data
  90. FuriString *str_result = furi_string_alloc();
  91. if (!str_result)
  92. {
  93. FURI_LOG_E(HTTP_TAG, "Failed to allocate FuriString");
  94. storage_file_close(file);
  95. storage_file_free(file);
  96. furi_record_close(RECORD_STORAGE);
  97. return NULL;
  98. }
  99. // Reset the FuriString to ensure it's empty before reading
  100. furi_string_reset(str_result);
  101. // Define a buffer to hold the read data
  102. uint8_t *buffer = (uint8_t *)malloc(MAX_FILE_SHOW);
  103. if (!buffer)
  104. {
  105. FURI_LOG_E(HTTP_TAG, "Failed to allocate buffer");
  106. furi_string_free(str_result);
  107. storage_file_close(file);
  108. storage_file_free(file);
  109. furi_record_close(RECORD_STORAGE);
  110. return NULL;
  111. }
  112. // Read data into the buffer
  113. size_t read_count = storage_file_read(file, buffer, MAX_FILE_SHOW);
  114. if (storage_file_get_error(file) != FSE_OK)
  115. {
  116. FURI_LOG_E(HTTP_TAG, "Error reading from file.");
  117. furi_string_free(str_result);
  118. storage_file_close(file);
  119. storage_file_free(file);
  120. furi_record_close(RECORD_STORAGE);
  121. return NULL;
  122. }
  123. // Append each byte to the FuriString
  124. for (size_t i = 0; i < read_count; i++)
  125. {
  126. furi_string_push_back(str_result, buffer[i]);
  127. }
  128. // Clean up
  129. storage_file_close(file);
  130. storage_file_free(file);
  131. furi_record_close(RECORD_STORAGE);
  132. free(buffer);
  133. return str_result;
  134. }
  135. // UART worker thread
  136. /**
  137. * @brief Worker thread to handle UART data asynchronously.
  138. * @return 0
  139. * @param context The context to pass to the callback.
  140. * @note This function will handle received data asynchronously via the callback.
  141. */
  142. // UART worker thread
  143. int32_t flipper_http_worker(void *context)
  144. {
  145. UNUSED(context);
  146. size_t rx_line_pos = 0;
  147. while (1)
  148. {
  149. uint32_t events = furi_thread_flags_wait(
  150. WorkerEvtStop | WorkerEvtRxDone, FuriFlagWaitAny, FuriWaitForever);
  151. if (events & WorkerEvtStop)
  152. {
  153. break;
  154. }
  155. if (events & WorkerEvtRxDone)
  156. {
  157. // Continuously read from the stream buffer until it's empty
  158. while (!furi_stream_buffer_is_empty(fhttp.flipper_http_stream))
  159. {
  160. // Read one byte at a time
  161. char c = 0;
  162. size_t received = furi_stream_buffer_receive(fhttp.flipper_http_stream, &c, 1, 0);
  163. if (received == 0)
  164. {
  165. // No more data to read
  166. break;
  167. }
  168. // Append the received byte to the file if saving is enabled
  169. if (fhttp.save_bytes)
  170. {
  171. // Add byte to the buffer
  172. fhttp.file_buffer[fhttp.file_buffer_len++] = c;
  173. // Write to file if buffer is full
  174. if (fhttp.file_buffer_len >= FILE_BUFFER_SIZE)
  175. {
  176. if (!flipper_http_append_to_file(
  177. fhttp.file_buffer,
  178. fhttp.file_buffer_len,
  179. fhttp.just_started_bytes,
  180. fhttp.file_path))
  181. {
  182. FURI_LOG_E(HTTP_TAG, "Failed to append data to file");
  183. }
  184. fhttp.file_buffer_len = 0;
  185. fhttp.just_started_bytes = false;
  186. }
  187. }
  188. // Handle line buffering only if callback is set (text data)
  189. if (fhttp.handle_rx_line_cb)
  190. {
  191. // Handle line buffering
  192. if (c == '\n' || rx_line_pos >= RX_LINE_BUFFER_SIZE - 1)
  193. {
  194. fhttp.rx_line_buffer[rx_line_pos] = '\0'; // Null-terminate the line
  195. // Invoke the callback with the complete line
  196. fhttp.handle_rx_line_cb(fhttp.rx_line_buffer, fhttp.callback_context);
  197. // Reset the line buffer position
  198. rx_line_pos = 0;
  199. }
  200. else
  201. {
  202. fhttp.rx_line_buffer[rx_line_pos++] = c; // Add character to the line buffer
  203. }
  204. }
  205. }
  206. }
  207. }
  208. return 0;
  209. }
  210. // Timer callback function
  211. /**
  212. * @brief Callback function for the GET timeout timer.
  213. * @return 0
  214. * @param context The context to pass to the callback.
  215. * @note This function will be called when the GET request times out.
  216. */
  217. void get_timeout_timer_callback(void *context)
  218. {
  219. UNUSED(context);
  220. FURI_LOG_E(HTTP_TAG, "Timeout reached: 2 seconds without receiving the end.");
  221. // Reset the state
  222. fhttp.started_receiving_get = false;
  223. fhttp.started_receiving_post = false;
  224. fhttp.started_receiving_put = false;
  225. fhttp.started_receiving_delete = false;
  226. // Update UART state
  227. fhttp.state = ISSUE;
  228. }
  229. // UART RX Handler Callback (Interrupt Context)
  230. /**
  231. * @brief A private callback function to handle received data asynchronously.
  232. * @return void
  233. * @param handle The UART handle.
  234. * @param event The event type.
  235. * @param context The context to pass to the callback.
  236. * @note This function will handle received data asynchronously via the callback.
  237. */
  238. void _flipper_http_rx_callback(
  239. FuriHalSerialHandle *handle,
  240. FuriHalSerialRxEvent event,
  241. void *context)
  242. {
  243. UNUSED(context);
  244. if (event == FuriHalSerialRxEventData)
  245. {
  246. uint8_t data = furi_hal_serial_async_rx(handle);
  247. furi_stream_buffer_send(fhttp.flipper_http_stream, &data, 1, 0);
  248. furi_thread_flags_set(fhttp.rx_thread_id, WorkerEvtRxDone);
  249. }
  250. }
  251. // UART initialization function
  252. /**
  253. * @brief Initialize UART.
  254. * @return true if the UART was initialized successfully, false otherwise.
  255. * @param context The context to pass to the callback.
  256. * @note The received data will be handled asynchronously via the callback.
  257. */
  258. bool flipper_http_init()
  259. {
  260. fhttp.flipper_http_stream = furi_stream_buffer_alloc(RX_BUF_SIZE, 1);
  261. if (!fhttp.flipper_http_stream)
  262. {
  263. FURI_LOG_E(HTTP_TAG, "Failed to allocate UART stream buffer.");
  264. return false;
  265. }
  266. fhttp.rx_thread = furi_thread_alloc();
  267. if (!fhttp.rx_thread)
  268. {
  269. FURI_LOG_E(HTTP_TAG, "Failed to allocate UART thread.");
  270. furi_stream_buffer_free(fhttp.flipper_http_stream);
  271. return false;
  272. }
  273. furi_thread_set_name(fhttp.rx_thread, "FlipperHTTP_RxThread");
  274. furi_thread_set_stack_size(fhttp.rx_thread, 1024);
  275. furi_thread_set_context(fhttp.rx_thread, &fhttp);
  276. furi_thread_set_callback(fhttp.rx_thread, flipper_http_worker);
  277. fhttp.handle_rx_line_cb = flipper_http_rx_callback;
  278. fhttp.callback_context = NULL;
  279. furi_thread_start(fhttp.rx_thread);
  280. fhttp.rx_thread_id = furi_thread_get_id(fhttp.rx_thread);
  281. // handle when the UART control is busy to avoid furi_check failed
  282. if (furi_hal_serial_control_is_busy(UART_CH))
  283. {
  284. FURI_LOG_E(HTTP_TAG, "UART control is busy.");
  285. return false;
  286. }
  287. fhttp.serial_handle = furi_hal_serial_control_acquire(UART_CH);
  288. if (!fhttp.serial_handle)
  289. {
  290. FURI_LOG_E(HTTP_TAG, "Failed to acquire UART control - handle is NULL");
  291. // Cleanup resources
  292. furi_thread_free(fhttp.rx_thread);
  293. furi_stream_buffer_free(fhttp.flipper_http_stream);
  294. return false;
  295. }
  296. // Initialize UART with acquired handle
  297. furi_hal_serial_init(fhttp.serial_handle, BAUDRATE);
  298. // Enable RX direction
  299. furi_hal_serial_enable_direction(fhttp.serial_handle, FuriHalSerialDirectionRx);
  300. // Start asynchronous RX with the callback
  301. furi_hal_serial_async_rx_start(fhttp.serial_handle, _flipper_http_rx_callback, &fhttp, false);
  302. // Wait for the TX to complete to ensure UART is ready
  303. furi_hal_serial_tx_wait_complete(fhttp.serial_handle);
  304. // Allocate the timer for handling timeouts
  305. fhttp.get_timeout_timer = furi_timer_alloc(
  306. get_timeout_timer_callback, // Callback function
  307. FuriTimerTypeOnce, // One-shot timer
  308. &fhttp // Context passed to callback
  309. );
  310. if (!fhttp.get_timeout_timer)
  311. {
  312. FURI_LOG_E(HTTP_TAG, "Failed to allocate HTTP request timeout timer.");
  313. // Cleanup resources
  314. furi_hal_serial_async_rx_stop(fhttp.serial_handle);
  315. furi_hal_serial_disable_direction(fhttp.serial_handle, FuriHalSerialDirectionRx);
  316. furi_hal_serial_control_release(fhttp.serial_handle);
  317. furi_hal_serial_deinit(fhttp.serial_handle);
  318. furi_thread_flags_set(fhttp.rx_thread_id, WorkerEvtStop);
  319. furi_thread_join(fhttp.rx_thread);
  320. furi_thread_free(fhttp.rx_thread);
  321. furi_stream_buffer_free(fhttp.flipper_http_stream);
  322. return false;
  323. }
  324. // Set the timer thread priority if needed
  325. furi_timer_set_thread_priority(FuriTimerThreadPriorityElevated);
  326. fhttp.last_response = (char *)malloc(RX_BUF_SIZE);
  327. if (!fhttp.last_response)
  328. {
  329. FURI_LOG_E(HTTP_TAG, "Failed to allocate memory for last_response.");
  330. return false;
  331. }
  332. // FURI_LOG_I(HTTP_TAG, "UART initialized successfully.");
  333. return true;
  334. }
  335. // Deinitialize UART
  336. /**
  337. * @brief Deinitialize UART.
  338. * @return void
  339. * @note This function will stop the asynchronous RX, release the serial handle, and free the resources.
  340. */
  341. void flipper_http_deinit()
  342. {
  343. if (fhttp.serial_handle == NULL)
  344. {
  345. FURI_LOG_E(HTTP_TAG, "UART handle is NULL. Already deinitialized?");
  346. return;
  347. }
  348. // Stop asynchronous RX
  349. furi_hal_serial_async_rx_stop(fhttp.serial_handle);
  350. // Release and deinitialize the serial handle
  351. furi_hal_serial_disable_direction(fhttp.serial_handle, FuriHalSerialDirectionRx);
  352. furi_hal_serial_control_release(fhttp.serial_handle);
  353. furi_hal_serial_deinit(fhttp.serial_handle);
  354. // Signal the worker thread to stop
  355. furi_thread_flags_set(fhttp.rx_thread_id, WorkerEvtStop);
  356. // Wait for the thread to finish
  357. furi_thread_join(fhttp.rx_thread);
  358. // Free the thread resources
  359. furi_thread_free(fhttp.rx_thread);
  360. // Free the stream buffer
  361. furi_stream_buffer_free(fhttp.flipper_http_stream);
  362. // Free the timer
  363. if (fhttp.get_timeout_timer)
  364. {
  365. furi_timer_free(fhttp.get_timeout_timer);
  366. fhttp.get_timeout_timer = NULL;
  367. }
  368. // Free the last response
  369. if (fhttp.last_response)
  370. {
  371. free(fhttp.last_response);
  372. fhttp.last_response = NULL;
  373. }
  374. // FURI_LOG_I("FlipperHTTP", "UART deinitialized successfully.");
  375. }
  376. // Function to send data over UART with newline termination
  377. /**
  378. * @brief Send data over UART with newline termination.
  379. * @return true if the data was sent successfully, false otherwise.
  380. * @param data The data to send over UART.
  381. * @note The data will be sent over UART with a newline character appended.
  382. */
  383. bool flipper_http_send_data(const char *data)
  384. {
  385. size_t data_length = strlen(data);
  386. if (data_length == 0)
  387. {
  388. FURI_LOG_E("FlipperHTTP", "Attempted to send empty data.");
  389. return false;
  390. }
  391. // Create a buffer with data + '\n'
  392. size_t send_length = data_length + 1; // +1 for '\n'
  393. if (send_length > 256)
  394. { // Ensure buffer size is sufficient
  395. FURI_LOG_E("FlipperHTTP", "Data too long to send over FHTTP.");
  396. return false;
  397. }
  398. char send_buffer[257]; // 256 + 1 for safety
  399. strncpy(send_buffer, data, 256);
  400. send_buffer[data_length] = '\n'; // Append newline
  401. send_buffer[data_length + 1] = '\0'; // Null-terminate
  402. if (fhttp.state == INACTIVE && ((strstr(send_buffer, "[PING]") == NULL) &&
  403. (strstr(send_buffer, "[WIFI/CONNECT]") == NULL)))
  404. {
  405. FURI_LOG_E("FlipperHTTP", "Cannot send data while INACTIVE.");
  406. fhttp.last_response = "Cannot send data while INACTIVE.";
  407. return false;
  408. }
  409. fhttp.state = SENDING;
  410. furi_hal_serial_tx(fhttp.serial_handle, (const uint8_t *)send_buffer, send_length);
  411. // Uncomment below line to log the data sent over UART
  412. // FURI_LOG_I("FlipperHTTP", "Sent data over UART: %s", send_buffer);
  413. fhttp.state = IDLE;
  414. return true;
  415. }
  416. // Function to send a PING request
  417. /**
  418. * @brief Send a PING request to check if the Wifi Dev Board is connected.
  419. * @return true if the request was successful, false otherwise.
  420. * @note The received data will be handled asynchronously via the callback.
  421. * @note This is best used to check if the Wifi Dev Board is connected.
  422. * @note The state will remain INACTIVE until a PONG is received.
  423. */
  424. bool flipper_http_ping()
  425. {
  426. const char *command = "[PING]";
  427. if (!flipper_http_send_data(command))
  428. {
  429. FURI_LOG_E("FlipperHTTP", "Failed to send PING command.");
  430. return false;
  431. }
  432. // set state as INACTIVE to be made IDLE if PONG is received
  433. fhttp.state = INACTIVE;
  434. // The response will be handled asynchronously via the callback
  435. return true;
  436. }
  437. // Function to list available commands
  438. /**
  439. * @brief Send a command to list available commands.
  440. * @return true if the request was successful, false otherwise.
  441. * @note The received data will be handled asynchronously via the callback.
  442. */
  443. bool flipper_http_list_commands()
  444. {
  445. const char *command = "[LIST]";
  446. if (!flipper_http_send_data(command))
  447. {
  448. FURI_LOG_E("FlipperHTTP", "Failed to send LIST command.");
  449. return false;
  450. }
  451. // The response will be handled asynchronously via the callback
  452. return true;
  453. }
  454. // Function to turn on the LED
  455. /**
  456. * @brief Allow the LED to display while processing.
  457. * @return true if the request was successful, false otherwise.
  458. * @note The received data will be handled asynchronously via the callback.
  459. */
  460. bool flipper_http_led_on()
  461. {
  462. const char *command = "[LED/ON]";
  463. if (!flipper_http_send_data(command))
  464. {
  465. FURI_LOG_E("FlipperHTTP", "Failed to send LED ON command.");
  466. return false;
  467. }
  468. // The response will be handled asynchronously via the callback
  469. return true;
  470. }
  471. // Function to turn off the LED
  472. /**
  473. * @brief Disable the LED from displaying while processing.
  474. * @return true if the request was successful, false otherwise.
  475. * @note The received data will be handled asynchronously via the callback.
  476. */
  477. bool flipper_http_led_off()
  478. {
  479. const char *command = "[LED/OFF]";
  480. if (!flipper_http_send_data(command))
  481. {
  482. FURI_LOG_E("FlipperHTTP", "Failed to send LED OFF command.");
  483. return false;
  484. }
  485. // The response will be handled asynchronously via the callback
  486. return true;
  487. }
  488. // Function to parse JSON data
  489. /**
  490. * @brief Parse JSON data.
  491. * @return true if the JSON data was parsed successfully, false otherwise.
  492. * @param key The key to parse from the JSON data.
  493. * @param json_data The JSON data to parse.
  494. * @note The received data will be handled asynchronously via the callback.
  495. */
  496. bool flipper_http_parse_json(const char *key, const char *json_data)
  497. {
  498. if (!key || !json_data)
  499. {
  500. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_parse_json.");
  501. return false;
  502. }
  503. char buffer[256];
  504. int ret =
  505. snprintf(buffer, sizeof(buffer), "[PARSE]{\"key\":\"%s\",\"json\":%s}", key, json_data);
  506. if (ret < 0 || ret >= (int)sizeof(buffer))
  507. {
  508. FURI_LOG_E("FlipperHTTP", "Failed to format JSON parse command.");
  509. return false;
  510. }
  511. if (!flipper_http_send_data(buffer))
  512. {
  513. FURI_LOG_E("FlipperHTTP", "Failed to send JSON parse command.");
  514. return false;
  515. }
  516. // The response will be handled asynchronously via the callback
  517. return true;
  518. }
  519. // Function to parse JSON array data
  520. /**
  521. * @brief Parse JSON array data.
  522. * @return true if the JSON array data was parsed successfully, false otherwise.
  523. * @param key The key to parse from the JSON array data.
  524. * @param index The index to parse from the JSON array data.
  525. * @param json_data The JSON array data to parse.
  526. * @note The received data will be handled asynchronously via the callback.
  527. */
  528. bool flipper_http_parse_json_array(const char *key, int index, const char *json_data)
  529. {
  530. if (!key || !json_data)
  531. {
  532. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_parse_json_array.");
  533. return false;
  534. }
  535. char buffer[256];
  536. int ret = snprintf(
  537. buffer,
  538. sizeof(buffer),
  539. "[PARSE/ARRAY]{\"key\":\"%s\",\"index\":%d,\"json\":%s}",
  540. key,
  541. index,
  542. json_data);
  543. if (ret < 0 || ret >= (int)sizeof(buffer))
  544. {
  545. FURI_LOG_E("FlipperHTTP", "Failed to format JSON parse array command.");
  546. return false;
  547. }
  548. if (!flipper_http_send_data(buffer))
  549. {
  550. FURI_LOG_E("FlipperHTTP", "Failed to send JSON parse array command.");
  551. return false;
  552. }
  553. // The response will be handled asynchronously via the callback
  554. return true;
  555. }
  556. // Function to scan for WiFi networks
  557. /**
  558. * @brief Send a command to scan for WiFi networks.
  559. * @return true if the request was successful, false otherwise.
  560. * @note The received data will be handled asynchronously via the callback.
  561. */
  562. bool flipper_http_scan_wifi()
  563. {
  564. const char *command = "[WIFI/SCAN]";
  565. if (!flipper_http_send_data(command))
  566. {
  567. FURI_LOG_E("FlipperHTTP", "Failed to send WiFi scan command.");
  568. return false;
  569. }
  570. // The response will be handled asynchronously via the callback
  571. return true;
  572. }
  573. // Function to save WiFi settings (returns true if successful)
  574. /**
  575. * @brief Send a command to save WiFi settings.
  576. * @return true if the request was successful, false otherwise.
  577. * @note The received data will be handled asynchronously via the callback.
  578. */
  579. bool flipper_http_save_wifi(const char *ssid, const char *password)
  580. {
  581. if (!ssid || !password)
  582. {
  583. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_save_wifi.");
  584. return false;
  585. }
  586. char buffer[256];
  587. int ret = snprintf(
  588. buffer, sizeof(buffer), "[WIFI/SAVE]{\"ssid\":\"%s\",\"password\":\"%s\"}", ssid, password);
  589. if (ret < 0 || ret >= (int)sizeof(buffer))
  590. {
  591. FURI_LOG_E("FlipperHTTP", "Failed to format WiFi save command.");
  592. return false;
  593. }
  594. if (!flipper_http_send_data(buffer))
  595. {
  596. FURI_LOG_E("FlipperHTTP", "Failed to send WiFi save command.");
  597. return false;
  598. }
  599. // The response will be handled asynchronously via the callback
  600. return true;
  601. }
  602. // Function to get IP address of WiFi Devboard
  603. /**
  604. * @brief Send a command to get the IP address of the WiFi Devboard
  605. * @return true if the request was successful, false otherwise.
  606. * @note The received data will be handled asynchronously via the callback.
  607. */
  608. bool flipper_http_ip_address()
  609. {
  610. const char *command = "[IP/ADDRESS]";
  611. if (!flipper_http_send_data(command))
  612. {
  613. FURI_LOG_E("FlipperHTTP", "Failed to send IP address command.");
  614. return false;
  615. }
  616. // The response will be handled asynchronously via the callback
  617. return true;
  618. }
  619. // Function to get IP address of the connected WiFi network
  620. /**
  621. * @brief Send a command to get the IP address of the connected WiFi network.
  622. * @return true if the request was successful, false otherwise.
  623. * @note The received data will be handled asynchronously via the callback.
  624. */
  625. bool flipper_http_ip_wifi()
  626. {
  627. const char *command = "[WIFI/IP]";
  628. if (!flipper_http_send_data(command))
  629. {
  630. FURI_LOG_E("FlipperHTTP", "Failed to send WiFi IP command.");
  631. return false;
  632. }
  633. // The response will be handled asynchronously via the callback
  634. return true;
  635. }
  636. // Function to disconnect from WiFi (returns true if successful)
  637. /**
  638. * @brief Send a command to disconnect from WiFi.
  639. * @return true if the request was successful, false otherwise.
  640. * @note The received data will be handled asynchronously via the callback.
  641. */
  642. bool flipper_http_disconnect_wifi()
  643. {
  644. const char *command = "[WIFI/DISCONNECT]";
  645. if (!flipper_http_send_data(command))
  646. {
  647. FURI_LOG_E("FlipperHTTP", "Failed to send WiFi disconnect command.");
  648. return false;
  649. }
  650. // The response will be handled asynchronously via the callback
  651. return true;
  652. }
  653. // Function to connect to WiFi (returns true if successful)
  654. /**
  655. * @brief Send a command to connect to WiFi.
  656. * @return true if the request was successful, false otherwise.
  657. * @note The received data will be handled asynchronously via the callback.
  658. */
  659. bool flipper_http_connect_wifi()
  660. {
  661. const char *command = "[WIFI/CONNECT]";
  662. if (!flipper_http_send_data(command))
  663. {
  664. FURI_LOG_E("FlipperHTTP", "Failed to send WiFi connect command.");
  665. return false;
  666. }
  667. // The response will be handled asynchronously via the callback
  668. return true;
  669. }
  670. // Function to send a GET request
  671. /**
  672. * @brief Send a GET request to the specified URL.
  673. * @return true if the request was successful, false otherwise.
  674. * @param url The URL to send the GET request to.
  675. * @note The received data will be handled asynchronously via the callback.
  676. */
  677. bool flipper_http_get_request(const char *url)
  678. {
  679. if (!url)
  680. {
  681. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_get_request.");
  682. return false;
  683. }
  684. // Prepare GET request command
  685. char command[256];
  686. int ret = snprintf(command, sizeof(command), "[GET]%s", url);
  687. if (ret < 0 || ret >= (int)sizeof(command))
  688. {
  689. FURI_LOG_E("FlipperHTTP", "Failed to format GET request command.");
  690. return false;
  691. }
  692. // Send GET request via UART
  693. if (!flipper_http_send_data(command))
  694. {
  695. FURI_LOG_E("FlipperHTTP", "Failed to send GET request command.");
  696. return false;
  697. }
  698. // The response will be handled asynchronously via the callback
  699. return true;
  700. }
  701. // Function to send a GET request with headers
  702. /**
  703. * @brief Send a GET request to the specified URL.
  704. * @return true if the request was successful, false otherwise.
  705. * @param url The URL to send the GET request to.
  706. * @param headers The headers to send with the GET request.
  707. * @note The received data will be handled asynchronously via the callback.
  708. */
  709. bool flipper_http_get_request_with_headers(const char *url, const char *headers)
  710. {
  711. if (!url || !headers)
  712. {
  713. FURI_LOG_E(
  714. "FlipperHTTP", "Invalid arguments provided to flipper_http_get_request_with_headers.");
  715. return false;
  716. }
  717. // Prepare GET request command with headers
  718. char command[256];
  719. int ret = snprintf(
  720. command, sizeof(command), "[GET/HTTP]{\"url\":\"%s\",\"headers\":%s}", url, headers);
  721. if (ret < 0 || ret >= (int)sizeof(command))
  722. {
  723. FURI_LOG_E("FlipperHTTP", "Failed to format GET request command with headers.");
  724. return false;
  725. }
  726. // Send GET request via UART
  727. if (!flipper_http_send_data(command))
  728. {
  729. FURI_LOG_E("FlipperHTTP", "Failed to send GET request command with headers.");
  730. return false;
  731. }
  732. // The response will be handled asynchronously via the callback
  733. return true;
  734. }
  735. // Function to send a GET request with headers and return bytes
  736. /**
  737. * @brief Send a GET request to the specified URL.
  738. * @return true if the request was successful, false otherwise.
  739. * @param url The URL to send the GET request to.
  740. * @param headers The headers to send with the GET request.
  741. * @note The received data will be handled asynchronously via the callback.
  742. */
  743. bool flipper_http_get_request_bytes(const char *url, const char *headers)
  744. {
  745. if (!url || !headers)
  746. {
  747. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_get_request_bytes.");
  748. return false;
  749. }
  750. // Prepare GET request command with headers
  751. char command[256];
  752. int ret = snprintf(
  753. command, sizeof(command), "[GET/BYTES]{\"url\":\"%s\",\"headers\":%s}", url, headers);
  754. if (ret < 0 || ret >= (int)sizeof(command))
  755. {
  756. FURI_LOG_E("FlipperHTTP", "Failed to format GET request command with headers.");
  757. return false;
  758. }
  759. // Send GET request via UART
  760. if (!flipper_http_send_data(command))
  761. {
  762. FURI_LOG_E("FlipperHTTP", "Failed to send GET request command with headers.");
  763. return false;
  764. }
  765. // The response will be handled asynchronously via the callback
  766. return true;
  767. }
  768. // Function to send a POST request with headers
  769. /**
  770. * @brief Send a POST request to the specified URL.
  771. * @return true if the request was successful, false otherwise.
  772. * @param url The URL to send the POST request to.
  773. * @param headers The headers to send with the POST request.
  774. * @param data The data to send with the POST request.
  775. * @note The received data will be handled asynchronously via the callback.
  776. */
  777. bool flipper_http_post_request_with_headers(
  778. const char *url,
  779. const char *headers,
  780. const char *payload)
  781. {
  782. if (!url || !headers || !payload)
  783. {
  784. FURI_LOG_E(
  785. "FlipperHTTP",
  786. "Invalid arguments provided to flipper_http_post_request_with_headers.");
  787. return false;
  788. }
  789. // Prepare POST request command with headers and data
  790. char command[256];
  791. int ret = snprintf(
  792. command,
  793. sizeof(command),
  794. "[POST/HTTP]{\"url\":\"%s\",\"headers\":%s,\"payload\":%s}",
  795. url,
  796. headers,
  797. payload);
  798. if (ret < 0 || ret >= (int)sizeof(command))
  799. {
  800. FURI_LOG_E("FlipperHTTP", "Failed to format POST request command with headers and data.");
  801. return false;
  802. }
  803. // Send POST request via UART
  804. if (!flipper_http_send_data(command))
  805. {
  806. FURI_LOG_E("FlipperHTTP", "Failed to send POST request command with headers and data.");
  807. return false;
  808. }
  809. // The response will be handled asynchronously via the callback
  810. return true;
  811. }
  812. // Function to send a POST request with headers and return bytes
  813. /**
  814. * @brief Send a POST request to the specified URL.
  815. * @return true if the request was successful, false otherwise.
  816. * @param url The URL to send the POST request to.
  817. * @param headers The headers to send with the POST request.
  818. * @param payload The data to send with the POST request.
  819. * @note The received data will be handled asynchronously via the callback.
  820. */
  821. bool flipper_http_post_request_bytes(const char *url, const char *headers, const char *payload)
  822. {
  823. if (!url || !headers || !payload)
  824. {
  825. FURI_LOG_E(
  826. "FlipperHTTP", "Invalid arguments provided to flipper_http_post_request_bytes.");
  827. return false;
  828. }
  829. // Prepare POST request command with headers and data
  830. char command[256];
  831. int ret = snprintf(
  832. command,
  833. sizeof(command),
  834. "[POST/BYTES]{\"url\":\"%s\",\"headers\":%s,\"payload\":%s}",
  835. url,
  836. headers,
  837. payload);
  838. if (ret < 0 || ret >= (int)sizeof(command))
  839. {
  840. FURI_LOG_E("FlipperHTTP", "Failed to format POST request command with headers and data.");
  841. return false;
  842. }
  843. // Send POST request via UART
  844. if (!flipper_http_send_data(command))
  845. {
  846. FURI_LOG_E("FlipperHTTP", "Failed to send POST request command with headers and data.");
  847. return false;
  848. }
  849. // The response will be handled asynchronously via the callback
  850. return true;
  851. }
  852. // Function to send a PUT request with headers
  853. /**
  854. * @brief Send a PUT request to the specified URL.
  855. * @return true if the request was successful, false otherwise.
  856. * @param url The URL to send the PUT request to.
  857. * @param headers The headers to send with the PUT request.
  858. * @param data The data to send with the PUT request.
  859. * @note The received data will be handled asynchronously via the callback.
  860. */
  861. bool flipper_http_put_request_with_headers(
  862. const char *url,
  863. const char *headers,
  864. const char *payload)
  865. {
  866. if (!url || !headers || !payload)
  867. {
  868. FURI_LOG_E(
  869. "FlipperHTTP", "Invalid arguments provided to flipper_http_put_request_with_headers.");
  870. return false;
  871. }
  872. // Prepare PUT request command with headers and data
  873. char command[256];
  874. int ret = snprintf(
  875. command,
  876. sizeof(command),
  877. "[PUT/HTTP]{\"url\":\"%s\",\"headers\":%s,\"payload\":%s}",
  878. url,
  879. headers,
  880. payload);
  881. if (ret < 0 || ret >= (int)sizeof(command))
  882. {
  883. FURI_LOG_E("FlipperHTTP", "Failed to format PUT request command with headers and data.");
  884. return false;
  885. }
  886. // Send PUT request via UART
  887. if (!flipper_http_send_data(command))
  888. {
  889. FURI_LOG_E("FlipperHTTP", "Failed to send PUT request command with headers and data.");
  890. return false;
  891. }
  892. // The response will be handled asynchronously via the callback
  893. return true;
  894. }
  895. // Function to send a DELETE request with headers
  896. /**
  897. * @brief Send a DELETE request to the specified URL.
  898. * @return true if the request was successful, false otherwise.
  899. * @param url The URL to send the DELETE request to.
  900. * @param headers The headers to send with the DELETE request.
  901. * @param data The data to send with the DELETE request.
  902. * @note The received data will be handled asynchronously via the callback.
  903. */
  904. bool flipper_http_delete_request_with_headers(
  905. const char *url,
  906. const char *headers,
  907. const char *payload)
  908. {
  909. if (!url || !headers || !payload)
  910. {
  911. FURI_LOG_E(
  912. "FlipperHTTP",
  913. "Invalid arguments provided to flipper_http_delete_request_with_headers.");
  914. return false;
  915. }
  916. // Prepare DELETE request command with headers and data
  917. char command[256];
  918. int ret = snprintf(
  919. command,
  920. sizeof(command),
  921. "[DELETE/HTTP]{\"url\":\"%s\",\"headers\":%s,\"payload\":%s}",
  922. url,
  923. headers,
  924. payload);
  925. if (ret < 0 || ret >= (int)sizeof(command))
  926. {
  927. FURI_LOG_E(
  928. "FlipperHTTP", "Failed to format DELETE request command with headers and data.");
  929. return false;
  930. }
  931. // Send DELETE request via UART
  932. if (!flipper_http_send_data(command))
  933. {
  934. FURI_LOG_E("FlipperHTTP", "Failed to send DELETE request command with headers and data.");
  935. return false;
  936. }
  937. // The response will be handled asynchronously via the callback
  938. return true;
  939. }
  940. // Function to trim leading and trailing spaces and newlines from a constant string
  941. static char *trim(const char *str)
  942. {
  943. const char *end;
  944. char *trimmed_str;
  945. size_t len;
  946. // Trim leading space
  947. while (isspace((unsigned char)*str))
  948. str++;
  949. // All spaces?
  950. if (*str == 0)
  951. return strdup(""); // Return an empty string if all spaces
  952. // Trim trailing space
  953. end = str + strlen(str) - 1;
  954. while (end > str && isspace((unsigned char)*end))
  955. end--;
  956. // Set length for the trimmed string
  957. len = end - str + 1;
  958. // Allocate space for the trimmed string and null terminator
  959. trimmed_str = (char *)malloc(len + 1);
  960. if (trimmed_str == NULL)
  961. {
  962. return NULL; // Handle memory allocation failure
  963. }
  964. // Copy the trimmed part of the string into trimmed_str
  965. strncpy(trimmed_str, str, len);
  966. trimmed_str[len] = '\0'; // Null terminate the string
  967. return trimmed_str;
  968. }
  969. // Function to handle received data asynchronously
  970. /**
  971. * @brief Callback function to handle received data asynchronously.
  972. * @return void
  973. * @param line The received line.
  974. * @param context The context passed to the callback.
  975. * @note The received data will be handled asynchronously via the callback and handles the state of the UART.
  976. */
  977. void flipper_http_rx_callback(const char *line, void *context)
  978. {
  979. if (!line)
  980. {
  981. FURI_LOG_E(HTTP_TAG, "Invalid arguments provided to flipper_http_rx_callback.");
  982. return;
  983. }
  984. UNUSED(context);
  985. // Trim the received line to check if it's empty
  986. char *trimmed_line = trim(line);
  987. if (trimmed_line != NULL && trimmed_line[0] != '\0')
  988. {
  989. // if the line is not [GET/END] or [POST/END] or [PUT/END] or [DELETE/END]
  990. if (strstr(trimmed_line, "[GET/END]") == NULL &&
  991. strstr(trimmed_line, "[POST/END]") == NULL &&
  992. strstr(trimmed_line, "[PUT/END]") == NULL &&
  993. strstr(trimmed_line, "[DELETE/END]") == NULL)
  994. {
  995. strncpy(fhttp.last_response, trimmed_line, RX_BUF_SIZE);
  996. }
  997. }
  998. free(trimmed_line); // Free the allocated memory for trimmed_line
  999. if (fhttp.state != INACTIVE && fhttp.state != ISSUE)
  1000. {
  1001. fhttp.state = RECEIVING;
  1002. }
  1003. // Uncomment below line to log the data received over UART
  1004. // FURI_LOG_I(HTTP_TAG, "Received UART line: %s", line);
  1005. // Check if we've started receiving data from a GET request
  1006. if (fhttp.started_receiving_get)
  1007. {
  1008. // Restart the timeout timer each time new data is received
  1009. furi_timer_restart(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1010. if (strstr(line, "[GET/END]") != NULL)
  1011. {
  1012. FURI_LOG_I(HTTP_TAG, "GET request completed.");
  1013. // Stop the timer since we've completed the GET request
  1014. furi_timer_stop(fhttp.get_timeout_timer);
  1015. fhttp.started_receiving_get = false;
  1016. fhttp.just_started_get = false;
  1017. fhttp.state = IDLE;
  1018. fhttp.save_bytes = false;
  1019. fhttp.save_received_data = false;
  1020. if (fhttp.is_bytes_request)
  1021. {
  1022. // Search for the binary marker `[GET/END]` in the file buffer
  1023. const char marker[] = "[GET/END]";
  1024. const size_t marker_len = sizeof(marker) - 1; // Exclude null terminator
  1025. for (size_t i = 0; i <= fhttp.file_buffer_len - marker_len; i++)
  1026. {
  1027. // Check if the marker is found
  1028. if (memcmp(&fhttp.file_buffer[i], marker, marker_len) == 0)
  1029. {
  1030. // Remove the marker by shifting the remaining data left
  1031. size_t remaining_len = fhttp.file_buffer_len - (i + marker_len);
  1032. memmove(&fhttp.file_buffer[i], &fhttp.file_buffer[i + marker_len], remaining_len);
  1033. fhttp.file_buffer_len -= marker_len;
  1034. break;
  1035. }
  1036. }
  1037. // If there is data left in the buffer, append it to the file
  1038. if (fhttp.file_buffer_len > 0)
  1039. {
  1040. if (!flipper_http_append_to_file(fhttp.file_buffer, fhttp.file_buffer_len, false, fhttp.file_path))
  1041. {
  1042. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1043. }
  1044. fhttp.file_buffer_len = 0;
  1045. }
  1046. }
  1047. fhttp.is_bytes_request = false;
  1048. return;
  1049. }
  1050. // Append the new line to the existing data
  1051. if (fhttp.save_received_data &&
  1052. !flipper_http_append_to_file(
  1053. line, strlen(line), !fhttp.just_started_get, fhttp.file_path))
  1054. {
  1055. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1056. fhttp.started_receiving_get = false;
  1057. fhttp.just_started_get = false;
  1058. fhttp.state = IDLE;
  1059. return;
  1060. }
  1061. if (!fhttp.just_started_get)
  1062. {
  1063. fhttp.just_started_get = true;
  1064. }
  1065. return;
  1066. }
  1067. // Check if we've started receiving data from a POST request
  1068. else if (fhttp.started_receiving_post)
  1069. {
  1070. // Restart the timeout timer each time new data is received
  1071. furi_timer_restart(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1072. if (strstr(line, "[POST/END]") != NULL)
  1073. {
  1074. FURI_LOG_I(HTTP_TAG, "POST request completed.");
  1075. // Stop the timer since we've completed the POST request
  1076. furi_timer_stop(fhttp.get_timeout_timer);
  1077. fhttp.started_receiving_post = false;
  1078. fhttp.just_started_post = false;
  1079. fhttp.state = IDLE;
  1080. fhttp.save_bytes = false;
  1081. fhttp.save_received_data = false;
  1082. if (fhttp.is_bytes_request)
  1083. {
  1084. // Search for the binary marker `[POST/END]` in the file buffer
  1085. const char marker[] = "[POST/END]";
  1086. const size_t marker_len = sizeof(marker) - 1; // Exclude null terminator
  1087. for (size_t i = 0; i <= fhttp.file_buffer_len - marker_len; i++)
  1088. {
  1089. // Check if the marker is found
  1090. if (memcmp(&fhttp.file_buffer[i], marker, marker_len) == 0)
  1091. {
  1092. // Remove the marker by shifting the remaining data left
  1093. size_t remaining_len = fhttp.file_buffer_len - (i + marker_len);
  1094. memmove(&fhttp.file_buffer[i], &fhttp.file_buffer[i + marker_len], remaining_len);
  1095. fhttp.file_buffer_len -= marker_len;
  1096. break;
  1097. }
  1098. }
  1099. // If there is data left in the buffer, append it to the file
  1100. if (fhttp.file_buffer_len > 0)
  1101. {
  1102. if (!flipper_http_append_to_file(fhttp.file_buffer, fhttp.file_buffer_len, false, fhttp.file_path))
  1103. {
  1104. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1105. }
  1106. fhttp.file_buffer_len = 0;
  1107. }
  1108. }
  1109. fhttp.is_bytes_request = false;
  1110. return;
  1111. }
  1112. // Append the new line to the existing data
  1113. if (fhttp.save_received_data &&
  1114. !flipper_http_append_to_file(
  1115. line, strlen(line), !fhttp.just_started_post, fhttp.file_path))
  1116. {
  1117. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1118. fhttp.started_receiving_post = false;
  1119. fhttp.just_started_post = false;
  1120. fhttp.state = IDLE;
  1121. return;
  1122. }
  1123. if (!fhttp.just_started_post)
  1124. {
  1125. fhttp.just_started_post = true;
  1126. }
  1127. return;
  1128. }
  1129. // Check if we've started receiving data from a PUT request
  1130. else if (fhttp.started_receiving_put)
  1131. {
  1132. // Restart the timeout timer each time new data is received
  1133. furi_timer_restart(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1134. if (strstr(line, "[PUT/END]") != NULL)
  1135. {
  1136. FURI_LOG_I(HTTP_TAG, "PUT request completed.");
  1137. // Stop the timer since we've completed the PUT request
  1138. furi_timer_stop(fhttp.get_timeout_timer);
  1139. fhttp.started_receiving_put = false;
  1140. fhttp.just_started_put = false;
  1141. fhttp.state = IDLE;
  1142. fhttp.save_bytes = false;
  1143. fhttp.is_bytes_request = false;
  1144. fhttp.save_received_data = false;
  1145. return;
  1146. }
  1147. // Append the new line to the existing data
  1148. if (fhttp.save_received_data &&
  1149. !flipper_http_append_to_file(
  1150. line, strlen(line), !fhttp.just_started_put, fhttp.file_path))
  1151. {
  1152. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1153. fhttp.started_receiving_put = false;
  1154. fhttp.just_started_put = false;
  1155. fhttp.state = IDLE;
  1156. return;
  1157. }
  1158. if (!fhttp.just_started_put)
  1159. {
  1160. fhttp.just_started_put = true;
  1161. }
  1162. return;
  1163. }
  1164. // Check if we've started receiving data from a DELETE request
  1165. else if (fhttp.started_receiving_delete)
  1166. {
  1167. // Restart the timeout timer each time new data is received
  1168. furi_timer_restart(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1169. if (strstr(line, "[DELETE/END]") != NULL)
  1170. {
  1171. FURI_LOG_I(HTTP_TAG, "DELETE request completed.");
  1172. // Stop the timer since we've completed the DELETE request
  1173. furi_timer_stop(fhttp.get_timeout_timer);
  1174. fhttp.started_receiving_delete = false;
  1175. fhttp.just_started_delete = false;
  1176. fhttp.state = IDLE;
  1177. fhttp.save_bytes = false;
  1178. fhttp.is_bytes_request = false;
  1179. fhttp.save_received_data = false;
  1180. return;
  1181. }
  1182. // Append the new line to the existing data
  1183. if (fhttp.save_received_data &&
  1184. !flipper_http_append_to_file(
  1185. line, strlen(line), !fhttp.just_started_delete, fhttp.file_path))
  1186. {
  1187. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1188. fhttp.started_receiving_delete = false;
  1189. fhttp.just_started_delete = false;
  1190. fhttp.state = IDLE;
  1191. return;
  1192. }
  1193. if (!fhttp.just_started_delete)
  1194. {
  1195. fhttp.just_started_delete = true;
  1196. }
  1197. return;
  1198. }
  1199. // Handle different types of responses
  1200. if (strstr(line, "[SUCCESS]") != NULL || strstr(line, "[CONNECTED]") != NULL)
  1201. {
  1202. FURI_LOG_I(HTTP_TAG, "Operation succeeded.");
  1203. }
  1204. else if (strstr(line, "[INFO]") != NULL)
  1205. {
  1206. FURI_LOG_I(HTTP_TAG, "Received info: %s", line);
  1207. if (fhttp.state == INACTIVE && strstr(line, "[INFO] Already connected to Wifi.") != NULL)
  1208. {
  1209. fhttp.state = IDLE;
  1210. }
  1211. }
  1212. else if (strstr(line, "[GET/SUCCESS]") != NULL)
  1213. {
  1214. FURI_LOG_I(HTTP_TAG, "GET request succeeded.");
  1215. fhttp.started_receiving_get = true;
  1216. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1217. fhttp.state = RECEIVING;
  1218. // for GET request, save data only if it's a bytes request
  1219. fhttp.save_bytes = fhttp.is_bytes_request;
  1220. fhttp.just_started_bytes = true;
  1221. fhttp.file_buffer_len = 0;
  1222. return;
  1223. }
  1224. else if (strstr(line, "[POST/SUCCESS]") != NULL)
  1225. {
  1226. FURI_LOG_I(HTTP_TAG, "POST request succeeded.");
  1227. fhttp.started_receiving_post = true;
  1228. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1229. fhttp.state = RECEIVING;
  1230. // for POST request, save data only if it's a bytes request
  1231. fhttp.save_bytes = fhttp.is_bytes_request;
  1232. fhttp.just_started_bytes = true;
  1233. fhttp.file_buffer_len = 0;
  1234. return;
  1235. }
  1236. else if (strstr(line, "[PUT/SUCCESS]") != NULL)
  1237. {
  1238. FURI_LOG_I(HTTP_TAG, "PUT request succeeded.");
  1239. fhttp.started_receiving_put = true;
  1240. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1241. fhttp.state = RECEIVING;
  1242. return;
  1243. }
  1244. else if (strstr(line, "[DELETE/SUCCESS]") != NULL)
  1245. {
  1246. FURI_LOG_I(HTTP_TAG, "DELETE request succeeded.");
  1247. fhttp.started_receiving_delete = true;
  1248. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1249. fhttp.state = RECEIVING;
  1250. return;
  1251. }
  1252. else if (strstr(line, "[DISCONNECTED]") != NULL)
  1253. {
  1254. FURI_LOG_I(HTTP_TAG, "WiFi disconnected successfully.");
  1255. }
  1256. else if (strstr(line, "[ERROR]") != NULL)
  1257. {
  1258. FURI_LOG_E(HTTP_TAG, "Received error: %s", line);
  1259. fhttp.state = ISSUE;
  1260. return;
  1261. }
  1262. else if (strstr(line, "[PONG]") != NULL)
  1263. {
  1264. FURI_LOG_I(HTTP_TAG, "Received PONG response: Wifi Dev Board is still alive.");
  1265. // send command to connect to WiFi
  1266. if (fhttp.state == INACTIVE)
  1267. {
  1268. fhttp.state = IDLE;
  1269. return;
  1270. }
  1271. }
  1272. if (fhttp.state == INACTIVE && strstr(line, "[PONG]") != NULL)
  1273. {
  1274. fhttp.state = IDLE;
  1275. }
  1276. else if (fhttp.state == INACTIVE && strstr(line, "[PONG]") == NULL)
  1277. {
  1278. fhttp.state = INACTIVE;
  1279. }
  1280. else
  1281. {
  1282. fhttp.state = IDLE;
  1283. }
  1284. }
  1285. /**
  1286. * @brief Process requests and parse JSON data asynchronously
  1287. * @param http_request The function to send the request
  1288. * @param parse_json The function to parse the JSON
  1289. * @return true if successful, false otherwise
  1290. */
  1291. bool flipper_http_process_response_async(bool (*http_request)(void), bool (*parse_json)(void))
  1292. {
  1293. if (http_request()) // start the async request
  1294. {
  1295. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1296. fhttp.state = RECEIVING;
  1297. }
  1298. else
  1299. {
  1300. FURI_LOG_E(HTTP_TAG, "Failed to send request");
  1301. return false;
  1302. }
  1303. while (fhttp.state == RECEIVING && furi_timer_is_running(fhttp.get_timeout_timer) > 0)
  1304. {
  1305. // Wait for the request to be received
  1306. furi_delay_ms(100);
  1307. }
  1308. furi_timer_stop(fhttp.get_timeout_timer);
  1309. if (!parse_json()) // parse the JSON before switching to the view (synchonous)
  1310. {
  1311. FURI_LOG_E(HTTP_TAG, "Failed to parse the JSON...");
  1312. return false;
  1313. }
  1314. return true;
  1315. }
  1316. /**
  1317. * @brief Perform a task while displaying a loading screen
  1318. * @param http_request The function to send the request
  1319. * @param parse_response The function to parse the response
  1320. * @param success_view_id The view ID to switch to on success
  1321. * @param failure_view_id The view ID to switch to on failure
  1322. * @param view_dispatcher The view dispatcher to use
  1323. * @return
  1324. */
  1325. void flipper_http_loading_task(bool (*http_request)(void),
  1326. bool (*parse_response)(void),
  1327. uint32_t success_view_id,
  1328. uint32_t failure_view_id,
  1329. ViewDispatcher **view_dispatcher)
  1330. {
  1331. if (fhttp.state == INACTIVE)
  1332. {
  1333. view_dispatcher_switch_to_view(*view_dispatcher, failure_view_id);
  1334. return;
  1335. }
  1336. Loading *loading;
  1337. int32_t loading_view_id = 987654321; // Random ID
  1338. loading = loading_alloc();
  1339. if (!loading)
  1340. {
  1341. FURI_LOG_E(HTTP_TAG, "Failed to allocate loading");
  1342. view_dispatcher_switch_to_view(*view_dispatcher, failure_view_id);
  1343. return;
  1344. }
  1345. view_dispatcher_add_view(*view_dispatcher, loading_view_id, loading_get_view(loading));
  1346. // Switch to the loading view
  1347. view_dispatcher_switch_to_view(*view_dispatcher, loading_view_id);
  1348. // Make the request
  1349. if (!flipper_http_process_response_async(http_request, parse_response))
  1350. {
  1351. FURI_LOG_E(HTTP_TAG, "Failed to make request");
  1352. view_dispatcher_switch_to_view(*view_dispatcher, failure_view_id);
  1353. view_dispatcher_remove_view(*view_dispatcher, loading_view_id);
  1354. loading_free(loading);
  1355. return;
  1356. }
  1357. // Switch to the success view
  1358. view_dispatcher_switch_to_view(*view_dispatcher, success_view_id);
  1359. view_dispatcher_remove_view(*view_dispatcher, loading_view_id);
  1360. loading_free(loading); // comment this out if you experience a freeze
  1361. }