flipper_http.h 53 KB

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