flipper_http.h 39 KB

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