flipper_http.c 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471
  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. return false;
  390. }
  391. // Create a buffer with data + '\n'
  392. size_t send_length = data_length + 1; // +1 for '\n'
  393. if (send_length > 256)
  394. { // Ensure buffer size is sufficient
  395. FURI_LOG_E("FlipperHTTP", "Data too long to send over FHTTP.");
  396. return false;
  397. }
  398. char send_buffer[257]; // 256 + 1 for safety
  399. strncpy(send_buffer, data, 256);
  400. send_buffer[data_length] = '\n'; // Append newline
  401. send_buffer[data_length + 1] = '\0'; // Null-terminate
  402. if (fhttp.state == INACTIVE && ((strstr(send_buffer, "[PING]") == NULL) &&
  403. (strstr(send_buffer, "[WIFI/CONNECT]") == NULL)))
  404. {
  405. FURI_LOG_E("FlipperHTTP", "Cannot send data while INACTIVE.");
  406. fhttp.last_response = "Cannot send data while INACTIVE.";
  407. return false;
  408. }
  409. fhttp.state = SENDING;
  410. furi_hal_serial_tx(fhttp.serial_handle, (const uint8_t *)send_buffer, send_length);
  411. // Uncomment below line to log the data sent over UART
  412. // FURI_LOG_I("FlipperHTTP", "Sent data over UART: %s", send_buffer);
  413. // fhttp.state = IDLE;
  414. return true;
  415. }
  416. // Function to send a PING request
  417. /**
  418. * @brief Send a PING request to check if the Wifi Dev Board is connected.
  419. * @return true if the request was successful, false otherwise.
  420. * @note The received data will be handled asynchronously via the callback.
  421. * @note This is best used to check if the Wifi Dev Board is connected.
  422. * @note The state will remain INACTIVE until a PONG is received.
  423. */
  424. bool flipper_http_ping()
  425. {
  426. const char *command = "[PING]";
  427. if (!flipper_http_send_data(command))
  428. {
  429. FURI_LOG_E("FlipperHTTP", "Failed to send PING command.");
  430. return false;
  431. }
  432. // set state as INACTIVE to be made IDLE if PONG is received
  433. fhttp.state = INACTIVE;
  434. // The response will be handled asynchronously via the callback
  435. return true;
  436. }
  437. // Function to list available commands
  438. /**
  439. * @brief Send a command to list available commands.
  440. * @return true if the request was successful, false otherwise.
  441. * @note The received data will be handled asynchronously via the callback.
  442. */
  443. bool flipper_http_list_commands()
  444. {
  445. const char *command = "[LIST]";
  446. if (!flipper_http_send_data(command))
  447. {
  448. FURI_LOG_E("FlipperHTTP", "Failed to send LIST command.");
  449. return false;
  450. }
  451. // The response will be handled asynchronously via the callback
  452. return true;
  453. }
  454. // Function to turn on the LED
  455. /**
  456. * @brief Allow the LED to display while processing.
  457. * @return true if the request was successful, false otherwise.
  458. * @note The received data will be handled asynchronously via the callback.
  459. */
  460. bool flipper_http_led_on()
  461. {
  462. const char *command = "[LED/ON]";
  463. if (!flipper_http_send_data(command))
  464. {
  465. FURI_LOG_E("FlipperHTTP", "Failed to send LED ON command.");
  466. return false;
  467. }
  468. // The response will be handled asynchronously via the callback
  469. return true;
  470. }
  471. // Function to turn off the LED
  472. /**
  473. * @brief Disable the LED from displaying while processing.
  474. * @return true if the request was successful, false otherwise.
  475. * @note The received data will be handled asynchronously via the callback.
  476. */
  477. bool flipper_http_led_off()
  478. {
  479. const char *command = "[LED/OFF]";
  480. if (!flipper_http_send_data(command))
  481. {
  482. FURI_LOG_E("FlipperHTTP", "Failed to send LED OFF command.");
  483. return false;
  484. }
  485. // The response will be handled asynchronously via the callback
  486. return true;
  487. }
  488. // Function to parse JSON data
  489. /**
  490. * @brief Parse JSON data.
  491. * @return true if the JSON data was parsed successfully, false otherwise.
  492. * @param key The key to parse from the JSON data.
  493. * @param json_data The JSON data to parse.
  494. * @note The received data will be handled asynchronously via the callback.
  495. */
  496. bool flipper_http_parse_json(const char *key, const char *json_data)
  497. {
  498. if (!key || !json_data)
  499. {
  500. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_parse_json.");
  501. return false;
  502. }
  503. char buffer[256];
  504. int ret =
  505. snprintf(buffer, sizeof(buffer), "[PARSE]{\"key\":\"%s\",\"json\":%s}", key, json_data);
  506. if (ret < 0 || ret >= (int)sizeof(buffer))
  507. {
  508. FURI_LOG_E("FlipperHTTP", "Failed to format JSON parse command.");
  509. return false;
  510. }
  511. if (!flipper_http_send_data(buffer))
  512. {
  513. FURI_LOG_E("FlipperHTTP", "Failed to send JSON parse command.");
  514. return false;
  515. }
  516. // The response will be handled asynchronously via the callback
  517. return true;
  518. }
  519. // Function to parse JSON array data
  520. /**
  521. * @brief Parse JSON array data.
  522. * @return true if the JSON array data was parsed successfully, false otherwise.
  523. * @param key The key to parse from the JSON array data.
  524. * @param index The index to parse from the JSON array data.
  525. * @param json_data The JSON array data to parse.
  526. * @note The received data will be handled asynchronously via the callback.
  527. */
  528. bool flipper_http_parse_json_array(const char *key, int index, const char *json_data)
  529. {
  530. if (!key || !json_data)
  531. {
  532. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_parse_json_array.");
  533. return false;
  534. }
  535. char buffer[256];
  536. int ret = snprintf(
  537. buffer,
  538. sizeof(buffer),
  539. "[PARSE/ARRAY]{\"key\":\"%s\",\"index\":%d,\"json\":%s}",
  540. key,
  541. index,
  542. json_data);
  543. if (ret < 0 || ret >= (int)sizeof(buffer))
  544. {
  545. FURI_LOG_E("FlipperHTTP", "Failed to format JSON parse array command.");
  546. return false;
  547. }
  548. if (!flipper_http_send_data(buffer))
  549. {
  550. FURI_LOG_E("FlipperHTTP", "Failed to send JSON parse array command.");
  551. return false;
  552. }
  553. // The response will be handled asynchronously via the callback
  554. return true;
  555. }
  556. // Function to scan for WiFi networks
  557. /**
  558. * @brief Send a command to scan for WiFi networks.
  559. * @return true if the request was successful, false otherwise.
  560. * @note The received data will be handled asynchronously via the callback.
  561. */
  562. bool flipper_http_scan_wifi()
  563. {
  564. if (!flipper_http_send_data("[WIFI/SCAN]"))
  565. {
  566. FURI_LOG_E("FlipperHTTP", "Failed to send WiFi scan command.");
  567. return false;
  568. }
  569. // custom for FlipWiFi app
  570. fhttp.just_started_get = true;
  571. snprintf(
  572. fhttp.file_path,
  573. sizeof(fhttp.file_path),
  574. STORAGE_EXT_PATH_PREFIX "/apps_data/flip_wifi/scan.txt");
  575. fhttp.save_received_data = true;
  576. // The response will be handled asynchronously via the callback
  577. return true;
  578. }
  579. // Function to save WiFi settings (returns true if successful)
  580. /**
  581. * @brief Send a command to save WiFi settings.
  582. * @return true if the request was successful, false otherwise.
  583. * @note The received data will be handled asynchronously via the callback.
  584. */
  585. bool flipper_http_save_wifi(const char *ssid, const char *password)
  586. {
  587. if (!ssid || !password)
  588. {
  589. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_save_wifi.");
  590. return false;
  591. }
  592. char buffer[256];
  593. int ret = snprintf(
  594. buffer, sizeof(buffer), "[WIFI/SAVE]{\"ssid\":\"%s\",\"password\":\"%s\"}", ssid, password);
  595. if (ret < 0 || ret >= (int)sizeof(buffer))
  596. {
  597. FURI_LOG_E("FlipperHTTP", "Failed to format WiFi save command.");
  598. return false;
  599. }
  600. if (!flipper_http_send_data(buffer))
  601. {
  602. FURI_LOG_E("FlipperHTTP", "Failed to send WiFi save command.");
  603. return false;
  604. }
  605. // The response will be handled asynchronously via the callback
  606. return true;
  607. }
  608. // Function to get IP address of WiFi Devboard
  609. /**
  610. * @brief Send a command to get the IP address of the WiFi Devboard
  611. * @return true if the request was successful, false otherwise.
  612. * @note The received data will be handled asynchronously via the callback.
  613. */
  614. bool flipper_http_ip_address()
  615. {
  616. if (!flipper_http_send_data("[IP/ADDRESS]"))
  617. {
  618. FURI_LOG_E("FlipperHTTP", "Failed to send IP address command.");
  619. return false;
  620. }
  621. // The response will be handled asynchronously via the callback
  622. return true;
  623. }
  624. // Function to get IP address of the connected WiFi network
  625. /**
  626. * @brief Send a command to get the IP address of the connected WiFi network.
  627. * @return true if the request was successful, false otherwise.
  628. * @note The received data will be handled asynchronously via the callback.
  629. */
  630. bool flipper_http_ip_wifi()
  631. {
  632. const char *command = "[WIFI/IP]";
  633. if (!flipper_http_send_data(command))
  634. {
  635. FURI_LOG_E("FlipperHTTP", "Failed to send WiFi IP command.");
  636. return false;
  637. }
  638. // The response will be handled asynchronously via the callback
  639. return true;
  640. }
  641. // Function to disconnect from WiFi (returns true if successful)
  642. /**
  643. * @brief Send a command to disconnect from WiFi.
  644. * @return true if the request was successful, false otherwise.
  645. * @note The received data will be handled asynchronously via the callback.
  646. */
  647. bool flipper_http_disconnect_wifi()
  648. {
  649. if (!flipper_http_send_data("[WIFI/DISCONNECT]"))
  650. {
  651. FURI_LOG_E("FlipperHTTP", "Failed to send WiFi disconnect command.");
  652. return false;
  653. }
  654. // The response will be handled asynchronously via the callback
  655. return true;
  656. }
  657. // Function to connect to WiFi (returns true if successful)
  658. /**
  659. * @brief Send a command to connect to WiFi.
  660. * @return true if the request was successful, false otherwise.
  661. * @note The received data will be handled asynchronously via the callback.
  662. */
  663. bool flipper_http_connect_wifi()
  664. {
  665. if (!flipper_http_send_data("[WIFI/CONNECT]"))
  666. {
  667. FURI_LOG_E("FlipperHTTP", "Failed to send WiFi connect command.");
  668. return false;
  669. }
  670. // The response will be handled asynchronously via the callback
  671. return true;
  672. }
  673. // Function to send a GET request
  674. /**
  675. * @brief Send a GET request to the specified URL.
  676. * @return true if the request was successful, false otherwise.
  677. * @param url The URL to send the GET request to.
  678. * @note The received data will be handled asynchronously via the callback.
  679. */
  680. bool flipper_http_get_request(const char *url)
  681. {
  682. if (!url)
  683. {
  684. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_get_request.");
  685. return false;
  686. }
  687. // Prepare GET request command
  688. char command[256];
  689. int ret = snprintf(command, sizeof(command), "[GET]%s", url);
  690. if (ret < 0 || ret >= (int)sizeof(command))
  691. {
  692. FURI_LOG_E("FlipperHTTP", "Failed to format GET request command.");
  693. return false;
  694. }
  695. // Send GET request via UART
  696. if (!flipper_http_send_data(command))
  697. {
  698. FURI_LOG_E("FlipperHTTP", "Failed to send GET request command.");
  699. return false;
  700. }
  701. // The response will be handled asynchronously via the callback
  702. return true;
  703. }
  704. // Function to send a GET request with headers
  705. /**
  706. * @brief Send a GET request to the specified URL.
  707. * @return true if the request was successful, false otherwise.
  708. * @param url The URL to send the GET request to.
  709. * @param headers The headers to send with the GET request.
  710. * @note The received data will be handled asynchronously via the callback.
  711. */
  712. bool flipper_http_get_request_with_headers(const char *url, const char *headers)
  713. {
  714. if (!url || !headers)
  715. {
  716. FURI_LOG_E(
  717. "FlipperHTTP", "Invalid arguments provided to flipper_http_get_request_with_headers.");
  718. return false;
  719. }
  720. // Prepare GET request command with headers
  721. char command[256];
  722. int ret = snprintf(
  723. command, sizeof(command), "[GET/HTTP]{\"url\":\"%s\",\"headers\":%s}", url, headers);
  724. if (ret < 0 || ret >= (int)sizeof(command))
  725. {
  726. FURI_LOG_E("FlipperHTTP", "Failed to format GET request command with headers.");
  727. return false;
  728. }
  729. // Send GET request via UART
  730. if (!flipper_http_send_data(command))
  731. {
  732. FURI_LOG_E("FlipperHTTP", "Failed to send GET request command with headers.");
  733. return false;
  734. }
  735. // The response will be handled asynchronously via the callback
  736. return true;
  737. }
  738. // Function to send a GET request with headers and return bytes
  739. /**
  740. * @brief Send a GET request to the specified URL.
  741. * @return true if the request was successful, false otherwise.
  742. * @param url The URL to send the GET request to.
  743. * @param headers The headers to send with the GET request.
  744. * @note The received data will be handled asynchronously via the callback.
  745. */
  746. bool flipper_http_get_request_bytes(const char *url, const char *headers)
  747. {
  748. if (!url || !headers)
  749. {
  750. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_get_request_bytes.");
  751. return false;
  752. }
  753. // Prepare GET request command with headers
  754. char command[256];
  755. int ret = snprintf(
  756. command, sizeof(command), "[GET/BYTES]{\"url\":\"%s\",\"headers\":%s}", url, headers);
  757. if (ret < 0 || ret >= (int)sizeof(command))
  758. {
  759. FURI_LOG_E("FlipperHTTP", "Failed to format GET request command with headers.");
  760. return false;
  761. }
  762. // Send GET request via UART
  763. if (!flipper_http_send_data(command))
  764. {
  765. FURI_LOG_E("FlipperHTTP", "Failed to send GET request command with headers.");
  766. return false;
  767. }
  768. // The response will be handled asynchronously via the callback
  769. return true;
  770. }
  771. // Function to send a POST request with headers
  772. /**
  773. * @brief Send a POST request to the specified URL.
  774. * @return true if the request was successful, false otherwise.
  775. * @param url The URL to send the POST request to.
  776. * @param headers The headers to send with the POST request.
  777. * @param data The data to send with the POST request.
  778. * @note The received data will be handled asynchronously via the callback.
  779. */
  780. bool flipper_http_post_request_with_headers(
  781. const char *url,
  782. const char *headers,
  783. const char *payload)
  784. {
  785. if (!url || !headers || !payload)
  786. {
  787. FURI_LOG_E(
  788. "FlipperHTTP",
  789. "Invalid arguments provided to flipper_http_post_request_with_headers.");
  790. return false;
  791. }
  792. // Prepare POST request command with headers and data
  793. char command[256];
  794. int ret = snprintf(
  795. command,
  796. sizeof(command),
  797. "[POST/HTTP]{\"url\":\"%s\",\"headers\":%s,\"payload\":%s}",
  798. url,
  799. headers,
  800. payload);
  801. if (ret < 0 || ret >= (int)sizeof(command))
  802. {
  803. FURI_LOG_E("FlipperHTTP", "Failed to format POST request command with headers and data.");
  804. return false;
  805. }
  806. // Send POST request via UART
  807. if (!flipper_http_send_data(command))
  808. {
  809. FURI_LOG_E("FlipperHTTP", "Failed to send POST request command with headers and data.");
  810. return false;
  811. }
  812. // The response will be handled asynchronously via the callback
  813. return true;
  814. }
  815. // Function to send a POST request with headers and return bytes
  816. /**
  817. * @brief Send a POST request to the specified URL.
  818. * @return true if the request was successful, false otherwise.
  819. * @param url The URL to send the POST request to.
  820. * @param headers The headers to send with the POST request.
  821. * @param payload The data to send with the POST request.
  822. * @note The received data will be handled asynchronously via the callback.
  823. */
  824. bool flipper_http_post_request_bytes(const char *url, const char *headers, const char *payload)
  825. {
  826. if (!url || !headers || !payload)
  827. {
  828. FURI_LOG_E(
  829. "FlipperHTTP", "Invalid arguments provided to flipper_http_post_request_bytes.");
  830. return false;
  831. }
  832. // Prepare POST request command with headers and data
  833. char command[256];
  834. int ret = snprintf(
  835. command,
  836. sizeof(command),
  837. "[POST/BYTES]{\"url\":\"%s\",\"headers\":%s,\"payload\":%s}",
  838. url,
  839. headers,
  840. payload);
  841. if (ret < 0 || ret >= (int)sizeof(command))
  842. {
  843. FURI_LOG_E("FlipperHTTP", "Failed to format POST request command with headers and data.");
  844. return false;
  845. }
  846. // Send POST request via UART
  847. if (!flipper_http_send_data(command))
  848. {
  849. FURI_LOG_E("FlipperHTTP", "Failed to send POST request command with headers and data.");
  850. return false;
  851. }
  852. // The response will be handled asynchronously via the callback
  853. return true;
  854. }
  855. // Function to send a PUT request with headers
  856. /**
  857. * @brief Send a PUT request to the specified URL.
  858. * @return true if the request was successful, false otherwise.
  859. * @param url The URL to send the PUT request to.
  860. * @param headers The headers to send with the PUT request.
  861. * @param data The data to send with the PUT request.
  862. * @note The received data will be handled asynchronously via the callback.
  863. */
  864. bool flipper_http_put_request_with_headers(
  865. const char *url,
  866. const char *headers,
  867. const char *payload)
  868. {
  869. if (!url || !headers || !payload)
  870. {
  871. FURI_LOG_E(
  872. "FlipperHTTP", "Invalid arguments provided to flipper_http_put_request_with_headers.");
  873. return false;
  874. }
  875. // Prepare PUT request command with headers and data
  876. char command[256];
  877. int ret = snprintf(
  878. command,
  879. sizeof(command),
  880. "[PUT/HTTP]{\"url\":\"%s\",\"headers\":%s,\"payload\":%s}",
  881. url,
  882. headers,
  883. payload);
  884. if (ret < 0 || ret >= (int)sizeof(command))
  885. {
  886. FURI_LOG_E("FlipperHTTP", "Failed to format PUT request command with headers and data.");
  887. return false;
  888. }
  889. // Send PUT request via UART
  890. if (!flipper_http_send_data(command))
  891. {
  892. FURI_LOG_E("FlipperHTTP", "Failed to send PUT request command with headers and data.");
  893. return false;
  894. }
  895. // The response will be handled asynchronously via the callback
  896. return true;
  897. }
  898. // Function to send a DELETE request with headers
  899. /**
  900. * @brief Send a DELETE request to the specified URL.
  901. * @return true if the request was successful, false otherwise.
  902. * @param url The URL to send the DELETE request to.
  903. * @param headers The headers to send with the DELETE request.
  904. * @param data The data to send with the DELETE request.
  905. * @note The received data will be handled asynchronously via the callback.
  906. */
  907. bool flipper_http_delete_request_with_headers(
  908. const char *url,
  909. const char *headers,
  910. const char *payload)
  911. {
  912. if (!url || !headers || !payload)
  913. {
  914. FURI_LOG_E(
  915. "FlipperHTTP",
  916. "Invalid arguments provided to flipper_http_delete_request_with_headers.");
  917. return false;
  918. }
  919. // Prepare DELETE request command with headers and data
  920. char command[256];
  921. int ret = snprintf(
  922. command,
  923. sizeof(command),
  924. "[DELETE/HTTP]{\"url\":\"%s\",\"headers\":%s,\"payload\":%s}",
  925. url,
  926. headers,
  927. payload);
  928. if (ret < 0 || ret >= (int)sizeof(command))
  929. {
  930. FURI_LOG_E(
  931. "FlipperHTTP", "Failed to format DELETE request command with headers and data.");
  932. return false;
  933. }
  934. // Send DELETE request via UART
  935. if (!flipper_http_send_data(command))
  936. {
  937. FURI_LOG_E("FlipperHTTP", "Failed to send DELETE request command with headers and data.");
  938. return false;
  939. }
  940. // The response will be handled asynchronously via the callback
  941. return true;
  942. }
  943. // Function to handle received data asynchronously
  944. /**
  945. * @brief Callback function to handle received data asynchronously.
  946. * @return void
  947. * @param line The received line.
  948. * @param context The context passed to the callback.
  949. * @note The received data will be handled asynchronously via the callback and handles the state of the UART.
  950. */
  951. void flipper_http_rx_callback(const char *line, void *context)
  952. {
  953. if (!line || !context)
  954. {
  955. FURI_LOG_E(HTTP_TAG, "Invalid arguments provided to flipper_http_rx_callback.");
  956. return;
  957. }
  958. // Trim the received line to check if it's empty
  959. char *trimmed_line = trim(line);
  960. if (trimmed_line != NULL && trimmed_line[0] != '\0')
  961. {
  962. // if the line is not [GET/END] or [POST/END] or [PUT/END] or [DELETE/END]
  963. if (strstr(trimmed_line, "[GET/END]") == NULL &&
  964. strstr(trimmed_line, "[POST/END]") == NULL &&
  965. strstr(trimmed_line, "[PUT/END]") == NULL &&
  966. strstr(trimmed_line, "[DELETE/END]") == NULL)
  967. {
  968. strncpy(fhttp.last_response, trimmed_line, RX_BUF_SIZE);
  969. }
  970. }
  971. free(trimmed_line); // Free the allocated memory for trimmed_line
  972. if (fhttp.state != INACTIVE && fhttp.state != ISSUE)
  973. {
  974. fhttp.state = RECEIVING;
  975. }
  976. // Uncomment below line to log the data received over UART
  977. // FURI_LOG_I(HTTP_TAG, "Received UART line: %s", line);
  978. // custom function to FlipWiFi
  979. if (fhttp.save_received_data)
  980. {
  981. if (!flipper_http_append_to_file(line, strlen(line), !fhttp.just_started_get, fhttp.file_path))
  982. {
  983. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  984. fhttp.just_started_get = false;
  985. fhttp.state = ISSUE;
  986. return;
  987. }
  988. }
  989. // Check if we've started receiving data from a GET request
  990. if (fhttp.started_receiving_get)
  991. {
  992. // Restart the timeout timer each time new data is received
  993. furi_timer_restart(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  994. if (strstr(line, "[GET/END]") != NULL)
  995. {
  996. FURI_LOG_I(HTTP_TAG, "GET request completed.");
  997. // Stop the timer since we've completed the GET request
  998. furi_timer_stop(fhttp.get_timeout_timer);
  999. fhttp.started_receiving_get = false;
  1000. fhttp.just_started_get = false;
  1001. fhttp.state = IDLE;
  1002. fhttp.save_bytes = false;
  1003. fhttp.save_received_data = false;
  1004. if (fhttp.is_bytes_request)
  1005. {
  1006. // Search for the binary marker `[GET/END]` in the file buffer
  1007. const char marker[] = "[GET/END]";
  1008. const size_t marker_len = sizeof(marker) - 1; // Exclude null terminator
  1009. for (size_t i = 0; i <= file_buffer_len - marker_len; i++)
  1010. {
  1011. // Check if the marker is found
  1012. if (memcmp(&file_buffer[i], marker, marker_len) == 0)
  1013. {
  1014. // Remove the marker by shifting the remaining data left
  1015. size_t remaining_len = file_buffer_len - (i + marker_len);
  1016. memmove(&file_buffer[i], &file_buffer[i + marker_len], remaining_len);
  1017. file_buffer_len -= marker_len;
  1018. break;
  1019. }
  1020. }
  1021. // If there is data left in the buffer, append it to the file
  1022. if (file_buffer_len > 0)
  1023. {
  1024. if (!flipper_http_append_to_file(file_buffer, file_buffer_len, false, fhttp.file_path))
  1025. {
  1026. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1027. }
  1028. file_buffer_len = 0;
  1029. }
  1030. }
  1031. fhttp.is_bytes_request = false;
  1032. return;
  1033. }
  1034. // Append the new line to the existing data
  1035. if (fhttp.save_received_data &&
  1036. !flipper_http_append_to_file(
  1037. line, strlen(line), !fhttp.just_started_get, fhttp.file_path))
  1038. {
  1039. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1040. fhttp.started_receiving_get = false;
  1041. fhttp.just_started_get = false;
  1042. fhttp.state = IDLE;
  1043. return;
  1044. }
  1045. if (!fhttp.just_started_get)
  1046. {
  1047. fhttp.just_started_get = true;
  1048. }
  1049. return;
  1050. }
  1051. // Check if we've started receiving data from a POST request
  1052. else if (fhttp.started_receiving_post)
  1053. {
  1054. // Restart the timeout timer each time new data is received
  1055. furi_timer_restart(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1056. if (strstr(line, "[POST/END]") != NULL)
  1057. {
  1058. FURI_LOG_I(HTTP_TAG, "POST request completed.");
  1059. // Stop the timer since we've completed the POST request
  1060. furi_timer_stop(fhttp.get_timeout_timer);
  1061. fhttp.started_receiving_post = false;
  1062. fhttp.just_started_post = false;
  1063. fhttp.state = IDLE;
  1064. fhttp.save_bytes = false;
  1065. fhttp.save_received_data = false;
  1066. if (fhttp.is_bytes_request)
  1067. {
  1068. // Search for the binary marker `[POST/END]` in the file buffer
  1069. const char marker[] = "[POST/END]";
  1070. const size_t marker_len = sizeof(marker) - 1; // Exclude null terminator
  1071. for (size_t i = 0; i <= file_buffer_len - marker_len; i++)
  1072. {
  1073. // Check if the marker is found
  1074. if (memcmp(&file_buffer[i], marker, marker_len) == 0)
  1075. {
  1076. // Remove the marker by shifting the remaining data left
  1077. size_t remaining_len = file_buffer_len - (i + marker_len);
  1078. memmove(&file_buffer[i], &file_buffer[i + marker_len], remaining_len);
  1079. file_buffer_len -= marker_len;
  1080. break;
  1081. }
  1082. }
  1083. // If there is data left in the buffer, append it to the file
  1084. if (file_buffer_len > 0)
  1085. {
  1086. if (!flipper_http_append_to_file(file_buffer, file_buffer_len, false, fhttp.file_path))
  1087. {
  1088. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1089. }
  1090. file_buffer_len = 0;
  1091. }
  1092. }
  1093. fhttp.is_bytes_request = false;
  1094. return;
  1095. }
  1096. // Append the new line to the existing data
  1097. if (fhttp.save_received_data &&
  1098. !flipper_http_append_to_file(
  1099. line, strlen(line), !fhttp.just_started_post, fhttp.file_path))
  1100. {
  1101. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1102. fhttp.started_receiving_post = false;
  1103. fhttp.just_started_post = false;
  1104. fhttp.state = IDLE;
  1105. return;
  1106. }
  1107. if (!fhttp.just_started_post)
  1108. {
  1109. fhttp.just_started_post = true;
  1110. }
  1111. return;
  1112. }
  1113. // Check if we've started receiving data from a PUT request
  1114. else if (fhttp.started_receiving_put)
  1115. {
  1116. // Restart the timeout timer each time new data is received
  1117. furi_timer_restart(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1118. if (strstr(line, "[PUT/END]") != NULL)
  1119. {
  1120. FURI_LOG_I(HTTP_TAG, "PUT request completed.");
  1121. // Stop the timer since we've completed the PUT request
  1122. furi_timer_stop(fhttp.get_timeout_timer);
  1123. fhttp.started_receiving_put = false;
  1124. fhttp.just_started_put = false;
  1125. fhttp.state = IDLE;
  1126. fhttp.save_bytes = false;
  1127. fhttp.is_bytes_request = false;
  1128. fhttp.save_received_data = false;
  1129. return;
  1130. }
  1131. // Append the new line to the existing data
  1132. if (fhttp.save_received_data &&
  1133. !flipper_http_append_to_file(
  1134. line, strlen(line), !fhttp.just_started_put, fhttp.file_path))
  1135. {
  1136. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1137. fhttp.started_receiving_put = false;
  1138. fhttp.just_started_put = false;
  1139. fhttp.state = IDLE;
  1140. return;
  1141. }
  1142. if (!fhttp.just_started_put)
  1143. {
  1144. fhttp.just_started_put = true;
  1145. }
  1146. return;
  1147. }
  1148. // Check if we've started receiving data from a DELETE request
  1149. else if (fhttp.started_receiving_delete)
  1150. {
  1151. // Restart the timeout timer each time new data is received
  1152. furi_timer_restart(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1153. if (strstr(line, "[DELETE/END]") != NULL)
  1154. {
  1155. FURI_LOG_I(HTTP_TAG, "DELETE request completed.");
  1156. // Stop the timer since we've completed the DELETE request
  1157. furi_timer_stop(fhttp.get_timeout_timer);
  1158. fhttp.started_receiving_delete = false;
  1159. fhttp.just_started_delete = false;
  1160. fhttp.state = IDLE;
  1161. fhttp.save_bytes = false;
  1162. fhttp.is_bytes_request = false;
  1163. fhttp.save_received_data = false;
  1164. return;
  1165. }
  1166. // Append the new line to the existing data
  1167. if (fhttp.save_received_data &&
  1168. !flipper_http_append_to_file(
  1169. line, strlen(line), !fhttp.just_started_delete, fhttp.file_path))
  1170. {
  1171. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1172. fhttp.started_receiving_delete = false;
  1173. fhttp.just_started_delete = false;
  1174. fhttp.state = IDLE;
  1175. return;
  1176. }
  1177. if (!fhttp.just_started_delete)
  1178. {
  1179. fhttp.just_started_delete = true;
  1180. }
  1181. return;
  1182. }
  1183. // Handle different types of responses
  1184. if (strstr(line, "[SUCCESS]") != NULL || strstr(line, "[CONNECTED]") != NULL)
  1185. {
  1186. FURI_LOG_I(HTTP_TAG, "Operation succeeded.");
  1187. }
  1188. else if (strstr(line, "[INFO]") != NULL)
  1189. {
  1190. FURI_LOG_I(HTTP_TAG, "Received info: %s", line);
  1191. if (fhttp.state == INACTIVE && strstr(line, "[INFO] Already connected to Wifi.") != NULL)
  1192. {
  1193. fhttp.state = IDLE;
  1194. }
  1195. }
  1196. else if (strstr(line, "[GET/SUCCESS]") != NULL)
  1197. {
  1198. FURI_LOG_I(HTTP_TAG, "GET request succeeded.");
  1199. fhttp.started_receiving_get = true;
  1200. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1201. fhttp.state = RECEIVING;
  1202. // for GET request, save data only if it's a bytes request
  1203. fhttp.save_bytes = fhttp.is_bytes_request;
  1204. file_buffer_len = 0;
  1205. return;
  1206. }
  1207. else if (strstr(line, "[POST/SUCCESS]") != NULL)
  1208. {
  1209. FURI_LOG_I(HTTP_TAG, "POST request succeeded.");
  1210. fhttp.started_receiving_post = true;
  1211. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1212. fhttp.state = RECEIVING;
  1213. // for POST request, save data only if it's a bytes request
  1214. fhttp.save_bytes = fhttp.is_bytes_request;
  1215. file_buffer_len = 0;
  1216. return;
  1217. }
  1218. else if (strstr(line, "[PUT/SUCCESS]") != NULL)
  1219. {
  1220. FURI_LOG_I(HTTP_TAG, "PUT request succeeded.");
  1221. fhttp.started_receiving_put = true;
  1222. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1223. fhttp.state = RECEIVING;
  1224. return;
  1225. }
  1226. else if (strstr(line, "[DELETE/SUCCESS]") != NULL)
  1227. {
  1228. FURI_LOG_I(HTTP_TAG, "DELETE request succeeded.");
  1229. fhttp.started_receiving_delete = true;
  1230. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1231. fhttp.state = RECEIVING;
  1232. return;
  1233. }
  1234. else if (strstr(line, "[DISCONNECTED]") != NULL)
  1235. {
  1236. FURI_LOG_I(HTTP_TAG, "WiFi disconnected successfully.");
  1237. }
  1238. else if (strstr(line, "[ERROR]") != NULL)
  1239. {
  1240. FURI_LOG_E(HTTP_TAG, "Received error: %s", line);
  1241. fhttp.state = ISSUE;
  1242. return;
  1243. }
  1244. else if (strstr(line, "[PONG]") != NULL)
  1245. {
  1246. FURI_LOG_I(HTTP_TAG, "Received PONG response: Wifi Dev Board is still alive.");
  1247. // send command to connect to WiFi
  1248. if (fhttp.state == INACTIVE)
  1249. {
  1250. fhttp.state = IDLE;
  1251. return;
  1252. }
  1253. }
  1254. if (fhttp.state == INACTIVE && strstr(line, "[PONG]") != NULL)
  1255. {
  1256. fhttp.state = IDLE;
  1257. }
  1258. else if (fhttp.state == INACTIVE && strstr(line, "[PONG]") == NULL)
  1259. {
  1260. fhttp.state = INACTIVE;
  1261. }
  1262. else
  1263. {
  1264. fhttp.state = IDLE;
  1265. }
  1266. }
  1267. // Function to trim leading and trailing spaces and newlines from a constant string
  1268. char *trim(const char *str)
  1269. {
  1270. const char *end;
  1271. char *trimmed_str;
  1272. size_t len;
  1273. // Trim leading space
  1274. while (isspace((unsigned char)*str))
  1275. str++;
  1276. // All spaces?
  1277. if (*str == 0)
  1278. return strdup(""); // Return an empty string if all spaces
  1279. // Trim trailing space
  1280. end = str + strlen(str) - 1;
  1281. while (end > str && isspace((unsigned char)*end))
  1282. end--;
  1283. // Set length for the trimmed string
  1284. len = end - str + 1;
  1285. // Allocate space for the trimmed string and null terminator
  1286. trimmed_str = (char *)malloc(len + 1);
  1287. if (trimmed_str == NULL)
  1288. {
  1289. return NULL; // Handle memory allocation failure
  1290. }
  1291. // Copy the trimmed part of the string into trimmed_str
  1292. strncpy(trimmed_str, str, len);
  1293. trimmed_str[len] = '\0'; // Null terminate the string
  1294. return trimmed_str;
  1295. }
  1296. /**
  1297. * @brief Process requests and parse JSON data asynchronously
  1298. * @param http_request The function to send the request
  1299. * @param parse_json The function to parse the JSON
  1300. * @return true if successful, false otherwise
  1301. */
  1302. bool flipper_http_process_response_async(bool (*http_request)(void), bool (*parse_json)(void))
  1303. {
  1304. if (http_request()) // start the async request
  1305. {
  1306. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1307. fhttp.state = RECEIVING;
  1308. }
  1309. else
  1310. {
  1311. FURI_LOG_E(HTTP_TAG, "Failed to send request");
  1312. return false;
  1313. }
  1314. while (fhttp.state == RECEIVING && furi_timer_is_running(fhttp.get_timeout_timer) > 0)
  1315. {
  1316. // Wait for the request to be received
  1317. furi_delay_ms(100);
  1318. }
  1319. furi_timer_stop(fhttp.get_timeout_timer);
  1320. if (!parse_json()) // parse the JSON before switching to the view (synchonous)
  1321. {
  1322. FURI_LOG_E(HTTP_TAG, "Failed to parse the JSON...");
  1323. return false;
  1324. }
  1325. return true;
  1326. }