flipper_http.c 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576
  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. size_t file_size = storage_file_size(file);
  401. // final memory check
  402. if (memmgr_heap_get_max_free_block() < file_size)
  403. {
  404. FURI_LOG_E(HTTP_TAG, "Not enough heap to read file.");
  405. storage_file_close(file);
  406. storage_file_free(file);
  407. furi_record_close(RECORD_STORAGE);
  408. return NULL;
  409. }
  410. // Allocate a buffer to hold the read data
  411. uint8_t *buffer = (uint8_t *)malloc(file_size);
  412. if (!buffer)
  413. {
  414. FURI_LOG_E(HTTP_TAG, "Failed to allocate buffer");
  415. storage_file_close(file);
  416. storage_file_free(file);
  417. furi_record_close(RECORD_STORAGE);
  418. return NULL;
  419. }
  420. // Allocate a FuriString to hold the received data
  421. FuriString *str_result = furi_string_alloc();
  422. if (!str_result)
  423. {
  424. FURI_LOG_E(HTTP_TAG, "Failed to allocate FuriString");
  425. storage_file_close(file);
  426. storage_file_free(file);
  427. furi_record_close(RECORD_STORAGE);
  428. return NULL;
  429. }
  430. // Reset the FuriString to ensure it's empty before reading
  431. furi_string_reset(str_result);
  432. // Read data into the buffer
  433. size_t read_count = storage_file_read(file, buffer, MAX_FILE_SHOW);
  434. if (storage_file_get_error(file) != FSE_OK)
  435. {
  436. FURI_LOG_E(HTTP_TAG, "Error reading from file.");
  437. furi_string_free(str_result);
  438. storage_file_close(file);
  439. storage_file_free(file);
  440. furi_record_close(RECORD_STORAGE);
  441. return NULL;
  442. }
  443. // Append each byte to the FuriString
  444. for (size_t i = 0; i < read_count; i++)
  445. {
  446. furi_string_push_back(str_result, buffer[i]);
  447. }
  448. // Clean up
  449. storage_file_close(file);
  450. storage_file_free(file);
  451. furi_record_close(RECORD_STORAGE);
  452. free(buffer);
  453. return str_result;
  454. }
  455. /**
  456. * @brief Load data from a file with a size limit.
  457. * @return The loaded data as a FuriString.
  458. * @param file_path The path to the file to load.
  459. * @param limit The size limit for loading data.
  460. */
  461. FuriString *flipper_http_load_from_file_with_limit(char *file_path, size_t limit)
  462. {
  463. if (memmgr_heap_get_max_free_block() < limit)
  464. {
  465. FURI_LOG_E(HTTP_TAG, "Not enough heap to read file.");
  466. return NULL;
  467. }
  468. // Open the storage record
  469. Storage *storage = furi_record_open(RECORD_STORAGE);
  470. if (!storage)
  471. {
  472. FURI_LOG_E(HTTP_TAG, "Failed to open storage record");
  473. return NULL;
  474. }
  475. // Allocate a file handle
  476. File *file = storage_file_alloc(storage);
  477. if (!file)
  478. {
  479. FURI_LOG_E(HTTP_TAG, "Failed to allocate storage file");
  480. furi_record_close(RECORD_STORAGE);
  481. return NULL;
  482. }
  483. // Open the file for reading
  484. if (!storage_file_open(file, file_path, FSAM_READ, FSOM_OPEN_EXISTING))
  485. {
  486. storage_file_free(file);
  487. furi_record_close(RECORD_STORAGE);
  488. FURI_LOG_E(HTTP_TAG, "Failed to open file for reading: %s", file_path);
  489. return NULL;
  490. }
  491. size_t file_size = storage_file_size(file);
  492. if (file_size > limit)
  493. {
  494. FURI_LOG_E(HTTP_TAG, "File size exceeds limit: %d > %d", file_size, limit);
  495. storage_file_close(file);
  496. storage_file_free(file);
  497. furi_record_close(RECORD_STORAGE);
  498. return NULL;
  499. }
  500. // final memory check
  501. if (memmgr_heap_get_max_free_block() < file_size)
  502. {
  503. FURI_LOG_E(HTTP_TAG, "Not enough heap to read file.");
  504. storage_file_close(file);
  505. storage_file_free(file);
  506. furi_record_close(RECORD_STORAGE);
  507. return NULL;
  508. }
  509. // Allocate a buffer to hold the read data
  510. uint8_t *buffer = (uint8_t *)malloc(file_size);
  511. if (!buffer)
  512. {
  513. FURI_LOG_E(HTTP_TAG, "Failed to allocate buffer");
  514. storage_file_close(file);
  515. storage_file_free(file);
  516. furi_record_close(RECORD_STORAGE);
  517. return NULL;
  518. }
  519. // Allocate a FuriString with preallocated capacity
  520. FuriString *str_result = furi_string_alloc();
  521. if (!str_result)
  522. {
  523. FURI_LOG_E(HTTP_TAG, "Failed to allocate FuriString");
  524. free(buffer);
  525. storage_file_close(file);
  526. storage_file_free(file);
  527. furi_record_close(RECORD_STORAGE);
  528. return NULL;
  529. }
  530. furi_string_reserve(str_result, file_size);
  531. // Read data into the buffer
  532. size_t read_count = storage_file_read(file, buffer, file_size);
  533. if (storage_file_get_error(file) != FSE_OK)
  534. {
  535. FURI_LOG_E(HTTP_TAG, "Error reading from file.");
  536. furi_string_free(str_result);
  537. free(buffer);
  538. storage_file_close(file);
  539. storage_file_free(file);
  540. furi_record_close(RECORD_STORAGE);
  541. return NULL;
  542. }
  543. if (read_count == 0)
  544. {
  545. FURI_LOG_E(HTTP_TAG, "No data read from file.");
  546. furi_string_free(str_result);
  547. free(buffer);
  548. storage_file_close(file);
  549. storage_file_free(file);
  550. furi_record_close(RECORD_STORAGE);
  551. return NULL;
  552. }
  553. // Append the entire buffer to FuriString in one operation
  554. furi_string_cat_str(str_result, (char *)buffer);
  555. // Clean up
  556. storage_file_close(file);
  557. storage_file_free(file);
  558. furi_record_close(RECORD_STORAGE);
  559. free(buffer);
  560. return str_result;
  561. }
  562. /**
  563. * @brief Perform a task while displaying a loading screen
  564. * @param fhttp The FlipperHTTP context
  565. * @param http_request The function to send the request
  566. * @param parse_response The function to parse the response
  567. * @param success_view_id The view ID to switch to on success
  568. * @param failure_view_id The view ID to switch to on failure
  569. * @param view_dispatcher The view dispatcher to use
  570. * @return
  571. */
  572. void flipper_http_loading_task(FlipperHTTP *fhttp,
  573. bool (*http_request)(void),
  574. bool (*parse_response)(void),
  575. uint32_t success_view_id,
  576. uint32_t failure_view_id,
  577. ViewDispatcher **view_dispatcher)
  578. {
  579. if (!fhttp)
  580. {
  581. FURI_LOG_E(HTTP_TAG, "Failed to get context.");
  582. return;
  583. }
  584. if (fhttp->state == INACTIVE)
  585. {
  586. view_dispatcher_switch_to_view(*view_dispatcher, failure_view_id);
  587. return;
  588. }
  589. Loading *loading;
  590. int32_t loading_view_id = 987654321; // Random ID
  591. loading = loading_alloc();
  592. if (!loading)
  593. {
  594. FURI_LOG_E(HTTP_TAG, "Failed to allocate loading");
  595. view_dispatcher_switch_to_view(*view_dispatcher, failure_view_id);
  596. return;
  597. }
  598. view_dispatcher_add_view(*view_dispatcher, loading_view_id, loading_get_view(loading));
  599. // Switch to the loading view
  600. view_dispatcher_switch_to_view(*view_dispatcher, loading_view_id);
  601. // Make the request
  602. if (!flipper_http_process_response_async(fhttp, http_request, parse_response))
  603. {
  604. FURI_LOG_E(HTTP_TAG, "Failed to make request");
  605. view_dispatcher_switch_to_view(*view_dispatcher, failure_view_id);
  606. view_dispatcher_remove_view(*view_dispatcher, loading_view_id);
  607. loading_free(loading);
  608. return;
  609. }
  610. // Switch to the success view
  611. view_dispatcher_switch_to_view(*view_dispatcher, success_view_id);
  612. view_dispatcher_remove_view(*view_dispatcher, loading_view_id);
  613. loading_free(loading); // comment this out if you experience a freeze
  614. }
  615. /**
  616. * @brief Parse JSON data.
  617. * @return true if the JSON data was parsed successfully, false otherwise.
  618. * @param fhttp The FlipperHTTP context
  619. * @param key The key to parse from the JSON data.
  620. * @param json_data The JSON data to parse.
  621. * @note The received data will be handled asynchronously via the callback.
  622. */
  623. bool flipper_http_parse_json(FlipperHTTP *fhttp, const char *key, const char *json_data)
  624. {
  625. if (!fhttp)
  626. {
  627. FURI_LOG_E(HTTP_TAG, "Failed to get context.");
  628. return false;
  629. }
  630. if (!key || !json_data)
  631. {
  632. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_parse_json.");
  633. return false;
  634. }
  635. char buffer[512];
  636. int ret =
  637. snprintf(buffer, sizeof(buffer), "[PARSE]{\"key\":\"%s\",\"json\":%s}", key, json_data);
  638. if (ret < 0 || ret >= (int)sizeof(buffer))
  639. {
  640. FURI_LOG_E("FlipperHTTP", "Failed to format JSON parse command.");
  641. return false;
  642. }
  643. return flipper_http_send_data(fhttp, buffer);
  644. }
  645. /**
  646. * @brief Parse JSON array data.
  647. * @return true if the JSON array data was parsed successfully, false otherwise.
  648. * @param fhttp The FlipperHTTP context
  649. * @param key The key to parse from the JSON array data.
  650. * @param index The index to parse from the JSON array data.
  651. * @param json_data The JSON array data to parse.
  652. * @note The received data will be handled asynchronously via the callback.
  653. */
  654. bool flipper_http_parse_json_array(FlipperHTTP *fhttp, const char *key, int index, const char *json_data)
  655. {
  656. if (!fhttp)
  657. {
  658. FURI_LOG_E(HTTP_TAG, "Failed to get context.");
  659. return false;
  660. }
  661. if (!key || !json_data)
  662. {
  663. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_parse_json_array.");
  664. return false;
  665. }
  666. char buffer[512];
  667. int ret = snprintf(
  668. buffer,
  669. sizeof(buffer),
  670. "[PARSE/ARRAY]{\"key\":\"%s\",\"index\":%d,\"json\":%s}",
  671. key,
  672. index,
  673. json_data);
  674. if (ret < 0 || ret >= (int)sizeof(buffer))
  675. {
  676. FURI_LOG_E("FlipperHTTP", "Failed to format JSON parse array command.");
  677. return false;
  678. }
  679. return flipper_http_send_data(fhttp, buffer);
  680. }
  681. /**
  682. * @brief Process requests and parse JSON data asynchronously
  683. * @param fhttp The FlipperHTTP context
  684. * @param http_request The function to send the request
  685. * @param parse_json The function to parse the JSON
  686. * @return true if successful, false otherwise
  687. */
  688. bool flipper_http_process_response_async(FlipperHTTP *fhttp, bool (*http_request)(void), bool (*parse_json)(void))
  689. {
  690. if (!fhttp)
  691. {
  692. FURI_LOG_E(HTTP_TAG, "Failed to get context.");
  693. return false;
  694. }
  695. if (http_request()) // start the async request
  696. {
  697. furi_timer_start(fhttp->get_timeout_timer, TIMEOUT_DURATION_TICKS);
  698. fhttp->state = RECEIVING;
  699. }
  700. else
  701. {
  702. FURI_LOG_E(HTTP_TAG, "Failed to send request");
  703. return false;
  704. }
  705. while (fhttp->state == RECEIVING && furi_timer_is_running(fhttp->get_timeout_timer) > 0)
  706. {
  707. // Wait for the request to be received
  708. furi_delay_ms(100);
  709. }
  710. furi_timer_stop(fhttp->get_timeout_timer);
  711. if (!parse_json()) // parse the JSON before switching to the view (synchonous)
  712. {
  713. FURI_LOG_E(HTTP_TAG, "Failed to parse the JSON...");
  714. return false;
  715. }
  716. return true;
  717. }
  718. /**
  719. * @brief Send a request to the specified URL.
  720. * @return true if the request was successful, false otherwise.
  721. * @param fhttp The FlipperHTTP context
  722. * @param method The HTTP method to use.
  723. * @param url The URL to send the request to.
  724. * @param headers The headers to send with the request.
  725. * @param payload The data to send with the request.
  726. * @note The received data will be handled asynchronously via the callback.
  727. */
  728. bool flipper_http_request(FlipperHTTP *fhttp, HTTPMethod method, const char *url, const char *headers, const char *payload)
  729. {
  730. if (!fhttp)
  731. {
  732. FURI_LOG_E("FlipperHTTP", "Failed to get context.");
  733. return false;
  734. }
  735. if (!url)
  736. {
  737. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_request.");
  738. return false;
  739. }
  740. // Prepare request command
  741. char command[512];
  742. int ret = 0;
  743. switch (method)
  744. {
  745. case GET:
  746. if (headers && strlen(headers) > 0)
  747. ret = snprintf(command, sizeof(command), "[GET/HTTP]{\"url\":\"%s\",\"headers\":%s}", url, headers);
  748. else
  749. ret = snprintf(command, sizeof(command), "[GET]%s", url);
  750. break;
  751. case POST:
  752. if (!headers || !payload)
  753. {
  754. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_request.");
  755. return false;
  756. }
  757. ret = snprintf(command, sizeof(command), "[POST/HTTP]{\"url\":\"%s\",\"headers\":%s,\"payload\":%s}", url, headers, payload);
  758. break;
  759. case PUT:
  760. if (!headers || !payload)
  761. {
  762. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_request.");
  763. return false;
  764. }
  765. ret = snprintf(command, sizeof(command), "[PUT/HTTP]{\"url\":\"%s\",\"headers\":%s,\"payload\":%s}", url, headers, payload);
  766. break;
  767. case DELETE:
  768. if (!headers || !payload)
  769. {
  770. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_request.");
  771. return false;
  772. }
  773. ret = snprintf(command, sizeof(command), "[DELETE/HTTP]{\"url\":\"%s\",\"headers\":%s,\"payload\":%s}", url, headers, payload);
  774. break;
  775. case BYTES:
  776. if (!headers)
  777. {
  778. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_request.");
  779. return false;
  780. }
  781. if (strlen(fhttp->file_path) == 0)
  782. {
  783. FURI_LOG_E("FlipperHTTP", "File path is not set.");
  784. return false;
  785. }
  786. fhttp->save_received_data = false;
  787. fhttp->is_bytes_request = true;
  788. ret = snprintf(command, sizeof(command), "[GET/BYTES]{\"url\":\"%s\",\"headers\":%s}", url, headers);
  789. break;
  790. case BYTES_POST:
  791. if (!headers || !payload)
  792. {
  793. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_request.");
  794. return false;
  795. }
  796. if (strlen(fhttp->file_path) == 0)
  797. {
  798. FURI_LOG_E("FlipperHTTP", "File path is not set.");
  799. return false;
  800. }
  801. fhttp->save_received_data = false;
  802. fhttp->is_bytes_request = true;
  803. ret = snprintf(command, sizeof(command), "[POST/BYTES]{\"url\":\"%s\",\"headers\":%s,\"payload\":%s}", url, headers, payload);
  804. break;
  805. }
  806. // check if ret is valid
  807. if (ret < 0 || ret >= (int)sizeof(command))
  808. {
  809. FURI_LOG_E("FlipperHTTP", "Failed to format request command.");
  810. return false;
  811. }
  812. // set method
  813. fhttp->method = method;
  814. // Send request via UART
  815. return flipper_http_send_data(fhttp, command);
  816. }
  817. /**
  818. * @brief Send a command to save WiFi settings.
  819. * @return true if the request was successful, false otherwise.
  820. * @param fhttp The FlipperHTTP context
  821. * @note The received data will be handled asynchronously via the callback.
  822. */
  823. bool flipper_http_save_wifi(FlipperHTTP *fhttp, const char *ssid, const char *password)
  824. {
  825. if (!fhttp)
  826. {
  827. FURI_LOG_E(HTTP_TAG, "Failed to get context.");
  828. return false;
  829. }
  830. if (!ssid || !password)
  831. {
  832. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_save_wifi.");
  833. return false;
  834. }
  835. char buffer[256];
  836. int ret = snprintf(
  837. buffer, sizeof(buffer), "[WIFI/SAVE]{\"ssid\":\"%s\",\"password\":\"%s\"}", ssid, password);
  838. if (ret < 0 || ret >= (int)sizeof(buffer))
  839. {
  840. FURI_LOG_E("FlipperHTTP", "Failed to format WiFi save command.");
  841. return false;
  842. }
  843. return flipper_http_send_data(fhttp, buffer);
  844. }
  845. /**
  846. * @brief Send a command.
  847. * @return true if the request was successful, false otherwise.
  848. * @param fhttp The FlipperHTTP context
  849. * @param command The command to send.
  850. * @note The received data will be handled asynchronously via the callback.
  851. */
  852. bool flipper_http_send_command(FlipperHTTP *fhttp, HTTPCommand command)
  853. {
  854. if (!fhttp)
  855. {
  856. FURI_LOG_E(HTTP_TAG, "flipper_http_send_command: Failed to get context.");
  857. return false;
  858. }
  859. switch (command)
  860. {
  861. case HTTP_CMD_WIFI_CONNECT:
  862. return flipper_http_send_data(fhttp, "[WIFI/CONNECT]");
  863. case HTTP_CMD_WIFI_DISCONNECT:
  864. return flipper_http_send_data(fhttp, "[WIFI/DISCONNECT]");
  865. case HTTP_CMD_IP_ADDRESS:
  866. return flipper_http_send_data(fhttp, "[IP/ADDRESS]");
  867. case HTTP_CMD_IP_WIFI:
  868. return flipper_http_send_data(fhttp, "[WIFI/IP]");
  869. case HTTP_CMD_SCAN:
  870. fhttp->method = GET;
  871. return flipper_http_send_data(fhttp, "[WIFI/SCAN]");
  872. case HTTP_CMD_LIST_COMMANDS:
  873. return flipper_http_send_data(fhttp, "[LIST]");
  874. case HTTP_CMD_LED_ON:
  875. return flipper_http_send_data(fhttp, "[LED/ON]");
  876. case HTTP_CMD_LED_OFF:
  877. return flipper_http_send_data(fhttp, "[LED/OFF]");
  878. case HTTP_CMD_PING:
  879. fhttp->state = INACTIVE; // set state as INACTIVE to be made IDLE if PONG is received
  880. return flipper_http_send_data(fhttp, "[PING]");
  881. case HTTP_CMD_REBOOT:
  882. return flipper_http_send_data(fhttp, "[REBOOT]");
  883. default:
  884. FURI_LOG_E(HTTP_TAG, "Invalid command.");
  885. return false;
  886. }
  887. }
  888. /**
  889. * @brief Send data over UART with newline termination.
  890. * @return true if the data was sent successfully, false otherwise.
  891. * @param fhttp The FlipperHTTP context
  892. * @param data The data to send over UART.
  893. * @note The data will be sent over UART with a newline character appended.
  894. */
  895. bool flipper_http_send_data(FlipperHTTP *fhttp, const char *data)
  896. {
  897. if (!fhttp)
  898. {
  899. FURI_LOG_E(HTTP_TAG, "Failed to get context.");
  900. return false;
  901. }
  902. size_t data_length = strlen(data);
  903. if (data_length == 0)
  904. {
  905. FURI_LOG_E("FlipperHTTP", "Attempted to send empty data.");
  906. return false;
  907. }
  908. // Create a buffer with data + '\n'
  909. size_t send_length = data_length + 1; // +1 for '\n'
  910. if (send_length > 512)
  911. { // Ensure buffer size is sufficient
  912. FURI_LOG_E("FlipperHTTP", "Data too long to send over FHTTP->");
  913. return false;
  914. }
  915. char send_buffer[513]; // 512 + 1 for safety
  916. strncpy(send_buffer, data, 512);
  917. send_buffer[data_length] = '\n'; // Append newline
  918. send_buffer[data_length + 1] = '\0'; // Null-terminate
  919. if (fhttp->state == INACTIVE && ((strstr(send_buffer, "[PING]") == NULL) &&
  920. (strstr(send_buffer, "[WIFI/CONNECT]") == NULL)))
  921. {
  922. FURI_LOG_E("FlipperHTTP", "Cannot send data while INACTIVE.");
  923. fhttp->last_response = "Cannot send data while INACTIVE.";
  924. return false;
  925. }
  926. fhttp->state = SENDING;
  927. furi_hal_serial_tx(fhttp->serial_handle, (const uint8_t *)send_buffer, send_length);
  928. // FURI_LOG_I("FlipperHTTP", "Sent data over UART: %s", send_buffer);
  929. fhttp->state = IDLE;
  930. return true;
  931. }
  932. // Function to set content length and status code
  933. static void set_header(FlipperHTTP *fhttp)
  934. {
  935. // example response: [GET/SUCCESS]{"Status-Code":200,"Content-Length":12528}
  936. if (!fhttp)
  937. {
  938. FURI_LOG_E(HTTP_TAG, "Invalid arguments provided to set_header.");
  939. return;
  940. }
  941. size_t error_size = -1;
  942. // reset values
  943. fhttp->content_length = 0;
  944. fhttp->status_code = 0;
  945. fhttp->bytes_received = 0;
  946. FuriString *furi_string = furi_string_alloc_set_str(fhttp->last_response);
  947. if (!furi_string)
  948. {
  949. FURI_LOG_E(HTTP_TAG, "Failed to allocate memory for furi_string.");
  950. return;
  951. }
  952. size_t status_code_start = furi_string_search_str(furi_string, "\"Status-Code\":", 0);
  953. if (status_code_start != error_size)
  954. {
  955. // trim everything, including the status code and colon
  956. furi_string_right(furi_string, status_code_start + strlen("\"Status-Code\":"));
  957. // find comma (we have this currently: 200,"Content-Length":12528})
  958. size_t comma = furi_string_search_str(furi_string, ",\"Content-Length\":", 0);
  959. if (comma == error_size)
  960. {
  961. FURI_LOG_E(HTTP_TAG, "Failed to find comma in furi_string.");
  962. furi_string_free(furi_string);
  963. return;
  964. }
  965. // set status code
  966. FuriString *status_code_str = furi_string_alloc();
  967. // dest, src, start, length
  968. furi_string_set_n(status_code_str, furi_string, 0, comma);
  969. fhttp->status_code = atoi(furi_string_get_cstr(status_code_str));
  970. furi_string_free(status_code_str);
  971. // trim left to remove everything before the content length
  972. furi_string_right(furi_string, comma + strlen(",\"Content-Length\":"));
  973. // find closing brace (we have this currently: 12528})
  974. size_t closing_brace = furi_string_search_str(furi_string, "}", 0);
  975. if (closing_brace == error_size)
  976. {
  977. FURI_LOG_E(HTTP_TAG, "Failed to find closing brace in furi_string.");
  978. furi_string_free(furi_string);
  979. return;
  980. }
  981. // set content length
  982. FuriString *content_length_str = furi_string_alloc();
  983. // dest, src, start, length
  984. furi_string_set_n(content_length_str, furi_string, 0, closing_brace);
  985. fhttp->content_length = atoi(furi_string_get_cstr(content_length_str));
  986. furi_string_free(content_length_str);
  987. }
  988. // print results
  989. // FURI_LOG_I(HTTP_TAG, "Status Code: %d", fhttp->status_code);
  990. // FURI_LOG_I(HTTP_TAG, "Content Length: %d", fhttp->content_length);
  991. // free the furi_string
  992. furi_string_free(furi_string);
  993. }
  994. // Function to trim leading and trailing spaces and newlines from a constant string
  995. static char *trim(const char *str)
  996. {
  997. const char *end;
  998. char *trimmed_str;
  999. size_t len;
  1000. // Trim leading space
  1001. while (isspace((unsigned char)*str))
  1002. str++;
  1003. // All spaces?
  1004. if (*str == 0)
  1005. return strdup(""); // Return an empty string if all spaces
  1006. // Trim trailing space
  1007. end = str + strlen(str) - 1;
  1008. while (end > str && isspace((unsigned char)*end))
  1009. end--;
  1010. // Set length for the trimmed string
  1011. len = end - str + 1;
  1012. // Allocate space for the trimmed string and null terminator
  1013. trimmed_str = (char *)malloc(len + 1);
  1014. if (trimmed_str == NULL)
  1015. {
  1016. return NULL; // Handle memory allocation failure
  1017. }
  1018. // Copy the trimmed part of the string into trimmed_str
  1019. strncpy(trimmed_str, str, len);
  1020. trimmed_str[len] = '\0'; // Null terminate the string
  1021. return trimmed_str;
  1022. }
  1023. /**
  1024. * @brief Callback function to handle received data asynchronously.
  1025. * @return void
  1026. * @param line The received line.
  1027. * @param context The FlipperHTTP context.
  1028. * @note The received data will be handled asynchronously via the callback and handles the state of the UART.
  1029. */
  1030. static void flipper_http_rx_callback(const char *line, void *context)
  1031. {
  1032. FlipperHTTP *fhttp = (FlipperHTTP *)context;
  1033. if (!fhttp)
  1034. {
  1035. FURI_LOG_E(HTTP_TAG, "Failed to get context.");
  1036. return;
  1037. }
  1038. if (!line)
  1039. {
  1040. FURI_LOG_E(HTTP_TAG, "Invalid arguments provided to flipper_http_rx_callback.");
  1041. return;
  1042. }
  1043. // Trim the received line to check if it's empty
  1044. char *trimmed_line = trim(line);
  1045. if (trimmed_line != NULL && trimmed_line[0] != '\0')
  1046. {
  1047. // if the line is not [GET/END] or [POST/END] or [PUT/END] or [DELETE/END]
  1048. if (strstr(trimmed_line, "[GET/END]") == NULL &&
  1049. strstr(trimmed_line, "[POST/END]") == NULL &&
  1050. strstr(trimmed_line, "[PUT/END]") == NULL &&
  1051. strstr(trimmed_line, "[DELETE/END]") == NULL)
  1052. {
  1053. strncpy(fhttp->last_response, trimmed_line, RX_BUF_SIZE);
  1054. }
  1055. }
  1056. free(trimmed_line); // Free the allocated memory for trimmed_line
  1057. if (fhttp->state != INACTIVE && fhttp->state != ISSUE)
  1058. {
  1059. fhttp->state = RECEIVING;
  1060. }
  1061. // Uncomment below line to log the data received over UART
  1062. // FURI_LOG_I(HTTP_TAG, "Received UART line: %s", line);
  1063. // Check if we've started receiving data from a GET request
  1064. if (fhttp->started_receiving && (fhttp->method == GET || fhttp->method == BYTES))
  1065. {
  1066. // Restart the timeout timer each time new data is received
  1067. furi_timer_restart(fhttp->get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1068. if (strstr(line, "[GET/END]") != NULL)
  1069. {
  1070. FURI_LOG_I(HTTP_TAG, "GET request completed.");
  1071. // Stop the timer since we've completed the GET request
  1072. furi_timer_stop(fhttp->get_timeout_timer);
  1073. fhttp->started_receiving = false;
  1074. fhttp->just_started = false;
  1075. fhttp->state = IDLE;
  1076. fhttp->save_bytes = false;
  1077. fhttp->save_received_data = false;
  1078. if (fhttp->is_bytes_request)
  1079. {
  1080. // Search for the binary marker `[GET/END]` in the file buffer
  1081. const char marker[] = "[GET/END]";
  1082. const size_t marker_len = sizeof(marker) - 1; // Exclude null terminator
  1083. for (size_t i = 0; i <= fhttp->file_buffer_len - marker_len; i++)
  1084. {
  1085. // Check if the marker is found
  1086. if (memcmp(&fhttp->file_buffer[i], marker, marker_len) == 0)
  1087. {
  1088. // Remove the marker by shifting the remaining data left
  1089. size_t remaining_len = fhttp->file_buffer_len - (i + marker_len);
  1090. memmove(&fhttp->file_buffer[i], &fhttp->file_buffer[i + marker_len], remaining_len);
  1091. fhttp->file_buffer_len -= marker_len;
  1092. break;
  1093. }
  1094. }
  1095. // If there is data left in the buffer, append it to the file
  1096. if (fhttp->file_buffer_len > 0)
  1097. {
  1098. if (!flipper_http_append_to_file(fhttp->file_buffer, fhttp->file_buffer_len, false, fhttp->file_path))
  1099. {
  1100. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1101. }
  1102. fhttp->file_buffer_len = 0;
  1103. }
  1104. }
  1105. fhttp->is_bytes_request = false;
  1106. return;
  1107. }
  1108. // Append the new line to the existing data
  1109. if (fhttp->save_received_data &&
  1110. !flipper_http_append_to_file(
  1111. line, strlen(line), !fhttp->just_started, fhttp->file_path))
  1112. {
  1113. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1114. fhttp->started_receiving = false;
  1115. fhttp->just_started = false;
  1116. fhttp->state = IDLE;
  1117. return;
  1118. }
  1119. if (!fhttp->just_started)
  1120. {
  1121. fhttp->just_started = true;
  1122. }
  1123. return;
  1124. }
  1125. // Check if we've started receiving data from a POST request
  1126. else if (fhttp->started_receiving && (fhttp->method == POST || fhttp->method == BYTES_POST))
  1127. {
  1128. // Restart the timeout timer each time new data is received
  1129. furi_timer_restart(fhttp->get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1130. if (strstr(line, "[POST/END]") != NULL)
  1131. {
  1132. FURI_LOG_I(HTTP_TAG, "POST request completed.");
  1133. // Stop the timer since we've completed the POST request
  1134. furi_timer_stop(fhttp->get_timeout_timer);
  1135. fhttp->started_receiving = false;
  1136. fhttp->just_started = false;
  1137. fhttp->state = IDLE;
  1138. fhttp->save_bytes = false;
  1139. fhttp->save_received_data = false;
  1140. if (fhttp->is_bytes_request)
  1141. {
  1142. // Search for the binary marker `[POST/END]` in the file buffer
  1143. const char marker[] = "[POST/END]";
  1144. const size_t marker_len = sizeof(marker) - 1; // Exclude null terminator
  1145. for (size_t i = 0; i <= fhttp->file_buffer_len - marker_len; i++)
  1146. {
  1147. // Check if the marker is found
  1148. if (memcmp(&fhttp->file_buffer[i], marker, marker_len) == 0)
  1149. {
  1150. // Remove the marker by shifting the remaining data left
  1151. size_t remaining_len = fhttp->file_buffer_len - (i + marker_len);
  1152. memmove(&fhttp->file_buffer[i], &fhttp->file_buffer[i + marker_len], remaining_len);
  1153. fhttp->file_buffer_len -= marker_len;
  1154. break;
  1155. }
  1156. }
  1157. // If there is data left in the buffer, append it to the file
  1158. if (fhttp->file_buffer_len > 0)
  1159. {
  1160. if (!flipper_http_append_to_file(fhttp->file_buffer, fhttp->file_buffer_len, false, fhttp->file_path))
  1161. {
  1162. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1163. }
  1164. fhttp->file_buffer_len = 0;
  1165. }
  1166. }
  1167. fhttp->is_bytes_request = false;
  1168. return;
  1169. }
  1170. // Append the new line to the existing data
  1171. if (fhttp->save_received_data &&
  1172. !flipper_http_append_to_file(
  1173. line, strlen(line), !fhttp->just_started, fhttp->file_path))
  1174. {
  1175. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1176. fhttp->started_receiving = false;
  1177. fhttp->just_started = false;
  1178. fhttp->state = IDLE;
  1179. return;
  1180. }
  1181. if (!fhttp->just_started)
  1182. {
  1183. fhttp->just_started = true;
  1184. }
  1185. return;
  1186. }
  1187. // Check if we've started receiving data from a PUT request
  1188. else if (fhttp->started_receiving && fhttp->method == PUT)
  1189. {
  1190. // Restart the timeout timer each time new data is received
  1191. furi_timer_restart(fhttp->get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1192. if (strstr(line, "[PUT/END]") != NULL)
  1193. {
  1194. FURI_LOG_I(HTTP_TAG, "PUT request completed.");
  1195. // Stop the timer since we've completed the PUT request
  1196. furi_timer_stop(fhttp->get_timeout_timer);
  1197. fhttp->started_receiving = false;
  1198. fhttp->just_started = false;
  1199. fhttp->state = IDLE;
  1200. fhttp->save_bytes = false;
  1201. fhttp->is_bytes_request = false;
  1202. fhttp->save_received_data = false;
  1203. return;
  1204. }
  1205. // Append the new line to the existing data
  1206. if (fhttp->save_received_data &&
  1207. !flipper_http_append_to_file(
  1208. line, strlen(line), !fhttp->just_started, fhttp->file_path))
  1209. {
  1210. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1211. fhttp->started_receiving = false;
  1212. fhttp->just_started = false;
  1213. fhttp->state = IDLE;
  1214. return;
  1215. }
  1216. if (!fhttp->just_started)
  1217. {
  1218. fhttp->just_started = true;
  1219. }
  1220. return;
  1221. }
  1222. // Check if we've started receiving data from a DELETE request
  1223. else if (fhttp->started_receiving && fhttp->method == DELETE)
  1224. {
  1225. // Restart the timeout timer each time new data is received
  1226. furi_timer_restart(fhttp->get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1227. if (strstr(line, "[DELETE/END]") != NULL)
  1228. {
  1229. FURI_LOG_I(HTTP_TAG, "DELETE request completed.");
  1230. // Stop the timer since we've completed the DELETE request
  1231. furi_timer_stop(fhttp->get_timeout_timer);
  1232. fhttp->started_receiving = false;
  1233. fhttp->just_started = false;
  1234. fhttp->state = IDLE;
  1235. fhttp->save_bytes = false;
  1236. fhttp->is_bytes_request = false;
  1237. fhttp->save_received_data = false;
  1238. return;
  1239. }
  1240. // Append the new line to the existing data
  1241. if (fhttp->save_received_data &&
  1242. !flipper_http_append_to_file(
  1243. line, strlen(line), !fhttp->just_started, fhttp->file_path))
  1244. {
  1245. FURI_LOG_E(HTTP_TAG, "Failed to append data to file.");
  1246. fhttp->started_receiving = false;
  1247. fhttp->just_started = false;
  1248. fhttp->state = IDLE;
  1249. return;
  1250. }
  1251. if (!fhttp->just_started)
  1252. {
  1253. fhttp->just_started = true;
  1254. }
  1255. return;
  1256. }
  1257. // Handle different types of responses
  1258. if (strstr(line, "[SUCCESS]") != NULL || strstr(line, "[CONNECTED]") != NULL)
  1259. {
  1260. FURI_LOG_I(HTTP_TAG, "Operation succeeded.");
  1261. }
  1262. else if (strstr(line, "[INFO]") != NULL)
  1263. {
  1264. FURI_LOG_I(HTTP_TAG, "Received info: %s", line);
  1265. if (fhttp->state == INACTIVE && strstr(line, "[INFO] Already connected to Wifi.") != NULL)
  1266. {
  1267. fhttp->state = IDLE;
  1268. }
  1269. }
  1270. else if (strstr(line, "[GET/SUCCESS]") != NULL)
  1271. {
  1272. FURI_LOG_I(HTTP_TAG, "GET request succeeded.");
  1273. furi_timer_start(fhttp->get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1274. fhttp->started_receiving = true;
  1275. fhttp->state = RECEIVING;
  1276. // for GET request, save data only if it's a bytes request
  1277. fhttp->save_bytes = fhttp->is_bytes_request;
  1278. fhttp->just_started_bytes = true;
  1279. fhttp->file_buffer_len = 0;
  1280. // set header
  1281. set_header(fhttp);
  1282. return;
  1283. }
  1284. else if (strstr(line, "[POST/SUCCESS]") != NULL)
  1285. {
  1286. FURI_LOG_I(HTTP_TAG, "POST request succeeded.");
  1287. furi_timer_start(fhttp->get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1288. fhttp->started_receiving = true;
  1289. fhttp->state = RECEIVING;
  1290. // for POST request, save data only if it's a bytes request
  1291. fhttp->save_bytes = fhttp->is_bytes_request;
  1292. fhttp->just_started_bytes = true;
  1293. fhttp->file_buffer_len = 0;
  1294. // set header
  1295. set_header(fhttp);
  1296. return;
  1297. }
  1298. else if (strstr(line, "[PUT/SUCCESS]") != NULL)
  1299. {
  1300. FURI_LOG_I(HTTP_TAG, "PUT request succeeded.");
  1301. furi_timer_start(fhttp->get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1302. fhttp->started_receiving = true;
  1303. fhttp->state = RECEIVING;
  1304. // set header
  1305. set_header(fhttp);
  1306. return;
  1307. }
  1308. else if (strstr(line, "[DELETE/SUCCESS]") != NULL)
  1309. {
  1310. FURI_LOG_I(HTTP_TAG, "DELETE request succeeded.");
  1311. furi_timer_start(fhttp->get_timeout_timer, TIMEOUT_DURATION_TICKS);
  1312. fhttp->started_receiving = true;
  1313. fhttp->state = RECEIVING;
  1314. // set header
  1315. set_header(fhttp);
  1316. return;
  1317. }
  1318. else if (strstr(line, "[DISCONNECTED]") != NULL)
  1319. {
  1320. FURI_LOG_I(HTTP_TAG, "WiFi disconnected successfully.");
  1321. }
  1322. else if (strstr(line, "[ERROR]") != NULL)
  1323. {
  1324. FURI_LOG_E(HTTP_TAG, "Received error: %s", line);
  1325. fhttp->state = ISSUE;
  1326. return;
  1327. }
  1328. else if (strstr(line, "[PONG]") != NULL)
  1329. {
  1330. FURI_LOG_I(HTTP_TAG, "Received PONG response: Wifi Dev Board is still alive.");
  1331. // send command to connect to WiFi
  1332. if (fhttp->state == INACTIVE)
  1333. {
  1334. fhttp->state = IDLE;
  1335. return;
  1336. }
  1337. }
  1338. if (fhttp->state == INACTIVE && strstr(line, "[PONG]") != NULL)
  1339. {
  1340. fhttp->state = IDLE;
  1341. }
  1342. else if (fhttp->state == INACTIVE && strstr(line, "[PONG]") == NULL)
  1343. {
  1344. fhttp->state = INACTIVE;
  1345. }
  1346. else
  1347. {
  1348. fhttp->state = IDLE;
  1349. }
  1350. }
  1351. /**
  1352. * @brief Send a request to the specified URL to start a WebSocket connection.
  1353. * @return true if the request was successful, false otherwise.
  1354. * @param fhttp The FlipperHTTP context
  1355. * @param url The URL to send the WebSocket request to.
  1356. * @param port The port to connect to
  1357. * @param headers The headers to send with the WebSocket request
  1358. * @note The received data will be handled asynchronously via the callback.
  1359. */
  1360. bool flipper_http_websocket_start(FlipperHTTP *fhttp, const char *url, uint16_t port, const char *headers)
  1361. {
  1362. if (!fhttp)
  1363. {
  1364. FURI_LOG_E(HTTP_TAG, "Failed to get context.");
  1365. return false;
  1366. }
  1367. if (!url || !headers)
  1368. {
  1369. FURI_LOG_E("FlipperHTTP", "Invalid arguments provided to flipper_http_websocket_start.");
  1370. return false;
  1371. }
  1372. // Prepare WebSocket request command with headers
  1373. char command[512];
  1374. int ret = snprintf(
  1375. command,
  1376. sizeof(command),
  1377. "[SOCKET/START]{\"url\":\"%s\",\"port\":%d,\"headers\":%s}",
  1378. url,
  1379. port,
  1380. headers);
  1381. if (ret < 0 || ret >= (int)sizeof(command))
  1382. {
  1383. FURI_LOG_E("FlipperHTTP", "Failed to format WebSocket start command with headers.");
  1384. return false;
  1385. }
  1386. // Send WebSocket request via UART
  1387. return flipper_http_send_data(fhttp, command);
  1388. }
  1389. /**
  1390. * @brief Send a request to stop the WebSocket connection.
  1391. * @return true if the request was successful, false otherwise.
  1392. * @param fhttp The FlipperHTTP context
  1393. * @note The received data will be handled asynchronously via the callback.
  1394. */
  1395. bool flipper_http_websocket_stop(FlipperHTTP *fhttp)
  1396. {
  1397. if (!fhttp)
  1398. {
  1399. FURI_LOG_E(HTTP_TAG, "Failed to get context.");
  1400. return false;
  1401. }
  1402. return flipper_http_send_data(fhttp, "[SOCKET/STOP]");
  1403. }