flipper_http.c 50 KB

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