flipper_http.h 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290
  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 (2 * 1000) // 2 seconds
  14. #define BAUDRATE (115200) // UART baudrate
  15. #define RX_BUF_SIZE 128 // UART RX buffer size
  16. #define RX_LINE_BUFFER_SIZE 2048 // UART RX line buffer size (increase for large responses)
  17. // Forward declaration for callback
  18. typedef void (*FlipperHTTP_Callback)(const char *line, void *context);
  19. // Functions
  20. bool flipper_http_init(FlipperHTTP_Callback callback, void *context);
  21. void flipper_http_deinit();
  22. //---
  23. void flipper_http_rx_callback(const char *line, void *context);
  24. bool flipper_http_send_data(const char *data);
  25. //---
  26. bool flipper_http_connect_wifi();
  27. bool flipper_http_disconnect_wifi();
  28. bool flipper_http_ping();
  29. bool flipper_http_scan_wifi();
  30. bool flipper_http_save_wifi(const char *ssid, const char *password);
  31. //---
  32. bool flipper_http_list_commands();
  33. bool flipper_http_led_on();
  34. bool flipper_http_led_off();
  35. bool flipper_http_parse_json(const char *key, const char *json_data);
  36. bool flipper_http_parse_json_array(const char *key, int index, const char *json_data);
  37. //---
  38. bool flipper_http_get_request(const char *url);
  39. bool flipper_http_get_request_with_headers(const char *url, const char *headers);
  40. bool flipper_http_post_request_with_headers(const char *url, const char *headers, const char *payload);
  41. bool flipper_http_put_request_with_headers(const char *url, const char *headers, const char *payload);
  42. bool flipper_http_delete_request_with_headers(const char *url, const char *headers, const char *payload);
  43. //---
  44. bool flipper_http_save_received_data(size_t bytes_received, const char line_buffer[]);
  45. static char *trim(const char *str);
  46. // State variable to track the UART state
  47. typedef enum
  48. {
  49. INACTIVE, // Inactive state
  50. IDLE, // Default state
  51. RECEIVING, // Receiving data
  52. SENDING, // Sending data
  53. ISSUE, // Issue with connection
  54. } SerialState;
  55. // Event Flags for UART Worker Thread
  56. typedef enum
  57. {
  58. WorkerEvtStop = (1 << 0),
  59. WorkerEvtRxDone = (1 << 1),
  60. } WorkerEvtFlags;
  61. // FlipperHTTP Structure
  62. typedef struct
  63. {
  64. FuriStreamBuffer *flipper_http_stream; // Stream buffer for UART communication
  65. FuriHalSerialHandle *serial_handle; // Serial handle for UART communication
  66. FuriThread *rx_thread; // Worker thread for UART
  67. uint8_t rx_buf[RX_BUF_SIZE]; // Buffer for received data
  68. FuriThreadId rx_thread_id; // Worker thread ID
  69. FlipperHTTP_Callback handle_rx_line_cb; // Callback for received lines
  70. void *callback_context; // Context for the callback
  71. SerialState state; // State of the UART
  72. // variable to store the last received data from the UART
  73. char *last_response;
  74. // Timer-related members
  75. FuriTimer *get_timeout_timer; // Timer for HTTP request timeout
  76. char *received_data; // Buffer to store received data
  77. bool started_receiving_get; // Indicates if a GET request has started
  78. bool just_started_get; // Indicates if GET data reception has just started
  79. bool started_receiving_post; // Indicates if a POST request has started
  80. bool just_started_post; // Indicates if POST data reception has just started
  81. bool started_receiving_put; // Indicates if a PUT request has started
  82. bool just_started_put; // Indicates if PUT data reception has just started
  83. bool started_receiving_delete; // Indicates if a DELETE request has started
  84. bool just_started_delete; // Indicates if DELETE data reception has just started
  85. } FlipperHTTP;
  86. FlipperHTTP fhttp;
  87. // fhttp.received_data holds the received data from HTTP requests
  88. // fhttp.last_response holds the last received data from the UART, which could be [GET/END], [POST/END], [PUT/END], [DELETE/END], etc
  89. // Timer callback function
  90. /**
  91. * @brief Callback function for the GET timeout timer.
  92. * @return 0
  93. * @param context The context to pass to the callback.
  94. * @note This function will be called when the GET request times out.
  95. */
  96. void get_timeout_timer_callback(void *context)
  97. {
  98. UNUSED(context);
  99. FURI_LOG_E(HTTP_TAG, "Timeout reached: 2 seconds without receiving the end.");
  100. // Reset the state
  101. fhttp.started_receiving_get = false;
  102. fhttp.started_receiving_post = false;
  103. fhttp.started_receiving_put = false;
  104. fhttp.started_receiving_delete = false;
  105. // Free received data if any
  106. if (fhttp.received_data)
  107. {
  108. free(fhttp.received_data);
  109. fhttp.received_data = NULL;
  110. }
  111. // Update UART state
  112. fhttp.state = ISSUE;
  113. }
  114. // UART RX Handler Callback (Interrupt Context)
  115. /**
  116. * @brief A private callback function to handle received data asynchronously.
  117. * @return void
  118. * @param handle The UART handle.
  119. * @param event The event type.
  120. * @param context The context to pass to the callback.
  121. * @note This function will handle received data asynchronously via the callback.
  122. */
  123. static void _flipper_http_rx_callback(FuriHalSerialHandle *handle, FuriHalSerialRxEvent event, void *context)
  124. {
  125. UNUSED(context);
  126. if (event == FuriHalSerialRxEventData)
  127. {
  128. uint8_t data = furi_hal_serial_async_rx(handle);
  129. furi_stream_buffer_send(fhttp.flipper_http_stream, &data, 1, 0);
  130. furi_thread_flags_set(fhttp.rx_thread_id, WorkerEvtRxDone);
  131. }
  132. }
  133. // UART worker thread
  134. /**
  135. * @brief Worker thread to handle UART data asynchronously.
  136. * @return 0
  137. * @param context The context to pass to the callback.
  138. * @note This function will handle received data asynchronously via the callback.
  139. */
  140. static int32_t flipper_http_worker(void *context)
  141. {
  142. UNUSED(context);
  143. size_t rx_line_pos = 0;
  144. char *rx_line_buffer = (char *)malloc(RX_LINE_BUFFER_SIZE);
  145. if (!rx_line_buffer)
  146. {
  147. // Handle malloc failure
  148. FURI_LOG_E(HTTP_TAG, "Failed to allocate memory for rx_line_buffer");
  149. return -1;
  150. }
  151. while (1)
  152. {
  153. uint32_t events = furi_thread_flags_wait(WorkerEvtStop | WorkerEvtRxDone, FuriFlagWaitAny, FuriWaitForever);
  154. if (events & WorkerEvtStop)
  155. break;
  156. if (events & WorkerEvtRxDone)
  157. {
  158. size_t len = furi_stream_buffer_receive(fhttp.flipper_http_stream, fhttp.rx_buf, RX_BUF_SIZE, 0);
  159. for (size_t i = 0; i < len; i++)
  160. {
  161. char c = fhttp.rx_buf[i];
  162. if (c == '\n' || rx_line_pos >= RX_LINE_BUFFER_SIZE - 1)
  163. {
  164. rx_line_buffer[rx_line_pos] = '\0';
  165. // Invoke the callback with the complete line
  166. if (fhttp.handle_rx_line_cb)
  167. {
  168. fhttp.handle_rx_line_cb(rx_line_buffer, fhttp.callback_context);
  169. }
  170. // Reset the line buffer
  171. rx_line_pos = 0;
  172. }
  173. else
  174. {
  175. rx_line_buffer[rx_line_pos++] = c;
  176. }
  177. }
  178. }
  179. }
  180. // Free the allocated memory before exiting the thread
  181. free(rx_line_buffer);
  182. return 0;
  183. }
  184. // UART initialization function
  185. /**
  186. * @brief Initialize UART.
  187. * @return true if the UART was initialized successfully, false otherwise.
  188. * @param callback The callback function to handle received data (ex. flipper_http_rx_callback).
  189. * @param context The context to pass to the callback.
  190. * @note The received data will be handled asynchronously via the callback.
  191. */
  192. bool flipper_http_init(FlipperHTTP_Callback callback, void *context)
  193. {
  194. if (!context)
  195. {
  196. FURI_LOG_E(HTTP_TAG, "Invalid context provided to flipper_http_init.");
  197. return false;
  198. }
  199. if (!callback)
  200. {
  201. FURI_LOG_E(HTTP_TAG, "Invalid callback provided to flipper_http_init.");
  202. return false;
  203. }
  204. fhttp.flipper_http_stream = furi_stream_buffer_alloc(RX_BUF_SIZE, 1);
  205. if (!fhttp.flipper_http_stream)
  206. {
  207. FURI_LOG_E(HTTP_TAG, "Failed to allocate UART stream buffer.");
  208. return false;
  209. }
  210. fhttp.rx_thread = furi_thread_alloc();
  211. if (!fhttp.rx_thread)
  212. {
  213. FURI_LOG_E(HTTP_TAG, "Failed to allocate UART thread.");
  214. furi_stream_buffer_free(fhttp.flipper_http_stream);
  215. return false;
  216. }
  217. furi_thread_set_name(fhttp.rx_thread, "FlipperHTTP_RxThread");
  218. furi_thread_set_stack_size(fhttp.rx_thread, 1024);
  219. furi_thread_set_context(fhttp.rx_thread, &fhttp);
  220. furi_thread_set_callback(fhttp.rx_thread, flipper_http_worker);
  221. fhttp.handle_rx_line_cb = callback;
  222. fhttp.callback_context = context;
  223. furi_thread_start(fhttp.rx_thread);
  224. fhttp.rx_thread_id = furi_thread_get_id(fhttp.rx_thread);
  225. // handle when the UART control is busy to avoid furi_check failed
  226. if (furi_hal_serial_control_is_busy(UART_CH))
  227. {
  228. FURI_LOG_E(HTTP_TAG, "UART control is busy.");
  229. return false;
  230. }
  231. fhttp.serial_handle = furi_hal_serial_control_acquire(UART_CH);
  232. if (!fhttp.serial_handle)
  233. {
  234. FURI_LOG_E(HTTP_TAG, "Failed to acquire UART control - handle is NULL");
  235. // Cleanup resources
  236. furi_thread_free(fhttp.rx_thread);
  237. furi_stream_buffer_free(fhttp.flipper_http_stream);
  238. return false;
  239. }
  240. // Initialize UART with acquired handle
  241. furi_hal_serial_init(fhttp.serial_handle, BAUDRATE);
  242. // Enable RX direction
  243. furi_hal_serial_enable_direction(fhttp.serial_handle, FuriHalSerialDirectionRx);
  244. // Start asynchronous RX with the callback
  245. furi_hal_serial_async_rx_start(fhttp.serial_handle, _flipper_http_rx_callback, &fhttp, false);
  246. // Wait for the TX to complete to ensure UART is ready
  247. furi_hal_serial_tx_wait_complete(fhttp.serial_handle);
  248. // Allocate the timer for handling timeouts
  249. fhttp.get_timeout_timer = furi_timer_alloc(
  250. get_timeout_timer_callback, // Callback function
  251. FuriTimerTypeOnce, // One-shot timer
  252. &fhttp // Context passed to callback
  253. );
  254. if (!fhttp.get_timeout_timer)
  255. {
  256. FURI_LOG_E(HTTP_TAG, "Failed to allocate HTTP request timeout timer.");
  257. // Cleanup resources
  258. furi_hal_serial_async_rx_stop(fhttp.serial_handle);
  259. furi_hal_serial_disable_direction(fhttp.serial_handle, FuriHalSerialDirectionRx);
  260. furi_hal_serial_control_release(fhttp.serial_handle);
  261. furi_hal_serial_deinit(fhttp.serial_handle);
  262. furi_thread_flags_set(fhttp.rx_thread_id, WorkerEvtStop);
  263. furi_thread_join(fhttp.rx_thread);
  264. furi_thread_free(fhttp.rx_thread);
  265. furi_stream_buffer_free(fhttp.flipper_http_stream);
  266. return false;
  267. }
  268. // Set the timer thread priority if needed
  269. furi_timer_set_thread_priority(FuriTimerThreadPriorityElevated);
  270. // FURI_LOG_I(HTTP_TAG, "UART initialized successfully.");
  271. return true;
  272. }
  273. // Deinitialize UART
  274. /**
  275. * @brief Deinitialize UART.
  276. * @return void
  277. * @note This function will stop the asynchronous RX, release the serial handle, and free the resources.
  278. */
  279. void flipper_http_deinit()
  280. {
  281. if (fhttp.serial_handle == NULL)
  282. {
  283. FURI_LOG_E(HTTP_TAG, "UART handle is NULL. Already deinitialized?");
  284. return;
  285. }
  286. // Stop asynchronous RX
  287. furi_hal_serial_async_rx_stop(fhttp.serial_handle);
  288. // Release and deinitialize the serial handle
  289. furi_hal_serial_disable_direction(fhttp.serial_handle, FuriHalSerialDirectionRx);
  290. furi_hal_serial_control_release(fhttp.serial_handle);
  291. furi_hal_serial_deinit(fhttp.serial_handle);
  292. // Signal the worker thread to stop
  293. furi_thread_flags_set(fhttp.rx_thread_id, WorkerEvtStop);
  294. // Wait for the thread to finish
  295. furi_thread_join(fhttp.rx_thread);
  296. // Free the thread resources
  297. furi_thread_free(fhttp.rx_thread);
  298. // Free the stream buffer
  299. furi_stream_buffer_free(fhttp.flipper_http_stream);
  300. // Free the timer
  301. if (fhttp.get_timeout_timer)
  302. {
  303. furi_timer_free(fhttp.get_timeout_timer);
  304. fhttp.get_timeout_timer = NULL;
  305. }
  306. // Free received data if any
  307. if (fhttp.received_data)
  308. {
  309. free(fhttp.received_data);
  310. fhttp.received_data = NULL;
  311. }
  312. // Free the last response
  313. if (fhttp.last_response)
  314. {
  315. free(fhttp.last_response);
  316. fhttp.last_response = NULL;
  317. }
  318. // FURI_LOG_I("FlipperHTTP", "UART deinitialized successfully.");
  319. }
  320. // Function to send data over UART with newline termination
  321. /**
  322. * @brief Send data over UART with newline termination.
  323. * @return true if the data was sent successfully, false otherwise.
  324. * @param data The data to send over UART.
  325. * @note The data will be sent over UART with a newline character appended.
  326. */
  327. bool flipper_http_send_data(const char *data)
  328. {
  329. size_t data_length = strlen(data);
  330. if (data_length == 0)
  331. {
  332. FURI_LOG_E("FlipperHTTP", "Attempted to send empty data.");
  333. return false;
  334. }
  335. // Create a buffer with data + '\n'
  336. size_t send_length = data_length + 1; // +1 for '\n'
  337. if (send_length > 256)
  338. { // Ensure buffer size is sufficient
  339. FURI_LOG_E("FlipperHTTP", "Data too long to send over FHTTP.");
  340. return false;
  341. }
  342. char send_buffer[257]; // 256 + 1 for safety
  343. strncpy(send_buffer, data, 256);
  344. send_buffer[data_length] = '\n'; // Append newline
  345. send_buffer[data_length + 1] = '\0'; // Null-terminate
  346. if (fhttp.state == INACTIVE && ((strstr(send_buffer, "[PING]") == NULL) && (strstr(send_buffer, "[WIFI/CONNECT]") == NULL)))
  347. {
  348. FURI_LOG_E("FlipperHTTP", "Cannot send data while INACTIVE.");
  349. fhttp.last_response = "Cannot send data while INACTIVE.";
  350. return false;
  351. }
  352. fhttp.state = SENDING;
  353. furi_hal_serial_tx(fhttp.serial_handle, (const uint8_t *)send_buffer, send_length);
  354. // Uncomment below line to log the data sent over UART
  355. // FURI_LOG_I("FlipperHTTP", "Sent data over UART: %s", send_buffer);
  356. fhttp.state = IDLE;
  357. return true;
  358. }
  359. // Function to send a PING request
  360. /**
  361. * @brief Send a PING request to check if the Wifi Dev Board is connected.
  362. * @return true if the request was successful, false otherwise.
  363. * @note The received data will be handled asynchronously via the callback.
  364. * @note This is best used to check if the Wifi Dev Board is connected.
  365. * @note The state will remain INACTIVE until a PONG is received.
  366. */
  367. bool flipper_http_ping()
  368. {
  369. const char *command = "[PING]";
  370. if (!flipper_http_send_data(command))
  371. {
  372. FURI_LOG_E("FlipperHTTP", "Failed to send PING command.");
  373. return false;
  374. }
  375. // set state as INACTIVE to be made IDLE if PONG is received
  376. fhttp.state = INACTIVE;
  377. // The response will be handled asynchronously via the callback
  378. return true;
  379. }
  380. // Function to list available commands
  381. /**
  382. * @brief Send a command to list available commands.
  383. * @return true if the request was successful, false otherwise.
  384. * @note The received data will be handled asynchronously via the callback.
  385. */
  386. bool flipper_http_list_commands()
  387. {
  388. const char *command = "[LIST]";
  389. if (!flipper_http_send_data(command))
  390. {
  391. FURI_LOG_E("FlipperHTTP", "Failed to send LIST command.");
  392. return false;
  393. }
  394. // The response will be handled asynchronously via the callback
  395. return true;
  396. }
  397. // Function to turn on the LED
  398. /**
  399. * @brief Send a command to turn on the LED.
  400. * @return true if the request was successful, false otherwise.
  401. * @note The received data will be handled asynchronously via the callback.
  402. */
  403. bool flipper_http_led_on()
  404. {
  405. const char *command = "[LED/ON]";
  406. if (!flipper_http_send_data(command))
  407. {
  408. FURI_LOG_E("FlipperHTTP", "Failed to send LED ON command.");
  409. return false;
  410. }
  411. // The response will be handled asynchronously via the callback
  412. return true;
  413. }
  414. // Function to turn off the LED
  415. /**
  416. * @brief Send a command to turn off the LED.
  417. * @return true if the request was successful, false otherwise.
  418. * @note The received data will be handled asynchronously via the callback.
  419. */
  420. bool flipper_http_led_off()
  421. {
  422. const char *command = "[LED/OFF]";
  423. if (!flipper_http_send_data(command))
  424. {
  425. FURI_LOG_E("FlipperHTTP", "Failed to send LED OFF command.");
  426. return false;
  427. }
  428. // The response will be handled asynchronously via the callback
  429. return true;
  430. }
  431. // Function to parse JSON data
  432. /**
  433. * @brief Parse JSON data.
  434. * @return true if the JSON data was parsed successfully, false otherwise.
  435. * @param key The key to parse from the JSON data.
  436. * @param json_data The JSON data to parse.
  437. * @note The received data will be handled asynchronously via the callback.
  438. */
  439. bool flipper_http_parse_json(const char *key, const char *json_data)
  440. {
  441. if (!key || !json_data)
  442. {
  443. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_parse_json.");
  444. return false;
  445. }
  446. char buffer[256];
  447. int ret = snprintf(buffer, sizeof(buffer), "[PARSE]{\"key\":\"%s\",\"json\":%s}", key, json_data);
  448. if (ret < 0 || ret >= (int)sizeof(buffer))
  449. {
  450. FURI_LOG_E("FlipperHTTP", "Failed to format JSON parse command.");
  451. return false;
  452. }
  453. if (!flipper_http_send_data(buffer))
  454. {
  455. FURI_LOG_E("FlipperHTTP", "Failed to send JSON parse command.");
  456. return false;
  457. }
  458. // The response will be handled asynchronously via the callback
  459. return true;
  460. }
  461. // Function to parse JSON array data
  462. /**
  463. * @brief Parse JSON array data.
  464. * @return true if the JSON array data was parsed successfully, false otherwise.
  465. * @param key The key to parse from the JSON array data.
  466. * @param index The index to parse from the JSON array data.
  467. * @param json_data The JSON array data to parse.
  468. * @note The received data will be handled asynchronously via the callback.
  469. */
  470. bool flipper_http_parse_json_array(const char *key, int index, const char *json_data)
  471. {
  472. if (!key || !json_data)
  473. {
  474. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_parse_json_array.");
  475. return false;
  476. }
  477. char buffer[256];
  478. int ret = snprintf(buffer, sizeof(buffer), "[PARSE/ARRAY]{\"key\":\"%s\",\"index\":%d,\"json\":%s}", key, index, json_data);
  479. if (ret < 0 || ret >= (int)sizeof(buffer))
  480. {
  481. FURI_LOG_E("FlipperHTTP", "Failed to format JSON parse array command.");
  482. return false;
  483. }
  484. if (!flipper_http_send_data(buffer))
  485. {
  486. FURI_LOG_E("FlipperHTTP", "Failed to send JSON parse array command.");
  487. return false;
  488. }
  489. // The response will be handled asynchronously via the callback
  490. return true;
  491. }
  492. // Function to scan for WiFi networks
  493. /**
  494. * @brief Send a command to scan for WiFi networks.
  495. * @return true if the request was successful, false otherwise.
  496. * @note The received data will be handled asynchronously via the callback.
  497. */
  498. bool flipper_http_scan_wifi()
  499. {
  500. const char *command = "[WIFI/SCAN]";
  501. if (!flipper_http_send_data(command))
  502. {
  503. FURI_LOG_E("FlipperHTTP", "Failed to send WiFi scan command.");
  504. return false;
  505. }
  506. // The response will be handled asynchronously via the callback
  507. return true;
  508. }
  509. // Function to save WiFi settings (returns true if successful)
  510. /**
  511. * @brief Send a command to save WiFi settings.
  512. * @return true if the request was successful, false otherwise.
  513. * @note The received data will be handled asynchronously via the callback.
  514. */
  515. bool flipper_http_save_wifi(const char *ssid, const char *password)
  516. {
  517. if (!ssid || !password)
  518. {
  519. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_save_wifi.");
  520. return false;
  521. }
  522. char buffer[256];
  523. int ret = snprintf(buffer, sizeof(buffer), "[WIFI/SAVE]{\"ssid\":\"%s\",\"password\":\"%s\"}", ssid, password);
  524. if (ret < 0 || ret >= (int)sizeof(buffer))
  525. {
  526. FURI_LOG_E("FlipperHTTP", "Failed to format WiFi save command.");
  527. return false;
  528. }
  529. if (!flipper_http_send_data(buffer))
  530. {
  531. FURI_LOG_E("FlipperHTTP", "Failed to send WiFi save command.");
  532. return false;
  533. }
  534. // The response will be handled asynchronously via the callback
  535. return true;
  536. }
  537. // Function to disconnect from WiFi (returns true if successful)
  538. /**
  539. * @brief Send a command to disconnect from WiFi.
  540. * @return true if the request was successful, false otherwise.
  541. * @note The received data will be handled asynchronously via the callback.
  542. */
  543. bool flipper_http_disconnect_wifi()
  544. {
  545. const char *command = "[WIFI/DISCONNECT]";
  546. if (!flipper_http_send_data(command))
  547. {
  548. FURI_LOG_E("FlipperHTTP", "Failed to send WiFi disconnect command.");
  549. return false;
  550. }
  551. // The response will be handled asynchronously via the callback
  552. return true;
  553. }
  554. // Function to connect to WiFi (returns true if successful)
  555. /**
  556. * @brief Send a command to connect to WiFi.
  557. * @return true if the request was successful, false otherwise.
  558. * @note The received data will be handled asynchronously via the callback.
  559. */
  560. bool flipper_http_connect_wifi()
  561. {
  562. const char *command = "[WIFI/CONNECT]";
  563. if (!flipper_http_send_data(command))
  564. {
  565. FURI_LOG_E("FlipperHTTP", "Failed to send WiFi connect command.");
  566. return false;
  567. }
  568. // The response will be handled asynchronously via the callback
  569. return true;
  570. }
  571. // Function to send a GET request
  572. /**
  573. * @brief Send a GET request to the specified URL.
  574. * @return true if the request was successful, false otherwise.
  575. * @param url The URL to send the GET request to.
  576. * @note The received data will be handled asynchronously via the callback.
  577. */
  578. bool flipper_http_get_request(const char *url)
  579. {
  580. if (!url)
  581. {
  582. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_get_request.");
  583. return false;
  584. }
  585. // Prepare GET request command
  586. char command[256];
  587. int ret = snprintf(command, sizeof(command), "[GET]%s", url);
  588. if (ret < 0 || ret >= (int)sizeof(command))
  589. {
  590. FURI_LOG_E("FlipperHTTP", "Failed to format GET request command.");
  591. return false;
  592. }
  593. // Send GET request via UART
  594. if (!flipper_http_send_data(command))
  595. {
  596. FURI_LOG_E("FlipperHTTP", "Failed to send GET request command.");
  597. return false;
  598. }
  599. // The response will be handled asynchronously via the callback
  600. return true;
  601. }
  602. // Function to send a GET request with headers
  603. /**
  604. * @brief Send a GET request to the specified URL.
  605. * @return true if the request was successful, false otherwise.
  606. * @param url The URL to send the GET request to.
  607. * @param headers The headers to send with the GET request.
  608. * @note The received data will be handled asynchronously via the callback.
  609. */
  610. bool flipper_http_get_request_with_headers(const char *url, const char *headers)
  611. {
  612. if (!url || !headers)
  613. {
  614. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_get_request_with_headers.");
  615. return false;
  616. }
  617. // Prepare GET request command with headers
  618. char command[256];
  619. int ret = snprintf(command, sizeof(command), "[GET/HTTP]{\"url\":\"%s\",\"headers\":%s}", url, headers);
  620. if (ret < 0 || ret >= (int)sizeof(command))
  621. {
  622. FURI_LOG_E("FlipperHTTP", "Failed to format GET request command with headers.");
  623. return false;
  624. }
  625. // Send GET request via UART
  626. if (!flipper_http_send_data(command))
  627. {
  628. FURI_LOG_E("FlipperHTTP", "Failed to send GET request command with headers.");
  629. return false;
  630. }
  631. // The response will be handled asynchronously via the callback
  632. return true;
  633. }
  634. // Function to send a POST request with headers
  635. /**
  636. * @brief Send a POST request to the specified URL.
  637. * @return true if the request was successful, false otherwise.
  638. * @param url The URL to send the POST request to.
  639. * @param headers The headers to send with the POST request.
  640. * @param data The data to send with the POST request.
  641. * @note The received data will be handled asynchronously via the callback.
  642. */
  643. bool flipper_http_post_request_with_headers(const char *url, const char *headers, const char *payload)
  644. {
  645. if (!url || !headers || !payload)
  646. {
  647. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_post_request_with_headers.");
  648. return false;
  649. }
  650. // Prepare POST request command with headers and data
  651. char command[256];
  652. int ret = snprintf(command, sizeof(command), "[POST/HTTP]{\"url\":\"%s\",\"headers\":%s,\"payload\":%s}", url, headers, payload);
  653. if (ret < 0 || ret >= (int)sizeof(command))
  654. {
  655. FURI_LOG_E("FlipperHTTP", "Failed to format POST request command with headers and data.");
  656. return false;
  657. }
  658. // Send POST request via UART
  659. if (!flipper_http_send_data(command))
  660. {
  661. FURI_LOG_E("FlipperHTTP", "Failed to send POST request command with headers and data.");
  662. return false;
  663. }
  664. // The response will be handled asynchronously via the callback
  665. return true;
  666. }
  667. // Function to send a PUT request with headers
  668. /**
  669. * @brief Send a PUT request to the specified URL.
  670. * @return true if the request was successful, false otherwise.
  671. * @param url The URL to send the PUT request to.
  672. * @param headers The headers to send with the PUT request.
  673. * @param data The data to send with the PUT request.
  674. * @note The received data will be handled asynchronously via the callback.
  675. */
  676. bool flipper_http_put_request_with_headers(const char *url, const char *headers, const char *payload)
  677. {
  678. if (!url || !headers || !payload)
  679. {
  680. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_put_request_with_headers.");
  681. return false;
  682. }
  683. // Prepare PUT request command with headers and data
  684. char command[256];
  685. int ret = snprintf(command, sizeof(command), "[PUT/HTTP]{\"url\":\"%s\",\"headers\":%s,\"payload\":%s}", url, headers, payload);
  686. if (ret < 0 || ret >= (int)sizeof(command))
  687. {
  688. FURI_LOG_E("FlipperHTTP", "Failed to format PUT request command with headers and data.");
  689. return false;
  690. }
  691. // Send PUT request via UART
  692. if (!flipper_http_send_data(command))
  693. {
  694. FURI_LOG_E("FlipperHTTP", "Failed to send PUT request command with headers and data.");
  695. return false;
  696. }
  697. // The response will be handled asynchronously via the callback
  698. return true;
  699. }
  700. // Function to send a DELETE request with headers
  701. /**
  702. * @brief Send a DELETE request to the specified URL.
  703. * @return true if the request was successful, false otherwise.
  704. * @param url The URL to send the DELETE request to.
  705. * @param headers The headers to send with the DELETE request.
  706. * @param data The data to send with the DELETE request.
  707. * @note The received data will be handled asynchronously via the callback.
  708. */
  709. bool flipper_http_delete_request_with_headers(const char *url, const char *headers, const char *payload)
  710. {
  711. if (!url || !headers || !payload)
  712. {
  713. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_delete_request_with_headers.");
  714. return false;
  715. }
  716. // Prepare DELETE request command with headers and data
  717. char command[256];
  718. int ret = snprintf(command, sizeof(command), "[DELETE/HTTP]{\"url\":\"%s\",\"headers\":%s,\"payload\":%s}", url, headers, payload);
  719. if (ret < 0 || ret >= (int)sizeof(command))
  720. {
  721. FURI_LOG_E("FlipperHTTP", "Failed to format DELETE request command with headers and data.");
  722. return false;
  723. }
  724. // Send DELETE request via UART
  725. if (!flipper_http_send_data(command))
  726. {
  727. FURI_LOG_E("FlipperHTTP", "Failed to send DELETE request command with headers and data.");
  728. return false;
  729. }
  730. // The response will be handled asynchronously via the callback
  731. return true;
  732. }
  733. // Function to handle received data asynchronously
  734. /**
  735. * @brief Callback function to handle received data asynchronously.
  736. * @return void
  737. * @param line The received line.
  738. * @param context The context passed to the callback.
  739. * @note The received data will be handled asynchronously via the callback and handles the state of the UART.
  740. */
  741. void flipper_http_rx_callback(const char *line, void *context)
  742. {
  743. if (!line || !context)
  744. {
  745. FURI_LOG_E(HTTP_TAG, "Invalid arguments provided to flipper_http_rx_callback.");
  746. return;
  747. }
  748. // Trim the received line to check if it's empty
  749. char *trimmed_line = trim(line);
  750. if (trimmed_line != NULL && trimmed_line[0] != '\0')
  751. {
  752. fhttp.last_response = (char *)line;
  753. }
  754. free(trimmed_line); // Free the allocated memory for trimmed_line
  755. if (fhttp.state != INACTIVE && fhttp.state != ISSUE)
  756. {
  757. fhttp.state = RECEIVING;
  758. }
  759. // Uncomment below line to log the data received over UART
  760. // FURI_LOG_I(HTTP_TAG, "Received UART line: %s", line);
  761. // Check if we've started receiving data from a GET request
  762. if (fhttp.started_receiving_get)
  763. {
  764. // Restart the timeout timer each time new data is received
  765. furi_timer_restart(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  766. if (strstr(line, "[GET/END]") != NULL)
  767. {
  768. FURI_LOG_I(HTTP_TAG, "GET request completed.");
  769. // Stop the timer since we've completed the GET request
  770. furi_timer_stop(fhttp.get_timeout_timer);
  771. if (fhttp.received_data)
  772. {
  773. // uncomment if you want to save the received data to the external storage
  774. // flipper_http_save_received_data(strlen(fhttp.received_data), fhttp.received_data);
  775. fhttp.started_receiving_get = false;
  776. fhttp.just_started_get = false;
  777. fhttp.state = IDLE;
  778. return;
  779. }
  780. else
  781. {
  782. FURI_LOG_E(HTTP_TAG, "No data received.");
  783. fhttp.started_receiving_get = false;
  784. fhttp.just_started_get = false;
  785. fhttp.state = IDLE;
  786. return;
  787. }
  788. }
  789. // Append the new line to the existing data
  790. if (fhttp.received_data == NULL)
  791. {
  792. fhttp.received_data = (char *)malloc(strlen(line) + 2); // +2 for newline and null terminator
  793. if (fhttp.received_data)
  794. {
  795. strcpy(fhttp.received_data, line);
  796. fhttp.received_data[strlen(line)] = '\n'; // Add newline
  797. fhttp.received_data[strlen(line) + 1] = '\0'; // Null terminator
  798. }
  799. }
  800. else
  801. {
  802. size_t current_len = strlen(fhttp.received_data);
  803. size_t new_size = current_len + strlen(line) + 2; // +2 for newline and null terminator
  804. fhttp.received_data = (char *)realloc(fhttp.received_data, new_size);
  805. if (fhttp.received_data)
  806. {
  807. memcpy(fhttp.received_data + current_len, line, strlen(line)); // Copy line at the end of the current data
  808. fhttp.received_data[current_len + strlen(line)] = '\n'; // Add newline
  809. fhttp.received_data[current_len + strlen(line) + 1] = '\0'; // Null terminator
  810. }
  811. }
  812. if (!fhttp.just_started_get)
  813. {
  814. fhttp.just_started_get = true;
  815. }
  816. return;
  817. }
  818. // Check if we've started receiving data from a POST request
  819. else if (fhttp.started_receiving_post)
  820. {
  821. // Restart the timeout timer each time new data is received
  822. furi_timer_restart(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  823. if (strstr(line, "[POST/END]") != NULL)
  824. {
  825. FURI_LOG_I(HTTP_TAG, "POST request completed.");
  826. // Stop the timer since we've completed the POST request
  827. furi_timer_stop(fhttp.get_timeout_timer);
  828. if (fhttp.received_data)
  829. {
  830. // uncomment if you want to save the received data to the external storage
  831. // flipper_http_save_received_data(strlen(fhttp.received_data), fhttp.received_data);
  832. fhttp.started_receiving_post = false;
  833. fhttp.just_started_post = false;
  834. fhttp.state = IDLE;
  835. return;
  836. }
  837. else
  838. {
  839. FURI_LOG_E(HTTP_TAG, "No data received.");
  840. fhttp.started_receiving_post = false;
  841. fhttp.just_started_post = false;
  842. fhttp.state = IDLE;
  843. return;
  844. }
  845. }
  846. // Append the new line to the existing data
  847. if (fhttp.received_data == NULL)
  848. {
  849. fhttp.received_data = (char *)malloc(strlen(line) + 2); // +2 for newline and null terminator
  850. if (fhttp.received_data)
  851. {
  852. strcpy(fhttp.received_data, line);
  853. fhttp.received_data[strlen(line)] = '\n'; // Add newline
  854. fhttp.received_data[strlen(line) + 1] = '\0'; // Null terminator
  855. }
  856. }
  857. else
  858. {
  859. size_t current_len = strlen(fhttp.received_data);
  860. size_t new_size = current_len + strlen(line) + 2; // +2 for newline and null terminator
  861. fhttp.received_data = (char *)realloc(fhttp.received_data, new_size);
  862. if (fhttp.received_data)
  863. {
  864. memcpy(fhttp.received_data + current_len, line, strlen(line)); // Copy line at the end of the current data
  865. fhttp.received_data[current_len + strlen(line)] = '\n'; // Add newline
  866. fhttp.received_data[current_len + strlen(line) + 1] = '\0'; // Null terminator
  867. }
  868. }
  869. if (!fhttp.just_started_post)
  870. {
  871. fhttp.just_started_post = true;
  872. }
  873. return;
  874. }
  875. // Check if we've started receiving data from a PUT request
  876. else if (fhttp.started_receiving_put)
  877. {
  878. // Restart the timeout timer each time new data is received
  879. furi_timer_restart(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  880. if (strstr(line, "[PUT/END]") != NULL)
  881. {
  882. FURI_LOG_I(HTTP_TAG, "PUT request completed.");
  883. // Stop the timer since we've completed the PUT request
  884. furi_timer_stop(fhttp.get_timeout_timer);
  885. if (fhttp.received_data)
  886. {
  887. // uncomment if you want to save the received data to the external storage
  888. // flipper_http_save_received_data(strlen(fhttp.received_data), fhttp.received_data);
  889. fhttp.started_receiving_put = false;
  890. fhttp.just_started_put = false;
  891. fhttp.state = IDLE;
  892. return;
  893. }
  894. else
  895. {
  896. FURI_LOG_E(HTTP_TAG, "No data received.");
  897. fhttp.started_receiving_put = false;
  898. fhttp.just_started_put = false;
  899. fhttp.state = IDLE;
  900. return;
  901. }
  902. }
  903. // Append the new line to the existing data
  904. if (fhttp.received_data == NULL)
  905. {
  906. fhttp.received_data = (char *)malloc(strlen(line) + 2); // +2 for newline and null terminator
  907. if (fhttp.received_data)
  908. {
  909. strcpy(fhttp.received_data, line);
  910. fhttp.received_data[strlen(line)] = '\n'; // Add newline
  911. fhttp.received_data[strlen(line) + 1] = '\0'; // Null terminator
  912. }
  913. }
  914. else
  915. {
  916. size_t current_len = strlen(fhttp.received_data);
  917. size_t new_size = current_len + strlen(line) + 2; // +2 for newline and null terminator
  918. fhttp.received_data = (char *)realloc(fhttp.received_data, new_size);
  919. if (fhttp.received_data)
  920. {
  921. memcpy(fhttp.received_data + current_len, line, strlen(line)); // Copy line at the end of the current data
  922. fhttp.received_data[current_len + strlen(line)] = '\n'; // Add newline
  923. fhttp.received_data[current_len + strlen(line) + 1] = '\0'; // Null terminator
  924. }
  925. }
  926. if (!fhttp.just_started_put)
  927. {
  928. fhttp.just_started_put = true;
  929. }
  930. return;
  931. }
  932. // Check if we've started receiving data from a DELETE request
  933. else if (fhttp.started_receiving_delete)
  934. {
  935. // Restart the timeout timer each time new data is received
  936. furi_timer_restart(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  937. if (strstr(line, "[DELETE/END]") != NULL)
  938. {
  939. FURI_LOG_I(HTTP_TAG, "DELETE request completed.");
  940. // Stop the timer since we've completed the DELETE request
  941. furi_timer_stop(fhttp.get_timeout_timer);
  942. if (fhttp.received_data)
  943. {
  944. // uncomment if you want to save the received data to the external storage
  945. // flipper_http_save_received_data(strlen(fhttp.received_data), fhttp.received_data);
  946. fhttp.started_receiving_delete = false;
  947. fhttp.just_started_delete = false;
  948. fhttp.state = IDLE;
  949. return;
  950. }
  951. else
  952. {
  953. FURI_LOG_E(HTTP_TAG, "No data received.");
  954. fhttp.started_receiving_delete = false;
  955. fhttp.just_started_delete = false;
  956. fhttp.state = IDLE;
  957. return;
  958. }
  959. }
  960. // Append the new line to the existing data
  961. if (fhttp.received_data == NULL)
  962. {
  963. fhttp.received_data = (char *)malloc(strlen(line) + 2); // +2 for newline and null terminator
  964. if (fhttp.received_data)
  965. {
  966. strcpy(fhttp.received_data, line);
  967. fhttp.received_data[strlen(line)] = '\n'; // Add newline
  968. fhttp.received_data[strlen(line) + 1] = '\0'; // Null terminator
  969. }
  970. }
  971. else
  972. {
  973. size_t current_len = strlen(fhttp.received_data);
  974. size_t new_size = current_len + strlen(line) + 2; // +2 for newline and null terminator
  975. fhttp.received_data = (char *)realloc(fhttp.received_data, new_size);
  976. if (fhttp.received_data)
  977. {
  978. memcpy(fhttp.received_data + current_len, line, strlen(line)); // Copy line at the end of the current data
  979. fhttp.received_data[current_len + strlen(line)] = '\n'; // Add newline
  980. fhttp.received_data[current_len + strlen(line) + 1] = '\0'; // Null terminator
  981. }
  982. }
  983. if (!fhttp.just_started_delete)
  984. {
  985. fhttp.just_started_delete = true;
  986. }
  987. return;
  988. }
  989. // Handle different types of responses
  990. if (strstr(line, "[SUCCESS]") != NULL || strstr(line, "[CONNECTED]") != NULL)
  991. {
  992. // FURI_LOG_I(HTTP_TAG, "Operation succeeded.");
  993. }
  994. else if (strstr(line, "[INFO]") != NULL)
  995. {
  996. FURI_LOG_I(HTTP_TAG, "Received info: %s", line);
  997. if (fhttp.state == INACTIVE && strstr(line, "[INFO] Already connected to Wifi.") != NULL)
  998. {
  999. fhttp.state = IDLE;
  1000. }
  1001. }
  1002. else if (strstr(line, "[GET/SUCCESS]") != NULL)
  1003. {
  1004. // FURI_LOG_I(HTTP_TAG, "GET request succeeded.");
  1005. fhttp.started_receiving_get = true;
  1006. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1007. fhttp.state = RECEIVING;
  1008. fhttp.received_data = NULL;
  1009. return;
  1010. }
  1011. else if (strstr(line, "[POST/SUCCESS]") != NULL)
  1012. {
  1013. // FURI_LOG_I(HTTP_TAG, "POST request succeeded.");
  1014. fhttp.started_receiving_post = true;
  1015. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1016. fhttp.state = RECEIVING;
  1017. fhttp.received_data = NULL;
  1018. return;
  1019. }
  1020. else if (strstr(line, "[PUT/SUCCESS]") != NULL)
  1021. {
  1022. // FURI_LOG_I(HTTP_TAG, "PUT request succeeded.");
  1023. fhttp.started_receiving_put = true;
  1024. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1025. fhttp.state = RECEIVING;
  1026. fhttp.received_data = NULL;
  1027. return;
  1028. }
  1029. else if (strstr(line, "[DELETE/SUCCESS]") != NULL)
  1030. {
  1031. // FURI_LOG_I(HTTP_TAG, "DELETE request succeeded.");
  1032. fhttp.started_receiving_delete = true;
  1033. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1034. fhttp.state = RECEIVING;
  1035. fhttp.received_data = NULL;
  1036. return;
  1037. }
  1038. else if (strstr(line, "[DISCONNECTED]") != NULL)
  1039. {
  1040. // FURI_LOG_I(HTTP_TAG, "WiFi disconnected successfully.");
  1041. }
  1042. else if (strstr(line, "[ERROR]") != NULL)
  1043. {
  1044. FURI_LOG_E(HTTP_TAG, "Received error: %s", line);
  1045. fhttp.state = ISSUE;
  1046. return;
  1047. }
  1048. else if (strstr(line, "[PONG]") != NULL)
  1049. {
  1050. FURI_LOG_I(HTTP_TAG, "Received PONG response: Wifi Dev Board is still alive.");
  1051. // send command to connect to WiFi
  1052. if (fhttp.state == INACTIVE)
  1053. {
  1054. fhttp.state = IDLE;
  1055. return;
  1056. }
  1057. }
  1058. if (fhttp.state == INACTIVE && strstr(line, "[PONG]") != NULL)
  1059. {
  1060. fhttp.state = IDLE;
  1061. }
  1062. else if (fhttp.state == INACTIVE && strstr(line, "[PONG]") == NULL)
  1063. {
  1064. fhttp.state = INACTIVE;
  1065. }
  1066. else
  1067. {
  1068. fhttp.state = IDLE;
  1069. }
  1070. }
  1071. // Function to save received data to a file
  1072. /**
  1073. * @brief Save the received data to a file.
  1074. * @return true if the data was saved successfully, false otherwise.
  1075. * @param bytes_received The number of bytes received.
  1076. * @param line_buffer The buffer containing the received data.
  1077. * @note The data will be saved to a file in the STORAGE_EXT_PATH_PREFIX "/apps_data/" http_tag "/received_data.txt" directory.
  1078. */
  1079. bool flipper_http_save_received_data(size_t bytes_received, const char line_buffer[])
  1080. {
  1081. const char *output_file_path = STORAGE_EXT_PATH_PREFIX "/apps_data/" http_tag "/received_data.txt";
  1082. // Ensure the directory exists
  1083. char directory_path[128];
  1084. snprintf(directory_path, sizeof(directory_path), STORAGE_EXT_PATH_PREFIX "/apps_data/" http_tag);
  1085. Storage *_storage = NULL;
  1086. File *_file = NULL;
  1087. // Open the storage if not opened already
  1088. // Initialize storage and create the directory if it doesn't exist
  1089. _storage = furi_record_open(RECORD_STORAGE);
  1090. storage_common_mkdir(_storage, directory_path); // Create directory if it doesn't exist
  1091. _file = storage_file_alloc(_storage);
  1092. // Open file for writing and append data line by line
  1093. if (!storage_file_open(_file, output_file_path, FSAM_WRITE, FSOM_CREATE_ALWAYS))
  1094. {
  1095. FURI_LOG_E(HTTP_TAG, "Failed to open output file for writing.");
  1096. storage_file_free(_file);
  1097. furi_record_close(RECORD_STORAGE);
  1098. return false;
  1099. }
  1100. // Write each line received from the UART to the file
  1101. if (bytes_received > 0 && _file)
  1102. {
  1103. storage_file_write(_file, line_buffer, bytes_received);
  1104. storage_file_write(_file, "\n", 1); // Add a newline after each line
  1105. }
  1106. else
  1107. {
  1108. FURI_LOG_E(HTTP_TAG, "No data received.");
  1109. return false;
  1110. }
  1111. if (_file)
  1112. {
  1113. storage_file_close(_file);
  1114. storage_file_free(_file);
  1115. _file = NULL;
  1116. }
  1117. if (_storage)
  1118. {
  1119. furi_record_close(RECORD_STORAGE);
  1120. _storage = NULL;
  1121. }
  1122. return true;
  1123. }
  1124. // Function to trim leading and trailing spaces and newlines from a constant string
  1125. char *trim(const char *str)
  1126. {
  1127. const char *end;
  1128. char *trimmed_str;
  1129. size_t len;
  1130. // Trim leading space
  1131. while (isspace((unsigned char)*str))
  1132. str++;
  1133. // All spaces?
  1134. if (*str == 0)
  1135. return strdup(""); // Return an empty string if all spaces
  1136. // Trim trailing space
  1137. end = str + strlen(str) - 1;
  1138. while (end > str && isspace((unsigned char)*end))
  1139. end--;
  1140. // Set length for the trimmed string
  1141. len = end - str + 1;
  1142. // Allocate space for the trimmed string and null terminator
  1143. trimmed_str = (char *)malloc(len + 1);
  1144. if (trimmed_str == NULL)
  1145. {
  1146. return NULL; // Handle memory allocation failure
  1147. }
  1148. // Copy the trimmed part of the string into trimmed_str
  1149. strncpy(trimmed_str, str, len);
  1150. trimmed_str[len] = '\0'; // Null terminate the string
  1151. return trimmed_str;
  1152. }
  1153. #endif // FLIPPER_HTTP_H