flipper_http.c 47 KB

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