flipper_http.h 40 KB

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