flipper_http.c 58 KB

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