flipper_http.h 44 KB

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