flipper_http.h 45 KB

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