FlipperHTTPPico.h 36 KB

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