FlipperHTTP.h 41 KB

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