flipper_http.h 45 KB

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