flipper_http.h 52 KB

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