flipper_http.c 49 KB

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