flipper_http.c 50 KB

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