FlipperHTTP.h 37 KB

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