flipper_http.h 33 KB

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