flipper_http.c 50 KB

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