flipper_http.c 52 KB

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