| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490 |
- /* FlipperHTTP.h for flipper-http.ino
- Author: JBlanked
- Github: https://github.com/jblanked/WebCrawler-FlipperZero/tree/main/assets/FlipperHTTP
- Info: This library is a wrapper around the HTTPClient library and is used to communicate with the FlipperZero over serial.
- Created: 2024-09-30
- Updated: 2024-10-26
- Change Log:
- - 2024-09-30: Initial commit
- .
- .
- .
- - 2024-10-16: Fixed typos and added [GET/BYTES], [POST/BYTES], and [WIFI/SACN] commands
- - 2024-10-17: Added [LIST], [REBOOT], [PARSE], [PARSE/ARRAY], [LED/ON], and [LED/OFF], and [IP/ADDRESS] commands
- - 2024-10-19: Added [WIFI/IP] command
- - 2024-10-21: Removed unnecessary println
- - 2024-10-22: Updated Post Bytes and Get Bytes methods
- - 2024-10-25: Updated to automatically connect to WiFi on boot if settings are saved
- - 2024-10-26: Updated the saveWifiSettings and loadWifiSettings methods to save and load a list of wifi networks, and added [WIFI/LIST] command
- */
- #include <WiFi.h>
- #include <HTTPClient.h>
- #include <WiFiClientSecure.h>
- #include "SPIFFS.h"
- #include <ArduinoJson.h>
- #include <Arduino.h>
- #define B_PIN 4 // Blue
- #define G_PIN 5 // Green
- #define R_PIN 6 // Red
- #define ON LOW
- #define OFF HIGH
- class FlipperHTTP
- {
- public:
- // Constructor
- FlipperHTTP()
- {
- }
- // Main methods for flipper-http.ino
- void loop();
- void setup()
- {
- Serial.begin(115200);
- // Initialize SPIFFS
- if (!SPIFFS.begin(true))
- {
- Serial.println("[ERROR] SPIFFS initialization failed.");
- ESP.restart();
- }
- this->useLED = true;
- this->ledStart();
- this->loadWifiSettings();
- Serial.flush();
- }
- // HTTP Methods
- String get(String url);
- String get(String url, const char *headerKeys[], const char *headerValues[], int headerSize);
- String post(String url, String payload);
- String post(String url, String payload, const char *headerKeys[], const char *headerValues[], int headerSize);
- String put(String url, String payload);
- String put(String url, String payload, const char *headerKeys[], const char *headerValues[], int headerSize);
- String delete_request(String url, String payload);
- String delete_request(String url, String payload, const char *headerKeys[], const char *headerValues[], int headerSize);
- // stream data as bytes
- bool get_bytes_to_file(String url, const char *headerKeys[], const char *headerValues[], int headerSize);
- bool post_bytes_to_file(String url, String payload, const char *headerKeys[], const char *headerValues[], int headerSize);
- // Save and Load settings to and from SPIFFS
- bool saveWifiSettings(String data);
- bool loadWifiSettings();
- // returns a string of all wifi networks
- String scanWifiNetworks()
- {
- int n = WiFi.scanNetworks();
- String networks = "";
- for (int i = 0; i < n; ++i)
- {
- networks += WiFi.SSID(i);
- if (i < n - 1)
- {
- networks += ", ";
- }
- }
- return networks;
- }
- // Connect to Wifi using the loaded SSID and Password
- bool connectToWifi();
- // Check if the Dev Board is connected to Wifi
- bool isConnectedToWifi() { return WiFi.status() == WL_CONNECTED; }
- // Read serial data until newline character
- String readSerialLine();
- // Clear serial buffer to avoid any residual data
- void clearSerialBuffer()
- {
- while (Serial.available() > 0)
- {
- Serial.read();
- }
- }
- // Turn on and off the LED
- void ledAction(int pin = G_PIN, int timeout = 250)
- {
- digitalWrite(pin, ON);
- delay(timeout);
- digitalWrite(pin, OFF);
- delay(timeout);
- }
- // Display LED sequence when Wifi Board is first connected to the Flipper
- void ledStart()
- {
- pinMode(B_PIN, OUTPUT); // Set Blue Pin mode as output
- pinMode(G_PIN, OUTPUT); // Set Green Pin mode as output
- pinMode(R_PIN, OUTPUT); // Set Red Pin mode as output
- digitalWrite(B_PIN, OFF);
- digitalWrite(R_PIN, OFF);
- ledAction();
- ledAction();
- ledAction();
- }
- // Starting LED (Green only)
- void ledStatus()
- {
- if (this->useLED)
- {
- digitalWrite(B_PIN, OFF);
- digitalWrite(R_PIN, OFF);
- digitalWrite(G_PIN, ON);
- }
- }
- // Turn off all LEDs
- void ledOff()
- {
- digitalWrite(B_PIN, OFF);
- digitalWrite(G_PIN, OFF);
- digitalWrite(R_PIN, OFF);
- }
- // get IP addresss
- String getIPAddress()
- {
- return WiFi.localIP().toString();
- }
- private:
- const char *settingsFilePath = "/flipper-http.json"; // Path to the settings file in the SPIFFS file system
- char loadedSSID[64] = {0}; // Variable to store SSID
- char loadedPassword[64] = {0}; // Variable to store password
- bool useLED = true; // Variable to control LED usage
- bool readSerialSettings(String receivedData, bool connectAfterSave);
- };
- // Connect to Wifi using the loaded SSID and Password
- bool FlipperHTTP::connectToWifi()
- {
- if (String(loadedSSID) == "" || String(loadedPassword) == "")
- {
- Serial.println("[ERROR] WiFi SSID or Password is empty.");
- return false;
- }
- WiFi.disconnect(true); // Ensure WiFi is disconnected before reconnecting
- WiFi.begin(loadedSSID, loadedPassword);
- int i = 0;
- while (!this->isConnectedToWifi() && i < 20)
- {
- delay(500);
- i++;
- Serial.print(".");
- }
- Serial.println(); // Move to next line after dots
- if (this->isConnectedToWifi())
- {
- Serial.println("[SUCCESS] Successfully connected to Wifi.");
- return true;
- }
- else
- {
- Serial.println("[ERROR] Failed to connect to Wifi.");
- return false;
- }
- }
- // Save WiFi settings to SPIFFS
- bool FlipperHTTP::saveWifiSettings(String jsonData)
- {
- DynamicJsonDocument doc(1024);
- DeserializationError error = deserializeJson(doc, jsonData);
- if (error)
- {
- Serial.println("[ERROR] Failed to parse JSON data.");
- return false;
- }
- const char *newSSID = doc["ssid"];
- const char *newPassword = doc["password"];
- // Load existing settings if they exist
- DynamicJsonDocument existingDoc(2048);
- File file = SPIFFS.open(settingsFilePath, FILE_READ);
- if (file)
- {
- deserializeJson(existingDoc, file);
- file.close();
- }
- // Check if SSID is already saved
- bool found = false;
- for (JsonObject wifi : existingDoc["wifi_list"].as<JsonArray>())
- {
- if (wifi["ssid"] == newSSID)
- {
- found = true;
- break;
- }
- }
- // Add new SSID and password if not found
- if (!found)
- {
- JsonArray wifiList = existingDoc["wifi_list"].to<JsonArray>();
- JsonObject newWifi = wifiList.createNestedObject();
- newWifi["ssid"] = newSSID;
- newWifi["password"] = newPassword;
- // Save updated list to file
- file = SPIFFS.open(settingsFilePath, FILE_WRITE);
- if (!file)
- {
- Serial.println("[ERROR] Failed to open file for writing.");
- return false;
- }
- serializeJson(existingDoc, file);
- file.close();
- }
- Serial.print("[SUCCESS] Settings saved to SPIFFS.");
- return true;
- }
- // Load WiFi settings from SPIFFS and attempt to connect
- bool FlipperHTTP::loadWifiSettings()
- {
- File file = SPIFFS.open(settingsFilePath, FILE_READ);
- if (!file)
- {
- return false;
- }
- // Read the entire file content
- String fileContent = file.readString();
- file.close();
- DynamicJsonDocument doc(2048);
- DeserializationError error = deserializeJson(doc, fileContent);
- if (error)
- {
- return false;
- }
- JsonArray wifiList = doc["wifi_list"].as<JsonArray>();
- for (JsonObject wifi : wifiList)
- {
- const char *ssid = wifi["ssid"];
- const char *password = wifi["password"];
- strlcpy(loadedSSID, ssid, sizeof(loadedSSID));
- strlcpy(loadedPassword, password, sizeof(loadedPassword));
- WiFi.begin(ssid, password);
- int attempts = 0;
- while (!this->isConnectedToWifi() && attempts < 4) // 2 seconds total, 500ms delay each
- {
- delay(500);
- attempts++;
- }
- if (this->isConnectedToWifi())
- {
- return true;
- }
- }
- return false;
- }
- String FlipperHTTP::readSerialLine()
- {
- String receivedData = "";
- while (Serial.available() > 0)
- {
- char incomingChar = Serial.read();
- if (incomingChar == '\n')
- {
- break;
- }
- receivedData += incomingChar;
- delay(1); // Minimal delay to allow buffer to fill
- }
- receivedData.trim(); // Remove any leading/trailing whitespace
- return receivedData;
- }
- bool FlipperHTTP::readSerialSettings(String receivedData, bool connectAfterSave)
- {
- DynamicJsonDocument doc(1024);
- DeserializationError error = deserializeJson(doc, receivedData);
- if (error)
- {
- Serial.print("[ERROR] Failed to parse JSON: ");
- Serial.println(error.c_str());
- return false;
- }
- // Extract values from JSON
- if (doc.containsKey("ssid") && doc.containsKey("password"))
- {
- strlcpy(loadedSSID, doc["ssid"], sizeof(loadedSSID)); // save ssid
- strlcpy(loadedPassword, doc["password"], sizeof(loadedPassword)); // save password
- }
- else
- {
- Serial.println("[ERROR] JSON does not contain ssid and password.");
- return false;
- }
- // Save to SPIFFS
- if (!this->saveWifiSettings(receivedData))
- {
- Serial.println("[ERROR] Failed to save settings to file.");
- return false;
- }
- // Attempt to reconnect with new settings
- if (connectAfterSave && this->connectToWifi())
- {
- Serial.println("[SUCCESS] Connected to the new Wifi network.");
- }
- return true;
- }
- String FlipperHTTP::get(String url)
- {
- WiFiClientSecure client;
- client.setInsecure(); // Bypass certificate validation
- HTTPClient http;
- String payload = "";
- if (http.begin(client, url))
- {
- int httpCode = http.GET();
- if (httpCode > 0)
- {
- payload = http.getString();
- http.end();
- return payload;
- }
- else
- {
- Serial.print("[ERROR] GET Request Failed, error: ");
- Serial.println(http.errorToString(httpCode).c_str());
- }
- http.end();
- }
- else
- {
- Serial.println("[ERROR] Unable to connect to the server.");
- }
- // Clear serial buffer to avoid any residual data
- this->clearSerialBuffer();
- return payload;
- }
- String FlipperHTTP::get(String url, const char *headerKeys[], const char *headerValues[], int headerSize)
- {
- WiFiClientSecure client;
- client.setInsecure(); // Bypass certificate
- HTTPClient http;
- String payload = "";
- http.collectHeaders(headerKeys, headerSize);
- if (http.begin(client, url))
- {
- for (int i = 0; i < headerSize; i++)
- {
- http.addHeader(headerKeys[i], headerValues[i]);
- }
- int httpCode = http.GET();
- if (httpCode > 0)
- {
- payload = http.getString();
- http.end();
- return payload;
- }
- else
- {
- Serial.print("[ERROR] GET Request Failed, error: ");
- Serial.println(http.errorToString(httpCode).c_str());
- }
- http.end();
- }
- else
- {
- Serial.println("[ERROR] Unable to connect to the server.");
- }
- // Clear serial buffer to avoid any residual data
- this->clearSerialBuffer();
- return payload;
- }
- String FlipperHTTP::delete_request(String url, String payload)
- {
- WiFiClientSecure client;
- client.setInsecure(); // Bypass certificate
- HTTPClient http;
- String response = "";
- if (http.begin(client, url))
- {
- int httpCode = http.sendRequest("DELETE", payload);
- if (httpCode > 0)
- {
- response = http.getString();
- http.end();
- return response;
- }
- else
- {
- Serial.print("[ERROR] DELETE Request Failed, error: ");
- Serial.println(http.errorToString(httpCode).c_str());
- }
- http.end();
- }
- else
- {
- Serial.println("[ERROR] Unable to connect to the server.");
- }
- // Clear serial buffer to avoid any residual data
- this->clearSerialBuffer();
- return response;
- }
- String FlipperHTTP::delete_request(String url, String payload, const char *headerKeys[], const char *headerValues[], int headerSize)
- {
- WiFiClientSecure client;
- client.setInsecure(); // Bypass certificate
- HTTPClient http;
- String response = "";
- http.collectHeaders(headerKeys, headerSize);
- if (http.begin(client, url))
- {
- for (int i = 0; i < headerSize; i++)
- {
- http.addHeader(headerKeys[i], headerValues[i]);
- }
- int httpCode = http.sendRequest("DELETE", payload);
- if (httpCode > 0)
- {
- response = http.getString();
- http.end();
- return response;
- }
- else
- {
- Serial.print("[ERROR] DELETE Request Failed, error: ");
- Serial.println(http.errorToString(httpCode).c_str());
- }
- http.end();
- }
- else
- {
- Serial.println("[ERROR] Unable to connect to the server.");
- }
- // Clear serial buffer to avoid any residual data
- this->clearSerialBuffer();
- return response;
- }
- String FlipperHTTP::post(String url, String payload, const char *headerKeys[], const char *headerValues[], int headerSize)
- {
- WiFiClientSecure client;
- client.setInsecure(); // Bypass certificate
- HTTPClient http;
- String response = "";
- http.collectHeaders(headerKeys, headerSize);
- if (http.begin(client, url))
- {
- for (int i = 0; i < headerSize; i++)
- {
- http.addHeader(headerKeys[i], headerValues[i]);
- }
- int httpCode = http.POST(payload);
- if (httpCode > 0)
- {
- response = http.getString();
- http.end();
- return response;
- }
- else
- {
- Serial.print("[ERROR] POST Request Failed, error: ");
- Serial.println(http.errorToString(httpCode).c_str());
- }
- http.end();
- }
- else
- {
- Serial.println("[ERROR] Unable to connect to the server.");
- }
- // Clear serial buffer to avoid any residual data
- this->clearSerialBuffer();
- return response;
- }
- String FlipperHTTP::post(String url, String payload)
- {
- WiFiClientSecure client;
- client.setInsecure(); // Bypass certificate
- HTTPClient http;
- String response = "";
- if (http.begin(client, url))
- {
- int httpCode = http.POST(payload);
- if (httpCode > 0)
- {
- response = http.getString();
- http.end();
- return response;
- }
- else
- {
- Serial.print("[ERROR] POST Request Failed, error: ");
- Serial.println(http.errorToString(httpCode).c_str());
- }
- http.end();
- }
- else
- {
- Serial.println("[ERROR] Unable to connect to the server.");
- }
- // Clear serial buffer to avoid any residual data
- this->clearSerialBuffer();
- return response;
- }
- String FlipperHTTP::put(String url, String payload, const char *headerKeys[], const char *headerValues[], int headerSize)
- {
- WiFiClientSecure client;
- client.setInsecure(); // Bypass certificate
- HTTPClient http;
- String response = "";
- http.collectHeaders(headerKeys, headerSize);
- if (http.begin(client, url))
- {
- for (int i = 0; i < headerSize; i++)
- {
- http.addHeader(headerKeys[i], headerValues[i]);
- }
- int httpCode = http.PUT(payload);
- if (httpCode > 0)
- {
- response = http.getString();
- http.end();
- return response;
- }
- else
- {
- Serial.print("[ERROR] PUT Request Failed, error: ");
- Serial.println(http.errorToString(httpCode).c_str());
- }
- http.end();
- }
- else
- {
- Serial.println("[ERROR] Unable to connect to the server.");
- }
- // Clear serial buffer to avoid any residual data
- this->clearSerialBuffer();
- return response;
- }
- String FlipperHTTP::put(String url, String payload)
- {
- WiFiClientSecure client;
- client.setInsecure(); // Bypass certificate
- HTTPClient http;
- String response = "";
- if (http.begin(client, url))
- {
- int httpCode = http.PUT(payload);
- if (httpCode > 0)
- {
- response = http.getString();
- http.end();
- return response;
- }
- else
- {
- Serial.print("[ERROR] PUT Request Failed, error: ");
- Serial.println(http.errorToString(httpCode).c_str());
- }
- http.end();
- }
- else
- {
- Serial.println("[ERROR] Unable to connect to the server.");
- }
- // Clear serial buffer to avoid any residual data
- this->clearSerialBuffer();
- return response;
- }
- bool FlipperHTTP::get_bytes_to_file(String url, const char *headerKeys[], const char *headerValues[], int headerSize)
- {
- WiFiClientSecure client;
- client.setInsecure(); // Bypass certificate
- HTTPClient http;
- http.collectHeaders(headerKeys, headerSize);
- if (http.begin(client, url))
- {
- for (int i = 0; i < headerSize; i++)
- {
- http.addHeader(headerKeys[i], headerValues[i]);
- }
- int httpCode = http.GET();
- if (httpCode > 0)
- {
- Serial.println("[GET/SUCCESS]");
- int len = http.getSize();
- uint8_t buff[512] = {0};
- WiFiClient *stream = http.getStreamPtr();
- // Check available heap memory before starting
- size_t freeHeap = ESP.getFreeHeap();
- const size_t minHeapThreshold = 1024; // Minimum heap space to avoid overflow
- if (freeHeap < minHeapThreshold)
- {
- Serial.println("[ERROR] Not enough memory to start processing the response.");
- http.end();
- return false;
- }
- // Stream data while connected and available
- while (http.connected() && (len > 0 || len == -1))
- {
- size_t size = stream->available();
- if (size)
- {
- int c = stream->readBytes(buff, ((size > sizeof(buff)) ? sizeof(buff) : size));
- Serial.write(buff, c); // Write data to serial
- if (len > 0)
- {
- len -= c;
- }
- }
- delay(1); // Yield control to the system
- }
- freeHeap = ESP.getFreeHeap();
- if (freeHeap < minHeapThreshold)
- {
- Serial.println("[ERROR] Not enough memory to continue processing the response.");
- http.end();
- return false;
- }
- // Flush the serial buffer to ensure all data is sent
- http.end();
- Serial.flush();
- Serial.println();
- Serial.println("[GET/END]");
- return true;
- }
- else
- {
- Serial.printf("[ERROR] GET request failed with error: %s\n", http.errorToString(httpCode).c_str());
- }
- http.end();
- }
- else
- {
- Serial.println("[ERROR] Unable to connect to the server.");
- }
- return false;
- }
- bool FlipperHTTP::post_bytes_to_file(String url, String payload, const char *headerKeys[], const char *headerValues[], int headerSize)
- {
- WiFiClientSecure client;
- client.setInsecure(); // Bypass certificate
- HTTPClient http;
- http.collectHeaders(headerKeys, headerSize);
- if (http.begin(client, url))
- {
- for (int i = 0; i < headerSize; i++)
- {
- http.addHeader(headerKeys[i], headerValues[i]);
- }
- int httpCode = http.POST(payload);
- if (httpCode > 0)
- {
- Serial.println("[POST/SUCCESS]");
- int len = http.getSize(); // Get the response content length
- uint8_t buff[512] = {0}; // Buffer for reading data
- WiFiClient *stream = http.getStreamPtr();
- // Check available heap memory before starting
- size_t freeHeap = ESP.getFreeHeap();
- const size_t minHeapThreshold = 1024; // Minimum heap space to avoid overflow
- if (freeHeap < minHeapThreshold)
- {
- Serial.println("[ERROR] Not enough memory to start processing the response.");
- http.end();
- return false;
- }
- // Stream data while connected and available
- while (http.connected() && (len > 0 || len == -1))
- {
- size_t size = stream->available();
- if (size)
- {
- int c = stream->readBytes(buff, ((size > sizeof(buff)) ? sizeof(buff) : size));
- Serial.write(buff, c); // Write data to serial
- if (len > 0)
- {
- len -= c;
- }
- }
- delay(1); // Yield control to the system
- }
- freeHeap = ESP.getFreeHeap();
- if (freeHeap < minHeapThreshold)
- {
- Serial.println("[ERROR] Not enough memory to continue processing the response.");
- http.end();
- return false;
- }
- http.end();
- // Flush the serial buffer to ensure all data is sent
- Serial.flush();
- Serial.println();
- Serial.println("[POST/END]");
- return true;
- }
- else
- {
- Serial.printf("[ERROR] POST request failed with error: %s\n", http.errorToString(httpCode).c_str());
- }
- http.end();
- }
- else
- {
- Serial.println("[ERROR] Unable to connect to the server.");
- }
- return false;
- }
- // Main loop for flipper-http.ino that handles all of the commands
- void FlipperHTTP::loop()
- {
- // Check if there's incoming serial data
- if (Serial.available() > 0)
- {
- // Read the incoming serial data until newline
- String _data = this->readSerialLine();
- if (_data.length() == 0)
- {
- // No complete command received
- return;
- }
- this->ledStatus();
- // print the available commands
- if (_data.startsWith("[LIST]"))
- {
- Serial.println("[LIST],[PING], [REBOOT], [WIFI/IP], [WIFI/SCAN], [WIFI/SAVE], [WIFI/CONNECT], [WIFI/DISCONNECT], [WIFI/LIST], [GET], [GET/HTTP], [POST/HTTP], [PUT/HTTP], [DELETE/HTTP], [GET/BYTES], [POST/BYTES], [PARSE], [PARSE/ARRAY], [LED/ON], [LED/OFF], [IP/ADDRESS]");
- }
- // handle [LED/ON] command
- else if (_data.startsWith("[LED/ON]"))
- {
- this->useLED = true;
- }
- // handle [LED/OFF] command
- else if (_data.startsWith("[LED/OFF]"))
- {
- this->useLED = false;
- }
- // handle [IP/ADDRESS] command (local IP)
- else if (_data.startsWith("[IP/ADDRESS]"))
- {
- Serial.println(this->getIPAddress());
- }
- // handle [WIFI/IP] command ip of connected wifi
- else if (_data.startsWith("[WIFI/IP]"))
- {
- if (!this->isConnectedToWifi() && !this->connectToWifi())
- {
- Serial.println("[ERROR] Not connected to Wifi. Failed to reconnect.");
- this->ledOff();
- return;
- }
- // Get Request
- String jsonData = this->get("https://httpbin.org/get");
- if (jsonData == "")
- {
- Serial.println("[ERROR] GET request failed or returned empty data.");
- return;
- }
- DynamicJsonDocument doc(1024);
- DeserializationError error = deserializeJson(doc, jsonData);
- if (error)
- {
- Serial.print("[ERROR] Failed to parse JSON.");
- this->ledOff();
- return;
- }
- if (!doc.containsKey("origin"))
- {
- Serial.println("[ERROR] JSON does not contain origin.");
- this->ledOff();
- return;
- }
- Serial.println(doc["origin"].as<String>());
- }
- // Ping/Pong to see if board/flipper is connected
- else if (_data.startsWith("[PING]"))
- {
- Serial.println("[PONG]");
- }
- // Handle [REBOOT] command
- else if (_data.startsWith("[REBOOT]"))
- {
- this->useLED = true;
- ESP.restart();
- }
- // scan for wifi networks
- else if (_data.startsWith("[WIFI/SCAN]"))
- {
- Serial.println(this->scanWifiNetworks());
- Serial.flush();
- }
- // Handle Wifi list command
- else if (_data.startsWith("[WIFI/LIST]"))
- {
- File file = SPIFFS.open(settingsFilePath, FILE_READ);
- if (!file)
- {
- Serial.println("[ERROR] Failed to open file for reading.");
- return;
- }
- // Read the entire file content
- String fileContent = file.readString();
- file.close();
- Serial.println(fileContent);
- Serial.flush();
- }
- // Handle [WIFI/SAVE] command
- else if (_data.startsWith("[WIFI/SAVE]"))
- {
- // Extract JSON data by removing the command part
- String jsonData = _data.substring(strlen("[WIFI/SAVE]"));
- jsonData.trim(); // Remove any leading/trailing whitespace
- // Parse and save the settings
- if (this->readSerialSettings(jsonData, true))
- {
- Serial.println("[SUCCESS] Wifi settings saved.");
- }
- else
- {
- Serial.println("[ERROR] Failed to save Wifi settings.");
- }
- }
- // Handle [WIFI/CONNECT] command
- else if (_data == "[WIFI/CONNECT]")
- {
- // Check if WiFi is already connected
- if (!this->isConnectedToWifi())
- {
- // Attempt to connect to Wifi
- if (this->connectToWifi())
- {
- Serial.println("[SUCCESS] Connected to Wifi.");
- }
- else
- {
- Serial.println("[ERROR] Failed to connect to Wifi.");
- }
- }
- else
- {
- Serial.println("[INFO] Already connected to Wifi.");
- }
- }
- // Handle [WIFI/DISCONNECT] command
- else if (_data == "[WIFI/DISCONNECT]")
- {
- WiFi.disconnect(true);
- Serial.println("[DISCONNECTED] Wifi has been disconnected.");
- }
- // Handle [GET] command
- else if (_data.startsWith("[GET]"))
- {
- if (!this->isConnectedToWifi() && !this->connectToWifi())
- {
- Serial.println("[ERROR] Not connected to Wifi. Failed to reconnect.");
- this->ledOff();
- return;
- }
- // Extract URL by removing the command part
- String url = _data.substring(strlen("[GET]"));
- url.trim();
- // GET request
- String getData = this->get(url);
- if (getData != "")
- {
- Serial.println("[GET/SUCCESS] GET request successful.");
- Serial.println(getData);
- Serial.flush();
- Serial.println();
- Serial.println("[GET/END]");
- }
- else
- {
- Serial.println("[ERROR] GET request failed or returned empty data.");
- }
- }
- // Handle [GET/HTTP] command
- else if (_data.startsWith("[GET/HTTP]"))
- {
- if (!this->isConnectedToWifi() && !this->connectToWifi())
- {
- Serial.println("[ERROR] Not connected to Wifi. Failed to reconnect.");
- this->ledOff();
- return;
- }
- // Extract the JSON by removing the command part
- String jsonData = _data.substring(strlen("[GET/HTTP]"));
- jsonData.trim();
- DynamicJsonDocument doc(1024);
- DeserializationError error = deserializeJson(doc, jsonData);
- if (error)
- {
- Serial.print("[ERROR] Failed to parse JSON.");
- this->ledOff();
- return;
- }
- // Extract values from JSON
- if (!doc.containsKey("url"))
- {
- Serial.println("[ERROR] JSON does not contain url.");
- this->ledOff();
- return;
- }
- String url = doc["url"];
- // Extract headers if available
- const char *headerKeys[10];
- const char *headerValues[10];
- int headerSize = 0;
- if (doc.containsKey("headers"))
- {
- JsonObject headers = doc["headers"];
- for (JsonPair header : headers)
- {
- headerKeys[headerSize] = header.key().c_str();
- headerValues[headerSize] = header.value();
- headerSize++;
- }
- }
- // GET request
- String getData = this->get(url, headerKeys, headerValues, headerSize);
- if (getData != "")
- {
- Serial.println("[GET/SUCCESS] GET request successful.");
- Serial.println(getData);
- Serial.flush();
- Serial.println();
- Serial.println("[GET/END]");
- }
- else
- {
- Serial.println("[ERROR] GET request failed or returned empty data.");
- }
- }
- // Handle [POST/HTTP] command
- else if (_data.startsWith("[POST/HTTP]"))
- {
- if (!this->isConnectedToWifi() && !this->connectToWifi())
- {
- Serial.println("[ERROR] Not connected to Wifi. Failed to reconnect.");
- this->ledOff();
- return;
- }
- // Extract the JSON by removing the command part
- String jsonData = _data.substring(strlen("[POST/HTTP]"));
- jsonData.trim();
- DynamicJsonDocument doc(1024);
- DeserializationError error = deserializeJson(doc, jsonData);
- if (error)
- {
- Serial.print("[ERROR] Failed to parse JSON.");
- this->ledOff();
- return;
- }
- // Extract values from JSON
- if (!doc.containsKey("url") || !doc.containsKey("payload"))
- {
- Serial.println("[ERROR] JSON does not contain url or payload.");
- this->ledOff();
- return;
- }
- String url = doc["url"];
- String payload = doc["payload"];
- // Extract headers if available
- const char *headerKeys[10];
- const char *headerValues[10];
- int headerSize = 0;
- if (doc.containsKey("headers"))
- {
- JsonObject headers = doc["headers"];
- for (JsonPair header : headers)
- {
- headerKeys[headerSize] = header.key().c_str();
- headerValues[headerSize] = header.value();
- headerSize++;
- }
- }
- // POST request
- String postData = this->post(url, payload, headerKeys, headerValues, headerSize);
- if (postData != "")
- {
- Serial.println("[POST/SUCCESS] POST request successful.");
- Serial.println(postData);
- Serial.flush();
- Serial.println();
- Serial.println("[POST/END]");
- }
- else
- {
- Serial.println("[ERROR] POST request failed or returned empty data.");
- }
- }
- // Handle [PUT/HTTP] command
- else if (_data.startsWith("[PUT/HTTP]"))
- {
- if (!this->isConnectedToWifi() && !this->connectToWifi())
- {
- Serial.println("[ERROR] Not connected to Wifi. Failed to reconnect.");
- this->ledOff();
- return;
- }
- // Extract the JSON by removing the command part
- String jsonData = _data.substring(strlen("[PUT/HTTP]"));
- jsonData.trim();
- DynamicJsonDocument doc(1024);
- DeserializationError error = deserializeJson(doc, jsonData);
- if (error)
- {
- Serial.print("[ERROR] Failed to parse JSON.");
- this->ledOff();
- return;
- }
- // Extract values from JSON
- if (!doc.containsKey("url") || !doc.containsKey("payload"))
- {
- Serial.println("[ERROR] JSON does not contain url or payload.");
- this->ledOff();
- return;
- }
- String url = doc["url"];
- String payload = doc["payload"];
- // Extract headers if available
- const char *headerKeys[10];
- const char *headerValues[10];
- int headerSize = 0;
- if (doc.containsKey("headers"))
- {
- JsonObject headers = doc["headers"];
- for (JsonPair header : headers)
- {
- headerKeys[headerSize] = header.key().c_str();
- headerValues[headerSize] = header.value();
- headerSize++;
- }
- }
- // PUT request
- String putData = this->put(url, payload, headerKeys, headerValues, headerSize);
- if (putData != "")
- {
- Serial.println("[PUT/SUCCESS] PUT request successful.");
- Serial.println(putData);
- Serial.flush();
- Serial.println();
- Serial.println("[PUT/END]");
- }
- else
- {
- Serial.println("[ERROR] PUT request failed or returned empty data.");
- }
- }
- // Handle [DELETE/HTTP] command
- else if (_data.startsWith("[DELETE/HTTP]"))
- {
- if (!this->isConnectedToWifi() && !this->connectToWifi())
- {
- Serial.println("[ERROR] Not connected to Wifi. Failed to reconnect.");
- this->ledOff();
- return;
- }
- // Extract the JSON by removing the command part
- String jsonData = _data.substring(strlen("[DELETE/HTTP]"));
- jsonData.trim();
- DynamicJsonDocument doc(1024);
- DeserializationError error = deserializeJson(doc, jsonData);
- if (error)
- {
- Serial.print("[ERROR] Failed to parse JSON.");
- this->ledOff();
- return;
- }
- // Extract values from JSON
- if (!doc.containsKey("url") || !doc.containsKey("payload"))
- {
- Serial.println("[ERROR] JSON does not contain url or payload.");
- this->ledOff();
- return;
- }
- String url = doc["url"];
- String payload = doc["payload"];
- // Extract headers if available
- const char *headerKeys[10];
- const char *headerValues[10];
- int headerSize = 0;
- if (doc.containsKey("headers"))
- {
- JsonObject headers = doc["headers"];
- for (JsonPair header : headers)
- {
- headerKeys[headerSize] = header.key().c_str();
- headerValues[headerSize] = header.value();
- headerSize++;
- }
- }
- // DELETE request
- String deleteData = this->delete_request(url, payload, headerKeys, headerValues, headerSize);
- if (deleteData != "")
- {
- Serial.println("[DELETE/SUCCESS] DELETE request successful.");
- Serial.println(deleteData);
- Serial.flush();
- Serial.println();
- Serial.println("[DELETE/END]");
- }
- else
- {
- Serial.println("[ERROR] DELETE request failed or returned empty data.");
- }
- }
- // Handle [GET/BYTES]
- else if (_data.startsWith("[GET/BYTES]"))
- {
- if (!this->isConnectedToWifi() && !this->connectToWifi())
- {
- Serial.println("[ERROR] Not connected to Wifi. Failed to reconnect.");
- this->ledOff();
- return;
- }
- // Extract the JSON by removing the command part
- String jsonData = _data.substring(strlen("[GET/BYTES]"));
- jsonData.trim();
- DynamicJsonDocument doc(1024);
- DeserializationError error = deserializeJson(doc, jsonData);
- if (error)
- {
- Serial.print("[ERROR] Failed to parse JSON.");
- this->ledOff();
- return;
- }
- // Extract values from JSON
- if (!doc.containsKey("url"))
- {
- Serial.println("[ERROR] JSON does not contain url.");
- this->ledOff();
- return;
- }
- String url = doc["url"];
- // Extract headers if available
- const char *headerKeys[10];
- const char *headerValues[10];
- int headerSize = 0;
- if (doc.containsKey("headers"))
- {
- JsonObject headers = doc["headers"];
- for (JsonPair header : headers)
- {
- headerKeys[headerSize] = header.key().c_str();
- headerValues[headerSize] = header.value();
- headerSize++;
- }
- }
- // GET request
- if (!this->get_bytes_to_file(url, headerKeys, headerValues, headerSize))
- {
- Serial.println("[ERROR] GET request failed or returned empty data.");
- }
- }
- // handle [POST/BYTES]
- else if (_data.startsWith("[POST/BYTES]"))
- {
- if (!this->isConnectedToWifi() && !this->connectToWifi())
- {
- Serial.println("[ERROR] Not connected to Wifi. Failed to reconnect.");
- this->ledOff();
- return;
- }
- // Extract the JSON by removing the command part
- String jsonData = _data.substring(strlen("[POST/BYTES]"));
- jsonData.trim();
- DynamicJsonDocument doc(1024);
- DeserializationError error = deserializeJson(doc, jsonData);
- if (error)
- {
- Serial.print("[ERROR] Failed to parse JSON.");
- this->ledOff();
- return;
- }
- // Extract values from JSON
- if (!doc.containsKey("url") || !doc.containsKey("payload"))
- {
- Serial.println("[ERROR] JSON does not contain url or payload.");
- this->ledOff();
- return;
- }
- String url = doc["url"];
- String payload = doc["payload"];
- // Extract headers if available
- const char *headerKeys[10];
- const char *headerValues[10];
- int headerSize = 0;
- if (doc.containsKey("headers"))
- {
- JsonObject headers = doc["headers"];
- for (JsonPair header : headers)
- {
- headerKeys[headerSize] = header.key().c_str();
- headerValues[headerSize] = header.value();
- headerSize++;
- }
- }
- // POST request
- if (!this->post_bytes_to_file(url, payload, headerKeys, headerValues, headerSize))
- {
- Serial.println("[ERROR] POST request failed or returned empty data.");
- }
- }
- // Handle [PARSE] command
- // the user will append the key to read from the json
- // example: [PARSE]{"key":"name","json":{"name":"John Doe"}}
- else if (_data.startsWith("[PARSE]"))
- {
- // Extract the JSON by removing the command part
- String jsonData = _data.substring(strlen("[PARSE]"));
- jsonData.trim();
- DynamicJsonDocument doc(1024);
- DeserializationError error = deserializeJson(doc, jsonData);
- if (error)
- {
- Serial.print("[ERROR] Failed to parse JSON.");
- this->ledOff();
- return;
- }
- // Extract values from JSON
- if (!doc.containsKey("key") || !doc.containsKey("json"))
- {
- Serial.println("[ERROR] JSON does not contain key or json.");
- this->ledOff();
- return;
- }
- String key = doc["key"];
- JsonObject json = doc["json"];
- if (json.containsKey(key))
- {
- Serial.println(json[key].as<String>());
- }
- else
- {
- Serial.println("[ERROR] Key not found in JSON.");
- }
- }
- // Handle [PARSE/ARRAY] command
- // the user will append the key to read and the index of the array to get it's key from the json
- // example: [PARSE/ARRAY]{"key":"name","index":"1","json":{"name":["John Doe","Jane Doe"]}}
- // this would return Jane Doe
- // and in this example it would return {"flavor": "red"}:
- // example: [PARSE/ARRAY]{"key":"flavor","index":"1","json":{"name":[{"flavor": "blue"},{"flavor": "red"}]}}
- else if (_data.startsWith("[PARSE/ARRAY]"))
- {
- // Extract the JSON by removing the command part
- String jsonData = _data.substring(strlen("[PARSE/ARRAY]"));
- jsonData.trim();
- DynamicJsonDocument doc(1024);
- DeserializationError error = deserializeJson(doc, jsonData);
- if (error)
- {
- Serial.print("[ERROR] Failed to parse JSON.");
- this->ledOff();
- return;
- }
- // Extract values from JSON
- if (!doc.containsKey("key") || !doc.containsKey("index") || !doc.containsKey("json"))
- {
- Serial.println("[ERROR] JSON does not contain key, index, or json.");
- this->ledOff();
- return;
- }
- String key = doc["key"];
- int index = doc["index"];
- JsonArray json = doc["json"];
- if (json[index].containsKey(key))
- {
- Serial.println(json[index][key].as<String>());
- }
- else
- {
- Serial.println("[ERROR] Key not found in JSON.");
- }
- }
- this->ledOff();
- }
- }
|