flipper_http.h 45 KB

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