flipper_http.c 50 KB

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