FlipperHTTP.h 40 KB

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