void ThingspeakClient::getLastChannelItem(String channelId, String readApiKey) { JsonStreamingParser parser; parser.setListener(this); WiFiClient client; // http://api.thingspeak.com/channels/CHANNEL_ID/feeds.json?results=2&api_key=API_KEY const char host[] = "api.thingspeak.com"; String url = "/channels/" + channelId +"/feeds.json?results=1&api_key=" + readApiKey; const int httpPort = 80; if (!client.connect(host, httpPort)) { Serial.println("connection failed"); return; } Serial.print("Requesting URL: "); Serial.println(url); // This will send the request to the server client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n"); int retryCounter = 0; while(!client.available()) { Serial.println("."); delay(1000); retryCounter++; if (retryCounter > 10) { return; } } int pos = 0; boolean isBody = false; char c; int size = 0; client.setNoDelay(false); while(client.connected()) { while((size = client.available()) > 0) { c = client.read(); if (c == '{' || c == '[') { isBody = true; } if (isBody) { parser.parse(c); } } } }
void EIoTCloudRestApi::sendParameter(const char * instaceParamId, String value) { WiFiClient client; while(!client.connect(EIOT_CLOUD_ADDRESS, EIOT_CLOUD_PORT)) { debug("connection failed"); wifiConnect(); } String url = ""; // URL: /RestApi/SetParameter/[instance id]/[parameter id]/[value] url += "/RestApi/SetParameter/" + String(instaceParamId) + "/" + value; // generate EasIoT cloud update parameter URL debug("POST data to URL: "); #ifdef DEBUG char buff[300]; url.toCharArray(buff, 300); debug(buff); #endif client.print(String("POST ") + url + " HTTP/1.1\r\n" + "Host: " + String(EIOT_CLOUD_ADDRESS) + "\r\n" + "Connection: close\r\n" + "Content-Length: 0\r\n" + "\r\n"); delay(100); while(client.available()){ #ifdef DEBUG String line = client.readStringUntil('\r'); line.toCharArray(buff, 300); debug(buff); #endif } }
String DHwifi::HttpRequest( String req ) { WiFiClient client; char host[99]; m_remoteServer.toCharArray( host, 99); const int httpPort = 80; if (!client.connect(host, httpPort)) { Serial.print( host ); Serial.println(" connection failed"); return ""; } client.print(String("GET ") + req + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n"); delay(10); String result; // Read all the lines of the reply from server and print them to Serial while (client.available()) { result = client.readStringUntil('\r'); } return result; }
String Iotfy_getdata(int no_of_bytes, int timeout) { int ctr=0; int pt=millis()/1000; String data=""; data.reserve(no_of_bytes); while(1) { if(client.available()) { char c=client.read(); data+=c; Serial.print(c); ctr++; if(ctr==no_of_bytes) break; } else { if(millis()/1000-pt>timeout) { pt=millis()/1000; break; } } } Serial.println("calling disconnect"); client.flush(); client.stop(); return data; }
void loop() { // NETWORKING // TODO FIGURE OUT WHETHRE THIS IS BLOCKING WiFiClient client = server.available(); if (!client) return; // TODO CONTINUE LOOPING int timeout = COMM_TIMEOUT; // TODO LESS BUSY WAIT? logMsg("New client"); while(!client.available() && --timeout>0) { delay(1); } if (timeout <= 0) { logMsg("TIMEOUT"); client.flush(); return; } // GET MSG // TODO FIGURE OUT WHY DOESN'T WORK DIRECTLY String str = client.readStringUntil(0); client.flush(); logMsg(String("Got message [") + str + "]"); // SEND REPLY client.print(processRequest(str).toString()); delay(1); logMsg("Client disonnected"); }
void loop() { static boolean packetActive = false; static uint8_t index = 0; static boolean readingReturn = false; static uint8_t rindex = 0; if (!client.connected()) { // try to connect to a new client client = server.available(); } else { // read data from the connected client if (client.available() > 0) { char c = client.read(); if (packetActive) { commandBuffer[index] = c; commandBuffer[++index] = 0; if (c == EOP) { comHandler(); packetActive = false; } } else if (c == SOP) { index = 0; commandBuffer[index] = c; commandBuffer[++index] = 0; packetActive = true; } if (returnReady) { client.println(returnBuffer); server.println(returnBuffer); Serial.println(returnBuffer); returnReady = false; } } } if (Serial.available() && !returnReady) { char s = Serial.read(); if (s == SOP) { readingReturn = true; rindex = 0; } if (readingReturn) { returnBuffer[rindex] = s; returnBuffer[++rindex] = 0; if (s == EOP) { returnReady = true; } } } }
uint8_t ESP8266WebServer::_uploadReadByte(WiFiClient& client){ int res = client.read(); if(res == -1){ while(!client.available() && client.connected()) yield(); res = client.read(); } return (uint8_t)res; }
void TimeClient::updateTime() { WiFiClient client; const int httpPort = 80; if (!client.connect("google.com", httpPort)) { Serial.println("connection failed"); return; } // This will send the request to the server client.print(String("GET / HTTP/1.1\r\n") + String("Host: google.com\r\n") + String("Connection: close\r\n\r\n")); int repeatCounter = 0; while(!client.available() && repeatCounter < 10) { delay(1000); Serial.println("."); repeatCounter++; } String line; int size = 0; client.setNoDelay(false); while(client.connected()) { while((size = client.available()) > 0) { line = client.readStringUntil('\n'); line.toUpperCase(); // example: // date: Thu, 19 Nov 2015 20:25:40 GMT if (line.startsWith("DATE: ")) { Serial.println(line.substring(23, 25) + ":" + line.substring(26, 28) + ":" +line.substring(29, 31)); int parsedHours = line.substring(23, 25).toInt(); int parsedMinutes = line.substring(26, 28).toInt(); int parsedSeconds = line.substring(29, 31).toInt(); Serial.println(String(parsedHours) + ":" + String(parsedMinutes) + ":" + String(parsedSeconds)); localEpoc = (parsedHours * 60 * 60 + parsedMinutes * 60 + parsedSeconds); Serial.println(localEpoc); localMillisAtUpdate = millis(); } } } }
void WundergroundClient::doUpdate(String url) { JsonStreamingParser parser; parser.setListener(this); WiFiClient client; const int httpPort = 80; if (!client.connect("api.wunderground.com", httpPort)) { Serial.println("connection failed"); return; } Serial.print("Requesting URL: "); Serial.println(url); // This will send the request to the server client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: api.wunderground.com\r\n" + "Connection: close\r\n\r\n"); int retryCounter = 0; while(!client.available()) { delay(1000); retryCounter++; if (retryCounter > 10) { return; } } int pos = 0; boolean isBody = false; char c; int size = 0; client.setNoDelay(false); while(client.connected()) { while((size = client.available()) > 0) { c = client.read(); if (c == '{' || c == '[') { isBody = true; } if (isBody) { parser.parse(c); } } } }
void transmitTele() { Serial.println("tele"); while(!alreadyConnectedTele) { //attempt to save a client connecting to the server teleClient = teleServer.available(); //if a client is connected, begin communication if (teleClient) { if (!alreadyConnectedTele) { // clead out the input buffer: teleClient.flush(); Serial.println("We have a new client"); alreadyConnectedTele = true; } } } for(int i = 0; i < 20; i++) { if (teleClient.available() > 0) { // read the bytes incoming from the client: char thisChar = teleClient.read(); // echo the bytes back to the client: if(thisChar == '1') teleServer.println(curSpeedKn * KNOTS_TO_MPS); if(thisChar == '2') teleServer.println(pollPing()); if(thisChar == '3') teleServer.println(distToTar()); if(thisChar == '4') teleServer.println(curLat); if(thisChar == '5') teleServer.println(curLon); if(thisChar == '6') teleServer.println(curHead); // echo the bytes to the server as well: Serial.println(thisChar); } } }
/** * Wait for a WiFiClient to connect * * @returns: True if the client is ready, false otherwise. * */ bool ESP8266WiFiMesh::waitForClient(WiFiClient curr_client, int max_wait) { int wait = max_wait; while(curr_client.connected() && !curr_client.available() && wait--) delay(3); /* Return false if the client isn't ready to communicate */ if (WiFi.status() == WL_DISCONNECTED || !curr_client.connected()) return false; return true; }
String wifiChat::checkForRequest() { tryConnect(); String requestString = ""; WiFiClient client = server.available(); Serial.print(client); if(!client) return requestString; //Serial.print("Client.available() = "); //Serial.print(client.available()); if (client.available() > 0) { char thisChar = client.read(); while(thisChar != '\n' && client.available() > 0) { requestString.concat(thisChar); thisChar = client.read(); } } return requestString; }
void loop() { // check the network connection once every 10 seconds: delay(10000); printCurrentNet(); // Trying to connect to http://hasthelargehadroncolliderdestroyedtheworldyet.com/ Serial5.println("Trying to connect to : www.hasthelargehadroncolliderdestroyedtheworldyet.com :"); httpRequest(); while( client.available() ) { Serial5.print((char)(client.read())); } Serial5.println("END"); }
//****************** Recieve data for ModBusMaster **************** void MgsModbus::MbmRun() { //****************** Read from socket **************** while (MbmClient.available()) { MbmByteArray[MbmCounter] = MbmClient.read(); if (MbmCounter > 4) { if (MbmCounter == MbmByteArray[5] + 5) { // the full answer is recieved MbmClient.stop(); MbmProcess(); #ifdef DEBUG Serial.println("recieve klaar"); #endif } } MbmCounter++; } }
void sync_led(WiFiClient client) { int new_brightness = -1; while (client.available()) { String line = client.readStringUntil('\r'); int ix_magic_ld = line.indexOf("ld"); int ix_colon = line.indexOf(":"); if (ix_magic_ld != -1) { // Sync the LEDs int ix_led = line.substring(ix_magic_ld + 2, ix_colon).toInt(); // The RGB value are encoded in Base 10 (not base 16) with "zero" padding. // LD<LED_INDEX>: FFFFFF // | | | | // 0 2 C 2 String hexval = line.substring(ix_colon + 2); long value = strtol(hexval.c_str(), NULL, 16); int led_r = value >> 16; int led_g = value >> 8 & 0xFF; int led_b = value & 0xFF; pixels.setPixelColor(ix_led, pixels.Color(led_r, led_g, led_b)); pixels.show(); #if DEBUG Serial.print("LED#"); Serial.print(ix_led); Serial.print(" <rgb>:"); Serial.print(led_r); Serial.print(','); Serial.print(led_g); Serial.print(','); Serial.print(led_b); Serial.print('\n'); #endif } int ix_magic_br = line.indexOf("brightness"); if (ix_magic_br != -1) { // Update the Brightness Values new_brightness = line.substring(ix_colon + 2).toInt(); } }
void RobotHostInterface::rcvCommand(struct HostCommand *command) { byte rawCmd = 0xFF; WiFiClient client = robotServer->available(); if (client) { Serial.print("Robot Client connected..."); Serial.println("Waiting for a command......" ); while (client.available() == 0 ) { delay( 100 ); } rawCmd = (byte)client.read(); Serial.print("Raw Command: "); Serial.print(rawCmd); command->cmd = rawCmd >> 3; command->arg = rawCmd & 0x07; Serial.print(", Cmd: "); Serial.print(command->cmd); Serial.print(", arg: "); Serial.println(command->arg); if (command->cmd == CMD_ARRIVAL || command->cmd == CMD_WATCHDOG) { if (command->cmd == CMD_ARRIVAL && getArrival()) { rawCmd = CMD_ARRIVAL << 3; setArrival(false); } else if (command->cmd == CMD_WATCHDOG) { rawCmd = 0xFF; } else { rawCmd = 0xFF; } } /* send acknowledgement */ robotServer->write(rawCmd); delay(100); client.stop(); Serial.println("Client Disconnected.\n"); } }
void loop() { // if there are incoming bytes available // from the server, read them and print them: while (client.available()) { char c = client.read(); Serial.write(c); } // if the server's disconnected, stop the client: if (!client.connected()) { Serial.println(); Serial.println("disconnecting from server."); client.stop(); // do nothing forevermore: while(true); } }
void APServer(){ WiFiClient client = server.available(); // Check if a client has connected if (!client) { return; } Serial.println(""); Serial.println("New client"); // Wait for data from client to become available while (client.connected() && !client.available()) { delay(1); } // Read the first line of HTTP request String req = client.readStringUntil('\r'); Serial.println(req); String s; String gsid; String gpwd; //if the form has been submitted if(req.indexOf("ssid")!=-1){ //TODO Make this a POST request //I'm basically hoping they're being nice int x = req.indexOf("ssid")+5; gsid = req.substring(x,req.indexOf("&",x)); x = req.indexOf("pwd")+4; gpwd = req.substring(x,req.indexOf(" ",x)); s = gsid; saveWifiConfig(gsid,gpwd); Serial.print("Restarting"); client.print("Thanks! Restarting to new configuration"); client.flush(); ESP.restart(); } else{ s = "<h1>Welcome to your ESP</h1><form action='/' method='get'><table><tr><td>SSID</td><td><input type='text' name='ssid'></td></tr><tr><td>Password</td><td><input type='text' name='pwd'></td><tr><td /><td><input type='submit' value='Submit'></td></tr></form>"; client.print(s); } client.flush(); delay(1); //Serial.println("Client disonnected"); }
void httpRequest() { // close any connection before send a new request. // This will free the socket on the WiFi shield client.stop(); // if there's a successful connection: if (client.connect("www.hasthelargehadroncolliderdestroyedtheworldyet.com", 80)) { Serial5.println("connecting..."); // send the HTTP PUT request: client.println("GET / HTTP/1.1"); client.println("Host: www.hasthelargehadroncolliderdestroyedtheworldyet.com"); //client.println("User-Agent: ArduinoWiFi/1.1"); client.println("Connection: close"); client.println(); if( client.connected() ) { Serial5.println("\tClient connected"); while( client.available() == 0 ) { //Waiting for data if( !client.connected() ) { Serial5.println("\tClient disconnected !"); break; } } } else { Serial5.println("\tClient not connected"); } } else { // if you couldn't make a connection: Serial5.println("\tconnection failed"); } }
void next_client() { // Listenning for new clients client = server.available(); if (client) { Serial.println("New client"); // bolean to locate when the http request ends boolean blank_line = true; while (client.connected()) { if (client.available()) { char c = client.read(); if (c == '\n' && blank_line) { client.println("HTTP/1.1 200 OK"); client.println("Content-Type: application/json"); client.println("Access-Control-Allow-Origin: *"); client.println("Connection: close"); client.println(); print_json(); break; } if (c == '\n') { // when starts reading a new line Serial.println(); blank_line = true; } else if (c != '\r') { // when finds a character on the current line Serial.write(c); blank_line = false; } } } // closing the client connection delay(1); client.stop(); Serial.println("Client disconnected."); } }
void WebServer::handleClient() { WiFiClient client = _server.available(); if (!client) { return; } #ifdef DEBUG DEBUG_OUTPUT.println("New client"); #endif // Wait for data from client to become available uint16_t maxWait = HTTP_MAX_DATA_WAIT; while(client.connected() && !client.available() && maxWait--){ delay(1); } if (!_parseRequest(client)) { return; } _currentClient = client; _handleRequest(); }
void waitForTarget() { //define a client object to connect to the server WiFiClient mainClient; //wait for a client to connect to the server while(!alreadyConnectedMain) { //attempt to save a client connecting to the server mainClient = mainServer.available(); //if a client is connected, begin communication if (mainClient) { if (!alreadyConnectedMain) { // clead out the input buffer: mainClient.flush(); Serial.println("We have a new client"); debugServer.println("We have a new client"); mainClient.println("Hello, client!"); alreadyConnectedMain = true; } } delay(100); delay(100); } Serial.println("writing"); debugClient.println("writing"); //mainServer.println("ready"); delay(1000); //Strings to read in latitude and longitude from the client char lat[50] = ""; char lon[50] = ""; int ind = 0; //Wait for input to be on the buffer while(!mainClient.available()); char destNum = '0'; while(!(destNum == '1' || destNum == '2' || destNum == '3')) { destNum = mainClient.read(); Serial.println(destNum); } if(destNum == '1') { tarLat = LAT1; tarLon = LON1; } if(destNum == '2') { tarLat = LAT2; tarLon = LON2; } if(destNum == '3') { tarLat = LAT3; tarLon = LON3; } /* //Read in characters from the input buffer until a new line character is reached //this will be the latitude while(mainClient.available()) { char c = mainClient.read(); lat[ind] = c; if(c == '\n') { lat[ind] = NULL; break; } ind++; } ind = 0; //Read in characters from the input buffer until a new line character is reached //this will be the longitude while(mainClient.available()) { char c = mainClient.read(); lon[ind] = c; if(c == '\n') { lon[ind] = NULL; break; } ind++; } mainClient.stop(); //convert from a string to a float tarLat = strtof(lat, NULL); tarLon = strtof(lon, NULL); //digitalWrite(LED1, LOW); //tarLat = atof(lat); //tarLon = atof(lon);*/ Serial.print("Lat: "); Serial.print(lat); Serial.print(" "); Serial.println(tarLat, 6); Serial.print("Lon: "); Serial.print(lon); Serial.print(" "); Serial.println(tarLon, 6); debugClient.print("Lat: "); debugClient.print(lat); debugClient.print(" "); debugClient.println(tarLat, 6); debugClient.print("Lon: "); debugClient.print(lon); debugClient.print(" "); debugClient.println(tarLon, 6); //Erick's //tarLat = 28.504906f; //tarLon = -81.457456f; //apt //tarLat = 28.582183f; //tarLon = -81.202770f; //apt 2 //tarLat = 28.582373f; //tarLon = -81.202996f; //curLat = 28.628811f; //curLon = -81.199479f; //mem mall //tarLat = 28.603710f; //tarLon = -81.199371f; //matt's //tarLat = 28.628391; //tarLon = -81.200013; }
void mainloop() { /////////////////// // do data logging /////////////////// if (millis() >= ulNextMeas_ms) { ds18b20(); sendTeperatureTS(temp1, temp2, temp3, temp4); ulNextMeas_ms = millis() + ulMeasDelta_ms; pfTemp1[ulMeasCount % ulNoMeasValues] = temp1; pfTemp2[ulMeasCount % ulNoMeasValues] = temp2; pfTemp3[ulMeasCount % ulNoMeasValues] = temp3; pfTemp4[ulMeasCount % ulNoMeasValues] = temp4; pulTime[ulMeasCount % ulNoMeasValues] = millis() / 1000 + ulSecs2000_timer; Serial.print("Logging Temperature1: "); Serial.print(pfTemp1[ulMeasCount % ulNoMeasValues]); Serial.print(" deg Celsius - Temperature2: "); Serial.print(pfTemp2[ulMeasCount % ulNoMeasValues]); Serial.print(" deg Celsius - Temperature3: "); Serial.print(pfTemp3[ulMeasCount % ulNoMeasValues]); Serial.print(" deg Celsius - Temperature4: "); Serial.print(pfTemp4[ulMeasCount % ulNoMeasValues]); Serial.print(" deg Celsius - Time: "); Serial.println(pulTime[ulMeasCount % ulNoMeasValues]); ulMeasCount++; } // Check if a client has connected WiFiClient client = server.available(); if (!client) { return; } // Wait until the client sends some data Serial.println("new client"); unsigned long ultimeout = millis() + 250; while (!client.available() && (millis() < ultimeout) ) { delay(1); } if (millis() > ultimeout) { Serial.println("client connection time-out!"); return; } // Read the first line of the request String sRequest = client.readStringUntil('\r'); //Serial.println(sRequest); client.flush(); // stop client, if request is empty if (sRequest == "") { Serial.println("empty request! - stopping client"); client.stop(); return; } // get path; end of path is either space or ? // Syntax is e.g. GET /?pin=MOTOR1STOP HTTP/1.1 String sPath = "", sParam = "", sCmd = ""; String sGetstart = "GET "; int iStart, iEndSpace, iEndQuest; iStart = sRequest.indexOf(sGetstart); if (iStart >= 0) { iStart += +sGetstart.length(); iEndSpace = sRequest.indexOf(" ", iStart); iEndQuest = sRequest.indexOf("?", iStart); // are there parameters? if (iEndSpace > 0) { if (iEndQuest > 0) { // there are parameters sPath = sRequest.substring(iStart, iEndQuest); sParam = sRequest.substring(iEndQuest, iEndSpace); } else { // NO parameters sPath = sRequest.substring(iStart, iEndSpace); } } } /////////////////////////////////////////////////////////////////////////////// // output parameters to serial, you may connect e.g. an Arduino and react on it /////////////////////////////////////////////////////////////////////////////// if (sParam.length() > 0) { int iEqu = sParam.indexOf("="); if (iEqu >= 0) { sCmd = sParam.substring(iEqu + 1, sParam.length()); Serial.print("Die Eingabe ist: "); Serial.println(sCmd); } } /////////////////////////// // format the html response /////////////////////////// // Startseite //////////////////////////////// String sResponse, sResponse2, sHeader; if (sPath == "/") { ulReqcount++; int iIndex = (ulMeasCount - 1) % ulNoMeasValues; sResponse = F("<html>\n<head>\n<title>WLAN Logger für Pufferspeichertemperatur</title>\n"); sResponse += F("</head>\n<body>\n<font color=\"#000000\"><body bgcolor=\"#d0d0f0\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=yes\"><h1>WLAN Logger für Pufferspeichertemperatur</h1>SMASE<BR><BR><FONT SIZE=+1>Letzte Messung um "); sResponse += F("Seite: Temperaturen -> Zeigt die gemessenen Temperaturen an <br>"); sResponse += F("<hr>Seite: Grafik -> Zeigt den Temperaturverlauf (Diagramm) der letzten 24 h an <br>"); sResponse += F("<hr>Seite: Grafik -> Zeigt den Temperaturverlauf (Tabelle) der letzten 24 h an <br>"); sResponse += F("<hr>Seite: Settings -> Einstellungen <br>"); sResponse += F(" <div style=\"clear:both;\"></div>"); sResponse2 = F("<p>Temperaturverlauf - Seiten laden länger:<BR> <a href=\"/anzeige\"><button>Temperaturen</button></a> <a href=\"/grafik\"><button>Grafik</button></a> <a href=\"/tabelle\"><button>Tabelle</button></a> <a href=\"/settings\"><button>Settings</button></a></p>"); sResponse2 += MakeHTTPFooter().c_str(); // Send the response to the client client.print(MakeHTTPHeader(sResponse.length() + sResponse2.length()).c_str()); client.print(sResponse); client.print(sResponse2); } if (sPath == "/anzeige") { ulReqcount++; int iIndex = (ulMeasCount - 1) % ulNoMeasValues; sResponse = F("<html>\n<head>\n<title>WLAN Logger für Pufferspeichertemperatur</title>\n<script type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"></script>\n"); sResponse += F("<script type=\"text/javascript\">\ngoogle.charts.load('current', {'packages':['gauge']});\n"); sResponse += F(" google.charts.setOnLoadCallback(drawGauge); \n"); sResponse += F("\nvar gaugeOptions = {min: 0, max: 100, greenFrom: 50, greenTo:75, yellowFrom: 75, yellowTo: 90,redFrom: 90, redTo: 100, minorTicks: 10, majorTicks: ['0','10','20','30','40','50','60','70','80','90','100']};\n"); sResponse += F(" var gauge; \n"); sResponse += F(" function drawGauge() { \n"); sResponse += F(" gaugeData = new google.visualization.DataTable(); \n"); sResponse += F(" gaugeData.addColumn('number', 'oben'); \n"); sResponse += F(" gaugeData.addColumn('number', 'mitte'); \n"); sResponse += F(" gaugeData.addColumn('number', 'unten'); \n"); sResponse += F(" gaugeData.addColumn('number', 'vorlauf'); \n"); sResponse += F(" gaugeData.addRows(2); \n"); sResponse += F(" gaugeData.setCell(0, 0, "); sResponse += pfTemp1[iIndex]; sResponse += F(" ); \n"); sResponse += F(" gaugeData.setCell(0, 1, "); sResponse += pfTemp2[iIndex]; sResponse += F(" ); \n"); sResponse += F(" gaugeData.setCell(0, 2, "); sResponse += pfTemp3[iIndex]; sResponse += F(" ); \n"); sResponse += F(" gaugeData.setCell(0, 3, "); sResponse += pfTemp4[iIndex]; sResponse += F(" ); \n"); sResponse += F(" gauge = new google.visualization.Gauge(document.getElementById('gauge_div')); \n"); sResponse += F(" gauge.draw(gaugeData, gaugeOptions); \n"); sResponse += F(" } \n"); sResponse += F(" </script> \n </head> \n <body> \n<font color=\"#000000\"><body bgcolor=\"#d0d0f0\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=yes\"><h1>WLAN Logger für Pufferspeichertemperatur</h1>SMASE<BR><BR><FONT SIZE=+1>Letzte Messung um "); sResponse += epoch_to_string(pulTime[iIndex]).c_str(); sResponse += F(" UTC<BR>\n"); sResponse += F("<fieldset><legend>Pufferspeicher</legend>"); sResponse += F(" <div id=\"gauge_div\" style=\"width:140px; height: 560px;\"></div> \n"); sResponse += F("</fieldset>"); sResponse += F(" <div style=\"clear:both;\"></div>"); sResponse2 = F("<p>Temperaturverlauf - Seiten laden länger:<BR> <a href=\"/lauf\"><button>Vorlauf</button></a> <a href=\"/grafik\"><button>Grafik</button></a> <a href=\"/tabelle\"><button>Tabelle</button></a> <a href=\"/settings\"><button>Settings</button></a></p>"); sResponse2 += MakeHTTPFooter().c_str(); // Send the response to the client client.print(MakeHTTPHeader(sResponse.length() + sResponse2.length()).c_str()); client.print(sResponse); client.print(sResponse2); } // Tabelle //////////////////////////////// else if (sPath == "/tabelle") //////////////////////////////////// // format the html page for /tabelle //////////////////////////////////// { ulReqcount++; unsigned long ulSizeList = MakeTable(&client, false); // get size of table first sResponse = F("<html><head><title>WLAN Logger für Pufferspeichertemperatur</title></head><body>"); sResponse += F("<font color=\"#000000\"><body bgcolor=\"#d0d0f0\">"); sResponse += F("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=yes\">"); sResponse += F("<h1>WLAN Logger für Pufferspeichertemperatur</h1>"); sResponse += F("<FONT SIZE=+1>"); sResponse += F("<a href=\"/\"><button>Startseite</button></a><BR><BR>Letzte Messungen im Abstand von "); sResponse += ulMeasDelta_ms; sResponse += F("ms<BR>"); // here the big table will follow later - but let us prepare the end first // part 2 of response - after the big table sResponse2 = MakeHTTPFooter().c_str(); // Send the response to the client - delete strings after use to keep mem low client.print(MakeHTTPHeader(sResponse.length() + sResponse2.length() + ulSizeList).c_str()); client.print(sResponse); sResponse = ""; MakeTable(&client, true); client.print(sResponse2); } // Diagramm //////////////////////////////// else if (sPath == "/grafik") /////////////////////////////////// // format the html page for /grafik /////////////////////////////////// { ulReqcount++; unsigned long ulSizeList = MakeList(&client, false); // get size of list first sResponse = F("<html>\n<head>\n<title>WLAN Logger für Pufferspeichertemperatur</title>\n<script type=\"text/javascript\" src=\"https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1','packages':['corechart']}]}\"></script>\n"); sResponse += F("<script type=\"text/javascript\"> google.setOnLoadCallback(drawChart);\nfunction drawChart() {var data = google.visualization.arrayToDataTable([\n['Zeit / UTC', 'Temperatur1', 'Temperatur2', 'Temperatur3', 'Temperatur4'],\n"); // here the big list will follow later - but let us prepare the end first // part 2 of response - after the big list sResponse2 = F("]);\nvar options = {title: 'Verlauf',\n"); sResponse2 += F("curveType:'function',legend:{ position: 'bottom'}};"); sResponse2 += F("var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));chart.draw(data, options);}\n</script>\n</head>\n"); sResponse2 += F("<body>\n<font color=\"#000000\"><body bgcolor=\"#d0d0f0\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=yes\"><h1>WLAN Logger für Pufferspeichertemperatur</h1><a href=\"/\"><button>Startseite</button></a><BR>"); sResponse2 += F("<BR>\n<div id=\"curve_chart\" style=\"width: 600px; height: 400px\"></div>"); sResponse2 += MakeHTTPFooter().c_str(); // Send the response to the client - delete strings after use to keep mem low client.print(MakeHTTPHeader(sResponse.length() + sResponse2.length() + ulSizeList).c_str()); client.print(sResponse); sResponse = ""; MakeList(&client, true); client.print(sResponse2); } // Einstellungen //////////////////////////////// else if (sPath == "/settings") { EEPROM.begin(512); delay(10); String apiKey = ""; for (int i = 81; i < 100; i++) { //DEBUG_PRINT(i); apiKey += char(EEPROM.read(i)); } EEPROM.end(); Serial.println("Thinkspeak: " + apiKey); EEPROM.begin(512); delay(10); String zeit = ""; for (int i = 100; i < 105; i++) { zeit += char(EEPROM.read(i)); } EEPROM.end(); Serial.print("Das ist die Zeitverschiebung: "); Serial.println(zeit); String zeittext = ""; if (zeit != "0000") { zeittext = "Sommerzeit"; } else { zeittext = "Winterzeit"; } ulReqcount++; unsigned long ulSizeList = MakeTable(&client, false); // get size of table first sResponse = F("<html><head><title>WLAN Logger für Pufferspeichertemperatur</title></head><body>"); sResponse += F("<font color=\"#000000\"><body bgcolor=\"#d0d0f0\">"); sResponse += F("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=yes\">"); sResponse += F("<h1>WLAN Logger für Pufferspeichertemperatur</h1>"); sResponse += F("<FONT SIZE=+1>"); sResponse += F("<a href=\"/\"><button>Startseite</button></a><BR><BR>Thingspeak API ist momentan: "); sResponse += apiKey; sResponse += F("<BR><BR>Das ist die Zeitverschiebung: "); sResponse += zeittext; sResponse += F("<fieldset><legend>EEPROM Setting</legend>"); sResponse += F("<p><a href=\"/reset\"><button>RESET</button></a> <a href=\"?pin=FUNCTION2ON\"><button>AUSLESEN</button></a></p>"); sResponse += F("</fieldset>"); sResponse += F("<fieldset><legend>Allgemein Setting</legend>"); sResponse += F("<p>Zeitumstellung <a href=\"?pin=SOMMERZEIT\"><button>SOMMERZEIT</button></a> <a href=\"?pin=WINTERZEIT\"><button>WINTERZEIT</button></a></p>"); sResponse += F("<form name=\"input\" action=\"\" method=\"get\">THINGSPEAK-API: <input type=\"text\" name=\"$\"><input type=\"submit\" value=\"Submit\"></form>"); sResponse += F("</fieldset>"); sResponse += F("<fieldset><legend>Temperatur kalibrieren</legend>"); sResponse += F("<p><a href=\"/temp1\"><button>Speicher oben</button></a> <a href=\"/temp2\"><button>Speicher mitte</button></a> <a href=\"/temp3\"><button>Speicher unten</button></a> <a href=\"/temp4\"><button>Vorlauf</button></a></p>"); sResponse += F("</fieldset>"); sResponse2 = MakeHTTPFooter().c_str(); // Send the response to the client client.print(MakeHTTPHeader(sResponse.length() + sResponse2.length()).c_str()); client.print(sResponse); client.print(sResponse2); delay(100); ////////////////////// // react on parameters ////////////////////// if (sCmd.length() > 0) { // write received command to html page sResponse += "Kommando:" + sCmd + "<BR>"; // EEPROM RESET //////////////////////////////// if (sCmd.indexOf("FUNCTION1ON") >= 0) { EEPROM.begin(512); // write a 0 to all 512 bytes of the EEPROM for (int i = 0; i < 512; i++) { EEPROM.write(i, 0); EEPROM.end(); } } // SHOW EEPROM //////////////////////////////// else if (sCmd.indexOf("FUNCTION2ON") >= 0) { EEPROM.begin(512); delay(10); String string3 = ""; for (int i = 0; i < 150; i++) { //DEBUG_PRINT(i); string3 += char(EEPROM.read(i)); } EEPROM.end(); Serial.println(string3); } // SOMMERZEIT EINSTELLEN //////////////////////////////// else if (sCmd.indexOf("SOMMERZEIT") >= 0) { String sommer = "3600"; Serial.print("Das wird gespeichert in der seite: "); Serial.println(sommer); EEPROM.begin(512); delay(10); int si = 0; for (int i = 100; i < 105; i++) { char c; if (si < sommer.length()) { c = sommer[si]; } else { c = 0; } EEPROM.write(i, c); si++; } EEPROM.end(); Serial.println("Wrote " + sommer); } // WINTERZEIT EINSTELLEN //////////////////////////////// else if (sCmd.indexOf("WINTERZEIT") >= 0) { String winter = "0000"; Serial.print("Das wird gespeichert in der seite: "); Serial.println(winter); EEPROM.begin(512); delay(10); int si = 0; for (int i = 100; i < 105; i++) { char c; if (si < winter.length()) { c = winter[si]; } else { c = 0; } EEPROM.write(i, c); si++; } EEPROM.end(); Serial.println("Wrote " + winter); } // SET THINGSPEAK API //////////////////////////////// else { Serial.print("Das wird gespeichert in der seite: "); Serial.println(sCmd); EEPROM.begin(512); delay(10); int si = 0; for (int i = 81; i < 100; i++) { char c; if (si < sCmd.length()) { c = sCmd[si]; //DEBUG_PRINT("Wrote: "); //DEBUG_PRINT(c); } else { c = 0; } EEPROM.write(i, c); si++; } EEPROM.end(); Serial.println("Wrote " + sCmd); } } } // Kalibrieren Temperatur 1 //////////////////////////////// else if (sPath == "/temp1") //////////////////////////////////// // format the html page for /tabelle //////////////////////////////////// { EEPROM.begin(512); delay(10); String temp1k = ""; for (int i = 110; i < 115; i++) { temp1k += char(EEPROM.read(i)); } EEPROM.end(); Serial.print("Das ist die Zeitverschiebung: "); Serial.println(temp1k); // settings(); ulReqcount++; unsigned long ulSizeList = MakeTable(&client, false); // get size of table first sResponse = F("<html><head><title>WLAN Logger für Pufferspeichertemperatur</title></head><body>"); sResponse += F("<font color=\"#000000\"><body bgcolor=\"#d0d0f0\">"); sResponse += F("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=yes\">"); sResponse += F("<h1>WLAN Logger für Pufferspeichertemperatur</h1>"); sResponse += F("<FONT SIZE=+1>"); sResponse += F("<a href=\"/\"><button>Startseite</button></a><BR><BR>Speicher oben: "); sResponse += temp1k; sResponse += F("Grad C<BR>"); sResponse += F("<form name=\"input\" action=\"\" method=\"get\">Speicher oben: <input type=\"text\" name=\"$\"><input type=\"submit\" value=\"Submit\"></form>"); sResponse += F("<p>Temperatur kalibrieren: <a href=\"/temp1\"><button>Speicher oben</button></a> <a href=\"/temp2\"><button>Speicher mitte</button></a> <a href=\"/temp3\"><button>Speicher unten</button></a> <a href=\"/temp4\"><button>Vorlauf</button></a> </p>"); sResponse2 = MakeHTTPFooter().c_str(); // Send the response to the client client.print(MakeHTTPHeader(sResponse.length() + sResponse2.length()).c_str()); client.print(sResponse); client.print(sResponse2); delay(100); ////////////////////// // react on parameters ////////////////////// if (sCmd.length() > 0) { // write received command to html page sResponse += "Kommando:" + sCmd + "<BR>"; // SET THINGSPEAK API //////////////////////////////// if (sCmd.toInt() != 0) { Serial.print("Das wird gespeichert in der seite: "); Serial.println(sCmd); EEPROM.begin(512); delay(10); int si = 0; for (int i = 110; i < 115; i++) { char c; if (si < sCmd.length()) { c = sCmd[si]; //DEBUG_PRINT("Wrote: "); //DEBUG_PRINT(c); } else { c = 0; } EEPROM.write(i, c); si++; } EEPROM.end(); Serial.println("Wrote " + sCmd); } else { Serial.println("Der Wert " + sCmd + " war keine Zahl!!!"); } } } // Kalibrieren Temperatur 2 //////////////////////////////// else if (sPath == "/temp2") //////////////////////////////////// // format the html page for /tabelle //////////////////////////////////// { EEPROM.begin(512); delay(10); String temp2k = ""; for (int i = 115; i < 120; i++) { temp2k += char(EEPROM.read(i)); } EEPROM.end(); Serial.print("Das ist die Zeitverschiebung: "); Serial.println(temp2k); // settings(); ulReqcount++; unsigned long ulSizeList = MakeTable(&client, false); // get size of table first sResponse = F("<html><head><title>WLAN Logger für Pufferspeichertemperatur</title></head><body>"); sResponse += F("<font color=\"#000000\"><body bgcolor=\"#d0d0f0\">"); sResponse += F("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=yes\">"); sResponse += F("<h1>WLAN Logger für Pufferspeichertemperatur</h1>"); sResponse += F("<FONT SIZE=+1>"); sResponse += F("<a href=\"/\"><button>Startseite</button></a><BR><BR>Speicher mitte: "); sResponse += temp2k; sResponse += F("Grad C<BR>"); sResponse += F("<form name=\"input\" action=\"\" method=\"get\">Speicher mitte: <input type=\"text\" name=\"$\"><input type=\"submit\" value=\"Submit\"></form>"); sResponse += F("<p>Temperatur kalibrieren: <a href=\"/temp1\"><button>Speicher oben</button></a> <a href=\"/temp2\"><button>Speicher mitte</button></a> <a href=\"/temp3\"><button>Speicher unten</button></a> <a href=\"/temp4\"><button>Vorlauf</button></a> </p>"); sResponse2 = MakeHTTPFooter().c_str(); // Send the response to the client client.print(MakeHTTPHeader(sResponse.length() + sResponse2.length()).c_str()); client.print(sResponse); client.print(sResponse2); delay(100); ////////////////////// // react on parameters ////////////////////// if (sCmd.length() > 0) { // write received command to html page sResponse += "Kommando:" + sCmd + "<BR>"; // SET THINGSPEAK API //////////////////////////////// if (sCmd.toInt() != 0) { Serial.print("Das wird gespeichert in der seite: "); Serial.println(sCmd); EEPROM.begin(512); delay(10); int si = 0; for (int i = 115; i < 120; i++) { char c; if (si < sCmd.length()) { c = sCmd[si]; //DEBUG_PRINT("Wrote: "); //DEBUG_PRINT(c); } else { c = 0; } EEPROM.write(i, c); si++; } EEPROM.end(); Serial.println("Wrote " + sCmd); } else { Serial.println("Der Wert " + sCmd + " war keine Zahl!!!"); } } } // Kalibrieren Temperatur 3 //////////////////////////////// else if (sPath == "/temp3") //////////////////////////////////// // format the html page for /tabelle //////////////////////////////////// { EEPROM.begin(512); delay(10); String temp3k = ""; for (int i = 120; i < 125; i++) { temp3k += char(EEPROM.read(i)); } EEPROM.end(); Serial.print("Das ist der aktuelle Korrekturwert: "); Serial.println(temp3k); // settings(); ulReqcount++; unsigned long ulSizeList = MakeTable(&client, false); // get size of table first sResponse = F("<html><head><title>WLAN Logger für Pufferspeichertemperatur</title></head><body>"); sResponse += F("<font color=\"#000000\"><body bgcolor=\"#d0d0f0\">"); sResponse += F("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=yes\">"); sResponse += F("<h1>WLAN Logger für Pufferspeichertemperatur</h1>"); sResponse += F("<FONT SIZE=+1>"); sResponse += F("<a href=\"/\"><button>Startseite</button></a><BR><BR>Speicher unten "); sResponse += temp3k; sResponse += F("Grad C<BR>"); sResponse += F("<form name=\"input\" action=\"\" method=\"get\">Speicher unten: <input type=\"text\" name=\"$\"><input type=\"submit\" value=\"Submit\"></form>"); sResponse += F("<p>Temperatur kalibrieren: <a href=\"/temp1\"><button>Speicher oben</button></a> <a href=\"/temp2\"><button>Speicher mitte</button></a> <a href=\"/temp3\"><button>Speicher unten</button></a> <a href=\"/temp4\"><button>Vorlauf</button></a> </p>"); sResponse2 = MakeHTTPFooter().c_str(); // Send the response to the client client.print(MakeHTTPHeader(sResponse.length() + sResponse2.length()).c_str()); client.print(sResponse); client.print(sResponse2); delay(100); ////////////////////// // react on parameters ////////////////////// if (sCmd.length() > 0) { // write received command to html page sResponse += "Kommando:" + sCmd + "<BR>"; // SET THINGSPEAK API //////////////////////////////// if (sCmd.toInt() != 0) { Serial.print("Das wird gespeichert in der seite: "); Serial.println(sCmd); EEPROM.begin(512); delay(10); int si = 0; for (int i = 120; i < 125; i++) { char c; if (si < sCmd.length()) { c = sCmd[si]; //DEBUG_PRINT("Wrote: "); //DEBUG_PRINT(c); } else { c = 0; } EEPROM.write(i, c); si++; } EEPROM.end(); Serial.println("Wrote " + sCmd); } else { Serial.println("Der Wert " + sCmd + " war keine Zahl!!!"); } } } // Kalibrieren Temperatur 4 //////////////////////////////// else if (sPath == "/temp4") //////////////////////////////////// // format the html page for /tabelle //////////////////////////////////// { EEPROM.begin(512); delay(10); String temp4k = ""; for (int i = 125; i < 130; i++) { temp4k += char(EEPROM.read(i)); } EEPROM.end(); Serial.print("Das ist die Zeitverschiebung: "); Serial.println(temp4k); // settings(); ulReqcount++; unsigned long ulSizeList = MakeTable(&client, false); // get size of table first sResponse = F("<html><head><title>WLAN Logger für Pufferspeichertemperatur</title></head><body>"); sResponse += F("<font color=\"#000000\"><body bgcolor=\"#d0d0f0\">"); sResponse += F("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=yes\">"); sResponse += F("<h1>WLAN Logger für Pufferspeichertemperatur</h1>"); sResponse += F("<FONT SIZE=+1>"); sResponse += F("<a href=\"/\"><button>Startseite</button></a><BR><BR>Anpassung Vorlauf: "); sResponse += temp4k; sResponse += F("Grad C<BR>"); sResponse += F("<form name=\"input\" action=\"\" method=\"get\">Vorlauf: <input type=\"text\" name=\"$\"><input type=\"submit\" value=\"Submit\"></form>"); sResponse += F("<p>Temperatur kalibrieren: <a href=\"/temp1\"><button>Speicher oben</button></a> <a href=\"/temp2\"><button>Speicher mitte</button></a> <a href=\"/temp3\"><button>Speicher unten</button></a> <a href=\"/temp4\"><button>Vorlauf</button></a> </p>"); sResponse2 = MakeHTTPFooter().c_str(); // Send the response to the client client.print(MakeHTTPHeader(sResponse.length() + sResponse2.length()).c_str()); client.print(sResponse); client.print(sResponse2); delay(100); ////////////////////// // react on parameters ////////////////////// if (sCmd.length() > 0) { // write received command to html page sResponse += "Kommando:" + sCmd + "<BR>"; // SET THINGSPEAK API //////////////////////////////// if (sCmd.toInt() != 0) { Serial.print("Das wird gespeichert in der seite: "); Serial.println(sCmd); EEPROM.begin(512); delay(10); int si = 0; for (int i = 125; i < 130; i++) { char c; if (si < sCmd.length()) { c = sCmd[si]; //DEBUG_PRINT("Wrote: "); //DEBUG_PRINT(c); } else { c = 0; } EEPROM.write(i, c); si++; } EEPROM.end(); Serial.println("Wrote " + sCmd); } else { Serial.println("Der Wert " + sCmd + " war keine Zahl!!!"); } } } // Send the response to the client client.print(sHeader); client.print(sResponse); // and stop the client client.stop(); Serial.println("Client disconnected"); }
AJ_Status AJ_Net_Recv(AJ_IOBuffer* buf, uint32_t len, uint32_t timeout) { AJ_Status status = AJ_ERR_READ; uint32_t ret; uint32_t rx = AJ_IO_BUF_SPACE(buf); uint32_t recvd = 0; unsigned long Recv_lastCall = millis(); // first we need to clear out our buffer uint32_t M = 0; AJ_InfoPrintf(("AJ_Net_Recv(buf=0x%p, len=%d., timeout=%d.)\n", buf, len, timeout)); if (rxLeftover != 0) { // there was something leftover from before, AJ_InfoPrintf(("AJ_NetRecv(): leftover was: %d\n", rxLeftover)); M = min(rx, rxLeftover); memcpy(buf->writePtr, rxDataStash, M); // copy leftover into buffer. buf->writePtr += M; // move the data pointer over memmove(rxDataStash, rxDataStash + M, rxLeftover - M); // shift left-overs toward the start. rxLeftover -= M; recvd += M; // we have read as many bytes as we can // higher level isn't requesting any more if (recvd == rx) { AJ_InfoPrintf(("AJ_Net_Recv(): status=AJ_OK\n")); return AJ_OK; } } if ((M != 0) && (rxLeftover != 0)) { AJ_InfoPrintf(("AJ_Net_REcv(): M was: %d, rxLeftover was: %d\n", M, rxLeftover)); } // wait for data to become available // time out if nothing arrives while (g_client.connected() && g_client.available() == 0 && (millis() - Recv_lastCall < timeout)) { delay(50); // wait for data or timeout } // return timeout if nothing is available AJ_InfoPrintf(("AJ_Net_Recv(): millis %d, Last_call %d timeout %d Avail: %d\n", millis(), Recv_lastCall, timeout, g_client.available())); if (g_client.connected() && (millis() - Recv_lastCall >= timeout) && (g_client.available() == 0)) { AJ_InfoPrintf(("AJ_Net_Recv(): timeout. status=AJ_ERR_TIMEOUT\n")); return AJ_ERR_TIMEOUT; } if (g_client.connected()) { uint32_t askFor = rx; askFor -= M; AJ_InfoPrintf(("AJ_Net_Recv(): ask for: %d\n", askFor)); ret = g_client.read(buf->writePtr, askFor); AJ_InfoPrintf(("AJ_Net_Recv(): read(): ret %d askfor %d\n", ret, askFor)); if (askFor < ret) { AJ_InfoPrintf(("AJ_Net_Recv(): BUFFER OVERRUN: askFor=%u, ret=%u\n", askFor, ret)); } if (ret == -1) { AJ_ErrPrintf(("AJ_Net_Recv(): read() failed. status=AJ_ERR_READ\n")); status = AJ_ERR_READ; } else { AJ_InfoPrintf(("AJ_Net_Recv(): ret now %d\n", ret)); AJ_DumpBytes("Recv", buf->writePtr, ret); if (ret > askFor) { AJ_InfoPrintf(("AJ_Net_Recv(): new leftover %d\n", ret - askFor)); // now shove the extra into the stash memcpy(rxDataStash + rxLeftover, buf->writePtr + askFor, ret - askFor); rxLeftover += (ret - askFor); buf->writePtr += rx; } else { buf->writePtr += ret; } status = AJ_OK; } } return status; }
void ArduinoOTAClass::_runUpdate() { if (!Update.begin(_size, _cmd)) { #ifdef OTA_DEBUG OTA_DEBUG.println("Update Begin Error"); #endif if (_error_callback) { _error_callback(OTA_BEGIN_ERROR); } _udp_ota->listen(*IP_ADDR_ANY, _port); _state = OTA_IDLE; return; } Update.setMD5(_md5.c_str()); WiFiUDP::stopAll(); WiFiClient::stopAll(); if (_start_callback) { _start_callback(); } if (_progress_callback) { _progress_callback(0, _size); } WiFiClient client; if (!client.connect(_ota_ip, _ota_port)) { #ifdef OTA_DEBUG OTA_DEBUG.printf("Connect Failed\n"); #endif _udp_ota->listen(*IP_ADDR_ANY, _port); if (_error_callback) { _error_callback(OTA_CONNECT_ERROR); } _state = OTA_IDLE; } uint32_t written, total = 0; while (!Update.isFinished() && client.connected()) { int waited = 1000; while (!client.available() && waited--) delay(1); if (!waited){ #ifdef OTA_DEBUG OTA_DEBUG.printf("Receive Failed\n"); #endif _udp_ota->listen(*IP_ADDR_ANY, _port); if (_error_callback) { _error_callback(OTA_RECEIVE_ERROR); } _state = OTA_IDLE; } written = Update.write(client); if (written > 0) { client.print(written, DEC); total += written; if(_progress_callback) { _progress_callback(total, _size); } } } if (Update.end()) { client.print("OK"); client.stop(); delay(10); #ifdef OTA_DEBUG OTA_DEBUG.printf("Update Success\nRebooting...\n"); #endif if (_end_callback) { _end_callback(); } ESP.restart(); } else { _udp_ota->listen(*IP_ADDR_ANY, _port); if (_error_callback) { _error_callback(OTA_END_ERROR); } Update.printError(client); #ifdef OTA_DEBUG Update.printError(OTA_DEBUG); #endif _state = OTA_IDLE; } }
int WiFiManager::serverLoop() { // Check for any mDNS queries and send responses mdns.update(); String s; WiFiClient client = server_s.available(); if (!client) { return(WM_WAIT); } DEBUG_PRINT("New client"); // Wait for data from client to become available while(client.connected() && !client.available()){ delay(1); } // Read the first line of HTTP request String req = client.readStringUntil('\r'); // First line of HTTP request looks like "GET /path HTTP/1.1" // Retrieve the "/path" part by finding the spaces int addr_start = req.indexOf(' '); int addr_end = req.indexOf(' ', addr_start + 1); if (addr_start == -1 || addr_end == -1) { DEBUG_PRINT("Invalid request: "); DEBUG_PRINT(req); return(WM_WAIT); } req = req.substring(addr_start + 1, addr_end); DEBUG_PRINT("Request: "); DEBUG_PRINT(req); client.flush(); if (req == "/") { s = HTTP_200; String head = HTTP_HEAD; head.replace("{v}", "Config ESP"); s += head; s += HTTP_SCRIPT; s += HTTP_STYLE; s += HTTP_HEAD_END; int n = WiFi.scanNetworks(); DEBUG_PRINT("scan done"); if (n == 0) { DEBUG_PRINT("no networks found"); s += "<div>No networks found. Refresh to scan again.</div>"; } else { for (int i = 0; i < n; ++i) { DEBUG_PRINT(WiFi.SSID(i)); DEBUG_PRINT(WiFi.RSSI(i)); String item = HTTP_ITEM; item.replace("{v}", WiFi.SSID(i)); s += item; delay(10); } } s += HTTP_FORM; s += HTTP_END; DEBUG_PRINT("Sending config page"); } else if ( req.startsWith("/s") ) { String qssid; qssid = urldecode(req.substring(8,req.indexOf('&')).c_str()); DEBUG_PRINT(qssid); DEBUG_PRINT(""); req = req.substring( req.indexOf('&') + 1); String qpass; qpass = urldecode(req.substring(req.lastIndexOf('=')+1).c_str()); setEEPROMString(0, 32, qssid); setEEPROMString(32, 64, qpass); EEPROM.commit(); s = HTTP_200; String head = HTTP_HEAD; head.replace("{v}", "Saved config"); s += HTTP_STYLE; s += HTTP_HEAD_END; s += "saved to eeprom...<br/>resetting in 10 seconds"; s += HTTP_END; client.print(s); client.flush(); DEBUG_PRINT("Saved WiFiConfig...restarting."); return WM_DONE; } else { s = HTTP_404; DEBUG_PRINT("Sending 404"); } client.print(s); DEBUG_PRINT("Done with client"); return(WM_WAIT); }
void loop(){ WiFiClient client = server.available(); // Listen for incoming clients if (client) { // Print local IP address and start web server Serial.println(""); Serial.println("WiFi connected."); Serial.println("IP address: "); Serial.println(WiFi.localIP()); //server.begin(); // If a new client connects, Serial.println("New Client."); // print a message out in the serial port String currentLine = ""; // make a String to hold incoming data from the client while (client.connected()) { // loop while the client's connected if (client.available()) { // if there's bytes to read from the client, char c = client.read(); // read a byte, then Serial.write(c); // print it out the serial monitor header += c; if (c == '\n') { // if the byte is a newline character // if the current line is blank, you got two newline characters in a row. // that's the end of the client HTTP request, so send a response: if (currentLine.length() == 0) { // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) // and a content-type so the client knows what's coming, then a blank line: client.println("HTTP/1.1 200 OK"); client.println("Content-type:text/html"); client.println("Connection: close"); client.println(); // turns the GPIOs on and off if (header.indexOf("GET /5/on") >= 0) { Serial.println("GPIO 5 on"); output5State = "on"; digitalWrite(output5, HIGH); } else if (header.indexOf("GET /5/off") >= 0) { Serial.println("GPIO 5 off"); output5State = "off"; digitalWrite(output5, LOW); } else if (header.indexOf("GET /4/on") >= 0) { Serial.println("GPIO 4 on"); output4State = "on"; digitalWrite(output4, HIGH); } else if (header.indexOf("GET /4/off") >= 0) { Serial.println("GPIO 4 off"); output4State = "off"; digitalWrite(output4, LOW); } // Display the HTML web page client.println("<!DOCTYPE html><html>"); client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"); client.println("<link rel=\"icon\" href=\"data:,\">"); // CSS to style the on/off buttons // Feel free to change the background-color and font-size attributes to fit your preferences client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}"); client.println(".button { background-color: #195B6A; border: none; color: white; padding: 16px 40px;"); client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}"); client.println(".button2 {background-color: #77878A;}</style></head>"); // Web Page Heading client.println("<body><h1>ESP8266 Web Server</h1>"); // Display current state, and ON/OFF buttons for GPIO 5 client.println("<p>GPIO 5 - State " + output5State + "</p>"); // If the output5State is off, it displays the ON button if (output5State=="off") { client.println("<p><a href=\"/5/on\"><button class=\"button\">ON</button></a></p>"); } else { client.println("<p><a href=\"/5/off\"><button class=\"button button2\">OFF</button></a></p>"); } // Display current state, and ON/OFF buttons for GPIO 4 client.println("<p>GPIO 4 - State " + output4State + "</p>"); // If the output4State is off, it displays the ON button if (output4State=="off") { client.println("<p><a href=\"/4/on\"><button class=\"button\">ON</button></a></p>"); } else { client.println("<p><a href=\"/4/off\"><button class=\"button button2\">OFF</button></a></p>"); } client.println("</body></html>"); // The HTTP response ends with another blank line client.println(); // Break out of the while loop break; } else { // if you got a newline, then clear currentLine currentLine = ""; } } else if (c != '\r') { // if you got anything else but a carriage return character, currentLine += c; // add it to the end of the currentLine } } } // Clear the header variable header = ""; // Close the connection client.stop(); Serial.println("Client disconnected."); Serial.println(""); } }
/* * ======== apLoop ======== */ __extern void apLoop() { /* Did a client connect/disconnect since the last time we checked? */ int a = WiFi.getTotalDevices(); if (a != num_clients) { if (a > num_clients) { // new Client connected int i; /* display all clients on the network */ Serial.println("New client connected. All clients:"); for (i = 0; i < a; i++) { Serial.print(" Client #"); Serial.print(i); Serial.print(" at IP address = "); Serial.print(WiFi.deviceIpAddress(i)); Serial.print(", MAC = "); Serial.println(WiFi.deviceMacAddress(i)); } } else { // a Client disconnected Serial.print("Client disconnected, "); Serial.print(a); Serial.println(" clients remaining."); } num_clients = a; } if (num_clients > 0) { /* listen for incoming clients */ WiFiClient client = server.available(); if (client) { /* if there's a client, read and process commands */ Serial.print("new client socket: "); Serial.println(++num_sockets); static char buffer[80] = {0}; int bufLen = 0; /* while connected to the client, read commands and send results */ while (client.connected()) { /* if there's a byte to read from the client .. */ if (client.available()) { /* copy it to the command buffer, byte at a time */ char c = client.read(); /* ignore bogus characters */ if (c == '\0' || c == '\r') continue; /* never overrun the command buffer */ if (bufLen >= (int)(sizeof (buffer))) { bufLen = sizeof (buffer) - 1; } buffer[bufLen++] = c; /* if there's a new line, we have a complete command */ if (c == '\n') { doCommand(buffer, bufLen, client); /* reset command buffer index to get next command */ bufLen = 0; } } } /* client disconnected, close the connection */ client.stop(); Serial.println("client socket disconnected"); } } delay(100); }
bool FOTAService(void) { FOTA_StateMachine_t state_current; String storage_bucket = EE_GetFirebaseStorageBucket(); state_current = state; switch (state) { case FOTA_Sm_IDLE: break; case FOTA_Sm_GET_MD5: { String md5file_url = String(F("/v0/b/")) + storage_bucket + String(F("/o/")) + VERS_HW_VER + String(FPSTR(md5file_name)) + String(F("?alt=media")); addr = String(F("https://")) + String(FPSTR(storage_host)) + md5file_url; DEBUG_PRINT("FOTA_Sm_GET_MD5 %s\n", addr.c_str()); http = new HTTPClient; http->setReuse(true); http->setTimeout(3000); bool res = http->begin(addr, storage_fingerprint); if (res == true) { int httpCode = http->GET(); // httpCode will be negative on error if (httpCode > 0) { // HTTP header has been send and Server response header has been handled DEBUG_PRINT("[HTTP] GET... code: %d\n", httpCode); // file found at server if (httpCode == HTTP_CODE_OK) { int size = http->getSize(); if (size == DIGEST_MD5_SIZE) { DEBUG_PRINT("md5file size %d\n", size); WiFiClient *stream = http->getStreamPtr(); digest_MD5 = (uint8_t *)malloc(DIGEST_MD5_SIZE); stream->read(digest_MD5, size); state = FOTA_Sm_CHECK; } else { DEBUG_PRINT("md5file size error: %d\n", size); state = FOTA_Sm_ERROR; } } else { DEBUG_PRINT("md5file httpCode error: %d\n", httpCode); state = FOTA_Sm_ERROR; } } else { DEBUG_PRINT("[HTTP] GET... failed, error: %s\n", http->errorToString(httpCode).c_str()); state = FOTA_Sm_ERROR; } } else { DEBUG_PRINT("[HTTP] begin... failed, error: %d\n", res); state = FOTA_Sm_ERROR; } } break; case FOTA_Sm_CHECK: { String file_url = String(F("/v0/b/")) + storage_bucket + String(F("/o/")) + VERS_HW_VER + String(FPSTR(file_name)) + String(F("?alt=media")); addr = String(F("https://")) + String(FPSTR(storage_host)) + file_url; DEBUG_PRINT("FOTA_Sm_CHECK %s\n", addr.c_str()); http->setReuse(true); bool res = http->begin(addr, storage_fingerprint); if (res == true) { int httpCode = http->GET(); // httpCode will be negative on error if (httpCode > 0) { http->end(); // HTTP header has been send and Server response header has been handled DEBUG_PRINT("[HTTP] GET... code: %d\n", httpCode); int size = http->getSize(); DEBUG_PRINT("file size %d\n", size); block = 0; num_blocks = (size + block_size - 1) / block_size; if (Update.begin(size, 0)) { Update.setMD5((char *)digest_MD5); buffer = (uint8_t *)malloc(block_size); state = FOTA_Sm_GET_BLOCK; } else { state = FOTA_Sm_ERROR; } } else { DEBUG_PRINT("file httpCode error: %d\n", httpCode); state = FOTA_Sm_ERROR; } } else { state = FOTA_Sm_ERROR; } } break; case FOTA_Sm_GET_BLOCK: { http->setReuse(true); bool res = http->begin(addr, storage_fingerprint); if (res == true) { String range = String(F("bytes=")) + String(block * block_size) + String(F("-")) + String(((block + 1) * block_size) - 1); http->addHeader(String(F("Range")), range); int httpCode = http->GET(); // httpCode will be negative on error if (httpCode > 0) { // HTTP header has been send and Server response header has been handled // Serial.printf("[HTTP] GET... code: %d\n", httpCode); int len = http->getSize(); // get tcp stream WiFiClient *stream = http->getStreamPtr(); int pos = 0; bool run = true; bool fail = false; while (run == true) { delay(1); if (pos < len) { size_t size = stream->available(); if (size) { uint16_t c = stream->readBytes(&buffer[pos], size); pos += c; } if (!http->connected() && (pos < len)) { run = false; fail = true; } } else { run = false; } } if (fail == false) { Update.write(buffer, pos); DEBUG_PRINT("[%03d]: %02d%% -- %d\r", block, 100 * block / num_blocks, ESP.getFreeHeap()); block++; if (block < num_blocks) { /* move to next block */ state = FOTA_Sm_GET_BLOCK; } else { if (!Update.end()) { DEBUG_PRINT("Update Error\n"); } state = FOTA_Sm_COMPLETE; } } else { state = FOTA_Sm_ERROR; } } else { DEBUG_PRINT("[HTTP] GET... failed, error: %s\n", http->errorToString(httpCode).c_str()); state = FOTA_Sm_ERROR; } } else { DEBUG_PRINT("begin error @ %d\n", block); state = FOTA_Sm_ERROR; } } break; case FOTA_Sm_ERROR: { if (http_fail_cnt++ < 20) { DEBUG_PRINT("retry %d\n", http_fail_cnt); state = state_last; } else { /* give-up */ DEBUG_PRINT("retry give-up\n"); Serial.flush(); ESP.restart(); } } break; case FOTA_Sm_COMPLETE: { DEBUG_PRINT("closing connection\n"); Serial.flush(); free(buffer); /* restar node anycase */ ESP.restart(); state = FOTA_Sm_IDLE; } break; } state_last = state_current; return (state != FOTA_Sm_IDLE); }
int uploadFile(const char* _filename, const char* _fileurl) { // upload new file to fs by downloading from a remote server, rather than reflash the entire spiffs int ret = false; HTTPClient http; //const char* fileUrl = "http://mypi3/iot/index.html"; //const char* fileName = "/test2.html"; if (hasSerial) Serial.printf("url %s\n", _fileurl); if (hasSerial) Serial.printf("file %s\n", _filename); http.begin(_fileurl); // init http client // start connection and send HTTP header int httpCode = http.GET(); // httpCode will be negative on error if(httpCode > 0) { // HTTP header has been send and Server response header has been handled // file found at server if(httpCode == HTTP_CODE_OK) { if (hasSerial) Serial.printf("HTTP client http status %d\n", httpCode); // get lenght of document (is -1 when Server sends no Content-Length header) int len = http.getSize(); int paysize = len; if (hasSerial) Serial.printf("HTTP content size %d bytes\n", paysize); // create buffer for read uint8_t buff[128] = { 0 }; // get tcp stream WiFiClient * stream = http.getStreamPtr(); // create or recreate file on spiffs File configFile = SPIFFS.open(_filename, "w"); if (!configFile) { if (hasSerial) Serial.printf("Failed to open %s for write.\n",_filename); return ret; } if (hasSerial) Serial.println("File open, write start."); // read all data from server while(http.connected() && (len > 0 || len == -1)) { // get available data size size_t size = stream->available(); if (size) { // read up to 128 byte int c = stream->readBytes(buff, ((size > sizeof(buff)) ? sizeof(buff) : size)); // write it to Serial configFile.write(buff, c); if(len > 0) { len -= c; } } } // EoF or http connection closed configFile.close(); http.end(); if (hasSerial) Serial.println("File closed, write complete."); return paysize; } else { if (hasSerial) Serial.printf("HTTP client http error %d\n", httpCode); return httpCode; } } else { if (hasSerial) Serial.printf("HTTP client http error %d\n", httpCode); return httpCode; } return 0; }