flipper_http.c 50 KB

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