flipper_http.h 52 KB

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