flipper_http.c 58 KB

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