flipper_http.h 51 KB

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