flipper_http.h 40 KB

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