flipper_http.h 40 KB

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