flipper_http.c 50 KB

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