FlipperHTTP.h 37 KB

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