flipper_http.c 52 KB

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