flipper_http.c 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597
  1. #include <flipper_http/flipper_http.h> // change this to where flipper_http.h is located
  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 > 512)
  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[513]; // 512 + 1 for safety
  411. strncpy(send_buffer, data, 512);
  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. const char *command = "[WIFI/SCAN]";
  577. if (!flipper_http_send_data(command))
  578. {
  579. FURI_LOG_E("FlipperHTTP", "Failed to send WiFi scan command.");
  580. return false;
  581. }
  582. // The response will be handled asynchronously via the callback
  583. return true;
  584. }
  585. // Function to save WiFi settings (returns true if successful)
  586. /**
  587. * @brief Send a command to save WiFi settings.
  588. * @return true if the request was successful, false otherwise.
  589. * @note The received data will be handled asynchronously via the callback.
  590. */
  591. bool flipper_http_save_wifi(const char *ssid, const char *password)
  592. {
  593. if (!ssid || !password)
  594. {
  595. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_save_wifi.");
  596. return false;
  597. }
  598. char buffer[256];
  599. int ret = snprintf(
  600. buffer, sizeof(buffer), "[WIFI/SAVE]{\"ssid\":\"%s\",\"password\":\"%s\"}", ssid, password);
  601. if (ret < 0 || ret >= (int)sizeof(buffer))
  602. {
  603. FURI_LOG_E("FlipperHTTP", "Failed to format WiFi save command.");
  604. return false;
  605. }
  606. if (!flipper_http_send_data(buffer))
  607. {
  608. FURI_LOG_E("FlipperHTTP", "Failed to send WiFi save command.");
  609. return false;
  610. }
  611. // The response will be handled asynchronously via the callback
  612. return true;
  613. }
  614. // Function to get IP address of WiFi Devboard
  615. /**
  616. * @brief Send a command to get the IP address of the WiFi Devboard
  617. * @return true if the request was successful, false otherwise.
  618. * @note The received data will be handled asynchronously via the callback.
  619. */
  620. bool flipper_http_ip_address()
  621. {
  622. const char *command = "[IP/ADDRESS]";
  623. if (!flipper_http_send_data(command))
  624. {
  625. FURI_LOG_E("FlipperHTTP", "Failed to send IP address command.");
  626. return false;
  627. }
  628. // The response will be handled asynchronously via the callback
  629. return true;
  630. }
  631. // Function to get IP address of the connected WiFi network
  632. /**
  633. * @brief Send a command to get the IP address of the connected WiFi network.
  634. * @return true if the request was successful, false otherwise.
  635. * @note The received data will be handled asynchronously via the callback.
  636. */
  637. bool flipper_http_ip_wifi()
  638. {
  639. const char *command = "[WIFI/IP]";
  640. if (!flipper_http_send_data(command))
  641. {
  642. FURI_LOG_E("FlipperHTTP", "Failed to send WiFi IP command.");
  643. return false;
  644. }
  645. // The response will be handled asynchronously via the callback
  646. return true;
  647. }
  648. // Function to disconnect from WiFi (returns true if successful)
  649. /**
  650. * @brief Send a command to disconnect from WiFi.
  651. * @return true if the request was successful, false otherwise.
  652. * @note The received data will be handled asynchronously via the callback.
  653. */
  654. bool flipper_http_disconnect_wifi()
  655. {
  656. const char *command = "[WIFI/DISCONNECT]";
  657. if (!flipper_http_send_data(command))
  658. {
  659. FURI_LOG_E("FlipperHTTP", "Failed to send WiFi disconnect command.");
  660. return false;
  661. }
  662. // The response will be handled asynchronously via the callback
  663. return true;
  664. }
  665. // Function to connect to WiFi (returns true if successful)
  666. /**
  667. * @brief Send a command to connect to WiFi.
  668. * @return true if the request was successful, false otherwise.
  669. * @note The received data will be handled asynchronously via the callback.
  670. */
  671. bool flipper_http_connect_wifi()
  672. {
  673. const char *command = "[WIFI/CONNECT]";
  674. if (!flipper_http_send_data(command))
  675. {
  676. FURI_LOG_E("FlipperHTTP", "Failed to send WiFi connect command.");
  677. return false;
  678. }
  679. // The response will be handled asynchronously via the callback
  680. return true;
  681. }
  682. // Function to send a GET request
  683. /**
  684. * @brief Send a GET request to the specified URL.
  685. * @return true if the request was successful, false otherwise.
  686. * @param url The URL to send the GET request to.
  687. * @note The received data will be handled asynchronously via the callback.
  688. */
  689. bool flipper_http_get_request(const char *url)
  690. {
  691. if (!url)
  692. {
  693. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_get_request.");
  694. return false;
  695. }
  696. // Prepare GET request command
  697. char command[512];
  698. int ret = snprintf(command, sizeof(command), "[GET]%s", url);
  699. if (ret < 0 || ret >= (int)sizeof(command))
  700. {
  701. FURI_LOG_E("FlipperHTTP", "Failed to format GET request command.");
  702. return false;
  703. }
  704. // Send GET request via UART
  705. if (!flipper_http_send_data(command))
  706. {
  707. FURI_LOG_E("FlipperHTTP", "Failed to send GET request command.");
  708. return false;
  709. }
  710. // The response will be handled asynchronously via the callback
  711. return true;
  712. }
  713. // Function to send a GET request with headers
  714. /**
  715. * @brief Send a GET request to the specified URL.
  716. * @return true if the request was successful, false otherwise.
  717. * @param url The URL to send the GET request to.
  718. * @param headers The headers to send with the GET request.
  719. * @note The received data will be handled asynchronously via the callback.
  720. */
  721. bool flipper_http_get_request_with_headers(const char *url, const char *headers)
  722. {
  723. if (!url || !headers)
  724. {
  725. FURI_LOG_E(
  726. "FlipperHTTP", "Invalid arguments provided to flipper_http_get_request_with_headers.");
  727. return false;
  728. }
  729. // Prepare GET request command with headers
  730. char command[512];
  731. int ret = snprintf(
  732. command, sizeof(command), "[GET/HTTP]{\"url\":\"%s\",\"headers\":%s}", url, headers);
  733. if (ret < 0 || ret >= (int)sizeof(command))
  734. {
  735. FURI_LOG_E("FlipperHTTP", "Failed to format GET request command with headers.");
  736. return false;
  737. }
  738. // Send GET request via UART
  739. if (!flipper_http_send_data(command))
  740. {
  741. FURI_LOG_E("FlipperHTTP", "Failed to send GET request command with headers.");
  742. return false;
  743. }
  744. // The response will be handled asynchronously via the callback
  745. return true;
  746. }
  747. // Function to send a GET request with headers and return bytes
  748. /**
  749. * @brief Send a GET request to the specified URL.
  750. * @return true if the request was successful, false otherwise.
  751. * @param url The URL to send the GET request to.
  752. * @param headers The headers to send with the GET request.
  753. * @note The received data will be handled asynchronously via the callback.
  754. */
  755. bool flipper_http_get_request_bytes(const char *url, const char *headers)
  756. {
  757. if (!url || !headers)
  758. {
  759. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_get_request_bytes.");
  760. return false;
  761. }
  762. // Prepare GET request command with headers
  763. char command[512];
  764. int ret = snprintf(
  765. command, sizeof(command), "[GET/BYTES]{\"url\":\"%s\",\"headers\":%s}", url, headers);
  766. if (ret < 0 || ret >= (int)sizeof(command))
  767. {
  768. FURI_LOG_E("FlipperHTTP", "Failed to format GET request command with headers.");
  769. return false;
  770. }
  771. // Send GET request via UART
  772. if (!flipper_http_send_data(command))
  773. {
  774. FURI_LOG_E("FlipperHTTP", "Failed to send GET request command with headers.");
  775. return false;
  776. }
  777. // The response will be handled asynchronously via the callback
  778. return true;
  779. }
  780. // Function to send a POST request with headers
  781. /**
  782. * @brief Send a POST request to the specified URL.
  783. * @return true if the request was successful, false otherwise.
  784. * @param url The URL to send the POST request to.
  785. * @param headers The headers to send with the POST request.
  786. * @param data The data to send with the POST request.
  787. * @note The received data will be handled asynchronously via the callback.
  788. */
  789. bool flipper_http_post_request_with_headers(
  790. const char *url,
  791. const char *headers,
  792. const char *payload)
  793. {
  794. if (!url || !headers || !payload)
  795. {
  796. FURI_LOG_E(
  797. "FlipperHTTP",
  798. "Invalid arguments provided to flipper_http_post_request_with_headers.");
  799. return false;
  800. }
  801. // Prepare POST request command with headers and data
  802. char command[512];
  803. int ret = snprintf(
  804. command,
  805. sizeof(command),
  806. "[POST/HTTP]{\"url\":\"%s\",\"headers\":%s,\"payload\":%s}",
  807. url,
  808. headers,
  809. payload);
  810. if (ret < 0 || ret >= (int)sizeof(command))
  811. {
  812. FURI_LOG_E("FlipperHTTP", "Failed to format POST request command with headers and data.");
  813. return false;
  814. }
  815. // Send POST request via UART
  816. if (!flipper_http_send_data(command))
  817. {
  818. FURI_LOG_E("FlipperHTTP", "Failed to send POST request command with headers and data.");
  819. return false;
  820. }
  821. // The response will be handled asynchronously via the callback
  822. return true;
  823. }
  824. // Function to send a POST request with headers and return bytes
  825. /**
  826. * @brief Send a POST request to the specified URL.
  827. * @return true if the request was successful, false otherwise.
  828. * @param url The URL to send the POST request to.
  829. * @param headers The headers to send with the POST request.
  830. * @param payload The data to send with the POST request.
  831. * @note The received data will be handled asynchronously via the callback.
  832. */
  833. bool flipper_http_post_request_bytes(const char *url, const char *headers, const char *payload)
  834. {
  835. if (!url || !headers || !payload)
  836. {
  837. FURI_LOG_E(
  838. "FlipperHTTP", "Invalid arguments provided to flipper_http_post_request_bytes.");
  839. return false;
  840. }
  841. // Prepare POST request command with headers and data
  842. char command[512];
  843. int ret = snprintf(
  844. command,
  845. sizeof(command),
  846. "[POST/BYTES]{\"url\":\"%s\",\"headers\":%s,\"payload\":%s}",
  847. url,
  848. headers,
  849. payload);
  850. if (ret < 0 || ret >= (int)sizeof(command))
  851. {
  852. FURI_LOG_E("FlipperHTTP", "Failed to format POST request command with headers and data.");
  853. return false;
  854. }
  855. // Send POST request via UART
  856. if (!flipper_http_send_data(command))
  857. {
  858. FURI_LOG_E("FlipperHTTP", "Failed to send POST request command with headers and data.");
  859. return false;
  860. }
  861. // The response will be handled asynchronously via the callback
  862. return true;
  863. }
  864. // Function to send a PUT request with headers
  865. /**
  866. * @brief Send a PUT request to the specified URL.
  867. * @return true if the request was successful, false otherwise.
  868. * @param url The URL to send the PUT request to.
  869. * @param headers The headers to send with the PUT request.
  870. * @param data The data to send with the PUT request.
  871. * @note The received data will be handled asynchronously via the callback.
  872. */
  873. bool flipper_http_put_request_with_headers(
  874. const char *url,
  875. const char *headers,
  876. const char *payload)
  877. {
  878. if (!url || !headers || !payload)
  879. {
  880. FURI_LOG_E(
  881. "FlipperHTTP", "Invalid arguments provided to flipper_http_put_request_with_headers.");
  882. return false;
  883. }
  884. // Prepare PUT request command with headers and data
  885. char command[256];
  886. int ret = snprintf(
  887. command,
  888. sizeof(command),
  889. "[PUT/HTTP]{\"url\":\"%s\",\"headers\":%s,\"payload\":%s}",
  890. url,
  891. headers,
  892. payload);
  893. if (ret < 0 || ret >= (int)sizeof(command))
  894. {
  895. FURI_LOG_E("FlipperHTTP", "Failed to format PUT request command with headers and data.");
  896. return false;
  897. }
  898. // Send PUT request via UART
  899. if (!flipper_http_send_data(command))
  900. {
  901. FURI_LOG_E("FlipperHTTP", "Failed to send PUT request command with headers and data.");
  902. return false;
  903. }
  904. // The response will be handled asynchronously via the callback
  905. return true;
  906. }
  907. // Function to send a DELETE request with headers
  908. /**
  909. * @brief Send a DELETE request to the specified URL.
  910. * @return true if the request was successful, false otherwise.
  911. * @param url The URL to send the DELETE request to.
  912. * @param headers The headers to send with the DELETE request.
  913. * @param data The data to send with the DELETE request.
  914. * @note The received data will be handled asynchronously via the callback.
  915. */
  916. bool flipper_http_delete_request_with_headers(
  917. const char *url,
  918. const char *headers,
  919. const char *payload)
  920. {
  921. if (!url || !headers || !payload)
  922. {
  923. FURI_LOG_E(
  924. "FlipperHTTP",
  925. "Invalid arguments provided to flipper_http_delete_request_with_headers.");
  926. return false;
  927. }
  928. // Prepare DELETE request command with headers and data
  929. char command[256];
  930. int ret = snprintf(
  931. command,
  932. sizeof(command),
  933. "[DELETE/HTTP]{\"url\":\"%s\",\"headers\":%s,\"payload\":%s}",
  934. url,
  935. headers,
  936. payload);
  937. if (ret < 0 || ret >= (int)sizeof(command))
  938. {
  939. FURI_LOG_E(
  940. "FlipperHTTP", "Failed to format DELETE request command with headers and data.");
  941. return false;
  942. }
  943. // Send DELETE request via UART
  944. if (!flipper_http_send_data(command))
  945. {
  946. FURI_LOG_E("FlipperHTTP", "Failed to send DELETE request command with headers and data.");
  947. return false;
  948. }
  949. // The response will be handled asynchronously via the callback
  950. return true;
  951. }
  952. // Function to handle received data asynchronously
  953. /**
  954. * @brief Callback function to handle received data asynchronously.
  955. * @return void
  956. * @param line The received line.
  957. * @param context The context passed to the callback.
  958. * @note The received data will be handled asynchronously via the callback and handles the state of the UART.
  959. */
  960. void flipper_http_rx_callback(const char *line, void *context)
  961. {
  962. if (!line || !context)
  963. {
  964. FURI_LOG_E(HTTP_TAG, "Invalid arguments provided to flipper_http_rx_callback.");
  965. return;
  966. }
  967. // Trim the received line to check if it's empty
  968. char *trimmed_line = trim(line);
  969. if (trimmed_line != NULL && trimmed_line[0] != '\0')
  970. {
  971. // if the line is not [GET/END] or [POST/END] or [PUT/END] or [DELETE/END]
  972. if (strstr(trimmed_line, "[GET/END]") == NULL &&
  973. strstr(trimmed_line, "[POST/END]") == NULL &&
  974. strstr(trimmed_line, "[PUT/END]") == NULL &&
  975. strstr(trimmed_line, "[DELETE/END]") == NULL)
  976. {
  977. strncpy(fhttp.last_response, trimmed_line, RX_BUF_SIZE);
  978. }
  979. }
  980. free(trimmed_line); // Free the allocated memory for trimmed_line
  981. if (fhttp.state != INACTIVE && fhttp.state != ISSUE)
  982. {
  983. fhttp.state = RECEIVING;
  984. }
  985. // Uncomment below line to log the data received over UART
  986. // FURI_LOG_I(HTTP_TAG, "Received UART line: %s", line);
  987. // Check if we've started receiving data from a GET request
  988. if (fhttp.started_receiving_get)
  989. {
  990. // Restart the timeout timer each time new data is received
  991. furi_timer_restart(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  992. if (strstr(line, "[GET/END]") != NULL)
  993. {
  994. FURI_LOG_I(HTTP_TAG, "GET request completed.");
  995. // Stop the timer since we've completed the GET request
  996. furi_timer_stop(fhttp.get_timeout_timer);
  997. fhttp.started_receiving_get = false;
  998. fhttp.just_started_get = false;
  999. fhttp.state = IDLE;
  1000. fhttp.save_bytes = false;
  1001. fhttp.save_received_data = false;
  1002. if (fhttp.is_bytes_request)
  1003. {
  1004. // Search for the binary marker `[GET/END]` in the file buffer
  1005. const char marker[] = "[GET/END]";
  1006. const size_t marker_len = sizeof(marker) - 1; // Exclude null terminator
  1007. for (size_t i = 0; i <= file_buffer_len - marker_len; i++)
  1008. {
  1009. // Check if the marker is found
  1010. if (memcmp(&file_buffer[i], marker, marker_len) == 0)
  1011. {
  1012. // Remove the marker by shifting the remaining data left
  1013. size_t remaining_len = file_buffer_len - (i + marker_len);
  1014. memmove(&file_buffer[i], &file_buffer[i + marker_len], remaining_len);
  1015. file_buffer_len -= marker_len;
  1016. break;
  1017. }
  1018. }
  1019. // If there is data left in the buffer, append it to the file
  1020. if (file_buffer_len > 0)
  1021. {
  1022. if (!flipper_http_append_to_file(file_buffer, file_buffer_len, false, fhttp.file_path))
  1023. {
  1024. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1025. }
  1026. file_buffer_len = 0;
  1027. }
  1028. }
  1029. fhttp.is_bytes_request = false;
  1030. return;
  1031. }
  1032. // Append the new line to the existing data
  1033. if (fhttp.save_received_data &&
  1034. !flipper_http_append_to_file(
  1035. line, strlen(line), !fhttp.just_started_get, fhttp.file_path))
  1036. {
  1037. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1038. fhttp.started_receiving_get = false;
  1039. fhttp.just_started_get = false;
  1040. fhttp.state = IDLE;
  1041. return;
  1042. }
  1043. if (!fhttp.just_started_get)
  1044. {
  1045. fhttp.just_started_get = true;
  1046. }
  1047. return;
  1048. }
  1049. // Check if we've started receiving data from a POST request
  1050. else if (fhttp.started_receiving_post)
  1051. {
  1052. // Restart the timeout timer each time new data is received
  1053. furi_timer_restart(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1054. if (strstr(line, "[POST/END]") != NULL)
  1055. {
  1056. FURI_LOG_I(HTTP_TAG, "POST request completed.");
  1057. // Stop the timer since we've completed the POST request
  1058. furi_timer_stop(fhttp.get_timeout_timer);
  1059. fhttp.started_receiving_post = false;
  1060. fhttp.just_started_post = false;
  1061. fhttp.state = IDLE;
  1062. fhttp.save_bytes = false;
  1063. fhttp.save_received_data = false;
  1064. if (fhttp.is_bytes_request)
  1065. {
  1066. // Search for the binary marker `[POST/END]` in the file buffer
  1067. const char marker[] = "[POST/END]";
  1068. const size_t marker_len = sizeof(marker) - 1; // Exclude null terminator
  1069. for (size_t i = 0; i <= file_buffer_len - marker_len; i++)
  1070. {
  1071. // Check if the marker is found
  1072. if (memcmp(&file_buffer[i], marker, marker_len) == 0)
  1073. {
  1074. // Remove the marker by shifting the remaining data left
  1075. size_t remaining_len = file_buffer_len - (i + marker_len);
  1076. memmove(&file_buffer[i], &file_buffer[i + marker_len], remaining_len);
  1077. file_buffer_len -= marker_len;
  1078. break;
  1079. }
  1080. }
  1081. // If there is data left in the buffer, append it to the file
  1082. if (file_buffer_len > 0)
  1083. {
  1084. if (!flipper_http_append_to_file(file_buffer, file_buffer_len, false, fhttp.file_path))
  1085. {
  1086. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1087. }
  1088. file_buffer_len = 0;
  1089. }
  1090. }
  1091. fhttp.is_bytes_request = false;
  1092. return;
  1093. }
  1094. // Append the new line to the existing data
  1095. if (fhttp.save_received_data &&
  1096. !flipper_http_append_to_file(
  1097. line, strlen(line), !fhttp.just_started_post, fhttp.file_path))
  1098. {
  1099. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1100. fhttp.started_receiving_post = false;
  1101. fhttp.just_started_post = false;
  1102. fhttp.state = IDLE;
  1103. return;
  1104. }
  1105. if (!fhttp.just_started_post)
  1106. {
  1107. fhttp.just_started_post = true;
  1108. }
  1109. return;
  1110. }
  1111. // Check if we've started receiving data from a PUT request
  1112. else if (fhttp.started_receiving_put)
  1113. {
  1114. // Restart the timeout timer each time new data is received
  1115. furi_timer_restart(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1116. if (strstr(line, "[PUT/END]") != NULL)
  1117. {
  1118. FURI_LOG_I(HTTP_TAG, "PUT request completed.");
  1119. // Stop the timer since we've completed the PUT request
  1120. furi_timer_stop(fhttp.get_timeout_timer);
  1121. fhttp.started_receiving_put = false;
  1122. fhttp.just_started_put = false;
  1123. fhttp.state = IDLE;
  1124. fhttp.save_bytes = false;
  1125. fhttp.is_bytes_request = false;
  1126. fhttp.save_received_data = false;
  1127. return;
  1128. }
  1129. // Append the new line to the existing data
  1130. if (fhttp.save_received_data &&
  1131. !flipper_http_append_to_file(
  1132. line, strlen(line), !fhttp.just_started_put, fhttp.file_path))
  1133. {
  1134. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1135. fhttp.started_receiving_put = false;
  1136. fhttp.just_started_put = false;
  1137. fhttp.state = IDLE;
  1138. return;
  1139. }
  1140. if (!fhttp.just_started_put)
  1141. {
  1142. fhttp.just_started_put = true;
  1143. }
  1144. return;
  1145. }
  1146. // Check if we've started receiving data from a DELETE request
  1147. else if (fhttp.started_receiving_delete)
  1148. {
  1149. // Restart the timeout timer each time new data is received
  1150. furi_timer_restart(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1151. if (strstr(line, "[DELETE/END]") != NULL)
  1152. {
  1153. FURI_LOG_I(HTTP_TAG, "DELETE request completed.");
  1154. // Stop the timer since we've completed the DELETE request
  1155. furi_timer_stop(fhttp.get_timeout_timer);
  1156. fhttp.started_receiving_delete = false;
  1157. fhttp.just_started_delete = false;
  1158. fhttp.state = IDLE;
  1159. fhttp.save_bytes = false;
  1160. fhttp.is_bytes_request = false;
  1161. fhttp.save_received_data = false;
  1162. return;
  1163. }
  1164. // Append the new line to the existing data
  1165. if (fhttp.save_received_data &&
  1166. !flipper_http_append_to_file(
  1167. line, strlen(line), !fhttp.just_started_delete, fhttp.file_path))
  1168. {
  1169. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1170. fhttp.started_receiving_delete = false;
  1171. fhttp.just_started_delete = false;
  1172. fhttp.state = IDLE;
  1173. return;
  1174. }
  1175. if (!fhttp.just_started_delete)
  1176. {
  1177. fhttp.just_started_delete = true;
  1178. }
  1179. return;
  1180. }
  1181. // Handle different types of responses
  1182. if (strstr(line, "[SUCCESS]") != NULL || strstr(line, "[CONNECTED]") != NULL)
  1183. {
  1184. FURI_LOG_I(HTTP_TAG, "Operation succeeded.");
  1185. }
  1186. else if (strstr(line, "[INFO]") != NULL)
  1187. {
  1188. FURI_LOG_I(HTTP_TAG, "Received info: %s", line);
  1189. if (fhttp.state == INACTIVE && strstr(line, "[INFO] Already connected to Wifi.") != NULL)
  1190. {
  1191. fhttp.state = IDLE;
  1192. }
  1193. }
  1194. else if (strstr(line, "[GET/SUCCESS]") != NULL)
  1195. {
  1196. FURI_LOG_I(HTTP_TAG, "GET request succeeded.");
  1197. fhttp.started_receiving_get = true;
  1198. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1199. fhttp.state = RECEIVING;
  1200. // for GET request, save data only if it's a bytes request
  1201. fhttp.save_bytes = fhttp.is_bytes_request;
  1202. fhttp.just_started_bytes = true;
  1203. file_buffer_len = 0;
  1204. return;
  1205. }
  1206. else if (strstr(line, "[POST/SUCCESS]") != NULL)
  1207. {
  1208. FURI_LOG_I(HTTP_TAG, "POST request succeeded.");
  1209. fhttp.started_receiving_post = true;
  1210. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1211. fhttp.state = RECEIVING;
  1212. // for POST request, save data only if it's a bytes request
  1213. fhttp.save_bytes = fhttp.is_bytes_request;
  1214. fhttp.just_started_bytes = true;
  1215. file_buffer_len = 0;
  1216. return;
  1217. }
  1218. else if (strstr(line, "[PUT/SUCCESS]") != NULL)
  1219. {
  1220. FURI_LOG_I(HTTP_TAG, "PUT request succeeded.");
  1221. fhttp.started_receiving_put = true;
  1222. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1223. fhttp.state = RECEIVING;
  1224. return;
  1225. }
  1226. else if (strstr(line, "[DELETE/SUCCESS]") != NULL)
  1227. {
  1228. FURI_LOG_I(HTTP_TAG, "DELETE request succeeded.");
  1229. fhttp.started_receiving_delete = true;
  1230. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1231. fhttp.state = RECEIVING;
  1232. return;
  1233. }
  1234. else if (strstr(line, "[DISCONNECTED]") != NULL)
  1235. {
  1236. FURI_LOG_I(HTTP_TAG, "WiFi disconnected successfully.");
  1237. }
  1238. else if (strstr(line, "[ERROR]") != NULL)
  1239. {
  1240. FURI_LOG_E(HTTP_TAG, "Received error: %s", line);
  1241. fhttp.state = ISSUE;
  1242. return;
  1243. }
  1244. else if (strstr(line, "[PONG]") != NULL)
  1245. {
  1246. FURI_LOG_I(HTTP_TAG, "Received PONG response: Wifi Dev Board is still alive.");
  1247. // send command to connect to WiFi
  1248. if (fhttp.state == INACTIVE)
  1249. {
  1250. fhttp.state = IDLE;
  1251. return;
  1252. }
  1253. }
  1254. if (fhttp.state == INACTIVE && strstr(line, "[PONG]") != NULL)
  1255. {
  1256. fhttp.state = IDLE;
  1257. }
  1258. else if (fhttp.state == INACTIVE && strstr(line, "[PONG]") == NULL)
  1259. {
  1260. fhttp.state = INACTIVE;
  1261. }
  1262. else
  1263. {
  1264. fhttp.state = IDLE;
  1265. }
  1266. }
  1267. // Function to trim leading and trailing spaces and newlines from a constant string
  1268. char *trim(const char *str)
  1269. {
  1270. const char *end;
  1271. char *trimmed_str;
  1272. size_t len;
  1273. // Trim leading space
  1274. while (isspace((unsigned char)*str))
  1275. str++;
  1276. // All spaces?
  1277. if (*str == 0)
  1278. return strdup(""); // Return an empty string if all spaces
  1279. // Trim trailing space
  1280. end = str + strlen(str) - 1;
  1281. while (end > str && isspace((unsigned char)*end))
  1282. end--;
  1283. // Set length for the trimmed string
  1284. len = end - str + 1;
  1285. // Allocate space for the trimmed string and null terminator
  1286. trimmed_str = (char *)malloc(len + 1);
  1287. if (trimmed_str == NULL)
  1288. {
  1289. return NULL; // Handle memory allocation failure
  1290. }
  1291. // Copy the trimmed part of the string into trimmed_str
  1292. strncpy(trimmed_str, str, len);
  1293. trimmed_str[len] = '\0'; // Null terminate the string
  1294. return trimmed_str;
  1295. }
  1296. /**
  1297. * @brief Process requests and parse JSON data asynchronously
  1298. * @param http_request The function to send the request
  1299. * @param parse_json The function to parse the JSON
  1300. * @return true if successful, false otherwise
  1301. */
  1302. bool flipper_http_process_response_async(bool (*http_request)(void), bool (*parse_json)(void))
  1303. {
  1304. if (http_request()) // start the async request
  1305. {
  1306. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1307. fhttp.state = RECEIVING;
  1308. }
  1309. else
  1310. {
  1311. FURI_LOG_E(HTTP_TAG, "Failed to send request");
  1312. return false;
  1313. }
  1314. while (fhttp.state == RECEIVING && furi_timer_is_running(fhttp.get_timeout_timer) > 0)
  1315. {
  1316. // Wait for the request to be received
  1317. furi_delay_ms(100);
  1318. }
  1319. furi_timer_stop(fhttp.get_timeout_timer);
  1320. if (!parse_json()) // parse the JSON before switching to the view (synchonous)
  1321. {
  1322. FURI_LOG_E(HTTP_TAG, "Failed to parse the JSON...");
  1323. return false;
  1324. }
  1325. return true;
  1326. }
  1327. bool flipper_http_process_response_async_2(bool (*http_request)(void), int (*parse_json)(void))
  1328. {
  1329. if (http_request()) // start the async request
  1330. {
  1331. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1332. fhttp.state = RECEIVING;
  1333. }
  1334. else
  1335. {
  1336. FURI_LOG_E(HTTP_TAG, "Failed to send request");
  1337. return false;
  1338. }
  1339. while (fhttp.state == RECEIVING && furi_timer_is_running(fhttp.get_timeout_timer) > 0)
  1340. {
  1341. // Wait for the request to be received
  1342. furi_delay_ms(100);
  1343. }
  1344. furi_timer_stop(fhttp.get_timeout_timer);
  1345. if (parse_json() < 1) // parse the JSON before switching to the view (synchonous)
  1346. {
  1347. FURI_LOG_E(HTTP_TAG, "Failed to parse the JSON...");
  1348. return false;
  1349. }
  1350. return true;
  1351. }
  1352. /**
  1353. * @brief Perform a task while displaying a loading screen
  1354. * @param http_request The function to send the request
  1355. * @param parse_response The function to parse the response
  1356. * @param success_view_id The view ID to switch to on success
  1357. * @param failure_view_id The view ID to switch to on failure
  1358. * @param view_dispatcher The view dispatcher to use
  1359. * @return
  1360. */
  1361. void flipper_http_loading_task(bool (*http_request)(void),
  1362. bool (*parse_response)(void),
  1363. uint32_t success_view_id,
  1364. uint32_t failure_view_id,
  1365. ViewDispatcher **view_dispatcher)
  1366. {
  1367. if (fhttp.state == INACTIVE)
  1368. {
  1369. view_dispatcher_switch_to_view(*view_dispatcher, failure_view_id);
  1370. return;
  1371. }
  1372. Loading *loading;
  1373. int32_t loading_view_id = 987654321; // Random ID
  1374. loading = loading_alloc();
  1375. if (!loading)
  1376. {
  1377. FURI_LOG_E(HTTP_TAG, "Failed to allocate loading");
  1378. view_dispatcher_switch_to_view(*view_dispatcher, failure_view_id);
  1379. return;
  1380. }
  1381. view_dispatcher_add_view(*view_dispatcher, loading_view_id, loading_get_view(loading));
  1382. // Switch to the loading view
  1383. view_dispatcher_switch_to_view(*view_dispatcher, loading_view_id);
  1384. // Make the request
  1385. if (!flipper_http_process_response_async(http_request, parse_response))
  1386. {
  1387. FURI_LOG_E(HTTP_TAG, "Failed to make request");
  1388. view_dispatcher_switch_to_view(*view_dispatcher, failure_view_id);
  1389. view_dispatcher_remove_view(*view_dispatcher, loading_view_id);
  1390. loading_free(loading);
  1391. return;
  1392. }
  1393. // Switch to the success view
  1394. view_dispatcher_switch_to_view(*view_dispatcher, success_view_id);
  1395. view_dispatcher_remove_view(*view_dispatcher, loading_view_id);
  1396. // loading_free(loading);
  1397. }
  1398. /**
  1399. * @brief Perform a task while displaying a loading screen
  1400. * @param http_request The function to send the request
  1401. * @param parse_response The function to parse the response
  1402. * @param success_view_id The view ID to switch to on success
  1403. * @param failure_view_id The view ID to switch to on failure
  1404. * @param view_dispatcher The view dispatcher to use
  1405. * @return
  1406. */
  1407. void flipper_http_loading_task_2(bool (*http_request)(void),
  1408. int (*parse_response)(void),
  1409. uint32_t success_view_id,
  1410. uint32_t failure_view_id,
  1411. ViewDispatcher **view_dispatcher)
  1412. {
  1413. Loading *loading;
  1414. int32_t loading_view_id = 987654321; // Random ID
  1415. loading = loading_alloc();
  1416. if (!loading)
  1417. {
  1418. FURI_LOG_E(HTTP_TAG, "Failed to allocate loading");
  1419. view_dispatcher_switch_to_view(*view_dispatcher, failure_view_id);
  1420. return;
  1421. }
  1422. view_dispatcher_add_view(*view_dispatcher, loading_view_id, loading_get_view(loading));
  1423. // Switch to the loading view
  1424. view_dispatcher_switch_to_view(*view_dispatcher, loading_view_id);
  1425. // Make the request
  1426. if (!flipper_http_process_response_async_2(http_request, parse_response))
  1427. {
  1428. FURI_LOG_E(HTTP_TAG, "Failed to make request");
  1429. view_dispatcher_switch_to_view(*view_dispatcher, failure_view_id);
  1430. view_dispatcher_remove_view(*view_dispatcher, loading_view_id);
  1431. loading_free(loading);
  1432. return;
  1433. }
  1434. // Switch to the success view
  1435. view_dispatcher_switch_to_view(*view_dispatcher, success_view_id);
  1436. view_dispatcher_remove_view(*view_dispatcher, loading_view_id);
  1437. loading_free(loading);
  1438. }