flipper_http.c 51 KB

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