flipper_http.c 47 KB

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