flipper_http.c 48 KB

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