flipper_http.c 50 KB

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