flipper_http.c 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468
  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, file_buffer_len, false, fhttp.file_path))
  168. {
  169. FURI_LOG_E(HTTP_TAG, "Failed to append data to file");
  170. }
  171. file_buffer_len = 0;
  172. }
  173. }
  174. // Handle line buffering only if callback is set (text data)
  175. if (fhttp.handle_rx_line_cb)
  176. {
  177. // Handle line buffering
  178. if (c == '\n' || rx_line_pos >= RX_LINE_BUFFER_SIZE - 1)
  179. {
  180. rx_line_buffer[rx_line_pos] = '\0'; // Null-terminate the line
  181. // Invoke the callback with the complete line
  182. fhttp.handle_rx_line_cb(rx_line_buffer, fhttp.callback_context);
  183. // Reset the line buffer position
  184. rx_line_pos = 0;
  185. }
  186. else
  187. {
  188. rx_line_buffer[rx_line_pos++] = c; // Add character to the line buffer
  189. }
  190. }
  191. }
  192. }
  193. }
  194. return 0;
  195. }
  196. // Timer callback function
  197. /**
  198. * @brief Callback function for the GET timeout timer.
  199. * @return 0
  200. * @param context The context to pass to the callback.
  201. * @note This function will be called when the GET request times out.
  202. */
  203. void get_timeout_timer_callback(void *context)
  204. {
  205. UNUSED(context);
  206. FURI_LOG_E(HTTP_TAG, "Timeout reached: 2 seconds without receiving the end.");
  207. // Reset the state
  208. fhttp.started_receiving_get = false;
  209. fhttp.started_receiving_post = false;
  210. fhttp.started_receiving_put = false;
  211. fhttp.started_receiving_delete = false;
  212. // Update UART state
  213. fhttp.state = ISSUE;
  214. }
  215. // UART RX Handler Callback (Interrupt Context)
  216. /**
  217. * @brief A private callback function to handle received data asynchronously.
  218. * @return void
  219. * @param handle The UART handle.
  220. * @param event The event type.
  221. * @param context The context to pass to the callback.
  222. * @note This function will handle received data asynchronously via the callback.
  223. */
  224. void _flipper_http_rx_callback(
  225. FuriHalSerialHandle *handle,
  226. FuriHalSerialRxEvent event,
  227. void *context)
  228. {
  229. UNUSED(context);
  230. if (event == FuriHalSerialRxEventData)
  231. {
  232. uint8_t data = furi_hal_serial_async_rx(handle);
  233. furi_stream_buffer_send(fhttp.flipper_http_stream, &data, 1, 0);
  234. furi_thread_flags_set(fhttp.rx_thread_id, WorkerEvtRxDone);
  235. }
  236. }
  237. // UART initialization function
  238. /**
  239. * @brief Initialize UART.
  240. * @return true if the UART was initialized successfully, false otherwise.
  241. * @param callback The callback function to handle received data (ex. flipper_http_rx_callback).
  242. * @param context The context to pass to the callback.
  243. * @note The received data will be handled asynchronously via the callback.
  244. */
  245. bool flipper_http_init(FlipperHTTP_Callback callback, void *context)
  246. {
  247. if (!context)
  248. {
  249. FURI_LOG_E(HTTP_TAG, "Invalid context provided to flipper_http_init.");
  250. return false;
  251. }
  252. if (!callback)
  253. {
  254. FURI_LOG_E(HTTP_TAG, "Invalid callback provided to flipper_http_init.");
  255. return false;
  256. }
  257. fhttp.flipper_http_stream = furi_stream_buffer_alloc(RX_BUF_SIZE, 1);
  258. if (!fhttp.flipper_http_stream)
  259. {
  260. FURI_LOG_E(HTTP_TAG, "Failed to allocate UART stream buffer.");
  261. return false;
  262. }
  263. fhttp.rx_thread = furi_thread_alloc();
  264. if (!fhttp.rx_thread)
  265. {
  266. FURI_LOG_E(HTTP_TAG, "Failed to allocate UART thread.");
  267. furi_stream_buffer_free(fhttp.flipper_http_stream);
  268. return false;
  269. }
  270. furi_thread_set_name(fhttp.rx_thread, "FlipperHTTP_RxThread");
  271. furi_thread_set_stack_size(fhttp.rx_thread, 1024);
  272. furi_thread_set_context(fhttp.rx_thread, &fhttp);
  273. furi_thread_set_callback(fhttp.rx_thread, flipper_http_worker);
  274. fhttp.handle_rx_line_cb = callback;
  275. fhttp.callback_context = context;
  276. furi_thread_start(fhttp.rx_thread);
  277. fhttp.rx_thread_id = furi_thread_get_id(fhttp.rx_thread);
  278. // handle when the UART control is busy to avoid furi_check failed
  279. if (furi_hal_serial_control_is_busy(UART_CH))
  280. {
  281. FURI_LOG_E(HTTP_TAG, "UART control is busy.");
  282. return false;
  283. }
  284. fhttp.serial_handle = furi_hal_serial_control_acquire(UART_CH);
  285. if (!fhttp.serial_handle)
  286. {
  287. FURI_LOG_E(HTTP_TAG, "Failed to acquire UART control - handle is NULL");
  288. // Cleanup resources
  289. furi_thread_free(fhttp.rx_thread);
  290. furi_stream_buffer_free(fhttp.flipper_http_stream);
  291. return false;
  292. }
  293. // Initialize UART with acquired handle
  294. furi_hal_serial_init(fhttp.serial_handle, BAUDRATE);
  295. // Enable RX direction
  296. furi_hal_serial_enable_direction(fhttp.serial_handle, FuriHalSerialDirectionRx);
  297. // Start asynchronous RX with the callback
  298. furi_hal_serial_async_rx_start(fhttp.serial_handle, _flipper_http_rx_callback, &fhttp, false);
  299. // Wait for the TX to complete to ensure UART is ready
  300. furi_hal_serial_tx_wait_complete(fhttp.serial_handle);
  301. // Allocate the timer for handling timeouts
  302. fhttp.get_timeout_timer = furi_timer_alloc(
  303. get_timeout_timer_callback, // Callback function
  304. FuriTimerTypeOnce, // One-shot timer
  305. &fhttp // Context passed to callback
  306. );
  307. if (!fhttp.get_timeout_timer)
  308. {
  309. FURI_LOG_E(HTTP_TAG, "Failed to allocate HTTP request timeout timer.");
  310. // Cleanup resources
  311. furi_hal_serial_async_rx_stop(fhttp.serial_handle);
  312. furi_hal_serial_disable_direction(fhttp.serial_handle, FuriHalSerialDirectionRx);
  313. furi_hal_serial_control_release(fhttp.serial_handle);
  314. furi_hal_serial_deinit(fhttp.serial_handle);
  315. furi_thread_flags_set(fhttp.rx_thread_id, WorkerEvtStop);
  316. furi_thread_join(fhttp.rx_thread);
  317. furi_thread_free(fhttp.rx_thread);
  318. furi_stream_buffer_free(fhttp.flipper_http_stream);
  319. return false;
  320. }
  321. // Set the timer thread priority if needed
  322. furi_timer_set_thread_priority(FuriTimerThreadPriorityElevated);
  323. fhttp.last_response = (char *)malloc(RX_BUF_SIZE);
  324. if (!fhttp.last_response)
  325. {
  326. FURI_LOG_E(HTTP_TAG, "Failed to allocate memory for last_response.");
  327. return false;
  328. }
  329. // FURI_LOG_I(HTTP_TAG, "UART initialized successfully.");
  330. return true;
  331. }
  332. // Deinitialize UART
  333. /**
  334. * @brief Deinitialize UART.
  335. * @return void
  336. * @note This function will stop the asynchronous RX, release the serial handle, and free the resources.
  337. */
  338. void flipper_http_deinit()
  339. {
  340. if (fhttp.serial_handle == NULL)
  341. {
  342. FURI_LOG_E(HTTP_TAG, "UART handle is NULL. Already deinitialized?");
  343. return;
  344. }
  345. // Stop asynchronous RX
  346. furi_hal_serial_async_rx_stop(fhttp.serial_handle);
  347. // Release and deinitialize the serial handle
  348. furi_hal_serial_disable_direction(fhttp.serial_handle, FuriHalSerialDirectionRx);
  349. furi_hal_serial_control_release(fhttp.serial_handle);
  350. furi_hal_serial_deinit(fhttp.serial_handle);
  351. // Signal the worker thread to stop
  352. furi_thread_flags_set(fhttp.rx_thread_id, WorkerEvtStop);
  353. // Wait for the thread to finish
  354. furi_thread_join(fhttp.rx_thread);
  355. // Free the thread resources
  356. furi_thread_free(fhttp.rx_thread);
  357. // Free the stream buffer
  358. furi_stream_buffer_free(fhttp.flipper_http_stream);
  359. // Free the timer
  360. if (fhttp.get_timeout_timer)
  361. {
  362. furi_timer_free(fhttp.get_timeout_timer);
  363. fhttp.get_timeout_timer = NULL;
  364. }
  365. // Free the last response
  366. if (fhttp.last_response)
  367. {
  368. free(fhttp.last_response);
  369. fhttp.last_response = NULL;
  370. }
  371. // FURI_LOG_I("FlipperHTTP", "UART deinitialized successfully.");
  372. }
  373. // Function to send data over UART with newline termination
  374. /**
  375. * @brief Send data over UART with newline termination.
  376. * @return true if the data was sent successfully, false otherwise.
  377. * @param data The data to send over UART.
  378. * @note The data will be sent over UART with a newline character appended.
  379. */
  380. bool flipper_http_send_data(const char *data)
  381. {
  382. size_t data_length = strlen(data);
  383. if (data_length == 0)
  384. {
  385. FURI_LOG_E("FlipperHTTP", "Attempted to send empty data.");
  386. return false;
  387. }
  388. // Create a buffer with data + '\n'
  389. size_t send_length = data_length + 1; // +1 for '\n'
  390. if (send_length > 256)
  391. { // Ensure buffer size is sufficient
  392. FURI_LOG_E("FlipperHTTP", "Data too long to send over FHTTP.");
  393. return false;
  394. }
  395. char send_buffer[257]; // 256 + 1 for safety
  396. strncpy(send_buffer, data, 256);
  397. send_buffer[data_length] = '\n'; // Append newline
  398. send_buffer[data_length + 1] = '\0'; // Null-terminate
  399. if (fhttp.state == INACTIVE && ((strstr(send_buffer, "[PING]") == NULL) &&
  400. (strstr(send_buffer, "[WIFI/CONNECT]") == NULL)))
  401. {
  402. FURI_LOG_E("FlipperHTTP", "Cannot send data while INACTIVE.");
  403. fhttp.last_response = "Cannot send data while INACTIVE.";
  404. return false;
  405. }
  406. fhttp.state = SENDING;
  407. furi_hal_serial_tx(fhttp.serial_handle, (const uint8_t *)send_buffer, send_length);
  408. // Uncomment below line to log the data sent over UART
  409. // FURI_LOG_I("FlipperHTTP", "Sent data over UART: %s", send_buffer);
  410. // fhttp.state = IDLE;
  411. return true;
  412. }
  413. // Function to send a PING request
  414. /**
  415. * @brief Send a PING request to check if the Wifi Dev Board is connected.
  416. * @return true if the request was successful, false otherwise.
  417. * @note The received data will be handled asynchronously via the callback.
  418. * @note This is best used to check if the Wifi Dev Board is connected.
  419. * @note The state will remain INACTIVE until a PONG is received.
  420. */
  421. bool flipper_http_ping()
  422. {
  423. const char *command = "[PING]";
  424. if (!flipper_http_send_data(command))
  425. {
  426. FURI_LOG_E("FlipperHTTP", "Failed to send PING command.");
  427. return false;
  428. }
  429. // set state as INACTIVE to be made IDLE if PONG is received
  430. fhttp.state = INACTIVE;
  431. // The response will be handled asynchronously via the callback
  432. return true;
  433. }
  434. // Function to list available commands
  435. /**
  436. * @brief Send a command to list available commands.
  437. * @return true if the request was successful, false otherwise.
  438. * @note The received data will be handled asynchronously via the callback.
  439. */
  440. bool flipper_http_list_commands()
  441. {
  442. const char *command = "[LIST]";
  443. if (!flipper_http_send_data(command))
  444. {
  445. FURI_LOG_E("FlipperHTTP", "Failed to send LIST command.");
  446. return false;
  447. }
  448. // The response will be handled asynchronously via the callback
  449. return true;
  450. }
  451. // Function to turn on the LED
  452. /**
  453. * @brief Allow the LED to display while processing.
  454. * @return true if the request was successful, false otherwise.
  455. * @note The received data will be handled asynchronously via the callback.
  456. */
  457. bool flipper_http_led_on()
  458. {
  459. const char *command = "[LED/ON]";
  460. if (!flipper_http_send_data(command))
  461. {
  462. FURI_LOG_E("FlipperHTTP", "Failed to send LED ON command.");
  463. return false;
  464. }
  465. // The response will be handled asynchronously via the callback
  466. return true;
  467. }
  468. // Function to turn off the LED
  469. /**
  470. * @brief Disable the LED from displaying while processing.
  471. * @return true if the request was successful, false otherwise.
  472. * @note The received data will be handled asynchronously via the callback.
  473. */
  474. bool flipper_http_led_off()
  475. {
  476. const char *command = "[LED/OFF]";
  477. if (!flipper_http_send_data(command))
  478. {
  479. FURI_LOG_E("FlipperHTTP", "Failed to send LED OFF command.");
  480. return false;
  481. }
  482. // The response will be handled asynchronously via the callback
  483. return true;
  484. }
  485. // Function to parse JSON data
  486. /**
  487. * @brief Parse JSON data.
  488. * @return true if the JSON data was parsed successfully, false otherwise.
  489. * @param key The key to parse from the JSON data.
  490. * @param json_data The JSON data to parse.
  491. * @note The received data will be handled asynchronously via the callback.
  492. */
  493. bool flipper_http_parse_json(const char *key, const char *json_data)
  494. {
  495. if (!key || !json_data)
  496. {
  497. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_parse_json.");
  498. return false;
  499. }
  500. char buffer[256];
  501. int ret =
  502. snprintf(buffer, sizeof(buffer), "[PARSE]{\"key\":\"%s\",\"json\":%s}", key, json_data);
  503. if (ret < 0 || ret >= (int)sizeof(buffer))
  504. {
  505. FURI_LOG_E("FlipperHTTP", "Failed to format JSON parse command.");
  506. return false;
  507. }
  508. if (!flipper_http_send_data(buffer))
  509. {
  510. FURI_LOG_E("FlipperHTTP", "Failed to send JSON parse command.");
  511. return false;
  512. }
  513. // The response will be handled asynchronously via the callback
  514. return true;
  515. }
  516. // Function to parse JSON array data
  517. /**
  518. * @brief Parse JSON array data.
  519. * @return true if the JSON array data was parsed successfully, false otherwise.
  520. * @param key The key to parse from the JSON array data.
  521. * @param index The index to parse from the JSON array data.
  522. * @param json_data The JSON array data to parse.
  523. * @note The received data will be handled asynchronously via the callback.
  524. */
  525. bool flipper_http_parse_json_array(const char *key, int index, const char *json_data)
  526. {
  527. if (!key || !json_data)
  528. {
  529. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_parse_json_array.");
  530. return false;
  531. }
  532. char buffer[256];
  533. int ret = snprintf(
  534. buffer,
  535. sizeof(buffer),
  536. "[PARSE/ARRAY]{\"key\":\"%s\",\"index\":%d,\"json\":%s}",
  537. key,
  538. index,
  539. json_data);
  540. if (ret < 0 || ret >= (int)sizeof(buffer))
  541. {
  542. FURI_LOG_E("FlipperHTTP", "Failed to format JSON parse array command.");
  543. return false;
  544. }
  545. if (!flipper_http_send_data(buffer))
  546. {
  547. FURI_LOG_E("FlipperHTTP", "Failed to send JSON parse array command.");
  548. return false;
  549. }
  550. // The response will be handled asynchronously via the callback
  551. return true;
  552. }
  553. // Function to scan for WiFi networks
  554. /**
  555. * @brief Send a command to scan for WiFi networks.
  556. * @return true if the request was successful, false otherwise.
  557. * @note The received data will be handled asynchronously via the callback.
  558. */
  559. bool flipper_http_scan_wifi()
  560. {
  561. if (!flipper_http_send_data("[WIFI/SCAN]"))
  562. {
  563. FURI_LOG_E("FlipperHTTP", "Failed to send WiFi scan command.");
  564. return false;
  565. }
  566. // custom for FlipWiFi app
  567. fhttp.just_started_get = true;
  568. snprintf(
  569. fhttp.file_path,
  570. sizeof(fhttp.file_path),
  571. STORAGE_EXT_PATH_PREFIX "/apps_data/flip_wifi/scan.txt");
  572. fhttp.save_received_data = true;
  573. // The response will be handled asynchronously via the callback
  574. return true;
  575. }
  576. // Function to save WiFi settings (returns true if successful)
  577. /**
  578. * @brief Send a command to save WiFi settings.
  579. * @return true if the request was successful, false otherwise.
  580. * @note The received data will be handled asynchronously via the callback.
  581. */
  582. bool flipper_http_save_wifi(const char *ssid, const char *password)
  583. {
  584. if (!ssid || !password)
  585. {
  586. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_save_wifi.");
  587. return false;
  588. }
  589. char buffer[256];
  590. int ret = snprintf(
  591. buffer, sizeof(buffer), "[WIFI/SAVE]{\"ssid\":\"%s\",\"password\":\"%s\"}", ssid, password);
  592. if (ret < 0 || ret >= (int)sizeof(buffer))
  593. {
  594. FURI_LOG_E("FlipperHTTP", "Failed to format WiFi save command.");
  595. return false;
  596. }
  597. if (!flipper_http_send_data(buffer))
  598. {
  599. FURI_LOG_E("FlipperHTTP", "Failed to send WiFi save command.");
  600. return false;
  601. }
  602. // The response will be handled asynchronously via the callback
  603. return true;
  604. }
  605. // Function to get IP address of WiFi Devboard
  606. /**
  607. * @brief Send a command to get the IP address of the WiFi Devboard
  608. * @return true if the request was successful, false otherwise.
  609. * @note The received data will be handled asynchronously via the callback.
  610. */
  611. bool flipper_http_ip_address()
  612. {
  613. if (!flipper_http_send_data("[IP/ADDRESS]"))
  614. {
  615. FURI_LOG_E("FlipperHTTP", "Failed to send IP address command.");
  616. return false;
  617. }
  618. // The response will be handled asynchronously via the callback
  619. return true;
  620. }
  621. // Function to get IP address of the connected WiFi network
  622. /**
  623. * @brief Send a command to get the IP address of the connected WiFi network.
  624. * @return true if the request was successful, false otherwise.
  625. * @note The received data will be handled asynchronously via the callback.
  626. */
  627. bool flipper_http_ip_wifi()
  628. {
  629. const char *command = "[WIFI/IP]";
  630. if (!flipper_http_send_data(command))
  631. {
  632. FURI_LOG_E("FlipperHTTP", "Failed to send WiFi IP command.");
  633. return false;
  634. }
  635. // The response will be handled asynchronously via the callback
  636. return true;
  637. }
  638. // Function to disconnect from WiFi (returns true if successful)
  639. /**
  640. * @brief Send a command to disconnect from WiFi.
  641. * @return true if the request was successful, false otherwise.
  642. * @note The received data will be handled asynchronously via the callback.
  643. */
  644. bool flipper_http_disconnect_wifi()
  645. {
  646. if (!flipper_http_send_data("[WIFI/DISCONNECT]"))
  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. if (!flipper_http_send_data("[WIFI/CONNECT]"))
  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 handle received data asynchronously
  941. /**
  942. * @brief Callback function to handle received data asynchronously.
  943. * @return void
  944. * @param line The received line.
  945. * @param context The context passed to the callback.
  946. * @note The received data will be handled asynchronously via the callback and handles the state of the UART.
  947. */
  948. void flipper_http_rx_callback(const char *line, void *context)
  949. {
  950. if (!line || !context)
  951. {
  952. FURI_LOG_E(HTTP_TAG, "Invalid arguments provided to flipper_http_rx_callback.");
  953. return;
  954. }
  955. // Trim the received line to check if it's empty
  956. char *trimmed_line = trim(line);
  957. if (trimmed_line != NULL && trimmed_line[0] != '\0')
  958. {
  959. // if the line is not [GET/END] or [POST/END] or [PUT/END] or [DELETE/END]
  960. if (strstr(trimmed_line, "[GET/END]") == NULL &&
  961. strstr(trimmed_line, "[POST/END]") == NULL &&
  962. strstr(trimmed_line, "[PUT/END]") == NULL &&
  963. strstr(trimmed_line, "[DELETE/END]") == NULL)
  964. {
  965. strncpy(fhttp.last_response, trimmed_line, RX_BUF_SIZE);
  966. }
  967. }
  968. free(trimmed_line); // Free the allocated memory for trimmed_line
  969. if (fhttp.state != INACTIVE && fhttp.state != ISSUE)
  970. {
  971. fhttp.state = RECEIVING;
  972. }
  973. // Uncomment below line to log the data received over UART
  974. // FURI_LOG_I(HTTP_TAG, "Received UART line: %s", line);
  975. // custom function to FlipWiFi
  976. if (fhttp.save_received_data)
  977. {
  978. if (!flipper_http_append_to_file(line, strlen(line), !fhttp.just_started_get, fhttp.file_path))
  979. {
  980. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  981. fhttp.just_started_get = false;
  982. fhttp.state = ISSUE;
  983. return;
  984. }
  985. }
  986. // Check if we've started receiving data from a GET request
  987. if (fhttp.started_receiving_get)
  988. {
  989. // Restart the timeout timer each time new data is received
  990. furi_timer_restart(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  991. if (strstr(line, "[GET/END]") != NULL)
  992. {
  993. FURI_LOG_I(HTTP_TAG, "GET request completed.");
  994. // Stop the timer since we've completed the GET request
  995. furi_timer_stop(fhttp.get_timeout_timer);
  996. fhttp.started_receiving_get = false;
  997. fhttp.just_started_get = false;
  998. fhttp.state = IDLE;
  999. fhttp.save_bytes = false;
  1000. fhttp.save_received_data = false;
  1001. if (fhttp.is_bytes_request)
  1002. {
  1003. // Search for the binary marker `[GET/END]` in the file buffer
  1004. const char marker[] = "[GET/END]";
  1005. const size_t marker_len = sizeof(marker) - 1; // Exclude null terminator
  1006. for (size_t i = 0; i <= file_buffer_len - marker_len; i++)
  1007. {
  1008. // Check if the marker is found
  1009. if (memcmp(&file_buffer[i], marker, marker_len) == 0)
  1010. {
  1011. // Remove the marker by shifting the remaining data left
  1012. size_t remaining_len = file_buffer_len - (i + marker_len);
  1013. memmove(&file_buffer[i], &file_buffer[i + marker_len], remaining_len);
  1014. file_buffer_len -= marker_len;
  1015. break;
  1016. }
  1017. }
  1018. // If there is data left in the buffer, append it to the file
  1019. if (file_buffer_len > 0)
  1020. {
  1021. if (!flipper_http_append_to_file(file_buffer, file_buffer_len, false, fhttp.file_path))
  1022. {
  1023. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1024. }
  1025. file_buffer_len = 0;
  1026. }
  1027. }
  1028. fhttp.is_bytes_request = false;
  1029. return;
  1030. }
  1031. // Append the new line to the existing data
  1032. if (fhttp.save_received_data &&
  1033. !flipper_http_append_to_file(
  1034. line, strlen(line), !fhttp.just_started_get, fhttp.file_path))
  1035. {
  1036. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1037. fhttp.started_receiving_get = false;
  1038. fhttp.just_started_get = false;
  1039. fhttp.state = IDLE;
  1040. return;
  1041. }
  1042. if (!fhttp.just_started_get)
  1043. {
  1044. fhttp.just_started_get = true;
  1045. }
  1046. return;
  1047. }
  1048. // Check if we've started receiving data from a POST request
  1049. else if (fhttp.started_receiving_post)
  1050. {
  1051. // Restart the timeout timer each time new data is received
  1052. furi_timer_restart(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1053. if (strstr(line, "[POST/END]") != NULL)
  1054. {
  1055. FURI_LOG_I(HTTP_TAG, "POST request completed.");
  1056. // Stop the timer since we've completed the POST request
  1057. furi_timer_stop(fhttp.get_timeout_timer);
  1058. fhttp.started_receiving_post = false;
  1059. fhttp.just_started_post = false;
  1060. fhttp.state = IDLE;
  1061. fhttp.save_bytes = false;
  1062. fhttp.save_received_data = false;
  1063. if (fhttp.is_bytes_request)
  1064. {
  1065. // Search for the binary marker `[POST/END]` in the file buffer
  1066. const char marker[] = "[POST/END]";
  1067. const size_t marker_len = sizeof(marker) - 1; // Exclude null terminator
  1068. for (size_t i = 0; i <= file_buffer_len - marker_len; i++)
  1069. {
  1070. // Check if the marker is found
  1071. if (memcmp(&file_buffer[i], marker, marker_len) == 0)
  1072. {
  1073. // Remove the marker by shifting the remaining data left
  1074. size_t remaining_len = file_buffer_len - (i + marker_len);
  1075. memmove(&file_buffer[i], &file_buffer[i + marker_len], remaining_len);
  1076. file_buffer_len -= marker_len;
  1077. break;
  1078. }
  1079. }
  1080. // If there is data left in the buffer, append it to the file
  1081. if (file_buffer_len > 0)
  1082. {
  1083. if (!flipper_http_append_to_file(file_buffer, file_buffer_len, false, fhttp.file_path))
  1084. {
  1085. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1086. }
  1087. file_buffer_len = 0;
  1088. }
  1089. }
  1090. fhttp.is_bytes_request = false;
  1091. return;
  1092. }
  1093. // Append the new line to the existing data
  1094. if (fhttp.save_received_data &&
  1095. !flipper_http_append_to_file(
  1096. line, strlen(line), !fhttp.just_started_post, fhttp.file_path))
  1097. {
  1098. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1099. fhttp.started_receiving_post = false;
  1100. fhttp.just_started_post = false;
  1101. fhttp.state = IDLE;
  1102. return;
  1103. }
  1104. if (!fhttp.just_started_post)
  1105. {
  1106. fhttp.just_started_post = true;
  1107. }
  1108. return;
  1109. }
  1110. // Check if we've started receiving data from a PUT request
  1111. else if (fhttp.started_receiving_put)
  1112. {
  1113. // Restart the timeout timer each time new data is received
  1114. furi_timer_restart(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1115. if (strstr(line, "[PUT/END]") != NULL)
  1116. {
  1117. FURI_LOG_I(HTTP_TAG, "PUT request completed.");
  1118. // Stop the timer since we've completed the PUT request
  1119. furi_timer_stop(fhttp.get_timeout_timer);
  1120. fhttp.started_receiving_put = false;
  1121. fhttp.just_started_put = false;
  1122. fhttp.state = IDLE;
  1123. fhttp.save_bytes = false;
  1124. fhttp.is_bytes_request = false;
  1125. fhttp.save_received_data = false;
  1126. return;
  1127. }
  1128. // Append the new line to the existing data
  1129. if (fhttp.save_received_data &&
  1130. !flipper_http_append_to_file(
  1131. line, strlen(line), !fhttp.just_started_put, fhttp.file_path))
  1132. {
  1133. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1134. fhttp.started_receiving_put = false;
  1135. fhttp.just_started_put = false;
  1136. fhttp.state = IDLE;
  1137. return;
  1138. }
  1139. if (!fhttp.just_started_put)
  1140. {
  1141. fhttp.just_started_put = true;
  1142. }
  1143. return;
  1144. }
  1145. // Check if we've started receiving data from a DELETE request
  1146. else if (fhttp.started_receiving_delete)
  1147. {
  1148. // Restart the timeout timer each time new data is received
  1149. furi_timer_restart(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1150. if (strstr(line, "[DELETE/END]") != NULL)
  1151. {
  1152. FURI_LOG_I(HTTP_TAG, "DELETE request completed.");
  1153. // Stop the timer since we've completed the DELETE request
  1154. furi_timer_stop(fhttp.get_timeout_timer);
  1155. fhttp.started_receiving_delete = false;
  1156. fhttp.just_started_delete = false;
  1157. fhttp.state = IDLE;
  1158. fhttp.save_bytes = false;
  1159. fhttp.is_bytes_request = false;
  1160. fhttp.save_received_data = false;
  1161. return;
  1162. }
  1163. // Append the new line to the existing data
  1164. if (fhttp.save_received_data &&
  1165. !flipper_http_append_to_file(
  1166. line, strlen(line), !fhttp.just_started_delete, fhttp.file_path))
  1167. {
  1168. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1169. fhttp.started_receiving_delete = false;
  1170. fhttp.just_started_delete = false;
  1171. fhttp.state = IDLE;
  1172. return;
  1173. }
  1174. if (!fhttp.just_started_delete)
  1175. {
  1176. fhttp.just_started_delete = true;
  1177. }
  1178. return;
  1179. }
  1180. // Handle different types of responses
  1181. if (strstr(line, "[SUCCESS]") != NULL || strstr(line, "[CONNECTED]") != NULL)
  1182. {
  1183. FURI_LOG_I(HTTP_TAG, "Operation succeeded.");
  1184. }
  1185. else if (strstr(line, "[INFO]") != NULL)
  1186. {
  1187. FURI_LOG_I(HTTP_TAG, "Received info: %s", line);
  1188. if (fhttp.state == INACTIVE && strstr(line, "[INFO] Already connected to Wifi.") != NULL)
  1189. {
  1190. fhttp.state = IDLE;
  1191. }
  1192. }
  1193. else if (strstr(line, "[GET/SUCCESS]") != NULL)
  1194. {
  1195. FURI_LOG_I(HTTP_TAG, "GET request succeeded.");
  1196. fhttp.started_receiving_get = true;
  1197. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1198. fhttp.state = RECEIVING;
  1199. // for GET request, save data only if it's a bytes request
  1200. fhttp.save_bytes = fhttp.is_bytes_request;
  1201. file_buffer_len = 0;
  1202. return;
  1203. }
  1204. else if (strstr(line, "[POST/SUCCESS]") != NULL)
  1205. {
  1206. FURI_LOG_I(HTTP_TAG, "POST request succeeded.");
  1207. fhttp.started_receiving_post = true;
  1208. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1209. fhttp.state = RECEIVING;
  1210. // for POST request, save data only if it's a bytes request
  1211. fhttp.save_bytes = fhttp.is_bytes_request;
  1212. file_buffer_len = 0;
  1213. return;
  1214. }
  1215. else if (strstr(line, "[PUT/SUCCESS]") != NULL)
  1216. {
  1217. FURI_LOG_I(HTTP_TAG, "PUT request succeeded.");
  1218. fhttp.started_receiving_put = true;
  1219. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1220. fhttp.state = RECEIVING;
  1221. return;
  1222. }
  1223. else if (strstr(line, "[DELETE/SUCCESS]") != NULL)
  1224. {
  1225. FURI_LOG_I(HTTP_TAG, "DELETE request succeeded.");
  1226. fhttp.started_receiving_delete = true;
  1227. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1228. fhttp.state = RECEIVING;
  1229. return;
  1230. }
  1231. else if (strstr(line, "[DISCONNECTED]") != NULL)
  1232. {
  1233. FURI_LOG_I(HTTP_TAG, "WiFi disconnected successfully.");
  1234. }
  1235. else if (strstr(line, "[ERROR]") != NULL)
  1236. {
  1237. FURI_LOG_E(HTTP_TAG, "Received error: %s", line);
  1238. fhttp.state = ISSUE;
  1239. return;
  1240. }
  1241. else if (strstr(line, "[PONG]") != NULL)
  1242. {
  1243. FURI_LOG_I(HTTP_TAG, "Received PONG response: Wifi Dev Board is still alive.");
  1244. // send command to connect to WiFi
  1245. if (fhttp.state == INACTIVE)
  1246. {
  1247. fhttp.state = IDLE;
  1248. return;
  1249. }
  1250. }
  1251. if (fhttp.state == INACTIVE && strstr(line, "[PONG]") != NULL)
  1252. {
  1253. fhttp.state = IDLE;
  1254. }
  1255. else if (fhttp.state == INACTIVE && strstr(line, "[PONG]") == NULL)
  1256. {
  1257. fhttp.state = INACTIVE;
  1258. }
  1259. else
  1260. {
  1261. fhttp.state = IDLE;
  1262. }
  1263. }
  1264. // Function to trim leading and trailing spaces and newlines from a constant string
  1265. char *trim(const char *str)
  1266. {
  1267. const char *end;
  1268. char *trimmed_str;
  1269. size_t len;
  1270. // Trim leading space
  1271. while (isspace((unsigned char)*str))
  1272. str++;
  1273. // All spaces?
  1274. if (*str == 0)
  1275. return strdup(""); // Return an empty string if all spaces
  1276. // Trim trailing space
  1277. end = str + strlen(str) - 1;
  1278. while (end > str && isspace((unsigned char)*end))
  1279. end--;
  1280. // Set length for the trimmed string
  1281. len = end - str + 1;
  1282. // Allocate space for the trimmed string and null terminator
  1283. trimmed_str = (char *)malloc(len + 1);
  1284. if (trimmed_str == NULL)
  1285. {
  1286. return NULL; // Handle memory allocation failure
  1287. }
  1288. // Copy the trimmed part of the string into trimmed_str
  1289. strncpy(trimmed_str, str, len);
  1290. trimmed_str[len] = '\0'; // Null terminate the string
  1291. return trimmed_str;
  1292. }
  1293. /**
  1294. * @brief Process requests and parse JSON data asynchronously
  1295. * @param http_request The function to send the request
  1296. * @param parse_json The function to parse the JSON
  1297. * @return true if successful, false otherwise
  1298. */
  1299. bool flipper_http_process_response_async(bool (*http_request)(void), bool (*parse_json)(void))
  1300. {
  1301. if (http_request()) // start the async request
  1302. {
  1303. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1304. fhttp.state = RECEIVING;
  1305. }
  1306. else
  1307. {
  1308. FURI_LOG_E(HTTP_TAG, "Failed to send request");
  1309. return false;
  1310. }
  1311. while (fhttp.state == RECEIVING && furi_timer_is_running(fhttp.get_timeout_timer) > 0)
  1312. {
  1313. // Wait for the request to be received
  1314. furi_delay_ms(100);
  1315. }
  1316. furi_timer_stop(fhttp.get_timeout_timer);
  1317. if (!parse_json()) // parse the JSON before switching to the view (synchonous)
  1318. {
  1319. FURI_LOG_E(HTTP_TAG, "Failed to parse the JSON...");
  1320. return false;
  1321. }
  1322. return true;
  1323. }