flipper_http.c 50 KB

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