flipper_http.c 49 KB

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