flipper_http.c 49 KB

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