// See if port 80 is accessable.  Try 8080 as well.
boolean WiFiManager::attemptClient(const char *szUrl)
{
  WiFiClient client;

  int i;
  Serial.print("Probe port 80");
  for(i = 0; i < 5; i++)
  {
    if (client.connect(szUrl, httpPort)) {
      client.stop();
      Serial.println("Port 80 success");
      return true;
    }
    Serial.print(".");
    delay(20);
  }
  httpPort = 8080;
  Serial.println("");
  Serial.print("Probe port 8080");
  for(i = 0; i < 5; i++)
  {
    if (client.connect(szUrl, httpPort)) {
      client.stop();
      Serial.println("Port 8080 success");
      return true;
    }
    Serial.print(".");
    delay(20);
  }
  Serial.println("");
  Serial.println("No joy");
  return false;  
}
Example #2
0
void connectClients() {
	if (server.hasClient()) {
		if (!serverClient || !serverClient.connected()) {
			if (serverClient) serverClient.stop();
			serverClient = server.available();
		} else {
			//no free/disconnected spot so reject
			WiFiClient rejectClient = server.available();
			rejectClient.stop();
		}
	}
}
Example #3
0
void Farmy::sendData(const char* device_id, String api_key, WiFiClient client, String data)
{
  // Todo: use retry to connect internet.
  Serial.println("Connected to Famry.");
  Serial.println("Posted:" + data);

  // Create HTTP POST Data
  String url = String("/api/v0/user_devices/") + device_id + "/sensor_datas/";
  client.print(String("POST ") + url + " HTTP/1.1\n"+ "Host: " + host + "\n");
  client.print(String("Host: ") + host + "\n");
  client.print("Content-Type: application/json\n");
  client.print(String("X-Farmy-Api-Key: ") + api_key + "\n");
  client.print("Content-Length: ");
  client.print(data.length());
  client.print("\n\n");

  client.print(data);
  Serial.println("Posted finished -----------");

  delay(500);
  if (!client.connected()) {
      Serial.println();
      Serial.println("disconnecting.");
      client.stop();
  }
}
Example #4
0
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;
}
Example #5
0
void WiFiClient::stopAllExcept(WiFiClient* except) 
{
    for (WiFiClient* it = _s_first; it; it = it->_next) {
        if (it != except) {
            it->stop();
        }
    }
}
Example #6
0
void Con::TCPhandler(){
   if (this->curType&CON_TCP){
      if (ConSrv.hasClient()){
         if (ConTcp.connected()){
            ConTcp.stop();
         }
         ConTcp=ConSrv.available();
         ConTcp.write("Hello\n",6);
      }  
   }
}
//****************** 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++;
  }
}
Example #8
0
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);
  }
}
Example #10
0
void sendTeperatureTS(int temp1, int temp2, int temp3, int temp4)
{
  WiFiClient client;

  if (client.connect(tsserver, 80)) { // use ip 184.106.153.149 or api.thingspeak.com
    Serial.println("WiFi Client connected_neu ");

    EEPROM.begin(512);
    delay(10);
    String apiKey = "";
    for (int i = 81; i < 97; i++)
    {
      apiKey += char(EEPROM.read(i));
    }
    EEPROM.end();
    Serial.println("Thingspeak-API_neu: " + apiKey);

    String postStr = apiKey;
    postStr += "&field1=";
    postStr += String(temp1);
    postStr += "&field2=";
    postStr += String(temp2);
    postStr += "&field3=";
    postStr += String(temp3);
    postStr += "&field4=";
    postStr += String(temp4);
    postStr += "\r\n\r\n";

    client.print("POST /update HTTP/1.1\n");
    client.print("Host: api.thingspeak.com\n");
    client.print("Connection: close\n");
    client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
    client.print("Content-Type: application/x-www-form-urlencoded\n");
    client.print("Content-Length: ");
    client.print(postStr.length());
    client.print("\n\n");
    client.print(postStr);
    delay(1000);
    Serial.println("Daten an Thingspeak gesendet");
  }//end if
  sent++;
  client.stop();
}//end send
bool connectSensorAPI()
{
  /* ToDo: Add SSL/TLS support */
  uint16_t port;
  char hostname[NODE_EEPROM_API_HOSTNAME_MAX_LENGTH + 1];

  if(WiFi.status() != WL_CONNECTED) {
    return false;
  }

  getAPIHostnameOrDefault(&hostname[0], NODE_EEPROM_API_HOSTNAME_MAX_LENGTH);
  hostname[NODE_EEPROM_API_HOSTNAME_MAX_LENGTH] = '\0';
  port = getAPIPortOrDefault();

  client.stop();
  if(client.connect(hostname, port)) {
    return true;
  }
  return false;
}
Example #12
0
/**
 * Handle incomming Connection Request
 */
void WebSocketsServer::handleNewClients(void) {
    WSclient_t * client;
    while(_server->hasClient()) {
        bool ok = false;
        // search free list entry for client
        for(uint8_t i = 0; i < WEBSOCKETS_SERVER_CLIENT_MAX; i++) {
            client = &_clients[i];

            // state is not connected or tcp connection is lost
            if(!clientIsConnected(client)) {

                // store new connection
                client->tcp = _server->available();
#ifdef ESP8266
                client->tcp.setNoDelay(true);
#endif
                // set Timeout for readBytesUntil and readStringUntil
                client->tcp.setTimeout(WEBSOCKETS_TCP_TIMEOUT);
                client->status = WSC_HEADER;

                IPAddress ip = client->tcp.remoteIP();
                DEBUG_WEBSOCKETS("[WS-Server][%d] new client from %d.%d.%d.%d\n", client->num, ip[0], ip[1], ip[2], ip[3]);
                ok = true;
                break;
            }
        }

        if(!ok) {
            // no free space to handle client
            WiFiClient tcpClient = _server->available();
            IPAddress ip = tcpClient.remoteIP();
            DEBUG_WEBSOCKETS("[WS-Server] no free space new client from %d.%d.%d.%d\n", ip[0], ip[1], ip[2], ip[3]);
            tcpClient.stop();
        }

#ifdef ESP8266
        delay(0);
#endif
    }
}
Example #13
0
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.");
  }
}
Example #15
0
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("");
  }
}
Example #16
0
File: wifi.cpp Project: energia/emt
/*
 *  ======== 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);
}
Example #17
0
bool ESPWebServer::handleClientRequest(ServoControl &servoInteraction, String htmlPage)
{ 
    bool clientHandled = false;

    WiFiClient client = m_server.available();   // Listen for incoming clients

    if (client) 
    {                            
        Serial.println("New Client.");
        String header = "";
        String currentLine = "";                // make a String to hold incoming data from the client
        while (client.connected())
        {            
            if (client.available()) 
            {
                char c = client.read();             // read a byte, then
                Serial.write(c);                    // print it out the serial monitor
                header += c;
                if (c == '\n') 
                {
                    // 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) 
                    {
                        // checks if the client signaled an interaction
                        int index;
                        servoInteraction.type = NONE;
                        if ((index = header.indexOf("GET /openBlinds")) >= 0) 
                        {
                            servoInteraction.type = OPEN_BLINDS;
                        }
                        else if ((index = header.indexOf("GET /closeBlinds")) >= 0) 
                        {
                            servoInteraction.type = CLOSE_BLINDS;
                        }
                        else if ((index = header.indexOf("GET /setOpenBlinds")) >= 0) 
                        {
                            String passedValue;
                            index += 20;
                            char newChar = header.charAt(index);
                            while(newChar != '"')
                            {
                              passedValue += newChar;
                              index++;
                              newChar = header.charAt(index);
                            }

                            servoInteraction.type = SET_OPEN;
                            servoInteraction.setting = passedValue.toInt();
                        }
                        else if ((index = header.indexOf("GET /setCloseBlinds")) >= 0) 
                        {
                            String passedValue;
                            index += 21;
                            char newChar = header.charAt(index);
                            while(newChar != '"')
                            {
                              passedValue += newChar;
                              index++;
                              newChar = header.charAt(index);
                            }

                            servoInteraction.type = SET_CLOSE;
                            servoInteraction.setting = passedValue.toInt();
                        }

                        // 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();
                        
                        // Display the HTML web page
                        client.println(htmlPage);

                        // Break out of the while loop
                        clientHandled = true;
                        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
                }
            }
        }
        // Close the connection
        client.stop();
        Serial.println("Client disconnected.");
        Serial.println(""); 
    }

    return clientHandled;
}
Example #18
0
void WiFiClient::stopAll()
{
    for (WiFiClient* it = _s_first; it; it = it->_next) {
        it->stop();
    }
}
//****************** Send data for ModBusMaster ****************
void MgsModbus::Req(MB_FC FC, word Ref, word Count, word Pos)
{
  MbmFC = FC;
  byte ServerIp[] = {192,168,2,8};
  MbmByteArray[0] = 0;  // ID high byte
  MbmByteArray[1] = 1;  // ID low byte
  MbmByteArray[2] = 0;  // protocol high byte
  MbmByteArray[3] = 0;  // protocol low byte
  MbmByteArray[5] = 6;  // Lenght low byte;
  MbmByteArray[4] = 0;  // Lenght high byte
  MbmByteArray[6] = 1;  // unit ID
  MbmByteArray[7] = FC; // function code
  MbmByteArray[8] = highByte(Ref);
  MbmByteArray[9] = lowByte(Ref);
  //****************** Read Coils (1) & Read Input discretes (2) **********************
  if(FC == MB_FC_READ_COILS || FC == MB_FC_READ_DISCRETE_INPUT) {
    if (Count < 1) {Count = 1;}
    if (Count > 125) {Count = 2000;}
    MbmByteArray[10] = highByte(Count);
    MbmByteArray[11] = lowByte(Count);
  }
  //****************** Read Registers (3) & Read Input registers (4) ******************
  if(FC == MB_FC_READ_REGISTERS || FC == MB_FC_READ_INPUT_REGISTER) {
    if (Count < 1) {Count = 1;}
    if (Count > 125) {Count = 125;}
    MbmByteArray[10] = highByte(Count);
    MbmByteArray[11] = lowByte(Count);
  }
  //****************** Write Coil (5) **********************
  if(MbmFC == MB_FC_WRITE_COIL) {
    if (GetBit(Pos)) {MbmByteArray[10] = 0xFF;} else {MbmByteArray[10] = 0;} // 0xFF coil on 0x00 coil off
    MbmByteArray[11] = 0; // always zero
  }
  //****************** Write Register (6) ******************
  if(MbmFC == MB_FC_WRITE_REGISTER) {
    MbmByteArray[10] = highByte(MbData[Pos]);
    MbmByteArray[11] = lowByte(MbData[Pos]);
  }
  //****************** Write Multiple Coils (15) **********************
  // not fuly tested
  if(MbmFC == MB_FC_WRITE_MULTIPLE_COILS) {
    if (Count < 1) {Count = 1;}
    if (Count > 800) {Count = 800;}
    MbmByteArray[10] = highByte(Count);
    MbmByteArray[11] = lowByte(Count);
    MbmByteArray[12] = (Count + 7) /8;
    MbmByteArray[4] = highByte(MbmByteArray[12] + 7); // Lenght high byte
    MbmByteArray[5] = lowByte(MbmByteArray[12] + 7); // Lenght low byte;
    for (int i=0; i<Count; i++) {
      bitWrite(MbmByteArray[13+(i/8)],i-((i/8)*8),GetBit(Pos+i));
    }
  }
  //****************** Write Multiple Registers (16) ******************
  if(MbmFC == MB_FC_WRITE_MULTIPLE_REGISTERS) {
    if (Count < 1) {Count = 1;}
    if (Count > 100) {Count = 100;}
    MbmByteArray[10] = highByte(Count);
    MbmByteArray[11] = lowByte(Count);
    MbmByteArray[12] = (Count*2);
    MbmByteArray[4] = highByte(MbmByteArray[12] + 7); // Lenght high byte
    MbmByteArray[5] = lowByte(MbmByteArray[12] + 7); // Lenght low byte;
    for (int i=0; i<Count;i++) {
      MbmByteArray[(i*2)+13] = highByte (MbData[Pos + i]);
      MbmByteArray[(i*2)+14] = lowByte (MbData[Pos + i]);
    }
  }
  //****************** ?? ******************
  if (MbmClient.connect(ServerIp,502)) {
    #ifdef DEBUG
      Serial.println("connected with modbus slave");
      Serial.print("Master request: ");
      for(int i=0;i<MbmByteArray[5]+6;i++) {
        if(MbmByteArray[i] < 16){Serial.print("0");}
        Serial.print(MbmByteArray[i],HEX);
        if (i != MbmByteArray[5]+5) {Serial.print(".");} else {Serial.println();}
      }
    #endif 
    // this for loop seems to cause a time delay or something that my modbus simulator does not like , for now we use 12 bytes   
   // for(int i=0;i<MbmByteArray[5]+6;i++) {
    //  MbmClient.write(MbmByteArray[i]);
   // }
    MbmClient.write((uint8_t*)MbmByteArray,12);
    MbmBitCount = Count;
  } else {
    #ifdef DEBUG
      Serial.println("connection with modbus master failed");
    #endif    
    MbmClient.stop();
  }
}
Example #20
0
// Process HTTP requests -- just call it inside the loop() function
void WebConfig::ProcessHTTP()
{
	// Accept any new web connection
	WiFiClient httpClient = pHttpServer->available();
	if (!httpClient) return;

	// Read the entire request
	String req = httpClient.readString();
	httpClient.flush();

	// after some time, do not open the web interface anymore.
	//if (millis() - startMillis > 2*60000) return;

	// response header
	String s;

	if (strlen(webLogin) > 0 || strlen(webPassword) > 0)
	{
		int authPos = req.indexOf("Authorization: Basic");

		if (authPos == -1)
		{
			// request authentication
			s = "HTTP/1.0 401 Authorization Required\r\nWWW-Authenticate: Basic realm=\"" + String(apName) + "\"\r\n\r\n";
			s += "<h1><b>ACCESS DENIED</b></h1>";
			httpClient.write(s.c_str(), s.length());
			httpClient.flush();
			return;
		}

		// there is authentication info, check it
		String authInfo = req.substring(authPos + 21);
		int endLinePos = authInfo.indexOf("\r");
		if (endLinePos == -1) { httpClient.print("Malformed request."); httpClient.stop(); return; }
		authInfo = authInfo.substring(0, endLinePos);
		if (strncmp(base64Auth, authInfo.c_str(), 64))
		{
			s = "<h1><b>ACCESS DENIED</b></h1>";
			httpClient.write(s.c_str(), s.length());
			httpClient.flush();
			return;
		}
	}

	byte mac[6];
	WiFi.macAddress(mac);
	String m = String(mac[0],HEX) + ":" + String(mac[1],HEX) + ":" + String(mac[2],HEX) + ":" + String(mac[3],HEX) + ":" + String(mac[4],HEX) + ":" + String(mac[5],HEX);

	//
	// generate HTTP response
	//

	// authentication succeeded, proceed normally
	s = "HTTP/1.1 200 OK\r\n";
	s += "Content-Type: text/html\r\n\r\n";
	s += "<!DOCTYPE HTML>\r\n<html><body>\r\n";

	// If there are parms, update variables and save settings
	bool updated = ProcessParms(req);
	if (updated)
	{
		s += "Parameters have been updated and microcontroller will restart.<br><br>\r\n";
	}

	// javascript to save configuration
	s += "<script>\r\n";
	s += "function save()\r\n";
	s += "{\r\n";
	s += "var webPort = document.getElementById('web_port').value;\r\n";
	s += "var webLogin = document.getElementById('web_login').value;\r\n";
	s += "var webPassword = document.getElementById('web_pass').value;\r\n";
	s += "var webPassword2 = document.getElementById('web_pass2').value;\r\n";
	s += "var modeap = document.getElementById('modeap').checked;\r\n";
	s += "if (modeap) isAP = true; else isAP = false;\r\n";
	s += "var apName = document.getElementById('ap_ssid').value;\r\n";
	s += "var apPassword = document.getElementById('ap_pass').value;\r\n";
	s += "var apPassword2 = document.getElementById('ap_pass2').value;\r\n";
	s += "var apChannel = document.getElementById('apChannel').value;\r\n";
	s += "var ssid = document.getElementById('ssid').value;\r\n";
	s += "var password = document.getElementById('pass').value;\r\n";
	s += "var password2 = document.getElementById('pass2').value;\r\n";
	s += "var udpPort = document.getElementById('udpPort').value;\r\n";
	s += "var tcpPort = document.getElementById('tcpPort').value;\r\n";
	s += "if (webPassword != webPassword2) { alert('WEB passwords dont match'); return; }\r\n";
	s += "if (apPassword != apPassword2) { alert('AP passwords dont match'); return; }\r\n";
	s += "if (password != password2) { alert('Router passwords dont match'); return; }\r\n";
	s += "window.location.search=webPort + '&' + webLogin + '&' + webPassword + '&' + btoa(webLogin+':'+webPassword) + '&' + (isAP?'1':'0') + '&' + apName + '&' + apPassword + '&' + apChannel + '&' + ssid + '&' + password + '&' + udpPort + '&' + tcpPort;\r\n";
	s += "}\r\n";
	s += "</script>\r\n";

	// write first part of response
	httpClient.write(s.c_str(), s.length());

	// title and mac address
	s = "<b>" + String(name) + "</b><br>\r\n";
	s += "MAC: " + m + "<br>\r\n";

	// web interface configuration
	s += "<table border=1>\r\n";
	s += "<tr><td colspan=2 bgcolor=#E0E0E0><b>WEB INTERFACE</b></td></tr>\r\n";
	s += "<tr><td>Port</td><td><input type=text id='web_port' value='" + String(webPort) + "'></td></tr>\r\n";
	s += "<tr><td>Login</td><td><input type=text id='web_login' value='" + String(webLogin) + "'></td></tr>\r\n";
	s += "<tr><td>Password</td><td><input type=password id='web_pass' value='" + String(webPassword) + "'></td></tr>\r\n";
	s += "<tr><td>Pass Confirm</td><td><input type=password id='web_pass2' value='" + String(webPassword) + "'></td></tr>\r\n";
	s += "</table>\r\n";

	// ap configuration
	s += "<table border=1>\r\n";
	s += "<tr><td colspan=2 bgcolor=#E0E0E0><b>ACCESS POINT</b></td></tr>\r\n";
	s += "<tr><td>Mode</td><td><input type=radio id='modeap' name='mode' value='ap'" + (isAP?String(" checked"):String("")) + ">Access Point</td></tr>\r\n";
	s += "<tr><td>Channel</td><td><select id='apChannel'>";
	for (byte c=1; c<14; c++) s += "<option value='" + String(c) + "'" + (c==apChannel?String(" selected"):String("")) + ">" + String(c) + "</option>";
	s += "</select></td></tr>\r\n";
	s += "<tr><td>SSID</td><td><input type=text id='ap_ssid' value='" + String(apName) + "'></td></tr>\r\n";
	s += "<tr><td>Password</td><td><input type=password id='ap_pass' value='" + String(apPassword) + "'></td></tr>\r\n";
	s += "<tr><td>Pass Confirm</td><td><input type=password id='ap_pass2' value='" + String(apPassword) + "'></td></tr>\r\n";
	s += "</table>\r\n";

	// station configuration
	s += "<table border=1>\r\n";
	s += "<tr><td colspan=2 bgcolor=#E0E0E0><b>STATION</b></td></tr>\r\n";
	s += "<tr><td>Mode</td><td><input type=radio id='modest' name='mode' value='station'" + (isAP?String(""):String(" checked")) + ">Station</td></tr>\r\n";
	s += "<tr><td>SSID</td><td><input type=text id='ssid' value='" + String(ssid) + "'></td></tr>\r\n";
	s += "<tr><td>Password</td><td><input type=password id='pass' value='" + String(password) + "'></td></tr>\r\n";
	s += "<tr><td>Pass Confirm</td><td><input type=password id='pass2' value='" + String(password) + "'></td></tr>\r\n";
	s += "</table>\r\n";

	// udp/tcp ports configuration
	s += "<table border=1>\r\n";
	s += "<tr><td colspan=2 bgcolor=#E0E0E0><b>UDP|TCP LISTENERS</b></td></tr>\r\n";
	s += "<tr><td>UDP Port</td><td><input type=text id='udpPort' value='" + String(udpPort) + "'></td></tr>\r\n";
	s += "<tr><td>TCP Port</td><td><input type=text id='tcpPort' value='" + String(tcpPort) + "'></td></tr>\r\n";
	s += "</table>\r\n";

	// save button
	s += "<input type=button value='Save and Reset' onClick='save()'>\r\n";

	// end of HTTP
	s += "</body></html>\r\n";

	// write second part of response
	httpClient.write(s.c_str(), s.length());
	httpClient.flush();

	if (updated)
	{
		// give some time
		delay(2000);

		// reset the microcontroller
		Reset();
	}
}
Example #21
0
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&uuml;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&uuml;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&auml;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&uuml;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&uuml;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&auml;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&uuml;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&uuml;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&uuml;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&uuml;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&uuml;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&uuml;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>&nbsp;<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>&nbsp;<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>&nbsp;<a href=\"/temp2\"><button>Speicher mitte</button></a>&nbsp;<a href=\"/temp3\"><button>Speicher unten</button></a>&nbsp;<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&uuml;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&uuml;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>&nbsp;<a href=\"/temp2\"><button>Speicher mitte</button></a>&nbsp;<a href=\"/temp3\"><button>Speicher unten</button></a>&nbsp;<a href=\"/temp4\"><button>Vorlauf</button></a>&nbsp;</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&uuml;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&uuml;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>&nbsp;<a href=\"/temp2\"><button>Speicher mitte</button></a>&nbsp;<a href=\"/temp3\"><button>Speicher unten</button></a>&nbsp;<a href=\"/temp4\"><button>Vorlauf</button></a>&nbsp;</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&uuml;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&uuml;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>&nbsp;<a href=\"/temp2\"><button>Speicher mitte</button></a>&nbsp;<a href=\"/temp3\"><button>Speicher unten</button></a>&nbsp;<a href=\"/temp4\"><button>Vorlauf</button></a>&nbsp;</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&uuml;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&uuml;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>&nbsp;<a href=\"/temp2\"><button>Speicher mitte</button></a>&nbsp;<a href=\"/temp3\"><button>Speicher unten</button></a>&nbsp;<a href=\"/temp4\"><button>Vorlauf</button></a>&nbsp;</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");

}
Example #22
0
/**
 * @brief Arduino setup function.
 */
void WiFi_setup()
{

  // Set Hostname.
  //hostname += String(ESP.getChipId(), HEX);
  WiFi.hostname(HOSTNAME);

  // Print hostname.
  //Serial.println("Hostname: " + hostname);
  Serial.println("Hostname: " + WiFi.hostname());


  // Initialize file system.
  if (!SPIFFS.begin())
  {
    Serial.println("Failed to mount file system");
    return;
  }

  // Load wifi connection information.
  if (! loadConfig(&station_ssid, &station_psk))
  {
    station_ssid = MY_ACCESSPOINT_SSID ;
    station_psk = MY_ACCESSPOINT_PSK ;

    Serial.println("No WiFi connection information available.");
  }

  // Check WiFi connection
  // ... check mode
  if (WiFi.getMode() != WIFI_STA)
  {
    WiFi.mode(WIFI_STA);
    delay(10);
  }

  // ... Compare file config with sdk config.
  if (WiFi.SSID() != station_ssid || WiFi.psk() != station_psk)
  {
    Serial.println("WiFi config changed.");

    // ... Try to connect to WiFi station.
    WiFi.begin(station_ssid.c_str(), station_psk.c_str());

    // ... Pritn new SSID
    Serial.print("new SSID: ");
    Serial.println(WiFi.SSID());

    // ... Uncomment this for debugging output.
    //WiFi.printDiag(Serial);
  }
  else
  {
    // ... Begin with sdk config.
    WiFi.begin();
  }

  Serial.println("Wait for WiFi connection.");

  // ... Give ESP 10 seconds to connect to station.
  unsigned long startTime = millis();
  while (WiFi.status() != WL_CONNECTED && millis() - startTime < 10000)
  {
    Serial.write('.');
    //Serial.print(WiFi.status());
    delay(500);
  }
  Serial.println();

  // Check connection
  if(WiFi.status() == WL_CONNECTED)
  {
    // ... print IP Address
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());

#if CLOUD_MODE

    // close any connection before send a new request.
    // This will free the socket on the WiFi shield
    client.stop();

    delay(1000);

    Serial.print("Connection to "); Serial.print(CLOUD_HOSTNAME); Serial.print(":"); Serial.print(CLOUD_PORT); Serial.print(" ");
    // if there's a successful connection:
    if (client.connect(CLOUD_HOSTNAME, CLOUD_PORT)) {
      Serial.println("succeed");
    } else {
      // if you couldn't make a connection:
      Serial.println("failed");
    }
#endif

  }
  else
  {
    Serial.println("Can not connect to WiFi station. Go into AP mode.");
    
    // Go into software AP mode.
    WiFi.mode(WIFI_AP);

    delay(10);

    WiFi.softAP(ap_default_ssid, ap_default_psk);

    Serial.print("IP address: ");
    Serial.println(WiFi.softAPIP());
  }

}
Example #23
0
t_httpUpdate_return ESP8266HTTPUpdate::update(const char * host, uint16_t port, const char * url, const char * current_version) {

    t_httpUpdate_return ret = HTTP_UPDATE_FAILED;
    WiFiClient tcp;
    DEBUG_HTTP_UPDATE("[httpUpdate] connected to %s:%u %s .... ", host, port, url);

    if(!tcp.connect(host, port)) {
        DEBUG_HTTP_UPDATE("failed.\n");
        return ret;
    }
    DEBUG_HTTP_UPDATE("ok.\n");

    // set Timeout for readBytesUntil and readStringUntil
    tcp.setTimeout(2000);
    tcp.setNoDelay(true);

    String req = "GET ";

    req += url;
    req += " HTTP/1.1\r\n"
            "Host: ";
    req += host;
    req += "\r\n"
            "Connection: close\r\n"
            "User-Agent: ESP8266-http-Update\r\n"
            "x-ESP8266-STA-MAC: ";
    req += WiFi.macAddress();
    req += "\r\n"
            "x-ESP8266-AP-MAC: ";
    req += WiFi.softAPmacAddress();
    req += "\r\n"
            "x-ESP8266-free-space: ";
    req += ESP.getFreeSketchSpace();
    req += "\r\n"
            "x-ESP8266-sketch-size: ";
    req += ESP.getSketchSize();
    req += "\r\n"
            "x-ESP8266-chip-size: ";
    req += ESP.getFlashChipRealSize();
    req += "\r\n"
           "x-ESP8266-sdk-version: ";
    req += ESP.getSdkVersion();

    if(current_version[0] != 0x00) {
        req += "\r\n"
               "x-ESP8266-version: ";
        req += current_version;
    }

    req += "\r\n"
           "\r\n";

    tcp.write(req.c_str(), req.length());

    uint32_t code = 0;
    size_t len = 0;

    while(true) {
        String headerLine = tcp.readStringUntil('\n');
        headerLine.trim(); // remove \r

        if(headerLine.length() > 0) {
            DEBUG_HTTP_UPDATE("[httpUpdate][Header] RX: %s\n", headerLine.c_str());
            if(headerLine.startsWith("HTTP/1.")) {
                // 9 = lenght of "HTTP/1.x "
                code = headerLine.substring(9, headerLine.indexOf(' ', 9)).toInt();
            } else if(headerLine.startsWith("Content-Length: ")) {
                // 16 = lenght of "Content-Length: "
                len = headerLine.substring(16).toInt();
            }
        } else {
            break;
        }
    }

    DEBUG_HTTP_UPDATE("[httpUpdate] Header read fin.\n");
    DEBUG_HTTP_UPDATE("[httpUpdate] Server header:\n");
    DEBUG_HTTP_UPDATE("[httpUpdate]  - code: %d\n", code);
    DEBUG_HTTP_UPDATE("[httpUpdate]  - len: %d\n", len);

    DEBUG_HTTP_UPDATE("[httpUpdate] ESP8266 info:\n");
    DEBUG_HTTP_UPDATE("[httpUpdate]  - free Space: %d\n", ESP.getFreeSketchSpace());
    DEBUG_HTTP_UPDATE("[httpUpdate]  - current Sketch Size: %d\n", ESP.getSketchSize());

    if(current_version[0] != 0x00) {
        DEBUG_HTTP_UPDATE("[httpUpdate]  - current version: %s\n", current_version);
    }

    switch(code) {
        case 200:  ///< OK (Start Update)
            if(len > 0) {
                if(len > ESP.getFreeSketchSpace()) {
                    ret = HTTP_UPDATE_FAILED;
                    DEBUG_HTTP_UPDATE("[httpUpdate] FreeSketchSpace to low (%d) needed: %d\n", ESP.getFreeSketchSpace(), len);
                } else {

                    WiFiUDP::stopAll();
                    WiFiClient::stopAllExcept(&tcp);

                    delay(100);

                    if(ESP.updateSketch(tcp, len, false, false)) {
                        ret = HTTP_UPDATE_OK;
                        DEBUG_HTTP_UPDATE("[httpUpdate] Update ok\n");
                        tcp.stop();
                        ESP.restart();
                    } else {
                        ret = HTTP_UPDATE_FAILED;
                        DEBUG_HTTP_UPDATE("[httpUpdate] Update failed\n");
                    }
                }
            } else {
                ret = HTTP_UPDATE_FAILED;
                DEBUG_HTTP_UPDATE("[httpUpdate] Content-Length is 0?!\n");
            }
            break;
        case 304:
            ///< Not Modified (No updates)
            ret = HTTP_UPDATE_NO_UPDATES;
            break;
        case 403:
            ///< Forbidden
            // todo handle login
        default:
            ret = HTTP_UPDATE_FAILED;
            DEBUG_HTTP_UPDATE("[httpUpdate] Code is (%d)\n", code);
            break;
    }

    return ret;
}
Example #24
0
void AJ_Net_Disconnect(AJ_NetSocket* netSock)
{
    AJ_InfoPrintf(("AJ_Net_Disconnect(nexSock=0x%p)\n", netSock));
    g_client.stop();
}
Example #25
0
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;
  }
}
////////////////////////////////////
// Scrape UTC Time from server
////////////////////////////////////
char* updateCurTime(void) {
    static int timeout_busy=0;
    int ipos;
    timeout_busy=0; //reset

    const char* timeServer = "aws.amazon.com";

    // send a bad header on purpose, so we get a 400 with a DATE: timestamp
    const char* timeServerGet = "GET example.com/ HTTP/1.1";
    String utctime;
    String GmtDate;
    static char dateStamp[20];
    static char chBuf[200];
    char utctimeraw[80];
    char* dpos;

    WiFiClient client;
    if (client.connect(timeServer, 80)) {
        //Send Request
        client.println(timeServerGet);
        client.println();
        while((!client.available())&&(timeout_busy++<5000)){
          // Wait until the client sends some data
          delay(1);
        }

        // kill client if timeout
        if(timeout_busy>=5000) {
            client.flush();
            client.stop();
            Serial.println("timeout receiving timeserver data\n");
            return dateStamp;
        }

        // read the http GET Response
        String req2 = client.readString();
        // Serial.println("");
        // Serial.println("");
        // Serial.print(req2);
        // Serial.println("");
        // Serial.println("");

        // close connection
        delay(1);
        client.flush();
        client.stop();

        ipos = req2.indexOf("Date:");
        if(ipos>0) {
          GmtDate = req2.substring(ipos,ipos+35);
          // Serial.println(GmtDate);
          utctime = GmtDate.substring(18,22) + getMonth(GmtDate.substring(14,17)) + GmtDate.substring(11,13) + GmtDate.substring(23,25) + GmtDate.substring(26,28) + GmtDate.substring(29,31);
          // Serial.println(utctime.substring(0,14));
          utctime.substring(0,14).toCharArray(dateStamp, 20);
        }
    }
    else {
      Serial.println("did not connect to timeserver\n");
    }
    timeout_busy=0;     // reset timeout
    return dateStamp;   // Return latest or last good dateStamp
}
Example #27
0
void GPSUploader::_sendNextGpsData() {
  int startTimeUploading = millis();
  if(!this->_initialized) return;
  Serial.printf("Upload: Pending messages: %d\n", this->_sdQueue.getCount());
  Serial.println("Upload: preparation");
  this->_sdQueue.flush();//avoid parallel flush() during server connection (too much mem)

  if(this->_sdQueue.getCount()==0) {
    Serial.println("Upload: no data to send");
    return;
  }

  //connect to server and send various POST on the same connection
  WiFiClient client;
  // Serial.printf("Host=%s:%d\n", this->_configNode.getUploadServerHost().c_str(), this->_configNode.getUploadServerPort());
  _watchdog.ping();
  int startTime = millis();
  if (!client.connect(this->_uploadServerHost.get(), this->_uploadServerPort.get())) {
     this->_totalUploadCountError++;
     this->_totalUploadTimeError+=(millis()-startTime);
     Serial.println("Upload: server connection failed");
     _watchdog.ping();
     return;
  }
  _watchdog.ping();

  //send
  //If this takes more than 10s, abort and loop again so that Wifi and MQTT won't lose connection
  for(int i=0; i<10 && ((millis()-startTimeUploading)<10000); i++) {
    // int len = 0;
    int sdRecordsCount = 0;
    int sdRecordsOK = 0;
    int sdRecordsError = 0;
    strcpy(this->_gpsUploadBuffer, "");

    // Serial.println("Upload: Preparing chunk");
    while(this->_sdQueue.peek(this->_gpsRecord, sdRecordsCount++) && strlen(this->_gpsUploadBuffer) < 1150) {
      //fill post with ~1200 bytes
      if(GPSUtils::validateNmeaChecksum(this->_gpsRecord)) {
        strcat(this->_gpsUploadBuffer, this->_gpsRecord);
        strcat(this->_gpsUploadBuffer, "\n");
        sdRecordsOK++;
      } else {
        Serial.printf("Upload: crc error %s\n", this->_gpsRecord);
        sdRecordsError++;
      }
      yield();
    }

    if(strlen(this->_gpsUploadBuffer)>0) {
      Serial.printf("Upload: records=%d err=%d\n", sdRecordsOK, sdRecordsError);

      Serial.println("POST /" + String(this->_uploadServerUri.c_str()));
      int startTime = millis();
      client.printf("POST /%s HTTP/1.1\r\nHost: %s\r\nContent-Length: %d\r\nContent-Type: text/plain\r\n\r\n",
                      this->_uploadServerUri.c_str(),
                      "api.devices.stutzthings.com",
                      // this->_uploadServerHost.get(),
                      strlen(this->_gpsUploadBuffer)
      );
      client.print(this->_gpsUploadBuffer);
      _watchdog.ping();
      // Serial.println("SENT");

      //wait for response available
      int timeout = millis();
      while (client.available() < 15) {
        if (millis() - timeout > 5000) {
          Serial.println("Upload: server response timeout");
          client.stop();
          this->_totalUploadBytesError += strlen(this->_gpsUploadBuffer);
          this->_totalUploadCountError++;
          this->_totalUploadTimeError+=(millis()-startTime);
          return;
        }
        delay(50);
        _watchdog.ping();
      }
      // Serial.println("RECEIVED RESPONSE");

      //process response
      bool success = false;
      if(client.readStringUntil(GCHAR_SPACE).length()>0) {
        String code = client.readStringUntil(GCHAR_SPACE);
        _watchdog.ping();
        if(code == "201") {
          Serial.println("Upload: 201 Created");
          success = true;
          this->_totalUploadBytesSuccess += strlen(this->_gpsUploadBuffer);
          this->_totalUploadCountSuccess++;
          this->_totalUploadTimeSuccess+=(millis()-startTime);
          this->_totalUploadRecordsSuccess+=sdRecordsOK;
          this->_totalUploadRecordCRCError+=sdRecordsError;
          this->_sdQueue.removeElements(sdRecordsCount);
          // Serial.println("Upload: sent records removed from disk");
        } else {
          this->_totalUploadBytesError += strlen(this->_gpsUploadBuffer);
          this->_totalUploadCountError++;
          this->_totalUploadTimeError+=(millis()-startTime);
          Serial.println("Upload: server error " + String(code));
        }
      } else {
        this->_totalUploadBytesError += strlen(this->_gpsUploadBuffer);
        this->_totalUploadCountError++;
        this->_totalUploadTimeError+=(millis()-startTime);
        Serial.println("Upload: invalid server response");
      }
      //drain response data
      // Serial.println("RESPONSE DRAIN0");
      _watchdog.ping();
      while(client.available()>0) {
        client.read();
      }
      // Serial.println("RESPONSE DRAIN1");
      // Serial.println("Upload: post finished");

    } else {
      Serial.println("Upload: no data pending");
      if(sdRecordsError>0) {
        this->_sdQueue.removeElements(sdRecordsError);
        this->_totalUploadRecordCRCError+=sdRecordsError;
      }
      break;
    }
    _watchdog.ping();
    yield();
    _watchdog.ping();
    // Serial.println("FINISHED POST");
  }

  client.stop();
}
Example #28
0
/*
 *  ======== 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;
            digitalWrite(MAIN_LED_PIN, !digitalRead(MAIN_LED_PIN));
            /* 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
            digitalWrite(MAIN_LED_PIN, !digitalRead(MAIN_LED_PIN));
            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[64] = {0};
            int bufLen = 0;

            /* while connected to the client, read commands and send results */
            unsigned int lapse = 0;
            unsigned int start = millis();
            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;
                    //Serial.print(num_sockets); Serial.print(": ");
                    //Serial.println((int)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;
                    }

                    lapse = 0;
                    start = millis();
                }
                else {
                    lapse = millis() - start;
                }
            }

            Serial.print("client socket disconnected: lapse = ");
            Serial.println(lapse);

            /* client disconnected or timed out, close the connection */
            client.stop();

            /* disconnect => implicitly stop the motor */
            motorWASD = ' ';
        }
    }

    /* check for new connections 2 times per second */
    delay(500);
}