flipper_http.h 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135
  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. FURI_LOG_I("FlipperHTTP", "UART deinitialized successfully.");
  305. }
  306. // Function to send data over UART with newline termination
  307. /**
  308. * @brief Send data over UART with newline termination.
  309. * @return true if the data was sent successfully, false otherwise.
  310. * @param data The data to send over UART.
  311. * @note The data will be sent over UART with a newline character appended.
  312. */
  313. bool flipper_http_send_data(const char *data)
  314. {
  315. size_t data_length = strlen(data);
  316. if (data_length == 0)
  317. {
  318. FURI_LOG_E("FlipperHTTP", "Attempted to send empty data.");
  319. return false;
  320. }
  321. // Create a buffer with data + '\n'
  322. size_t send_length = data_length + 1; // +1 for '\n'
  323. if (send_length > 256)
  324. { // Ensure buffer size is sufficient
  325. FURI_LOG_E("FlipperHTTP", "Data too long to send over FHTTP.");
  326. return false;
  327. }
  328. char send_buffer[257]; // 256 + 1 for safety
  329. strncpy(send_buffer, data, 256);
  330. send_buffer[data_length] = '\n'; // Append newline
  331. send_buffer[data_length + 1] = '\0'; // Null-terminate
  332. if (fhttp.state == INACTIVE && ((strstr(send_buffer, "[PING]") == NULL) && (strstr(send_buffer, "[WIFI/CONNECT]") == NULL)))
  333. {
  334. FURI_LOG_E("FlipperHTTP", "Cannot send data while INACTIVE.");
  335. fhttp.last_response = "Cannot send data while INACTIVE.";
  336. return false;
  337. }
  338. fhttp.state = SENDING;
  339. furi_hal_serial_tx(fhttp.serial_handle, (const uint8_t *)send_buffer, send_length);
  340. // Uncomment below line to log the data sent over UART
  341. // FURI_LOG_I("FlipperHTTP", "Sent data over UART: %s", send_buffer);
  342. fhttp.state = IDLE;
  343. return true;
  344. }
  345. // Function to send a PING request
  346. /**
  347. * @brief Send a GET request to the specified URL.
  348. * @return true if the request was successful, false otherwise.
  349. * @param url The URL to send the GET request to.
  350. * @note The received data will be handled asynchronously via the callback.
  351. * @note This is best used to check if the Wifi Dev Board is connected.
  352. * @note The state will remain INACTIVE until a PONG is received.
  353. */
  354. bool flipper_http_ping()
  355. {
  356. const char *command = "[PING]";
  357. if (!flipper_http_send_data(command))
  358. {
  359. FURI_LOG_E("FlipperHTTP", "Failed to send PING command.");
  360. return false;
  361. }
  362. // set state as INACTIVE to be made IDLE if PONG is received
  363. fhttp.state = INACTIVE;
  364. // The response will be handled asynchronously via the callback
  365. return true;
  366. }
  367. // Function to save WiFi settings (returns true if successful)
  368. /**
  369. * @brief Send a command to save WiFi settings.
  370. * @return true if the request was successful, false otherwise.
  371. * @note The received data will be handled asynchronously via the callback.
  372. */
  373. bool flipper_http_save_wifi(const char *ssid, const char *password)
  374. {
  375. if (!ssid || !password)
  376. {
  377. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_save_wifi.");
  378. return false;
  379. }
  380. char buffer[256];
  381. int ret = snprintf(buffer, sizeof(buffer), "[WIFI/SAVE]{\"ssid\":\"%s\",\"password\":\"%s\"}", ssid, password);
  382. if (ret < 0 || ret >= (int)sizeof(buffer))
  383. {
  384. FURI_LOG_E("FlipperHTTP", "Failed to format WiFi save command.");
  385. return false;
  386. }
  387. if (!flipper_http_send_data(buffer))
  388. {
  389. FURI_LOG_E("FlipperHTTP", "Failed to send WiFi save command.");
  390. return false;
  391. }
  392. // The response will be handled asynchronously via the callback
  393. return true;
  394. }
  395. // Function to disconnect from WiFi (returns true if successful)
  396. /**
  397. * @brief Send a command to disconnect from WiFi.
  398. * @return true if the request was successful, false otherwise.
  399. * @note The received data will be handled asynchronously via the callback.
  400. */
  401. bool flipper_http_disconnect_wifi()
  402. {
  403. const char *command = "[WIFI/DISCONNECT]";
  404. if (!flipper_http_send_data(command))
  405. {
  406. FURI_LOG_E("FlipperHTTP", "Failed to send WiFi disconnect command.");
  407. return false;
  408. }
  409. // The response will be handled asynchronously via the callback
  410. return true;
  411. }
  412. // Function to connect to WiFi (returns true if successful)
  413. /**
  414. * @brief Send a command to connect to WiFi.
  415. * @return true if the request was successful, false otherwise.
  416. * @note The received data will be handled asynchronously via the callback.
  417. */
  418. bool flipper_http_connect_wifi()
  419. {
  420. const char *command = "[WIFI/CONNECT]";
  421. if (!flipper_http_send_data(command))
  422. {
  423. FURI_LOG_E("FlipperHTTP", "Failed to send WiFi connect command.");
  424. return false;
  425. }
  426. // The response will be handled asynchronously via the callback
  427. return true;
  428. }
  429. // Function to send a GET request
  430. /**
  431. * @brief Send a GET request to the specified URL.
  432. * @return true if the request was successful, false otherwise.
  433. * @param url The URL to send the GET request to.
  434. * @note The received data will be handled asynchronously via the callback.
  435. */
  436. bool flipper_http_get_request(const char *url)
  437. {
  438. if (!url)
  439. {
  440. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_get_request.");
  441. return false;
  442. }
  443. // Prepare GET request command
  444. char command[256];
  445. int ret = snprintf(command, sizeof(command), "[GET]%s", url);
  446. if (ret < 0 || ret >= (int)sizeof(command))
  447. {
  448. FURI_LOG_E("FlipperHTTP", "Failed to format GET request command.");
  449. return false;
  450. }
  451. // Send GET request via UART
  452. if (!flipper_http_send_data(command))
  453. {
  454. FURI_LOG_E("FlipperHTTP", "Failed to send GET request command.");
  455. return false;
  456. }
  457. // The response will be handled asynchronously via the callback
  458. return true;
  459. }
  460. // Function to send a GET request with headers
  461. /**
  462. * @brief Send a GET request to the specified URL.
  463. * @return true if the request was successful, false otherwise.
  464. * @param url The URL to send the GET request to.
  465. * @param headers The headers to send with the GET request.
  466. * @note The received data will be handled asynchronously via the callback.
  467. */
  468. bool flipper_http_get_request_with_headers(const char *url, const char *headers)
  469. {
  470. if (!url || !headers)
  471. {
  472. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_get_request_with_headers.");
  473. return false;
  474. }
  475. // Prepare GET request command with headers
  476. char command[256];
  477. int ret = snprintf(command, sizeof(command), "[GET/HTTP]{\"url\":\"%s\",\"headers\":%s}", url, headers);
  478. if (ret < 0 || ret >= (int)sizeof(command))
  479. {
  480. FURI_LOG_E("FlipperHTTP", "Failed to format GET request command with headers.");
  481. return false;
  482. }
  483. // Send GET request via UART
  484. if (!flipper_http_send_data(command))
  485. {
  486. FURI_LOG_E("FlipperHTTP", "Failed to send GET request command with headers.");
  487. return false;
  488. }
  489. // The response will be handled asynchronously via the callback
  490. return true;
  491. }
  492. // Function to send a POST request with headers
  493. /**
  494. * @brief Send a POST request to the specified URL.
  495. * @return true if the request was successful, false otherwise.
  496. * @param url The URL to send the POST request to.
  497. * @param headers The headers to send with the POST request.
  498. * @param data The data to send with the POST request.
  499. * @note The received data will be handled asynchronously via the callback.
  500. */
  501. bool flipper_http_post_request_with_headers(const char *url, const char *headers, const char *payload)
  502. {
  503. if (!url || !headers || !payload)
  504. {
  505. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_post_request_with_headers.");
  506. return false;
  507. }
  508. // Prepare POST request command with headers and data
  509. char command[256];
  510. int ret = snprintf(command, sizeof(command), "[POST/HTTP]{\"url\":\"%s\",\"headers\":%s,\"payload\":%s}", url, headers, payload);
  511. if (ret < 0 || ret >= (int)sizeof(command))
  512. {
  513. FURI_LOG_E("FlipperHTTP", "Failed to format POST request command with headers and data.");
  514. return false;
  515. }
  516. // Send POST request via UART
  517. if (!flipper_http_send_data(command))
  518. {
  519. FURI_LOG_E("FlipperHTTP", "Failed to send POST request command with headers and data.");
  520. return false;
  521. }
  522. // The response will be handled asynchronously via the callback
  523. return true;
  524. }
  525. // Function to send a PUT request with headers
  526. /**
  527. * @brief Send a PUT request to the specified URL.
  528. * @return true if the request was successful, false otherwise.
  529. * @param url The URL to send the PUT request to.
  530. * @param headers The headers to send with the PUT request.
  531. * @param data The data to send with the PUT request.
  532. * @note The received data will be handled asynchronously via the callback.
  533. */
  534. bool flipper_http_put_request_with_headers(const char *url, const char *headers, const char *payload)
  535. {
  536. if (!url || !headers || !payload)
  537. {
  538. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_put_request_with_headers.");
  539. return false;
  540. }
  541. // Prepare PUT request command with headers and data
  542. char command[256];
  543. int ret = snprintf(command, sizeof(command), "[PUT/HTTP]{\"url\":\"%s\",\"headers\":%s,\"payload\":%s}", url, headers, payload);
  544. if (ret < 0 || ret >= (int)sizeof(command))
  545. {
  546. FURI_LOG_E("FlipperHTTP", "Failed to format PUT request command with headers and data.");
  547. return false;
  548. }
  549. // Send PUT request via UART
  550. if (!flipper_http_send_data(command))
  551. {
  552. FURI_LOG_E("FlipperHTTP", "Failed to send PUT request command with headers and data.");
  553. return false;
  554. }
  555. // The response will be handled asynchronously via the callback
  556. return true;
  557. }
  558. // Function to send a DELETE request with headers
  559. /**
  560. * @brief Send a DELETE request to the specified URL.
  561. * @return true if the request was successful, false otherwise.
  562. * @param url The URL to send the DELETE request to.
  563. * @param headers The headers to send with the DELETE request.
  564. * @param data The data to send with the DELETE request.
  565. * @note The received data will be handled asynchronously via the callback.
  566. */
  567. bool flipper_http_delete_request_with_headers(const char *url, const char *headers, const char *payload)
  568. {
  569. if (!url || !headers || !payload)
  570. {
  571. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_delete_request_with_headers.");
  572. return false;
  573. }
  574. // Prepare DELETE request command with headers and data
  575. char command[256];
  576. int ret = snprintf(command, sizeof(command), "[DELETE/HTTP]{\"url\":\"%s\",\"headers\":%s,\"payload\":%s}", url, headers, payload);
  577. if (ret < 0 || ret >= (int)sizeof(command))
  578. {
  579. FURI_LOG_E("FlipperHTTP", "Failed to format DELETE request command with headers and data.");
  580. return false;
  581. }
  582. // Send DELETE request via UART
  583. if (!flipper_http_send_data(command))
  584. {
  585. FURI_LOG_E("FlipperHTTP", "Failed to send DELETE request command with headers and data.");
  586. return false;
  587. }
  588. // The response will be handled asynchronously via the callback
  589. return true;
  590. }
  591. // Function to handle received data asynchronously
  592. /**
  593. * @brief Callback function to handle received data asynchronously.
  594. * @return void
  595. * @param line The received line.
  596. * @param context The context passed to the callback.
  597. * @note The received data will be handled asynchronously via the callback and handles the state of the UART.
  598. */
  599. void flipper_http_rx_callback(const char *line, void *context)
  600. {
  601. if (!line || !context)
  602. {
  603. FURI_LOG_E(HTTP_TAG, "Invalid arguments provided to flipper_http_rx_callback.");
  604. return;
  605. }
  606. // Trim the received line to check if it's empty
  607. char *trimmed_line = trim(line);
  608. if (trimmed_line != NULL && trimmed_line[0] != '\0')
  609. {
  610. fhttp.last_response = (char *)line;
  611. }
  612. free(trimmed_line); // Free the allocated memory for trimmed_line
  613. if (fhttp.state != INACTIVE && fhttp.state != ISSUE)
  614. {
  615. fhttp.state = RECEIVING;
  616. }
  617. // Uncomment below line to log the data received over UART
  618. // FURI_LOG_I(HTTP_TAG, "Received UART line: %s", line);
  619. // Check if we've started receiving data from a GET request
  620. if (fhttp.started_receiving_get)
  621. {
  622. // Restart the timeout timer each time new data is received
  623. furi_timer_restart(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  624. if (strstr(line, "[GET/END]") != NULL)
  625. {
  626. FURI_LOG_I(HTTP_TAG, "GET request completed.");
  627. // Stop the timer since we've completed the GET request
  628. furi_timer_stop(fhttp.get_timeout_timer);
  629. if (fhttp.received_data)
  630. {
  631. // uncomment if you want to save the received data to the external storage
  632. flipper_http_save_received_data(strlen(fhttp.received_data), fhttp.received_data);
  633. fhttp.started_receiving_get = false;
  634. fhttp.just_started_get = false;
  635. fhttp.state = IDLE;
  636. return;
  637. }
  638. else
  639. {
  640. FURI_LOG_E(HTTP_TAG, "No data received.");
  641. fhttp.started_receiving_get = false;
  642. fhttp.just_started_get = false;
  643. fhttp.state = IDLE;
  644. return;
  645. }
  646. }
  647. // Append the new line to the existing data
  648. if (fhttp.received_data == NULL)
  649. {
  650. fhttp.received_data = (char *)malloc(strlen(line) + 2); // +2 for newline and null terminator
  651. if (fhttp.received_data)
  652. {
  653. strcpy(fhttp.received_data, line);
  654. fhttp.received_data[strlen(line)] = '\n'; // Add newline
  655. fhttp.received_data[strlen(line) + 1] = '\0'; // Null terminator
  656. }
  657. }
  658. else
  659. {
  660. size_t current_len = strlen(fhttp.received_data);
  661. size_t new_size = current_len + strlen(line) + 2; // +2 for newline and null terminator
  662. fhttp.received_data = (char *)realloc(fhttp.received_data, new_size);
  663. if (fhttp.received_data)
  664. {
  665. memcpy(fhttp.received_data + current_len, line, strlen(line)); // Copy line at the end of the current data
  666. fhttp.received_data[current_len + strlen(line)] = '\n'; // Add newline
  667. fhttp.received_data[current_len + strlen(line) + 1] = '\0'; // Null terminator
  668. }
  669. }
  670. if (!fhttp.just_started_get)
  671. {
  672. fhttp.just_started_get = true;
  673. }
  674. return;
  675. }
  676. // Check if we've started receiving data from a POST request
  677. else if (fhttp.started_receiving_post)
  678. {
  679. // Restart the timeout timer each time new data is received
  680. furi_timer_restart(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  681. if (strstr(line, "[POST/END]") != NULL)
  682. {
  683. FURI_LOG_I(HTTP_TAG, "POST request completed.");
  684. // Stop the timer since we've completed the POST request
  685. furi_timer_stop(fhttp.get_timeout_timer);
  686. if (fhttp.received_data)
  687. {
  688. // uncomment if you want to save the received data to the external storage
  689. flipper_http_save_received_data(strlen(fhttp.received_data), fhttp.received_data);
  690. fhttp.started_receiving_post = false;
  691. fhttp.just_started_post = false;
  692. fhttp.state = IDLE;
  693. return;
  694. }
  695. else
  696. {
  697. FURI_LOG_E(HTTP_TAG, "No data received.");
  698. fhttp.started_receiving_post = false;
  699. fhttp.just_started_post = false;
  700. fhttp.state = IDLE;
  701. return;
  702. }
  703. }
  704. // Append the new line to the existing data
  705. if (fhttp.received_data == NULL)
  706. {
  707. fhttp.received_data = (char *)malloc(strlen(line) + 2); // +2 for newline and null terminator
  708. if (fhttp.received_data)
  709. {
  710. strcpy(fhttp.received_data, line);
  711. fhttp.received_data[strlen(line)] = '\n'; // Add newline
  712. fhttp.received_data[strlen(line) + 1] = '\0'; // Null terminator
  713. }
  714. }
  715. else
  716. {
  717. size_t current_len = strlen(fhttp.received_data);
  718. size_t new_size = current_len + strlen(line) + 2; // +2 for newline and null terminator
  719. fhttp.received_data = (char *)realloc(fhttp.received_data, new_size);
  720. if (fhttp.received_data)
  721. {
  722. memcpy(fhttp.received_data + current_len, line, strlen(line)); // Copy line at the end of the current data
  723. fhttp.received_data[current_len + strlen(line)] = '\n'; // Add newline
  724. fhttp.received_data[current_len + strlen(line) + 1] = '\0'; // Null terminator
  725. }
  726. }
  727. if (!fhttp.just_started_post)
  728. {
  729. fhttp.just_started_post = true;
  730. }
  731. return;
  732. }
  733. // Check if we've started receiving data from a PUT request
  734. else if (fhttp.started_receiving_put)
  735. {
  736. // Restart the timeout timer each time new data is received
  737. furi_timer_restart(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  738. if (strstr(line, "[PUT/END]") != NULL)
  739. {
  740. FURI_LOG_I(HTTP_TAG, "PUT request completed.");
  741. // Stop the timer since we've completed the PUT request
  742. furi_timer_stop(fhttp.get_timeout_timer);
  743. if (fhttp.received_data)
  744. {
  745. // uncomment if you want to save the received data to the external storage
  746. flipper_http_save_received_data(strlen(fhttp.received_data), fhttp.received_data);
  747. fhttp.started_receiving_put = false;
  748. fhttp.just_started_put = false;
  749. fhttp.state = IDLE;
  750. return;
  751. }
  752. else
  753. {
  754. FURI_LOG_E(HTTP_TAG, "No data received.");
  755. fhttp.started_receiving_put = false;
  756. fhttp.just_started_put = false;
  757. fhttp.state = IDLE;
  758. return;
  759. }
  760. }
  761. // Append the new line to the existing data
  762. if (fhttp.received_data == NULL)
  763. {
  764. fhttp.received_data = (char *)malloc(strlen(line) + 2); // +2 for newline and null terminator
  765. if (fhttp.received_data)
  766. {
  767. strcpy(fhttp.received_data, line);
  768. fhttp.received_data[strlen(line)] = '\n'; // Add newline
  769. fhttp.received_data[strlen(line) + 1] = '\0'; // Null terminator
  770. }
  771. }
  772. else
  773. {
  774. size_t current_len = strlen(fhttp.received_data);
  775. size_t new_size = current_len + strlen(line) + 2; // +2 for newline and null terminator
  776. fhttp.received_data = (char *)realloc(fhttp.received_data, new_size);
  777. if (fhttp.received_data)
  778. {
  779. memcpy(fhttp.received_data + current_len, line, strlen(line)); // Copy line at the end of the current data
  780. fhttp.received_data[current_len + strlen(line)] = '\n'; // Add newline
  781. fhttp.received_data[current_len + strlen(line) + 1] = '\0'; // Null terminator
  782. }
  783. }
  784. if (!fhttp.just_started_put)
  785. {
  786. fhttp.just_started_put = true;
  787. }
  788. return;
  789. }
  790. // Check if we've started receiving data from a DELETE request
  791. else if (fhttp.started_receiving_delete)
  792. {
  793. // Restart the timeout timer each time new data is received
  794. furi_timer_restart(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  795. if (strstr(line, "[DELETE/END]") != NULL)
  796. {
  797. FURI_LOG_I(HTTP_TAG, "DELETE request completed.");
  798. // Stop the timer since we've completed the DELETE request
  799. furi_timer_stop(fhttp.get_timeout_timer);
  800. if (fhttp.received_data)
  801. {
  802. // uncomment if you want to save the received data to the external storage
  803. flipper_http_save_received_data(strlen(fhttp.received_data), fhttp.received_data);
  804. fhttp.started_receiving_delete = false;
  805. fhttp.just_started_delete = false;
  806. fhttp.state = IDLE;
  807. return;
  808. }
  809. else
  810. {
  811. FURI_LOG_E(HTTP_TAG, "No data received.");
  812. fhttp.started_receiving_delete = false;
  813. fhttp.just_started_delete = false;
  814. fhttp.state = IDLE;
  815. return;
  816. }
  817. }
  818. // Append the new line to the existing data
  819. if (fhttp.received_data == NULL)
  820. {
  821. fhttp.received_data = (char *)malloc(strlen(line) + 2); // +2 for newline and null terminator
  822. if (fhttp.received_data)
  823. {
  824. strcpy(fhttp.received_data, line);
  825. fhttp.received_data[strlen(line)] = '\n'; // Add newline
  826. fhttp.received_data[strlen(line) + 1] = '\0'; // Null terminator
  827. }
  828. }
  829. else
  830. {
  831. size_t current_len = strlen(fhttp.received_data);
  832. size_t new_size = current_len + strlen(line) + 2; // +2 for newline and null terminator
  833. fhttp.received_data = (char *)realloc(fhttp.received_data, new_size);
  834. if (fhttp.received_data)
  835. {
  836. memcpy(fhttp.received_data + current_len, line, strlen(line)); // Copy line at the end of the current data
  837. fhttp.received_data[current_len + strlen(line)] = '\n'; // Add newline
  838. fhttp.received_data[current_len + strlen(line) + 1] = '\0'; // Null terminator
  839. }
  840. }
  841. if (!fhttp.just_started_delete)
  842. {
  843. fhttp.just_started_delete = true;
  844. }
  845. return;
  846. }
  847. // Handle different types of responses
  848. if (strstr(line, "[SUCCESS]") != NULL || strstr(line, "[CONNECTED]") != NULL)
  849. {
  850. FURI_LOG_I(HTTP_TAG, "Operation succeeded.");
  851. }
  852. else if (strstr(line, "[INFO]") != NULL)
  853. {
  854. FURI_LOG_I(HTTP_TAG, "Received info: %s", line);
  855. if (fhttp.state == INACTIVE && strstr(line, "[INFO] Already connected to Wifi.") != NULL)
  856. {
  857. fhttp.state = IDLE;
  858. }
  859. }
  860. else if (strstr(line, "[GET/SUCCESS]") != NULL)
  861. {
  862. FURI_LOG_I(HTTP_TAG, "GET request succeeded.");
  863. fhttp.started_receiving_get = true;
  864. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  865. fhttp.state = RECEIVING;
  866. free(fhttp.received_data);
  867. fhttp.received_data = NULL;
  868. return;
  869. }
  870. else if (strstr(line, "[POST/SUCCESS]") != NULL)
  871. {
  872. FURI_LOG_I(HTTP_TAG, "POST request succeeded.");
  873. fhttp.started_receiving_post = true;
  874. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  875. fhttp.state = RECEIVING;
  876. free(fhttp.received_data);
  877. fhttp.received_data = NULL;
  878. return;
  879. }
  880. else if (strstr(line, "[PUT/SUCCESS]") != NULL)
  881. {
  882. FURI_LOG_I(HTTP_TAG, "PUT request succeeded.");
  883. fhttp.started_receiving_put = true;
  884. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  885. fhttp.state = RECEIVING;
  886. free(fhttp.received_data);
  887. fhttp.received_data = NULL;
  888. return;
  889. }
  890. else if (strstr(line, "[DELETE/SUCCESS]") != NULL)
  891. {
  892. FURI_LOG_I(HTTP_TAG, "DELETE request succeeded.");
  893. fhttp.started_receiving_delete = true;
  894. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  895. fhttp.state = RECEIVING;
  896. free(fhttp.received_data);
  897. fhttp.received_data = NULL;
  898. return;
  899. }
  900. else if (strstr(line, "[DISCONNECTED]") != NULL)
  901. {
  902. FURI_LOG_I(HTTP_TAG, "WiFi disconnected successfully.");
  903. }
  904. else if (strstr(line, "[ERROR]") != NULL)
  905. {
  906. FURI_LOG_E(HTTP_TAG, "Received error: %s", line);
  907. fhttp.state = ISSUE;
  908. return;
  909. }
  910. else if (strstr(line, "[PONG]") != NULL)
  911. {
  912. FURI_LOG_I(HTTP_TAG, "Received PONG response: Wifi Dev Board is still alive.");
  913. // send command to connect to WiFi
  914. if (fhttp.state == INACTIVE)
  915. {
  916. fhttp.state = IDLE;
  917. return;
  918. }
  919. }
  920. if (fhttp.state == INACTIVE && strstr(line, "[PONG]") != NULL)
  921. {
  922. fhttp.state = IDLE;
  923. }
  924. else if (fhttp.state == INACTIVE && strstr(line, "[PONG]") == NULL)
  925. {
  926. fhttp.state = INACTIVE;
  927. }
  928. else
  929. {
  930. fhttp.state = IDLE;
  931. }
  932. }
  933. // Function to save received data to a file
  934. /**
  935. * @brief Save the received data to a file.
  936. * @return true if the data was saved successfully, false otherwise.
  937. * @param bytes_received The number of bytes received.
  938. * @param line_buffer The buffer containing the received data.
  939. * @note The data will be saved to a file in the STORAGE_EXT_PATH_PREFIX "/apps_data/" http_tag "/received_data.txt" directory.
  940. */
  941. bool flipper_http_save_received_data(size_t bytes_received, const char line_buffer[])
  942. {
  943. const char *output_file_path = STORAGE_EXT_PATH_PREFIX "/apps_data/" http_tag "/received_data.txt";
  944. // Ensure the directory exists
  945. char directory_path[128];
  946. snprintf(directory_path, sizeof(directory_path), STORAGE_EXT_PATH_PREFIX "/apps_data/" http_tag);
  947. Storage *_storage = NULL;
  948. File *_file = NULL;
  949. // Open the storage if not opened already
  950. // Initialize storage and create the directory if it doesn't exist
  951. _storage = furi_record_open(RECORD_STORAGE);
  952. storage_common_mkdir(_storage, directory_path); // Create directory if it doesn't exist
  953. _file = storage_file_alloc(_storage);
  954. // Open file for writing and append data line by line
  955. if (!storage_file_open(_file, output_file_path, FSAM_WRITE, FSOM_CREATE_ALWAYS))
  956. {
  957. FURI_LOG_E(HTTP_TAG, "Failed to open output file for writing.");
  958. storage_file_free(_file);
  959. furi_record_close(RECORD_STORAGE);
  960. return false;
  961. }
  962. // Write each line received from the UART to the file
  963. if (bytes_received > 0 && _file)
  964. {
  965. storage_file_write(_file, line_buffer, bytes_received);
  966. storage_file_write(_file, "\n", 1); // Add a newline after each line
  967. }
  968. else
  969. {
  970. FURI_LOG_E(HTTP_TAG, "No data received.");
  971. return false;
  972. }
  973. if (_file)
  974. {
  975. storage_file_close(_file);
  976. storage_file_free(_file);
  977. _file = NULL;
  978. }
  979. if (_storage)
  980. {
  981. furi_record_close(RECORD_STORAGE);
  982. _storage = NULL;
  983. }
  984. return true;
  985. }
  986. // Function to trim leading and trailing spaces and newlines from a constant string
  987. char *trim(const char *str)
  988. {
  989. const char *end;
  990. char *trimmed_str;
  991. size_t len;
  992. // Trim leading space
  993. while (isspace((unsigned char)*str))
  994. str++;
  995. // All spaces?
  996. if (*str == 0)
  997. return strdup(""); // Return an empty string if all spaces
  998. // Trim trailing space
  999. end = str + strlen(str) - 1;
  1000. while (end > str && isspace((unsigned char)*end))
  1001. end--;
  1002. // Set length for the trimmed string
  1003. len = end - str + 1;
  1004. // Allocate space for the trimmed string and null terminator
  1005. trimmed_str = (char *)malloc(len + 1);
  1006. if (trimmed_str == NULL)
  1007. {
  1008. return NULL; // Handle memory allocation failure
  1009. }
  1010. // Copy the trimmed part of the string into trimmed_str
  1011. strncpy(trimmed_str, str, len);
  1012. trimmed_str[len] = '\0'; // Null terminate the string
  1013. return trimmed_str;
  1014. }
  1015. #endif // FLIPPER_HTTP_H