flipper_http.h 40 KB

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