flipper_http.h 50 KB

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