flipper_http.h 41 KB

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