flipper_http.c 52 KB

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