flipper_http.h 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392
  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 (3 * 1000) // 3 seconds
  14. #define BAUDRATE (115200) // UART baudrate
  15. #define RX_BUF_SIZE 2048 // UART RX buffer size
  16. #define RX_LINE_BUFFER_SIZE 2048 // UART RX line buffer size (increase for large responses)
  17. #define MAX_FILE_SHOW 5000 // Maximum data from file to show
  18. // Forward declaration for callback
  19. typedef void (*FlipperHTTP_Callback)(const char* line, void* context);
  20. // Functions
  21. bool flipper_http_init(FlipperHTTP_Callback callback, void* context);
  22. void flipper_http_deinit();
  23. //---
  24. void flipper_http_rx_callback(const char* line, void* context);
  25. bool flipper_http_send_data(const char* data);
  26. //---
  27. bool flipper_http_connect_wifi();
  28. bool flipper_http_disconnect_wifi();
  29. bool flipper_http_ping();
  30. bool flipper_http_scan_wifi();
  31. bool flipper_http_save_wifi(const char* ssid, const char* password);
  32. bool flipper_http_ip_wifi();
  33. bool flipper_http_ip_address();
  34. //---
  35. bool flipper_http_list_commands();
  36. bool flipper_http_led_on();
  37. bool flipper_http_led_off();
  38. bool flipper_http_parse_json(const char* key, const char* json_data);
  39. bool flipper_http_parse_json_array(const char* key, int index, const char* json_data);
  40. //---
  41. bool flipper_http_get_request(const char* url);
  42. bool flipper_http_get_request_with_headers(const char* url, const char* headers);
  43. bool flipper_http_post_request_with_headers(
  44. const char* url,
  45. const char* headers,
  46. const char* payload);
  47. bool flipper_http_put_request_with_headers(
  48. const char* url,
  49. const char* headers,
  50. const char* payload);
  51. bool flipper_http_delete_request_with_headers(
  52. const char* url,
  53. const char* headers,
  54. const char* payload);
  55. //---
  56. bool flipper_http_get_request_bytes(const char* url, const char* headers);
  57. bool flipper_http_post_request_bytes(const char* url, const char* headers, const char* payload);
  58. //
  59. bool flipper_http_append_to_file(
  60. const void* data,
  61. size_t data_size,
  62. bool start_new_file,
  63. char* file_path);
  64. FuriString* flipper_http_load_from_file(char* file_path);
  65. static char* trim(const char* str);
  66. //
  67. bool flipper_http_process_response_async(bool (*http_request)(void), bool (*parse_json)(void));
  68. // State variable to track the UART state
  69. typedef enum {
  70. INACTIVE, // Inactive state
  71. IDLE, // Default state
  72. RECEIVING, // Receiving data
  73. SENDING, // Sending data
  74. ISSUE, // Issue with connection
  75. } SerialState;
  76. // Event Flags for UART Worker Thread
  77. typedef enum {
  78. WorkerEvtStop = (1 << 0),
  79. WorkerEvtRxDone = (1 << 1),
  80. } WorkerEvtFlags;
  81. // FlipperHTTP Structure
  82. typedef struct {
  83. FuriStreamBuffer* flipper_http_stream; // Stream buffer for UART communication
  84. FuriHalSerialHandle* serial_handle; // Serial handle for UART communication
  85. FuriThread* rx_thread; // Worker thread for UART
  86. FuriThreadId rx_thread_id; // Worker thread ID
  87. FlipperHTTP_Callback handle_rx_line_cb; // Callback for received lines
  88. void* callback_context; // Context for the callback
  89. SerialState state; // State of the UART
  90. // variable to store the last received data from the UART
  91. char* last_response;
  92. char file_path[256]; // Path to save the received data
  93. // Timer-related members
  94. FuriTimer* get_timeout_timer; // Timer for HTTP request timeout
  95. bool started_receiving_get; // Indicates if a GET request has started
  96. bool just_started_get; // Indicates if GET data reception has just started
  97. bool started_receiving_post; // Indicates if a POST request has started
  98. bool just_started_post; // Indicates if POST data reception has just started
  99. bool started_receiving_put; // Indicates if a PUT request has started
  100. bool just_started_put; // Indicates if PUT data reception has just started
  101. bool started_receiving_delete; // Indicates if a DELETE request has started
  102. bool just_started_delete; // Indicates if DELETE data reception has just started
  103. // Buffer to hold the raw bytes received from the UART
  104. uint8_t* received_bytes;
  105. size_t received_bytes_len; // Length of the received bytes
  106. bool is_bytes_request; // Flag to indicate if the request is for bytes
  107. bool save_bytes; // Flag to save the received data to a file
  108. bool save_received_data; // Flag to save the received data to a file
  109. } FlipperHTTP;
  110. static FlipperHTTP fhttp;
  111. // Global static array for the line buffer
  112. static char rx_line_buffer[RX_LINE_BUFFER_SIZE];
  113. #define FILE_BUFFER_SIZE 512
  114. static uint8_t file_buffer[FILE_BUFFER_SIZE];
  115. // fhttp.last_response holds the last received data from the UART, which could be [GET/END], [POST/END], [PUT/END], [DELETE/END], etc
  116. // Function to append received data to file
  117. // make sure to initialize the file path before calling this function
  118. bool flipper_http_append_to_file(
  119. const void* data,
  120. size_t data_size,
  121. bool start_new_file,
  122. char* file_path) {
  123. Storage* storage = furi_record_open(RECORD_STORAGE);
  124. File* file = storage_file_alloc(storage);
  125. if(start_new_file) {
  126. // Open the file in write mode
  127. if(!storage_file_open(file, file_path, FSAM_WRITE, FSOM_CREATE_ALWAYS)) {
  128. FURI_LOG_E(HTTP_TAG, "Failed to open file for writing: %s", file_path);
  129. storage_file_free(file);
  130. furi_record_close(RECORD_STORAGE);
  131. return false;
  132. }
  133. } else {
  134. // Open the file in append mode
  135. if(!storage_file_open(file, file_path, FSAM_WRITE, FSOM_OPEN_APPEND)) {
  136. FURI_LOG_E(HTTP_TAG, "Failed to open file for appending: %s", file_path);
  137. storage_file_free(file);
  138. furi_record_close(RECORD_STORAGE);
  139. return false;
  140. }
  141. }
  142. // Write the data to the file
  143. if(storage_file_write(file, data, data_size) != data_size) {
  144. FURI_LOG_E(HTTP_TAG, "Failed to append data to file");
  145. storage_file_close(file);
  146. storage_file_free(file);
  147. furi_record_close(RECORD_STORAGE);
  148. return false;
  149. }
  150. storage_file_close(file);
  151. storage_file_free(file);
  152. furi_record_close(RECORD_STORAGE);
  153. return true;
  154. }
  155. FuriString* flipper_http_load_from_file(char* file_path) {
  156. // Open the storage record
  157. Storage* storage = furi_record_open(RECORD_STORAGE);
  158. if(!storage) {
  159. FURI_LOG_E(HTTP_TAG, "Failed to open storage record");
  160. return NULL;
  161. }
  162. // Allocate a file handle
  163. File* file = storage_file_alloc(storage);
  164. if(!file) {
  165. FURI_LOG_E(HTTP_TAG, "Failed to allocate storage file");
  166. furi_record_close(RECORD_STORAGE);
  167. return NULL;
  168. }
  169. // Open the file for reading
  170. if(!storage_file_open(file, file_path, FSAM_READ, FSOM_OPEN_EXISTING)) {
  171. storage_file_free(file);
  172. furi_record_close(RECORD_STORAGE);
  173. return NULL; // Return false if the file does not exist
  174. }
  175. // Allocate a FuriString to hold the received data
  176. FuriString* str_result = furi_string_alloc();
  177. if(!str_result) {
  178. FURI_LOG_E(HTTP_TAG, "Failed to allocate FuriString");
  179. storage_file_close(file);
  180. storage_file_free(file);
  181. furi_record_close(RECORD_STORAGE);
  182. return NULL;
  183. }
  184. // Reset the FuriString to ensure it's empty before reading
  185. furi_string_reset(str_result);
  186. // Define a buffer to hold the read data
  187. uint8_t* buffer = (uint8_t*)malloc(MAX_FILE_SHOW);
  188. if(!buffer) {
  189. FURI_LOG_E(HTTP_TAG, "Failed to allocate buffer");
  190. furi_string_free(str_result);
  191. storage_file_close(file);
  192. storage_file_free(file);
  193. furi_record_close(RECORD_STORAGE);
  194. return NULL;
  195. }
  196. // Read data into the buffer
  197. size_t read_count = storage_file_read(file, buffer, MAX_FILE_SHOW);
  198. if(storage_file_get_error(file) != FSE_OK) {
  199. FURI_LOG_E(HTTP_TAG, "Error reading from file.");
  200. furi_string_free(str_result);
  201. storage_file_close(file);
  202. storage_file_free(file);
  203. furi_record_close(RECORD_STORAGE);
  204. return false;
  205. }
  206. // Append each byte to the FuriString
  207. for(size_t i = 0; i < read_count; i++) {
  208. furi_string_push_back(str_result, buffer[i]);
  209. }
  210. // Check if there is more data beyond the maximum size
  211. char extra_byte;
  212. storage_file_read(file, &extra_byte, 1);
  213. // Clean up
  214. storage_file_close(file);
  215. storage_file_free(file);
  216. furi_record_close(RECORD_STORAGE);
  217. free(buffer);
  218. return str_result;
  219. }
  220. // UART worker thread
  221. /**
  222. * @brief Worker thread to handle UART data asynchronously.
  223. * @return 0
  224. * @param context The context to pass to the callback.
  225. * @note This function will handle received data asynchronously via the callback.
  226. */
  227. // UART worker thread
  228. static int32_t flipper_http_worker(void* context) {
  229. UNUSED(context);
  230. size_t rx_line_pos = 0;
  231. static size_t file_buffer_len = 0;
  232. while(1) {
  233. uint32_t events = furi_thread_flags_wait(
  234. WorkerEvtStop | WorkerEvtRxDone, FuriFlagWaitAny, FuriWaitForever);
  235. if(events & WorkerEvtStop) break;
  236. if(events & WorkerEvtRxDone) {
  237. // Continuously read from the stream buffer until it's empty
  238. while(!furi_stream_buffer_is_empty(fhttp.flipper_http_stream)) {
  239. // Read one byte at a time
  240. char c = 0;
  241. size_t received = furi_stream_buffer_receive(fhttp.flipper_http_stream, &c, 1, 0);
  242. if(received == 0) {
  243. // No more data to read
  244. break;
  245. }
  246. // Append the received byte to the file if saving is enabled
  247. if(fhttp.save_bytes) {
  248. // Add byte to the buffer
  249. file_buffer[file_buffer_len++] = c;
  250. // Write to file if buffer is full
  251. if(file_buffer_len >= FILE_BUFFER_SIZE) {
  252. if(!flipper_http_append_to_file(
  253. file_buffer, file_buffer_len, false, fhttp.file_path)) {
  254. FURI_LOG_E(HTTP_TAG, "Failed to append data to file");
  255. }
  256. file_buffer_len = 0;
  257. }
  258. }
  259. // Handle line buffering only if callback is set (text data)
  260. if(fhttp.handle_rx_line_cb) {
  261. // Handle line buffering
  262. if(c == '\n' || rx_line_pos >= RX_LINE_BUFFER_SIZE - 1) {
  263. rx_line_buffer[rx_line_pos] = '\0'; // Null-terminate the line
  264. // Invoke the callback with the complete line
  265. fhttp.handle_rx_line_cb(rx_line_buffer, fhttp.callback_context);
  266. // save the received data
  267. // Reset the line buffer position
  268. rx_line_pos = 0;
  269. } else {
  270. rx_line_buffer[rx_line_pos++] = c; // Add character to the line buffer
  271. }
  272. }
  273. }
  274. }
  275. }
  276. if(fhttp.save_bytes) {
  277. // Write the remaining data to the file
  278. if(file_buffer_len > 0) {
  279. if(!flipper_http_append_to_file(file_buffer, file_buffer_len, false, fhttp.file_path)) {
  280. FURI_LOG_E(HTTP_TAG, "Failed to append remaining data to file");
  281. }
  282. }
  283. }
  284. // remove [POST/END] and/or [GET/END] from the file
  285. if(fhttp.save_bytes) {
  286. char* end = NULL;
  287. if((end = strstr(fhttp.file_path, "[POST/END]")) != NULL) {
  288. *end = '\0';
  289. } else if((end = strstr(fhttp.file_path, "[GET/END]")) != NULL) {
  290. *end = '\0';
  291. }
  292. }
  293. // remove newline from the from the end of the file
  294. if(fhttp.save_bytes) {
  295. char* end = NULL;
  296. if((end = strstr(fhttp.file_path, "\n")) != NULL) {
  297. *end = '\0';
  298. }
  299. }
  300. // Reset the file buffer length
  301. file_buffer_len = 0;
  302. return 0;
  303. }
  304. // Timer callback function
  305. /**
  306. * @brief Callback function for the GET timeout timer.
  307. * @return 0
  308. * @param context The context to pass to the callback.
  309. * @note This function will be called when the GET request times out.
  310. */
  311. void get_timeout_timer_callback(void* context) {
  312. UNUSED(context);
  313. FURI_LOG_E(HTTP_TAG, "Timeout reached: 2 seconds without receiving the end.");
  314. // Reset the state
  315. fhttp.started_receiving_get = false;
  316. fhttp.started_receiving_post = false;
  317. fhttp.started_receiving_put = false;
  318. fhttp.started_receiving_delete = false;
  319. // Update UART state
  320. fhttp.state = ISSUE;
  321. }
  322. // UART RX Handler Callback (Interrupt Context)
  323. /**
  324. * @brief A private callback function to handle received data asynchronously.
  325. * @return void
  326. * @param handle The UART handle.
  327. * @param event The event type.
  328. * @param context The context to pass to the callback.
  329. * @note This function will handle received data asynchronously via the callback.
  330. */
  331. static void _flipper_http_rx_callback(
  332. FuriHalSerialHandle* handle,
  333. FuriHalSerialRxEvent event,
  334. void* context) {
  335. UNUSED(context);
  336. if(event == FuriHalSerialRxEventData) {
  337. uint8_t data = furi_hal_serial_async_rx(handle);
  338. furi_stream_buffer_send(fhttp.flipper_http_stream, &data, 1, 0);
  339. furi_thread_flags_set(fhttp.rx_thread_id, WorkerEvtRxDone);
  340. }
  341. }
  342. // UART initialization function
  343. /**
  344. * @brief Initialize UART.
  345. * @return true if the UART was initialized successfully, false otherwise.
  346. * @param callback The callback function to handle received data (ex. flipper_http_rx_callback).
  347. * @param context The context to pass to the callback.
  348. * @note The received data will be handled asynchronously via the callback.
  349. */
  350. bool flipper_http_init(FlipperHTTP_Callback callback, void* context) {
  351. if(!context) {
  352. FURI_LOG_E(HTTP_TAG, "Invalid context provided to flipper_http_init.");
  353. return false;
  354. }
  355. if(!callback) {
  356. FURI_LOG_E(HTTP_TAG, "Invalid callback provided to flipper_http_init.");
  357. return false;
  358. }
  359. fhttp.flipper_http_stream = furi_stream_buffer_alloc(RX_BUF_SIZE, 1);
  360. if(!fhttp.flipper_http_stream) {
  361. FURI_LOG_E(HTTP_TAG, "Failed to allocate UART stream buffer.");
  362. return false;
  363. }
  364. fhttp.rx_thread = furi_thread_alloc();
  365. if(!fhttp.rx_thread) {
  366. FURI_LOG_E(HTTP_TAG, "Failed to allocate UART thread.");
  367. furi_stream_buffer_free(fhttp.flipper_http_stream);
  368. return false;
  369. }
  370. furi_thread_set_name(fhttp.rx_thread, "FlipperHTTP_RxThread");
  371. furi_thread_set_stack_size(fhttp.rx_thread, 1024);
  372. furi_thread_set_context(fhttp.rx_thread, &fhttp);
  373. furi_thread_set_callback(fhttp.rx_thread, flipper_http_worker);
  374. fhttp.handle_rx_line_cb = callback;
  375. fhttp.callback_context = context;
  376. furi_thread_start(fhttp.rx_thread);
  377. fhttp.rx_thread_id = furi_thread_get_id(fhttp.rx_thread);
  378. // handle when the UART control is busy to avoid furi_check failed
  379. if(furi_hal_serial_control_is_busy(UART_CH)) {
  380. FURI_LOG_E(HTTP_TAG, "UART control is busy.");
  381. return false;
  382. }
  383. fhttp.serial_handle = furi_hal_serial_control_acquire(UART_CH);
  384. if(!fhttp.serial_handle) {
  385. FURI_LOG_E(HTTP_TAG, "Failed to acquire UART control - handle is NULL");
  386. // Cleanup resources
  387. furi_thread_free(fhttp.rx_thread);
  388. furi_stream_buffer_free(fhttp.flipper_http_stream);
  389. return false;
  390. }
  391. // Initialize UART with acquired handle
  392. furi_hal_serial_init(fhttp.serial_handle, BAUDRATE);
  393. // Enable RX direction
  394. furi_hal_serial_enable_direction(fhttp.serial_handle, FuriHalSerialDirectionRx);
  395. // Start asynchronous RX with the callback
  396. furi_hal_serial_async_rx_start(fhttp.serial_handle, _flipper_http_rx_callback, &fhttp, false);
  397. // Wait for the TX to complete to ensure UART is ready
  398. furi_hal_serial_tx_wait_complete(fhttp.serial_handle);
  399. // Allocate the timer for handling timeouts
  400. fhttp.get_timeout_timer = furi_timer_alloc(
  401. get_timeout_timer_callback, // Callback function
  402. FuriTimerTypeOnce, // One-shot timer
  403. &fhttp // Context passed to callback
  404. );
  405. if(!fhttp.get_timeout_timer) {
  406. FURI_LOG_E(HTTP_TAG, "Failed to allocate HTTP request timeout timer.");
  407. // Cleanup resources
  408. furi_hal_serial_async_rx_stop(fhttp.serial_handle);
  409. furi_hal_serial_disable_direction(fhttp.serial_handle, FuriHalSerialDirectionRx);
  410. furi_hal_serial_control_release(fhttp.serial_handle);
  411. furi_hal_serial_deinit(fhttp.serial_handle);
  412. furi_thread_flags_set(fhttp.rx_thread_id, WorkerEvtStop);
  413. furi_thread_join(fhttp.rx_thread);
  414. furi_thread_free(fhttp.rx_thread);
  415. furi_stream_buffer_free(fhttp.flipper_http_stream);
  416. return false;
  417. }
  418. // Set the timer thread priority if needed
  419. furi_timer_set_thread_priority(FuriTimerThreadPriorityElevated);
  420. fhttp.last_response = (char*)malloc(RX_BUF_SIZE);
  421. if(!fhttp.last_response) {
  422. FURI_LOG_E(HTTP_TAG, "Failed to allocate memory for last_response.");
  423. return false;
  424. }
  425. // FURI_LOG_I(HTTP_TAG, "UART initialized successfully.");
  426. return true;
  427. }
  428. // Deinitialize UART
  429. /**
  430. * @brief Deinitialize UART.
  431. * @return void
  432. * @note This function will stop the asynchronous RX, release the serial handle, and free the resources.
  433. */
  434. void flipper_http_deinit() {
  435. if(fhttp.serial_handle == NULL) {
  436. FURI_LOG_E(HTTP_TAG, "UART handle is NULL. Already deinitialized?");
  437. return;
  438. }
  439. // Stop asynchronous RX
  440. furi_hal_serial_async_rx_stop(fhttp.serial_handle);
  441. // Release and deinitialize the serial handle
  442. furi_hal_serial_disable_direction(fhttp.serial_handle, FuriHalSerialDirectionRx);
  443. furi_hal_serial_control_release(fhttp.serial_handle);
  444. furi_hal_serial_deinit(fhttp.serial_handle);
  445. // Signal the worker thread to stop
  446. furi_thread_flags_set(fhttp.rx_thread_id, WorkerEvtStop);
  447. // Wait for the thread to finish
  448. furi_thread_join(fhttp.rx_thread);
  449. // Free the thread resources
  450. furi_thread_free(fhttp.rx_thread);
  451. // Free the stream buffer
  452. furi_stream_buffer_free(fhttp.flipper_http_stream);
  453. // Free the timer
  454. if(fhttp.get_timeout_timer) {
  455. furi_timer_free(fhttp.get_timeout_timer);
  456. fhttp.get_timeout_timer = NULL;
  457. }
  458. // Free the last response
  459. if(fhttp.last_response) {
  460. free(fhttp.last_response);
  461. fhttp.last_response = NULL;
  462. }
  463. // FURI_LOG_I("FlipperHTTP", "UART deinitialized successfully.");
  464. }
  465. // Function to send data over UART with newline termination
  466. /**
  467. * @brief Send data over UART with newline termination.
  468. * @return true if the data was sent successfully, false otherwise.
  469. * @param data The data to send over UART.
  470. * @note The data will be sent over UART with a newline character appended.
  471. */
  472. bool flipper_http_send_data(const char* data) {
  473. size_t data_length = strlen(data);
  474. if(data_length == 0) {
  475. FURI_LOG_E("FlipperHTTP", "Attempted to send empty data.");
  476. return false;
  477. }
  478. // Create a buffer with data + '\n'
  479. size_t send_length = data_length + 1; // +1 for '\n'
  480. if(send_length > 256) { // Ensure buffer size is sufficient
  481. FURI_LOG_E("FlipperHTTP", "Data too long to send over FHTTP.");
  482. return false;
  483. }
  484. char send_buffer[257]; // 256 + 1 for safety
  485. strncpy(send_buffer, data, 256);
  486. send_buffer[data_length] = '\n'; // Append newline
  487. send_buffer[data_length + 1] = '\0'; // Null-terminate
  488. if(fhttp.state == INACTIVE && ((strstr(send_buffer, "[PING]") == NULL) &&
  489. (strstr(send_buffer, "[WIFI/CONNECT]") == NULL))) {
  490. FURI_LOG_E("FlipperHTTP", "Cannot send data while INACTIVE.");
  491. fhttp.last_response = "Cannot send data while INACTIVE.";
  492. return false;
  493. }
  494. fhttp.state = SENDING;
  495. furi_hal_serial_tx(fhttp.serial_handle, (const uint8_t*)send_buffer, send_length);
  496. // Uncomment below line to log the data sent over UART
  497. // FURI_LOG_I("FlipperHTTP", "Sent data over UART: %s", send_buffer);
  498. fhttp.state = IDLE;
  499. return true;
  500. }
  501. // Function to send a PING request
  502. /**
  503. * @brief Send a PING request to check if the Wifi Dev Board is connected.
  504. * @return true if the request was successful, false otherwise.
  505. * @note The received data will be handled asynchronously via the callback.
  506. * @note This is best used to check if the Wifi Dev Board is connected.
  507. * @note The state will remain INACTIVE until a PONG is received.
  508. */
  509. bool flipper_http_ping() {
  510. const char* command = "[PING]";
  511. if(!flipper_http_send_data(command)) {
  512. FURI_LOG_E("FlipperHTTP", "Failed to send PING command.");
  513. return false;
  514. }
  515. // set state as INACTIVE to be made IDLE if PONG is received
  516. fhttp.state = INACTIVE;
  517. // The response will be handled asynchronously via the callback
  518. return true;
  519. }
  520. // Function to list available commands
  521. /**
  522. * @brief Send a command to list available commands.
  523. * @return true if the request was successful, false otherwise.
  524. * @note The received data will be handled asynchronously via the callback.
  525. */
  526. bool flipper_http_list_commands() {
  527. const char* command = "[LIST]";
  528. if(!flipper_http_send_data(command)) {
  529. FURI_LOG_E("FlipperHTTP", "Failed to send LIST command.");
  530. return false;
  531. }
  532. // The response will be handled asynchronously via the callback
  533. return true;
  534. }
  535. // Function to turn on the LED
  536. /**
  537. * @brief Allow the LED to display while processing.
  538. * @return true if the request was successful, false otherwise.
  539. * @note The received data will be handled asynchronously via the callback.
  540. */
  541. bool flipper_http_led_on() {
  542. const char* command = "[LED/ON]";
  543. if(!flipper_http_send_data(command)) {
  544. FURI_LOG_E("FlipperHTTP", "Failed to send LED ON command.");
  545. return false;
  546. }
  547. // The response will be handled asynchronously via the callback
  548. return true;
  549. }
  550. // Function to turn off the LED
  551. /**
  552. * @brief Disable the LED from displaying while processing.
  553. * @return true if the request was successful, false otherwise.
  554. * @note The received data will be handled asynchronously via the callback.
  555. */
  556. bool flipper_http_led_off() {
  557. const char* command = "[LED/OFF]";
  558. if(!flipper_http_send_data(command)) {
  559. FURI_LOG_E("FlipperHTTP", "Failed to send LED OFF command.");
  560. return false;
  561. }
  562. // The response will be handled asynchronously via the callback
  563. return true;
  564. }
  565. // Function to parse JSON data
  566. /**
  567. * @brief Parse JSON data.
  568. * @return true if the JSON data was parsed successfully, false otherwise.
  569. * @param key The key to parse from the JSON data.
  570. * @param json_data The JSON data to parse.
  571. * @note The received data will be handled asynchronously via the callback.
  572. */
  573. bool flipper_http_parse_json(const char* key, const char* json_data) {
  574. if(!key || !json_data) {
  575. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_parse_json.");
  576. return false;
  577. }
  578. char buffer[256];
  579. int ret =
  580. snprintf(buffer, sizeof(buffer), "[PARSE]{\"key\":\"%s\",\"json\":%s}", key, json_data);
  581. if(ret < 0 || ret >= (int)sizeof(buffer)) {
  582. FURI_LOG_E("FlipperHTTP", "Failed to format JSON parse command.");
  583. return false;
  584. }
  585. if(!flipper_http_send_data(buffer)) {
  586. FURI_LOG_E("FlipperHTTP", "Failed to send JSON parse command.");
  587. return false;
  588. }
  589. // The response will be handled asynchronously via the callback
  590. return true;
  591. }
  592. // Function to parse JSON array data
  593. /**
  594. * @brief Parse JSON array data.
  595. * @return true if the JSON array data was parsed successfully, false otherwise.
  596. * @param key The key to parse from the JSON array data.
  597. * @param index The index to parse from the JSON array data.
  598. * @param json_data The JSON array data to parse.
  599. * @note The received data will be handled asynchronously via the callback.
  600. */
  601. bool flipper_http_parse_json_array(const char* key, int index, const char* json_data) {
  602. if(!key || !json_data) {
  603. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_parse_json_array.");
  604. return false;
  605. }
  606. char buffer[256];
  607. int ret = snprintf(
  608. buffer,
  609. sizeof(buffer),
  610. "[PARSE/ARRAY]{\"key\":\"%s\",\"index\":%d,\"json\":%s}",
  611. key,
  612. index,
  613. json_data);
  614. if(ret < 0 || ret >= (int)sizeof(buffer)) {
  615. FURI_LOG_E("FlipperHTTP", "Failed to format JSON parse array command.");
  616. return false;
  617. }
  618. if(!flipper_http_send_data(buffer)) {
  619. FURI_LOG_E("FlipperHTTP", "Failed to send JSON parse array command.");
  620. return false;
  621. }
  622. // The response will be handled asynchronously via the callback
  623. return true;
  624. }
  625. // Function to scan for WiFi networks
  626. /**
  627. * @brief Send a command to scan for WiFi networks.
  628. * @return true if the request was successful, false otherwise.
  629. * @note The received data will be handled asynchronously via the callback.
  630. */
  631. bool flipper_http_scan_wifi() {
  632. const char* command = "[WIFI/SCAN]";
  633. if(!flipper_http_send_data(command)) {
  634. FURI_LOG_E("FlipperHTTP", "Failed to send WiFi scan command.");
  635. return false;
  636. }
  637. // The response will be handled asynchronously via the callback
  638. return true;
  639. }
  640. // Function to save WiFi settings (returns true if successful)
  641. /**
  642. * @brief Send a command to save WiFi settings.
  643. * @return true if the request was successful, false otherwise.
  644. * @note The received data will be handled asynchronously via the callback.
  645. */
  646. bool flipper_http_save_wifi(const char* ssid, const char* password) {
  647. if(!ssid || !password) {
  648. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_save_wifi.");
  649. return false;
  650. }
  651. char buffer[256];
  652. int ret = snprintf(
  653. buffer, sizeof(buffer), "[WIFI/SAVE]{\"ssid\":\"%s\",\"password\":\"%s\"}", ssid, password);
  654. if(ret < 0 || ret >= (int)sizeof(buffer)) {
  655. FURI_LOG_E("FlipperHTTP", "Failed to format WiFi save command.");
  656. return false;
  657. }
  658. if(!flipper_http_send_data(buffer)) {
  659. FURI_LOG_E("FlipperHTTP", "Failed to send WiFi save command.");
  660. return false;
  661. }
  662. // The response will be handled asynchronously via the callback
  663. return true;
  664. }
  665. // Function to get IP address of WiFi Devboard
  666. /**
  667. * @brief Send a command to get the IP address of the WiFi Devboard
  668. * @return true if the request was successful, false otherwise.
  669. * @note The received data will be handled asynchronously via the callback.
  670. */
  671. bool flipper_http_ip_address() {
  672. const char* command = "[IP/ADDRESS]";
  673. if(!flipper_http_send_data(command)) {
  674. FURI_LOG_E("FlipperHTTP", "Failed to send IP address command.");
  675. return false;
  676. }
  677. // The response will be handled asynchronously via the callback
  678. return true;
  679. }
  680. // Function to get IP address of the connected WiFi network
  681. /**
  682. * @brief Send a command to get the IP address of the connected WiFi network.
  683. * @return true if the request was successful, false otherwise.
  684. * @note The received data will be handled asynchronously via the callback.
  685. */
  686. bool flipper_http_ip_wifi() {
  687. const char* command = "[WIFI/IP]";
  688. if(!flipper_http_send_data(command)) {
  689. FURI_LOG_E("FlipperHTTP", "Failed to send WiFi IP command.");
  690. return false;
  691. }
  692. // The response will be handled asynchronously via the callback
  693. return true;
  694. }
  695. // Function to disconnect from WiFi (returns true if successful)
  696. /**
  697. * @brief Send a command to disconnect from WiFi.
  698. * @return true if the request was successful, false otherwise.
  699. * @note The received data will be handled asynchronously via the callback.
  700. */
  701. bool flipper_http_disconnect_wifi() {
  702. const char* command = "[WIFI/DISCONNECT]";
  703. if(!flipper_http_send_data(command)) {
  704. FURI_LOG_E("FlipperHTTP", "Failed to send WiFi disconnect command.");
  705. return false;
  706. }
  707. // The response will be handled asynchronously via the callback
  708. return true;
  709. }
  710. // Function to connect to WiFi (returns true if successful)
  711. /**
  712. * @brief Send a command to connect to WiFi.
  713. * @return true if the request was successful, false otherwise.
  714. * @note The received data will be handled asynchronously via the callback.
  715. */
  716. bool flipper_http_connect_wifi() {
  717. const char* command = "[WIFI/CONNECT]";
  718. if(!flipper_http_send_data(command)) {
  719. FURI_LOG_E("FlipperHTTP", "Failed to send WiFi connect command.");
  720. return false;
  721. }
  722. // The response will be handled asynchronously via the callback
  723. return true;
  724. }
  725. // Function to send a GET request
  726. /**
  727. * @brief Send a GET request to the specified URL.
  728. * @return true if the request was successful, false otherwise.
  729. * @param url The URL to send the GET request to.
  730. * @note The received data will be handled asynchronously via the callback.
  731. */
  732. bool flipper_http_get_request(const char* url) {
  733. if(!url) {
  734. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_get_request.");
  735. return false;
  736. }
  737. // Prepare GET request command
  738. char command[256];
  739. int ret = snprintf(command, sizeof(command), "[GET]%s", url);
  740. if(ret < 0 || ret >= (int)sizeof(command)) {
  741. FURI_LOG_E("FlipperHTTP", "Failed to format GET request command.");
  742. return false;
  743. }
  744. // Send GET request via UART
  745. if(!flipper_http_send_data(command)) {
  746. FURI_LOG_E("FlipperHTTP", "Failed to send GET request command.");
  747. return false;
  748. }
  749. // The response will be handled asynchronously via the callback
  750. return true;
  751. }
  752. // Function to send a GET request with headers
  753. /**
  754. * @brief Send a GET request to the specified URL.
  755. * @return true if the request was successful, false otherwise.
  756. * @param url The URL to send the GET request to.
  757. * @param headers The headers to send with the GET request.
  758. * @note The received data will be handled asynchronously via the callback.
  759. */
  760. bool flipper_http_get_request_with_headers(const char* url, const char* headers) {
  761. if(!url || !headers) {
  762. FURI_LOG_E(
  763. "FlipperHTTP", "Invalid arguments provided to flipper_http_get_request_with_headers.");
  764. return false;
  765. }
  766. // Prepare GET request command with headers
  767. char command[256];
  768. int ret = snprintf(
  769. command, sizeof(command), "[GET/HTTP]{\"url\":\"%s\",\"headers\":%s}", url, headers);
  770. if(ret < 0 || ret >= (int)sizeof(command)) {
  771. FURI_LOG_E("FlipperHTTP", "Failed to format GET request command with headers.");
  772. return false;
  773. }
  774. // Send GET request via UART
  775. if(!flipper_http_send_data(command)) {
  776. FURI_LOG_E("FlipperHTTP", "Failed to send GET request command with headers.");
  777. return false;
  778. }
  779. // The response will be handled asynchronously via the callback
  780. return true;
  781. }
  782. // Function to send a GET request with headers and return bytes
  783. /**
  784. * @brief Send a GET request to the specified URL.
  785. * @return true if the request was successful, false otherwise.
  786. * @param url The URL to send the GET request to.
  787. * @param headers The headers to send with the GET request.
  788. * @note The received data will be handled asynchronously via the callback.
  789. */
  790. bool flipper_http_get_request_bytes(const char* url, const char* headers) {
  791. if(!url || !headers) {
  792. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_get_request_bytes.");
  793. return false;
  794. }
  795. // Prepare GET request command with headers
  796. char command[256];
  797. int ret = snprintf(
  798. command, sizeof(command), "[GET/BYTES]{\"url\":\"%s\",\"headers\":%s}", url, headers);
  799. if(ret < 0 || ret >= (int)sizeof(command)) {
  800. FURI_LOG_E("FlipperHTTP", "Failed to format GET request command with headers.");
  801. return false;
  802. }
  803. // Send GET request via UART
  804. if(!flipper_http_send_data(command)) {
  805. FURI_LOG_E("FlipperHTTP", "Failed to send GET request command with headers.");
  806. return false;
  807. }
  808. // The response will be handled asynchronously via the callback
  809. return true;
  810. }
  811. // Function to send a POST request with headers
  812. /**
  813. * @brief Send a POST request to the specified URL.
  814. * @return true if the request was successful, false otherwise.
  815. * @param url The URL to send the POST request to.
  816. * @param headers The headers to send with the POST request.
  817. * @param data The data to send with the POST request.
  818. * @note The received data will be handled asynchronously via the callback.
  819. */
  820. bool flipper_http_post_request_with_headers(
  821. const char* url,
  822. const char* headers,
  823. const char* payload) {
  824. if(!url || !headers || !payload) {
  825. FURI_LOG_E(
  826. "FlipperHTTP",
  827. "Invalid arguments provided to flipper_http_post_request_with_headers.");
  828. return false;
  829. }
  830. // Prepare POST request command with headers and data
  831. char command[256];
  832. int ret = snprintf(
  833. command,
  834. sizeof(command),
  835. "[POST/HTTP]{\"url\":\"%s\",\"headers\":%s,\"payload\":%s}",
  836. url,
  837. headers,
  838. payload);
  839. if(ret < 0 || ret >= (int)sizeof(command)) {
  840. FURI_LOG_E("FlipperHTTP", "Failed to format POST request command with headers and data.");
  841. return false;
  842. }
  843. // Send POST request via UART
  844. if(!flipper_http_send_data(command)) {
  845. FURI_LOG_E("FlipperHTTP", "Failed to send POST request command with headers and data.");
  846. return false;
  847. }
  848. // The response will be handled asynchronously via the callback
  849. return true;
  850. }
  851. // Function to send a POST request with headers and return bytes
  852. /**
  853. * @brief Send a POST request to the specified URL.
  854. * @return true if the request was successful, false otherwise.
  855. * @param url The URL to send the POST request to.
  856. * @param headers The headers to send with the POST request.
  857. * @param payload The data to send with the POST request.
  858. * @note The received data will be handled asynchronously via the callback.
  859. */
  860. bool flipper_http_post_request_bytes(const char* url, const char* headers, const char* payload) {
  861. if(!url || !headers || !payload) {
  862. FURI_LOG_E(
  863. "FlipperHTTP", "Invalid arguments provided to flipper_http_post_request_bytes.");
  864. return false;
  865. }
  866. // Prepare POST request command with headers and data
  867. char command[256];
  868. int ret = snprintf(
  869. command,
  870. sizeof(command),
  871. "[POST/BYTES]{\"url\":\"%s\",\"headers\":%s,\"payload\":%s}",
  872. url,
  873. headers,
  874. payload);
  875. if(ret < 0 || ret >= (int)sizeof(command)) {
  876. FURI_LOG_E("FlipperHTTP", "Failed to format POST request command with headers and data.");
  877. return false;
  878. }
  879. // Send POST request via UART
  880. if(!flipper_http_send_data(command)) {
  881. FURI_LOG_E("FlipperHTTP", "Failed to send POST request command with headers and data.");
  882. return false;
  883. }
  884. // The response will be handled asynchronously via the callback
  885. return true;
  886. }
  887. // Function to send a PUT request with headers
  888. /**
  889. * @brief Send a PUT request to the specified URL.
  890. * @return true if the request was successful, false otherwise.
  891. * @param url The URL to send the PUT request to.
  892. * @param headers The headers to send with the PUT request.
  893. * @param data The data to send with the PUT request.
  894. * @note The received data will be handled asynchronously via the callback.
  895. */
  896. bool flipper_http_put_request_with_headers(
  897. const char* url,
  898. const char* headers,
  899. const char* payload) {
  900. if(!url || !headers || !payload) {
  901. FURI_LOG_E(
  902. "FlipperHTTP", "Invalid arguments provided to flipper_http_put_request_with_headers.");
  903. return false;
  904. }
  905. // Prepare PUT request command with headers and data
  906. char command[256];
  907. int ret = snprintf(
  908. command,
  909. sizeof(command),
  910. "[PUT/HTTP]{\"url\":\"%s\",\"headers\":%s,\"payload\":%s}",
  911. url,
  912. headers,
  913. payload);
  914. if(ret < 0 || ret >= (int)sizeof(command)) {
  915. FURI_LOG_E("FlipperHTTP", "Failed to format PUT request command with headers and data.");
  916. return false;
  917. }
  918. // Send PUT request via UART
  919. if(!flipper_http_send_data(command)) {
  920. FURI_LOG_E("FlipperHTTP", "Failed to send PUT request command with headers and data.");
  921. return false;
  922. }
  923. // The response will be handled asynchronously via the callback
  924. return true;
  925. }
  926. // Function to send a DELETE request with headers
  927. /**
  928. * @brief Send a DELETE request to the specified URL.
  929. * @return true if the request was successful, false otherwise.
  930. * @param url The URL to send the DELETE request to.
  931. * @param headers The headers to send with the DELETE request.
  932. * @param data The data to send with the DELETE request.
  933. * @note The received data will be handled asynchronously via the callback.
  934. */
  935. bool flipper_http_delete_request_with_headers(
  936. const char* url,
  937. const char* headers,
  938. const char* payload) {
  939. if(!url || !headers || !payload) {
  940. FURI_LOG_E(
  941. "FlipperHTTP",
  942. "Invalid arguments provided to flipper_http_delete_request_with_headers.");
  943. return false;
  944. }
  945. // Prepare DELETE request command with headers and data
  946. char command[256];
  947. int ret = snprintf(
  948. command,
  949. sizeof(command),
  950. "[DELETE/HTTP]{\"url\":\"%s\",\"headers\":%s,\"payload\":%s}",
  951. url,
  952. headers,
  953. payload);
  954. if(ret < 0 || ret >= (int)sizeof(command)) {
  955. FURI_LOG_E(
  956. "FlipperHTTP", "Failed to format DELETE request command with headers and data.");
  957. return false;
  958. }
  959. // Send DELETE request via UART
  960. if(!flipper_http_send_data(command)) {
  961. FURI_LOG_E("FlipperHTTP", "Failed to send DELETE request command with headers and data.");
  962. return false;
  963. }
  964. // The response will be handled asynchronously via the callback
  965. return true;
  966. }
  967. // Function to handle received data asynchronously
  968. /**
  969. * @brief Callback function to handle received data asynchronously.
  970. * @return void
  971. * @param line The received line.
  972. * @param context The context passed to the callback.
  973. * @note The received data will be handled asynchronously via the callback and handles the state of the UART.
  974. */
  975. void flipper_http_rx_callback(const char* line, void* context) {
  976. if(!line || !context) {
  977. FURI_LOG_E(HTTP_TAG, "Invalid arguments provided to flipper_http_rx_callback.");
  978. return;
  979. }
  980. // Trim the received line to check if it's empty
  981. char* trimmed_line = trim(line);
  982. if(trimmed_line != NULL && trimmed_line[0] != '\0') {
  983. // if the line is not [GET/END] or [POST/END] or [PUT/END] or [DELETE/END]
  984. if(strstr(trimmed_line, "[GET/END]") == NULL &&
  985. strstr(trimmed_line, "[POST/END]") == NULL &&
  986. strstr(trimmed_line, "[PUT/END]") == NULL &&
  987. strstr(trimmed_line, "[DELETE/END]") == NULL) {
  988. strncpy(fhttp.last_response, trimmed_line, RX_BUF_SIZE);
  989. }
  990. }
  991. free(trimmed_line); // Free the allocated memory for trimmed_line
  992. if(fhttp.state != INACTIVE && fhttp.state != ISSUE) {
  993. fhttp.state = RECEIVING;
  994. }
  995. // Uncomment below line to log the data received over UART
  996. FURI_LOG_I(HTTP_TAG, "Received UART line: %s", line);
  997. // Check if we've started receiving data from a GET request
  998. if(fhttp.started_receiving_get) {
  999. // Restart the timeout timer each time new data is received
  1000. furi_timer_restart(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1001. if(strstr(line, "[GET/END]") != NULL) {
  1002. FURI_LOG_I(HTTP_TAG, "GET request completed.");
  1003. // Stop the timer since we've completed the GET request
  1004. furi_timer_stop(fhttp.get_timeout_timer);
  1005. fhttp.started_receiving_get = false;
  1006. fhttp.just_started_get = false;
  1007. fhttp.state = IDLE;
  1008. fhttp.save_bytes = false;
  1009. fhttp.is_bytes_request = false;
  1010. fhttp.save_received_data = false;
  1011. return;
  1012. }
  1013. // Append the new line to the existing data
  1014. if(fhttp.save_received_data &&
  1015. !flipper_http_append_to_file(
  1016. line, strlen(line), !fhttp.just_started_get, fhttp.file_path)) {
  1017. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1018. fhttp.started_receiving_get = false;
  1019. fhttp.just_started_get = false;
  1020. fhttp.state = IDLE;
  1021. return;
  1022. }
  1023. if(!fhttp.just_started_get) {
  1024. fhttp.just_started_get = true;
  1025. }
  1026. return;
  1027. }
  1028. // Check if we've started receiving data from a POST request
  1029. else if(fhttp.started_receiving_post) {
  1030. // Restart the timeout timer each time new data is received
  1031. furi_timer_restart(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1032. if(strstr(line, "[POST/END]") != NULL) {
  1033. FURI_LOG_I(HTTP_TAG, "POST request completed.");
  1034. // Stop the timer since we've completed the POST request
  1035. furi_timer_stop(fhttp.get_timeout_timer);
  1036. fhttp.started_receiving_post = false;
  1037. fhttp.just_started_post = false;
  1038. fhttp.state = IDLE;
  1039. fhttp.save_bytes = false;
  1040. fhttp.is_bytes_request = false;
  1041. fhttp.save_received_data = false;
  1042. return;
  1043. }
  1044. // Append the new line to the existing data
  1045. if(fhttp.save_received_data &&
  1046. !flipper_http_append_to_file(
  1047. line, strlen(line), !fhttp.just_started_post, fhttp.file_path)) {
  1048. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1049. fhttp.started_receiving_post = false;
  1050. fhttp.just_started_post = false;
  1051. fhttp.state = IDLE;
  1052. return;
  1053. }
  1054. if(!fhttp.just_started_post) {
  1055. fhttp.just_started_post = true;
  1056. }
  1057. return;
  1058. }
  1059. // Check if we've started receiving data from a PUT request
  1060. else if(fhttp.started_receiving_put) {
  1061. // Restart the timeout timer each time new data is received
  1062. furi_timer_restart(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1063. if(strstr(line, "[PUT/END]") != NULL) {
  1064. FURI_LOG_I(HTTP_TAG, "PUT request completed.");
  1065. // Stop the timer since we've completed the PUT request
  1066. furi_timer_stop(fhttp.get_timeout_timer);
  1067. fhttp.started_receiving_put = false;
  1068. fhttp.just_started_put = false;
  1069. fhttp.state = IDLE;
  1070. fhttp.save_bytes = false;
  1071. fhttp.is_bytes_request = false;
  1072. fhttp.save_received_data = false;
  1073. return;
  1074. }
  1075. // Append the new line to the existing data
  1076. if(fhttp.save_received_data &&
  1077. !flipper_http_append_to_file(
  1078. line, strlen(line), !fhttp.just_started_put, fhttp.file_path)) {
  1079. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1080. fhttp.started_receiving_put = false;
  1081. fhttp.just_started_put = false;
  1082. fhttp.state = IDLE;
  1083. return;
  1084. }
  1085. if(!fhttp.just_started_put) {
  1086. fhttp.just_started_put = true;
  1087. }
  1088. return;
  1089. }
  1090. // Check if we've started receiving data from a DELETE request
  1091. else if(fhttp.started_receiving_delete) {
  1092. // Restart the timeout timer each time new data is received
  1093. furi_timer_restart(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1094. if(strstr(line, "[DELETE/END]") != NULL) {
  1095. FURI_LOG_I(HTTP_TAG, "DELETE request completed.");
  1096. // Stop the timer since we've completed the DELETE request
  1097. furi_timer_stop(fhttp.get_timeout_timer);
  1098. fhttp.started_receiving_delete = false;
  1099. fhttp.just_started_delete = false;
  1100. fhttp.state = IDLE;
  1101. fhttp.save_bytes = false;
  1102. fhttp.is_bytes_request = false;
  1103. fhttp.save_received_data = false;
  1104. return;
  1105. }
  1106. // Append the new line to the existing data
  1107. if(fhttp.save_received_data &&
  1108. !flipper_http_append_to_file(
  1109. line, strlen(line), !fhttp.just_started_delete, fhttp.file_path)) {
  1110. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1111. fhttp.started_receiving_delete = false;
  1112. fhttp.just_started_delete = false;
  1113. fhttp.state = IDLE;
  1114. return;
  1115. }
  1116. if(!fhttp.just_started_delete) {
  1117. fhttp.just_started_delete = true;
  1118. }
  1119. return;
  1120. }
  1121. // Handle different types of responses
  1122. if(strstr(line, "[SUCCESS]") != NULL || strstr(line, "[CONNECTED]") != NULL) {
  1123. FURI_LOG_I(HTTP_TAG, "Operation succeeded.");
  1124. } else if(strstr(line, "[INFO]") != NULL) {
  1125. FURI_LOG_I(HTTP_TAG, "Received info: %s", line);
  1126. if(fhttp.state == INACTIVE && strstr(line, "[INFO] Already connected to Wifi.") != NULL) {
  1127. fhttp.state = IDLE;
  1128. }
  1129. } else if(strstr(line, "[GET/SUCCESS]") != NULL) {
  1130. FURI_LOG_I(HTTP_TAG, "GET request succeeded.");
  1131. fhttp.started_receiving_get = true;
  1132. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1133. fhttp.state = RECEIVING;
  1134. // for GET request, save data only if it's a bytes request
  1135. fhttp.save_bytes = fhttp.is_bytes_request;
  1136. return;
  1137. } else if(strstr(line, "[POST/SUCCESS]") != NULL) {
  1138. FURI_LOG_I(HTTP_TAG, "POST request succeeded.");
  1139. fhttp.started_receiving_post = true;
  1140. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1141. fhttp.state = RECEIVING;
  1142. // for POST request, save data only if it's a bytes request
  1143. fhttp.save_bytes = fhttp.is_bytes_request;
  1144. return;
  1145. } else if(strstr(line, "[PUT/SUCCESS]") != NULL) {
  1146. FURI_LOG_I(HTTP_TAG, "PUT request succeeded.");
  1147. fhttp.started_receiving_put = true;
  1148. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1149. fhttp.state = RECEIVING;
  1150. return;
  1151. } else if(strstr(line, "[DELETE/SUCCESS]") != NULL) {
  1152. FURI_LOG_I(HTTP_TAG, "DELETE request succeeded.");
  1153. fhttp.started_receiving_delete = true;
  1154. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1155. fhttp.state = RECEIVING;
  1156. return;
  1157. } else if(strstr(line, "[DISCONNECTED]") != NULL) {
  1158. FURI_LOG_I(HTTP_TAG, "WiFi disconnected successfully.");
  1159. } else if(strstr(line, "[ERROR]") != NULL) {
  1160. FURI_LOG_E(HTTP_TAG, "Received error: %s", line);
  1161. fhttp.state = ISSUE;
  1162. return;
  1163. } else if(strstr(line, "[PONG]") != NULL) {
  1164. FURI_LOG_I(HTTP_TAG, "Received PONG response: Wifi Dev Board is still alive.");
  1165. // send command to connect to WiFi
  1166. if(fhttp.state == INACTIVE) {
  1167. fhttp.state = IDLE;
  1168. return;
  1169. }
  1170. }
  1171. if(fhttp.state == INACTIVE && strstr(line, "[PONG]") != NULL) {
  1172. fhttp.state = IDLE;
  1173. } else if(fhttp.state == INACTIVE && strstr(line, "[PONG]") == NULL) {
  1174. fhttp.state = INACTIVE;
  1175. } else {
  1176. fhttp.state = IDLE;
  1177. }
  1178. }
  1179. // Function to trim leading and trailing spaces and newlines from a constant string
  1180. char* trim(const char* str) {
  1181. const char* end;
  1182. char* trimmed_str;
  1183. size_t len;
  1184. // Trim leading space
  1185. while(isspace((unsigned char)*str))
  1186. str++;
  1187. // All spaces?
  1188. if(*str == 0) return strdup(""); // Return an empty string if all spaces
  1189. // Trim trailing space
  1190. end = str + strlen(str) - 1;
  1191. while(end > str && isspace((unsigned char)*end))
  1192. end--;
  1193. // Set length for the trimmed string
  1194. len = end - str + 1;
  1195. // Allocate space for the trimmed string and null terminator
  1196. trimmed_str = (char*)malloc(len + 1);
  1197. if(trimmed_str == NULL) {
  1198. return NULL; // Handle memory allocation failure
  1199. }
  1200. // Copy the trimmed part of the string into trimmed_str
  1201. strncpy(trimmed_str, str, len);
  1202. trimmed_str[len] = '\0'; // Null terminate the string
  1203. return trimmed_str;
  1204. }
  1205. /**
  1206. * @brief Process requests and parse JSON data asynchronously
  1207. * @param http_request The function to send the request
  1208. * @param parse_json The function to parse the JSON
  1209. * @return true if successful, false otherwise
  1210. */
  1211. bool flipper_http_process_response_async(bool (*http_request)(void), bool (*parse_json)(void)) {
  1212. if(http_request()) // start the async request
  1213. {
  1214. furi_timer_start(fhttp.get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1215. fhttp.state = RECEIVING;
  1216. } else {
  1217. FURI_LOG_E(HTTP_TAG, "Failed to send request");
  1218. return false;
  1219. }
  1220. while(fhttp.state == RECEIVING && furi_timer_is_running(fhttp.get_timeout_timer) > 0) {
  1221. // Wait for the request to be received
  1222. furi_delay_ms(100);
  1223. }
  1224. furi_timer_stop(fhttp.get_timeout_timer);
  1225. if(!parse_json()) // parse the JSON before switching to the view (synchonous)
  1226. {
  1227. FURI_LOG_E(HTTP_TAG, "Failed to parse the JSON...");
  1228. return false;
  1229. }
  1230. return true;
  1231. }
  1232. #endif // FLIPPER_HTTP_H