FlipperHTTPPico.h 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414
  1. /* FlipperHTTPPico.h for flipper-http-pico.ino (for the Rasberry Pi Pico W)
  2. Author: JBlanked
  3. Github: https://github.com/jblanked/WebCrawler-FlipperZero/tree/main/assets/FlipperHTTP
  4. Info: This library is a wrapper around the HTTPClient library and is used to communicate with the FlipperZero over serial.
  5. Created: 2024-10-24
  6. Updated: 2024-10-25
  7. Change Log:
  8. - 2024-10-24: Initial commit
  9. - 2024-10-25: Updated the readSerialLine method to use readStringUntil instead of reading char by char, and added Auto connect
  10. - Reading char by char worked on the dev board but was missing chars on the Pico
  11. */
  12. #include <WiFi.h>
  13. #include <HTTPClient.h>
  14. #include <WiFiClientSecure.h>
  15. #include <ArduinoJson.h>
  16. #include <Arduino.h>
  17. #include <LittleFS.h> // replacement for SPIFFS
  18. // Define UART parameters
  19. #define BAUD_RATE 115200
  20. #define PICO_LED LED_BUILTIN
  21. #define ON HIGH
  22. #define OFF LOW
  23. SerialPIO SerialPico(0, 1);
  24. class FlipperHTTP
  25. {
  26. public:
  27. // Constructor
  28. FlipperHTTP()
  29. {
  30. }
  31. // Main methods for flipper-http.ino
  32. void loop();
  33. void setup()
  34. {
  35. SerialPico.begin(BAUD_RATE);
  36. if (!LittleFS.begin())
  37. {
  38. SerialPico.println("An Error has occurred while mounting LittleFS. Attempting to format...");
  39. if (LittleFS.format())
  40. {
  41. SerialPico.println("File system formatted successfully. Re-mounting...");
  42. if (!LittleFS.begin())
  43. {
  44. SerialPico.println("Failed to re-mount LittleFS after formatting.");
  45. delay(1000);
  46. return;
  47. }
  48. }
  49. else
  50. {
  51. SerialPico.println("File system formatting failed.");
  52. delay(1000);
  53. return;
  54. }
  55. }
  56. this->loadWifiSettings();
  57. this->useLED = true;
  58. this->ledStart();
  59. SerialPico.flush();
  60. }
  61. // HTTP Methods
  62. String get(String url);
  63. String get(String url, const char *headerKeys[], const char *headerValues[], int headerSize);
  64. String post(String url, String payload);
  65. String post(String url, String payload, const char *headerKeys[], const char *headerValues[], int headerSize);
  66. String put(String url, String payload);
  67. String put(String url, String payload, const char *headerKeys[], const char *headerValues[], int headerSize);
  68. String delete_request(String url, String payload);
  69. String delete_request(String url, String payload, const char *headerKeys[], const char *headerValues[], int headerSize);
  70. // stream data as bytes
  71. bool get_bytes_to_file(String url, const char *headerKeys[], const char *headerValues[], int headerSize);
  72. bool post_bytes_to_file(String url, String payload, const char *headerKeys[], const char *headerValues[], int headerSize);
  73. // Save and Load settings to and from SPIFFS
  74. bool saveWifiSettings(String data);
  75. bool loadWifiSettings();
  76. // returns a string of all wifi networks
  77. String scanWifiNetworks()
  78. {
  79. int n = WiFi.scanNetworks();
  80. String networks = "";
  81. for (int i = 0; i < n; ++i)
  82. {
  83. networks += WiFi.SSID(i);
  84. if (i < n - 1)
  85. {
  86. networks += ", ";
  87. }
  88. }
  89. return networks;
  90. }
  91. // Connect to Wifi using the loaded SSID and Password
  92. bool connectToWifi();
  93. // Check if the Dev Board is connected to Wifi
  94. bool isConnectedToWifi() { return WiFi.status() == WL_CONNECTED; }
  95. // Read serial data until newline character
  96. String readSerialLine();
  97. // Clear serial buffer to avoid any residual data
  98. void clearSerialBuffer()
  99. {
  100. while (SerialPico.available() > 0)
  101. {
  102. SerialPico.read();
  103. }
  104. }
  105. // Function to flash the LED
  106. void ledAction(int timeout = 250)
  107. {
  108. digitalWrite(PICO_LED, ON);
  109. delay(timeout);
  110. digitalWrite(PICO_LED, OFF);
  111. delay(timeout);
  112. }
  113. // Display LED sequence when Wifi Board is first connected to the Flipper
  114. void ledStart()
  115. {
  116. // Initialize LED pin
  117. pinMode(PICO_LED, OUTPUT);
  118. ledAction();
  119. ledAction();
  120. ledAction();
  121. }
  122. // Starting LED (Green only)
  123. void ledStatus()
  124. {
  125. if (this->useLED)
  126. {
  127. digitalWrite(PICO_LED, ON);
  128. }
  129. }
  130. // Turn off all LEDs
  131. void ledOff()
  132. {
  133. digitalWrite(PICO_LED, OFF);
  134. }
  135. // get IP addresss
  136. String getIPAddress()
  137. {
  138. return WiFi.localIP().toString();
  139. }
  140. private:
  141. const char *settingsFilePath = "/flipper-http.json"; // Path to the settings file in the SPIFFS file system
  142. char loadedSSID[64] = {0}; // Variable to store SSID
  143. char loadedPassword[64] = {0}; // Variable to store password
  144. bool useLED = true; // Variable to control LED usage
  145. bool readSerialSettings(String receivedData, bool connectAfterSave);
  146. };
  147. // Connect to Wifi using the loaded SSID and Password
  148. bool FlipperHTTP::connectToWifi()
  149. {
  150. if (String(loadedSSID) == "" || String(loadedPassword) == "")
  151. {
  152. SerialPico.println("[ERROR] WiFi SSID or Password is empty.");
  153. return false;
  154. }
  155. WiFi.disconnect(true); // Ensure WiFi is disconnected before reconnecting
  156. WiFi.begin(loadedSSID, loadedPassword);
  157. int i = 0;
  158. while (!this->isConnectedToWifi() && i < 20)
  159. {
  160. delay(500);
  161. i++;
  162. SerialPico.print(".");
  163. }
  164. SerialPico.println(); // Move to next line after dots
  165. if (this->isConnectedToWifi())
  166. {
  167. SerialPico.println("[SUCCESS] Successfully connected to Wifi.");
  168. return true;
  169. }
  170. else
  171. {
  172. SerialPico.println("[ERROR] Failed to connect to Wifi.");
  173. return false;
  174. }
  175. }
  176. // Save WiFi settings to LittleFS
  177. bool FlipperHTTP::saveWifiSettings(String jsonData)
  178. {
  179. File file = LittleFS.open(settingsFilePath, "w");
  180. if (!file)
  181. {
  182. SerialPico.println("[ERROR] Failed to open file for writing.");
  183. return false;
  184. }
  185. file.print(jsonData);
  186. file.close();
  187. SerialPico.println("[SUCCESS] Settings saved to LittleFS.");
  188. return true;
  189. }
  190. // Load WiFi settings from LittleFS
  191. bool FlipperHTTP::loadWifiSettings()
  192. {
  193. File file = LittleFS.open(settingsFilePath, "r");
  194. if (!file)
  195. {
  196. return false;
  197. }
  198. // Read the entire file content
  199. String fileContent = file.readString();
  200. file.close();
  201. // Attempt to parse the JSON data
  202. DynamicJsonDocument doc(1024);
  203. DeserializationError error = deserializeJson(doc, fileContent);
  204. if (error)
  205. {
  206. return false;
  207. }
  208. // Extract values from JSON
  209. if (doc.containsKey("ssid") && doc.containsKey("password"))
  210. {
  211. strlcpy(loadedSSID, doc["ssid"], sizeof(loadedSSID)); // save ssid
  212. strlcpy(loadedPassword, doc["password"], sizeof(loadedPassword)); // save password
  213. }
  214. else
  215. {
  216. return false;
  217. }
  218. return this->connectToWifi();
  219. }
  220. String FlipperHTTP::readSerialLine()
  221. {
  222. String receivedData = "";
  223. // this worked on dev board but even with delay changes, it was missing chars
  224. // while (SerialPico.available() > 0)
  225. // {
  226. // char incomingChar = SerialPico.read();
  227. // if (incomingChar == '\n')
  228. // {
  229. // break;
  230. // }
  231. // receivedData += incomingChar;
  232. // delay(5); // Minimal delay to allow buffer to fill
  233. // }
  234. receivedData = SerialPico.readStringUntil('\n');
  235. receivedData.trim(); // Remove any leading/trailing whitespace
  236. return receivedData;
  237. }
  238. bool FlipperHTTP::readSerialSettings(String receivedData, bool connectAfterSave)
  239. {
  240. DynamicJsonDocument doc(1024);
  241. DeserializationError error = deserializeJson(doc, receivedData);
  242. if (error)
  243. {
  244. SerialPico.print("[ERROR] Failed to parse JSON: ");
  245. SerialPico.println(error.c_str());
  246. return false;
  247. }
  248. // Extract values from JSON
  249. if (doc.containsKey("ssid") && doc.containsKey("password"))
  250. {
  251. strlcpy(loadedSSID, doc["ssid"], sizeof(loadedSSID));
  252. strlcpy(loadedPassword, doc["password"], sizeof(loadedPassword));
  253. }
  254. else
  255. {
  256. SerialPico.println("[ERROR] JSON does not contain ssid and password.");
  257. return false;
  258. }
  259. // Save to SPIFFS
  260. if (!this->saveWifiSettings(receivedData))
  261. {
  262. SerialPico.println("[ERROR] Failed to save settings to file.");
  263. return false;
  264. }
  265. // Attempt to reconnect with new settings
  266. if (connectAfterSave && this->connectToWifi())
  267. {
  268. SerialPico.println("[SUCCESS] Connected to the new Wifi network.");
  269. }
  270. return true;
  271. }
  272. String FlipperHTTP::get(String url)
  273. {
  274. WiFiClientSecure client;
  275. client.setInsecure(); // Bypass certificate validation
  276. HTTPClient http;
  277. String payload = "";
  278. if (http.begin(client, url))
  279. {
  280. int httpCode = http.GET();
  281. if (httpCode > 0)
  282. {
  283. payload = http.getString();
  284. http.end();
  285. return payload;
  286. }
  287. else
  288. {
  289. SerialPico.print("[ERROR] GET Request Failed, error: ");
  290. SerialPico.println(http.errorToString(httpCode).c_str());
  291. }
  292. http.end();
  293. }
  294. else
  295. {
  296. SerialPico.println("[ERROR] Unable to connect to the server.");
  297. }
  298. // Clear serial buffer to avoid any residual data
  299. this->clearSerialBuffer();
  300. return payload;
  301. }
  302. String FlipperHTTP::get(String url, const char *headerKeys[], const char *headerValues[], int headerSize)
  303. {
  304. WiFiClientSecure client;
  305. client.setInsecure(); // Bypass certificate
  306. HTTPClient http;
  307. String payload = "";
  308. http.collectHeaders(headerKeys, headerSize);
  309. if (http.begin(client, url))
  310. {
  311. for (int i = 0; i < headerSize; i++)
  312. {
  313. http.addHeader(headerKeys[i], headerValues[i]);
  314. }
  315. int httpCode = http.GET();
  316. if (httpCode > 0)
  317. {
  318. payload = http.getString();
  319. http.end();
  320. return payload;
  321. }
  322. else
  323. {
  324. SerialPico.print("[ERROR] GET Request Failed, error: ");
  325. SerialPico.println(http.errorToString(httpCode).c_str());
  326. }
  327. http.end();
  328. }
  329. else
  330. {
  331. SerialPico.println("[ERROR] Unable to connect to the server.");
  332. }
  333. // Clear serial buffer to avoid any residual data
  334. this->clearSerialBuffer();
  335. return payload;
  336. }
  337. String FlipperHTTP::delete_request(String url, String payload)
  338. {
  339. WiFiClientSecure client;
  340. client.setInsecure(); // Bypass certificate
  341. HTTPClient http;
  342. String response = "";
  343. if (http.begin(client, url))
  344. {
  345. int httpCode = http.sendRequest("DELETE", payload);
  346. if (httpCode > 0)
  347. {
  348. response = http.getString();
  349. http.end();
  350. return response;
  351. }
  352. else
  353. {
  354. SerialPico.print("[ERROR] DELETE Request Failed, error: ");
  355. SerialPico.println(http.errorToString(httpCode).c_str());
  356. }
  357. http.end();
  358. }
  359. else
  360. {
  361. SerialPico.println("[ERROR] Unable to connect to the server.");
  362. }
  363. // Clear serial buffer to avoid any residual data
  364. this->clearSerialBuffer();
  365. return response;
  366. }
  367. String FlipperHTTP::delete_request(String url, String payload, const char *headerKeys[], const char *headerValues[], int headerSize)
  368. {
  369. WiFiClientSecure client;
  370. client.setInsecure(); // Bypass certificate
  371. HTTPClient http;
  372. String response = "";
  373. http.collectHeaders(headerKeys, headerSize);
  374. if (http.begin(client, url))
  375. {
  376. for (int i = 0; i < headerSize; i++)
  377. {
  378. http.addHeader(headerKeys[i], headerValues[i]);
  379. }
  380. int httpCode = http.sendRequest("DELETE", payload);
  381. if (httpCode > 0)
  382. {
  383. response = http.getString();
  384. http.end();
  385. return response;
  386. }
  387. else
  388. {
  389. SerialPico.print("[ERROR] DELETE Request Failed, error: ");
  390. SerialPico.println(http.errorToString(httpCode).c_str());
  391. }
  392. http.end();
  393. }
  394. else
  395. {
  396. SerialPico.println("[ERROR] Unable to connect to the server.");
  397. }
  398. // Clear serial buffer to avoid any residual data
  399. this->clearSerialBuffer();
  400. return response;
  401. }
  402. String FlipperHTTP::post(String url, String payload, const char *headerKeys[], const char *headerValues[], int headerSize)
  403. {
  404. WiFiClientSecure client;
  405. client.setInsecure(); // Bypass certificate
  406. HTTPClient http;
  407. String response = "";
  408. http.collectHeaders(headerKeys, headerSize);
  409. if (http.begin(client, url))
  410. {
  411. for (int i = 0; i < headerSize; i++)
  412. {
  413. http.addHeader(headerKeys[i], headerValues[i]);
  414. }
  415. int httpCode = http.POST(payload);
  416. if (httpCode > 0)
  417. {
  418. response = http.getString();
  419. http.end();
  420. return response;
  421. }
  422. else
  423. {
  424. SerialPico.print("[ERROR] POST Request Failed, error: ");
  425. SerialPico.println(http.errorToString(httpCode).c_str());
  426. }
  427. http.end();
  428. }
  429. else
  430. {
  431. SerialPico.println("[ERROR] Unable to connect to the server.");
  432. }
  433. // Clear serial buffer to avoid any residual data
  434. this->clearSerialBuffer();
  435. return response;
  436. }
  437. String FlipperHTTP::post(String url, String payload)
  438. {
  439. WiFiClientSecure client;
  440. client.setInsecure(); // Bypass certificate
  441. HTTPClient http;
  442. String response = "";
  443. if (http.begin(client, url))
  444. {
  445. int httpCode = http.POST(payload);
  446. if (httpCode > 0)
  447. {
  448. response = http.getString();
  449. http.end();
  450. return response;
  451. }
  452. else
  453. {
  454. SerialPico.print("[ERROR] POST Request Failed, error: ");
  455. SerialPico.println(http.errorToString(httpCode).c_str());
  456. }
  457. http.end();
  458. }
  459. else
  460. {
  461. SerialPico.println("[ERROR] Unable to connect to the server.");
  462. }
  463. // Clear serial buffer to avoid any residual data
  464. this->clearSerialBuffer();
  465. return response;
  466. }
  467. String FlipperHTTP::put(String url, String payload, const char *headerKeys[], const char *headerValues[], int headerSize)
  468. {
  469. WiFiClientSecure client;
  470. client.setInsecure(); // Bypass certificate
  471. HTTPClient http;
  472. String response = "";
  473. http.collectHeaders(headerKeys, headerSize);
  474. if (http.begin(client, url))
  475. {
  476. for (int i = 0; i < headerSize; i++)
  477. {
  478. http.addHeader(headerKeys[i], headerValues[i]);
  479. }
  480. int httpCode = http.PUT(payload);
  481. if (httpCode > 0)
  482. {
  483. response = http.getString();
  484. http.end();
  485. return response;
  486. }
  487. else
  488. {
  489. SerialPico.print("[ERROR] PUT Request Failed, error: ");
  490. SerialPico.println(http.errorToString(httpCode).c_str());
  491. }
  492. http.end();
  493. }
  494. else
  495. {
  496. SerialPico.println("[ERROR] Unable to connect to the server.");
  497. }
  498. // Clear serial buffer to avoid any residual data
  499. this->clearSerialBuffer();
  500. return response;
  501. }
  502. String FlipperHTTP::put(String url, String payload)
  503. {
  504. WiFiClientSecure client;
  505. client.setInsecure(); // Bypass certificate
  506. HTTPClient http;
  507. String response = "";
  508. if (http.begin(client, url))
  509. {
  510. int httpCode = http.PUT(payload);
  511. if (httpCode > 0)
  512. {
  513. response = http.getString();
  514. http.end();
  515. return response;
  516. }
  517. else
  518. {
  519. SerialPico.print("[ERROR] PUT Request Failed, error: ");
  520. SerialPico.println(http.errorToString(httpCode).c_str());
  521. }
  522. http.end();
  523. }
  524. else
  525. {
  526. SerialPico.println("[ERROR] Unable to connect to the server.");
  527. }
  528. // Clear serial buffer to avoid any residual data
  529. this->clearSerialBuffer();
  530. return response;
  531. }
  532. bool FlipperHTTP::get_bytes_to_file(String url, const char *headerKeys[], const char *headerValues[], int headerSize)
  533. {
  534. WiFiClientSecure client;
  535. client.setInsecure(); // Bypass certificate
  536. HTTPClient http;
  537. http.collectHeaders(headerKeys, headerSize);
  538. if (http.begin(client, url))
  539. {
  540. for (int i = 0; i < headerSize; i++)
  541. {
  542. http.addHeader(headerKeys[i], headerValues[i]);
  543. }
  544. int httpCode = http.GET();
  545. if (httpCode > 0)
  546. {
  547. SerialPico.println("[GET/SUCCESS]");
  548. int len = http.getSize();
  549. uint8_t buff[512] = {0};
  550. WiFiClient *stream = http.getStreamPtr();
  551. // Check available heap memory before starting
  552. // size_t freeHeap = ESP.getFreeHeap();
  553. // const size_t minHeapThreshold = 1024; // Minimum heap space to avoid overflow
  554. // if (freeHeap < minHeapThreshold)
  555. // {
  556. // SerialPico.println("[ERROR] Not enough memory to start processing the response.");
  557. // http.end();
  558. // return false;
  559. // }
  560. // Stream data while connected and available
  561. while (http.connected() && (len > 0 || len == -1))
  562. {
  563. size_t size = stream->available();
  564. if (size)
  565. {
  566. int c = stream->readBytes(buff, ((size > sizeof(buff)) ? sizeof(buff) : size));
  567. SerialPico.write(buff, c); // Write data to serial
  568. if (len > 0)
  569. {
  570. len -= c;
  571. }
  572. }
  573. delay(1); // Yield control to the system
  574. }
  575. // freeHeap = ESP.getFreeHeap();
  576. // if (freeHeap < minHeapThreshold)
  577. // {
  578. // SerialPico.println("[ERROR] Not enough memory to continue processing the response.");
  579. // http.end();
  580. // return false;
  581. // }
  582. // Flush the serial buffer to ensure all data is sent
  583. http.end();
  584. SerialPico.flush();
  585. SerialPico.println();
  586. SerialPico.println("[GET/END]");
  587. return true;
  588. }
  589. else
  590. {
  591. SerialPico.printf("[ERROR] GET request failed with error: %s\n", http.errorToString(httpCode).c_str());
  592. }
  593. http.end();
  594. }
  595. else
  596. {
  597. SerialPico.println("[ERROR] Unable to connect to the server.");
  598. }
  599. return false;
  600. }
  601. bool FlipperHTTP::post_bytes_to_file(String url, String payload, const char *headerKeys[], const char *headerValues[], int headerSize)
  602. {
  603. WiFiClientSecure client;
  604. client.setInsecure(); // Bypass certificate
  605. HTTPClient http;
  606. http.collectHeaders(headerKeys, headerSize);
  607. if (http.begin(client, url))
  608. {
  609. for (int i = 0; i < headerSize; i++)
  610. {
  611. http.addHeader(headerKeys[i], headerValues[i]);
  612. }
  613. int httpCode = http.POST(payload);
  614. if (httpCode > 0)
  615. {
  616. SerialPico.println("[POST/SUCCESS]");
  617. int len = http.getSize(); // Get the response content length
  618. uint8_t buff[512] = {0}; // Buffer for reading data
  619. WiFiClient *stream = http.getStreamPtr();
  620. // Check available heap memory before starting
  621. // size_t freeHeap = ESP.getFreeHeap();
  622. // const size_t minHeapThreshold = 1024; // Minimum heap space to avoid overflow
  623. // if (freeHeap < minHeapThreshold)
  624. // {
  625. // SerialPico.println("[ERROR] Not enough memory to start processing the response.");
  626. // http.end();
  627. // return false;
  628. // }
  629. // Stream data while connected and available
  630. while (http.connected() && (len > 0 || len == -1))
  631. {
  632. size_t size = stream->available();
  633. if (size)
  634. {
  635. int c = stream->readBytes(buff, ((size > sizeof(buff)) ? sizeof(buff) : size));
  636. SerialPico.write(buff, c); // Write data to serial
  637. if (len > 0)
  638. {
  639. len -= c;
  640. }
  641. }
  642. delay(1); // Yield control to the system
  643. }
  644. // freeHeap = ESP.getFreeHeap();
  645. // if (freeHeap < minHeapThreshold)
  646. // {
  647. // SerialPico.println("[ERROR] Not enough memory to continue processing the response.");
  648. // http.end();
  649. // return false;
  650. // }
  651. http.end();
  652. // Flush the serial buffer to ensure all data is sent
  653. SerialPico.flush();
  654. SerialPico.println();
  655. SerialPico.println("[POST/END]");
  656. return true;
  657. }
  658. else
  659. {
  660. SerialPico.printf("[ERROR] POST request failed with error: %s\n", http.errorToString(httpCode).c_str());
  661. }
  662. http.end();
  663. }
  664. else
  665. {
  666. SerialPico.println("[ERROR] Unable to connect to the server.");
  667. }
  668. return false;
  669. }
  670. // Main loop for flipper-http.ino that handles all of the commands
  671. void FlipperHTTP::loop()
  672. {
  673. // Check if there's incoming serial data
  674. if (SerialPico.available() > 0)
  675. {
  676. // Read the incoming serial data until newline
  677. String _data = this->readSerialLine();
  678. this->ledStatus();
  679. // print the available commands
  680. if (_data.startsWith("[LIST]"))
  681. {
  682. SerialPico.println("[LIST],[PING], [REBOOT], [WIFI/IP], [WIFI/SCAN], [WIFI/SAVE], [WIFI/CONNECT], [WIFI/DISCONNECT], [GET], [GET/HTTP], [POST/HTTP], [PUT/HTTP], [DELETE/HTTP], [GET/BYTES], [POST/BYTES], [PARSE], [PARSE/ARRAY], [LED/ON], [LED/OFF], [IP/ADDRESS]");
  683. }
  684. // handle [LED/ON] command
  685. else if (_data.startsWith("[LED/ON]"))
  686. {
  687. this->useLED = true;
  688. }
  689. // handle [LED/OFF] command
  690. else if (_data.startsWith("[LED/OFF]"))
  691. {
  692. this->useLED = false;
  693. }
  694. // handle [IP/ADDRESS] command (local IP)
  695. else if (_data.startsWith("[IP/ADDRESS]"))
  696. {
  697. SerialPico.println(this->getIPAddress());
  698. }
  699. // handle [WIFI/IP] command ip of connected wifi
  700. else if (_data.startsWith("[WIFI/IP]"))
  701. {
  702. if (!this->isConnectedToWifi() && !this->connectToWifi())
  703. {
  704. SerialPico.println("[ERROR] Not connected to Wifi. Failed to reconnect.");
  705. this->ledOff();
  706. return;
  707. }
  708. // Get Request
  709. String jsonData = this->get("https://httpbin.org/get");
  710. if (jsonData == "")
  711. {
  712. SerialPico.println("[ERROR] GET request failed or returned empty data.");
  713. return;
  714. }
  715. DynamicJsonDocument doc(1024);
  716. DeserializationError error = deserializeJson(doc, jsonData);
  717. if (error)
  718. {
  719. SerialPico.print("[ERROR] Failed to parse JSON.");
  720. this->ledOff();
  721. return;
  722. }
  723. if (!doc.containsKey("origin"))
  724. {
  725. SerialPico.println("[ERROR] JSON does not contain origin.");
  726. this->ledOff();
  727. return;
  728. }
  729. SerialPico.println(doc["origin"].as<String>());
  730. }
  731. // Ping/Pong to see if board/flipper is connected
  732. else if (_data.startsWith("[PING]"))
  733. {
  734. SerialPico.println("[PONG]");
  735. }
  736. // Handle [REBOOT] command
  737. else if (_data.startsWith("[REBOOT]"))
  738. {
  739. this->useLED = true;
  740. // ESP.restart();
  741. }
  742. // scan for wifi networks
  743. else if (_data.startsWith("[WIFI/SCAN]"))
  744. {
  745. SerialPico.println(this->scanWifiNetworks());
  746. SerialPico.flush();
  747. }
  748. // Handle [WIFI/SAVE] command
  749. else if (_data.startsWith("[WIFI/SAVE]"))
  750. {
  751. // Extract JSON data by removing the command part
  752. String jsonData = _data.substring(strlen("[WIFI/SAVE]"));
  753. jsonData.trim(); // Remove any leading/trailing whitespace
  754. // Parse and save the settings
  755. if (this->readSerialSettings(jsonData, true))
  756. {
  757. SerialPico.println("[SUCCESS] Wifi settings saved.");
  758. }
  759. else
  760. {
  761. SerialPico.println("[ERROR] Failed to save Wifi settings.");
  762. }
  763. }
  764. // Handle [WIFI/CONNECT] command
  765. else if (_data == "[WIFI/CONNECT]")
  766. {
  767. // Check if WiFi is already connected
  768. if (!this->isConnectedToWifi())
  769. {
  770. // Attempt to connect to Wifi
  771. if (this->connectToWifi())
  772. {
  773. SerialPico.println("[SUCCESS] Connected to Wifi.");
  774. }
  775. else
  776. {
  777. SerialPico.println("[ERROR] Failed to connect to Wifi.");
  778. }
  779. }
  780. else
  781. {
  782. SerialPico.println("[INFO] Already connected to Wifi.");
  783. }
  784. }
  785. // Handle [WIFI/DISCONNECT] command
  786. else if (_data == "[WIFI/DISCONNECT]")
  787. {
  788. WiFi.disconnect(true);
  789. SerialPico.println("[DISCONNECTED] Wifi has been disconnected.");
  790. }
  791. // Handle [GET] command
  792. else if (_data.startsWith("[GET]"))
  793. {
  794. if (!this->isConnectedToWifi() && !this->connectToWifi())
  795. {
  796. SerialPico.println("[ERROR] Not connected to Wifi. Failed to reconnect.");
  797. this->ledOff();
  798. return;
  799. }
  800. // Extract URL by removing the command part
  801. String url = _data.substring(strlen("[GET]"));
  802. url.trim();
  803. // GET request
  804. String getData = this->get(url);
  805. if (getData != "")
  806. {
  807. SerialPico.println("[GET/SUCCESS] GET request successful.");
  808. SerialPico.println(getData);
  809. SerialPico.flush();
  810. SerialPico.println();
  811. SerialPico.println("[GET/END]");
  812. }
  813. else
  814. {
  815. SerialPico.println("[ERROR] GET request failed or returned empty data.");
  816. }
  817. }
  818. // Handle [GET/HTTP] command
  819. else if (_data.startsWith("[GET/HTTP]"))
  820. {
  821. if (!this->isConnectedToWifi() && !this->connectToWifi())
  822. {
  823. SerialPico.println("[ERROR] Not connected to Wifi. Failed to reconnect.");
  824. this->ledOff();
  825. return;
  826. }
  827. // Extract the JSON by removing the command part
  828. String jsonData = _data.substring(strlen("[GET/HTTP]"));
  829. jsonData.trim();
  830. DynamicJsonDocument doc(1024);
  831. DeserializationError error = deserializeJson(doc, jsonData);
  832. if (error)
  833. {
  834. SerialPico.print("[ERROR] Failed to parse JSON.");
  835. this->ledOff();
  836. return;
  837. }
  838. // Extract values from JSON
  839. if (!doc.containsKey("url"))
  840. {
  841. SerialPico.println("[ERROR] JSON does not contain url.");
  842. this->ledOff();
  843. return;
  844. }
  845. String url = doc["url"];
  846. // Extract headers if available
  847. const char *headerKeys[10];
  848. const char *headerValues[10];
  849. int headerSize = 0;
  850. if (doc.containsKey("headers"))
  851. {
  852. JsonObject headers = doc["headers"];
  853. for (JsonPair header : headers)
  854. {
  855. headerKeys[headerSize] = header.key().c_str();
  856. headerValues[headerSize] = header.value();
  857. headerSize++;
  858. }
  859. }
  860. // GET request
  861. String getData = this->get(url, headerKeys, headerValues, headerSize);
  862. if (getData != "")
  863. {
  864. SerialPico.println("[GET/SUCCESS] GET request successful.");
  865. SerialPico.println(getData);
  866. SerialPico.flush();
  867. SerialPico.println();
  868. SerialPico.println("[GET/END]");
  869. }
  870. else
  871. {
  872. SerialPico.println("[ERROR] GET request failed or returned empty data.");
  873. }
  874. }
  875. // Handle [POST/HTTP] command
  876. else if (_data.startsWith("[POST/HTTP]"))
  877. {
  878. if (!this->isConnectedToWifi() && !this->connectToWifi())
  879. {
  880. SerialPico.println("[ERROR] Not connected to Wifi. Failed to reconnect.");
  881. this->ledOff();
  882. return;
  883. }
  884. // Extract the JSON by removing the command part
  885. String jsonData = _data.substring(strlen("[POST/HTTP]"));
  886. jsonData.trim();
  887. DynamicJsonDocument doc(1024);
  888. DeserializationError error = deserializeJson(doc, jsonData);
  889. if (error)
  890. {
  891. SerialPico.print("[ERROR] Failed to parse JSON.");
  892. this->ledOff();
  893. return;
  894. }
  895. // Extract values from JSON
  896. if (!doc.containsKey("url") || !doc.containsKey("payload"))
  897. {
  898. SerialPico.println("[ERROR] JSON does not contain url or payload.");
  899. this->ledOff();
  900. return;
  901. }
  902. String url = doc["url"];
  903. String payload = doc["payload"];
  904. // Extract headers if available
  905. const char *headerKeys[10];
  906. const char *headerValues[10];
  907. int headerSize = 0;
  908. if (doc.containsKey("headers"))
  909. {
  910. JsonObject headers = doc["headers"];
  911. for (JsonPair header : headers)
  912. {
  913. headerKeys[headerSize] = header.key().c_str();
  914. headerValues[headerSize] = header.value();
  915. headerSize++;
  916. }
  917. }
  918. // POST request
  919. String postData = this->post(url, payload, headerKeys, headerValues, headerSize);
  920. if (postData != "")
  921. {
  922. SerialPico.println("[POST/SUCCESS] POST request successful.");
  923. SerialPico.println(postData);
  924. SerialPico.flush();
  925. SerialPico.println();
  926. SerialPico.println("[POST/END]");
  927. }
  928. else
  929. {
  930. SerialPico.println("[ERROR] POST request failed or returned empty data.");
  931. }
  932. }
  933. // Handle [PUT/HTTP] command
  934. else if (_data.startsWith("[PUT/HTTP]"))
  935. {
  936. if (!this->isConnectedToWifi() && !this->connectToWifi())
  937. {
  938. SerialPico.println("[ERROR] Not connected to Wifi. Failed to reconnect.");
  939. this->ledOff();
  940. return;
  941. }
  942. // Extract the JSON by removing the command part
  943. String jsonData = _data.substring(strlen("[PUT/HTTP]"));
  944. jsonData.trim();
  945. DynamicJsonDocument doc(1024);
  946. DeserializationError error = deserializeJson(doc, jsonData);
  947. if (error)
  948. {
  949. SerialPico.print("[ERROR] Failed to parse JSON.");
  950. this->ledOff();
  951. return;
  952. }
  953. // Extract values from JSON
  954. if (!doc.containsKey("url") || !doc.containsKey("payload"))
  955. {
  956. SerialPico.println("[ERROR] JSON does not contain url or payload.");
  957. this->ledOff();
  958. return;
  959. }
  960. String url = doc["url"];
  961. String payload = doc["payload"];
  962. // Extract headers if available
  963. const char *headerKeys[10];
  964. const char *headerValues[10];
  965. int headerSize = 0;
  966. if (doc.containsKey("headers"))
  967. {
  968. JsonObject headers = doc["headers"];
  969. for (JsonPair header : headers)
  970. {
  971. headerKeys[headerSize] = header.key().c_str();
  972. headerValues[headerSize] = header.value();
  973. headerSize++;
  974. }
  975. }
  976. // PUT request
  977. String putData = this->put(url, payload, headerKeys, headerValues, headerSize);
  978. if (putData != "")
  979. {
  980. SerialPico.println("[PUT/SUCCESS] PUT request successful.");
  981. SerialPico.println(putData);
  982. SerialPico.flush();
  983. SerialPico.println();
  984. SerialPico.println("[PUT/END]");
  985. }
  986. else
  987. {
  988. SerialPico.println("[ERROR] PUT request failed or returned empty data.");
  989. }
  990. }
  991. // Handle [DELETE/HTTP] command
  992. else if (_data.startsWith("[DELETE/HTTP]"))
  993. {
  994. if (!this->isConnectedToWifi() && !this->connectToWifi())
  995. {
  996. SerialPico.println("[ERROR] Not connected to Wifi. Failed to reconnect.");
  997. this->ledOff();
  998. return;
  999. }
  1000. // Extract the JSON by removing the command part
  1001. String jsonData = _data.substring(strlen("[DELETE/HTTP]"));
  1002. jsonData.trim();
  1003. DynamicJsonDocument doc(1024);
  1004. DeserializationError error = deserializeJson(doc, jsonData);
  1005. if (error)
  1006. {
  1007. SerialPico.print("[ERROR] Failed to parse JSON.");
  1008. this->ledOff();
  1009. return;
  1010. }
  1011. // Extract values from JSON
  1012. if (!doc.containsKey("url") || !doc.containsKey("payload"))
  1013. {
  1014. SerialPico.println("[ERROR] JSON does not contain url or payload.");
  1015. this->ledOff();
  1016. return;
  1017. }
  1018. String url = doc["url"];
  1019. String payload = doc["payload"];
  1020. // Extract headers if available
  1021. const char *headerKeys[10];
  1022. const char *headerValues[10];
  1023. int headerSize = 0;
  1024. if (doc.containsKey("headers"))
  1025. {
  1026. JsonObject headers = doc["headers"];
  1027. for (JsonPair header : headers)
  1028. {
  1029. headerKeys[headerSize] = header.key().c_str();
  1030. headerValues[headerSize] = header.value();
  1031. headerSize++;
  1032. }
  1033. }
  1034. // DELETE request
  1035. String deleteData = this->delete_request(url, payload, headerKeys, headerValues, headerSize);
  1036. if (deleteData != "")
  1037. {
  1038. SerialPico.println("[DELETE/SUCCESS] DELETE request successful.");
  1039. SerialPico.println(deleteData);
  1040. SerialPico.flush();
  1041. SerialPico.println();
  1042. SerialPico.println("[DELETE/END]");
  1043. }
  1044. else
  1045. {
  1046. SerialPico.println("[ERROR] DELETE request failed or returned empty data.");
  1047. }
  1048. }
  1049. // Handle [GET/BYTES]
  1050. else if (_data.startsWith("[GET/BYTES]"))
  1051. {
  1052. if (!this->isConnectedToWifi() && !this->connectToWifi())
  1053. {
  1054. SerialPico.println("[ERROR] Not connected to Wifi. Failed to reconnect.");
  1055. this->ledOff();
  1056. return;
  1057. }
  1058. // Extract the JSON by removing the command part
  1059. String jsonData = _data.substring(strlen("[GET/BYTES]"));
  1060. jsonData.trim();
  1061. DynamicJsonDocument doc(1024);
  1062. DeserializationError error = deserializeJson(doc, jsonData);
  1063. if (error)
  1064. {
  1065. SerialPico.print("[ERROR] Failed to parse JSON.");
  1066. this->ledOff();
  1067. return;
  1068. }
  1069. // Extract values from JSON
  1070. if (!doc.containsKey("url"))
  1071. {
  1072. SerialPico.println("[ERROR] JSON does not contain url.");
  1073. this->ledOff();
  1074. return;
  1075. }
  1076. String url = doc["url"];
  1077. // Extract headers if available
  1078. const char *headerKeys[10];
  1079. const char *headerValues[10];
  1080. int headerSize = 0;
  1081. if (doc.containsKey("headers"))
  1082. {
  1083. JsonObject headers = doc["headers"];
  1084. for (JsonPair header : headers)
  1085. {
  1086. headerKeys[headerSize] = header.key().c_str();
  1087. headerValues[headerSize] = header.value();
  1088. headerSize++;
  1089. }
  1090. }
  1091. // GET request
  1092. if (!this->get_bytes_to_file(url, headerKeys, headerValues, headerSize))
  1093. {
  1094. SerialPico.println("[ERROR] GET request failed or returned empty data.");
  1095. }
  1096. }
  1097. // handle [POST/BYTES]
  1098. else if (_data.startsWith("[POST/BYTES]"))
  1099. {
  1100. if (!this->isConnectedToWifi() && !this->connectToWifi())
  1101. {
  1102. SerialPico.println("[ERROR] Not connected to Wifi. Failed to reconnect.");
  1103. this->ledOff();
  1104. return;
  1105. }
  1106. // Extract the JSON by removing the command part
  1107. String jsonData = _data.substring(strlen("[POST/BYTES]"));
  1108. jsonData.trim();
  1109. DynamicJsonDocument doc(1024);
  1110. DeserializationError error = deserializeJson(doc, jsonData);
  1111. if (error)
  1112. {
  1113. SerialPico.print("[ERROR] Failed to parse JSON.");
  1114. this->ledOff();
  1115. return;
  1116. }
  1117. // Extract values from JSON
  1118. if (!doc.containsKey("url") || !doc.containsKey("payload"))
  1119. {
  1120. SerialPico.println("[ERROR] JSON does not contain url or payload.");
  1121. this->ledOff();
  1122. return;
  1123. }
  1124. String url = doc["url"];
  1125. String payload = doc["payload"];
  1126. // Extract headers if available
  1127. const char *headerKeys[10];
  1128. const char *headerValues[10];
  1129. int headerSize = 0;
  1130. if (doc.containsKey("headers"))
  1131. {
  1132. JsonObject headers = doc["headers"];
  1133. for (JsonPair header : headers)
  1134. {
  1135. headerKeys[headerSize] = header.key().c_str();
  1136. headerValues[headerSize] = header.value();
  1137. headerSize++;
  1138. }
  1139. }
  1140. // POST request
  1141. if (!this->post_bytes_to_file(url, payload, headerKeys, headerValues, headerSize))
  1142. {
  1143. SerialPico.println("[ERROR] POST request failed or returned empty data.");
  1144. }
  1145. }
  1146. // Handle [PARSE] command
  1147. // the user will append the key to read from the json
  1148. // example: [PARSE]{"key":"name","json":{"name":"John Doe"}}
  1149. else if (_data.startsWith("[PARSE]"))
  1150. {
  1151. // Extract the JSON by removing the command part
  1152. String jsonData = _data.substring(strlen("[PARSE]"));
  1153. jsonData.trim();
  1154. DynamicJsonDocument doc(1024);
  1155. DeserializationError error = deserializeJson(doc, jsonData);
  1156. if (error)
  1157. {
  1158. SerialPico.print("[ERROR] Failed to parse JSON.");
  1159. this->ledOff();
  1160. return;
  1161. }
  1162. // Extract values from JSON
  1163. if (!doc.containsKey("key") || !doc.containsKey("json"))
  1164. {
  1165. SerialPico.println("[ERROR] JSON does not contain key or json.");
  1166. this->ledOff();
  1167. return;
  1168. }
  1169. String key = doc["key"];
  1170. JsonObject json = doc["json"];
  1171. if (json.containsKey(key))
  1172. {
  1173. SerialPico.println(json[key].as<String>());
  1174. }
  1175. else
  1176. {
  1177. SerialPico.println("[ERROR] Key not found in JSON.");
  1178. }
  1179. }
  1180. // Handle [PARSE/ARRAY] command
  1181. // the user will append the key to read and the index of the array to get it's key from the json
  1182. // example: [PARSE/ARRAY]{"key":"name","index":"1","json":{"name":["John Doe","Jane Doe"]}}
  1183. // this would return Jane Doe
  1184. // and in this example it would return {"flavor": "red"}:
  1185. // example: [PARSE/ARRAY]{"key":"flavor","index":"1","json":{"name":[{"flavor": "blue"},{"flavor": "red"}]}}
  1186. else if (_data.startsWith("[PARSE/ARRAY]"))
  1187. {
  1188. // Extract the JSON by removing the command part
  1189. String jsonData = _data.substring(strlen("[PARSE/ARRAY]"));
  1190. jsonData.trim();
  1191. DynamicJsonDocument doc(1024);
  1192. DeserializationError error = deserializeJson(doc, jsonData);
  1193. if (error)
  1194. {
  1195. SerialPico.print("[ERROR] Failed to parse JSON.");
  1196. this->ledOff();
  1197. return;
  1198. }
  1199. // Extract values from JSON
  1200. if (!doc.containsKey("key") || !doc.containsKey("index") || !doc.containsKey("json"))
  1201. {
  1202. SerialPico.println("[ERROR] JSON does not contain key, index, or json.");
  1203. this->ledOff();
  1204. return;
  1205. }
  1206. String key = doc["key"];
  1207. int index = doc["index"];
  1208. JsonArray json = doc["json"];
  1209. if (json[index].containsKey(key))
  1210. {
  1211. SerialPico.println(json[index][key].as<String>());
  1212. }
  1213. else
  1214. {
  1215. SerialPico.println("[ERROR] Key not found in JSON.");
  1216. }
  1217. }
  1218. this->ledOff();
  1219. }
  1220. }