Example #1
0
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;
    
}
Example #2
0
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");
}
extern "C" void MW_WifiTCPFinalread(uint8_t wifitcpindex, uint8_t *data, uint32_t serverport, int32_t *outStatus)
{
    int libFcnOutput;
    WiFiClient client = server[wifitcpindex].available();
    if (client == true) {
        libFcnOutput = client.read();
        *data = (uint8_t) libFcnOutput;
        *outStatus = (libFcnOutput != -1);
    }

    else
    {
        //When the client is not connected the status flag is accordingly toggled. 
        *outStatus = 0;
    }
}
//****************** 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 #5
0
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");
  while(!client.available()) {
    Serial.println(".");
    delay(1000); 
  }
  
  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);
      }
    }
  }  
}
Example #6
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);
  }
}
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 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 #10
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 #11
0
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;
}
Example #12
0
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);
}
Example #13
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 #14
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 #15
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);
}
Example #16
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 #17
0
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;
}
//****************** Recieve data for ModBusSlave ****************
void MgsModbus::MbsRun()
{  
  //****************** Read from socket ****************
  WiFiClient client = MbServer.available();
  if(client.available())
  {
    delay(10);
    int i = 0;
    while(client.available())
    {
      MbsByteArray[i] = client.read();
      i++;
    }
    MbsFC = SetFC(MbsByteArray[7]);  //Byte 7 of request is FC
  }
  int Start, WordDataLength, ByteDataLength, CoilDataLength, MessageLength;
  //****************** Read Coils (1 & 2) **********************
  if(MbsFC == MB_FC_READ_COILS || MbsFC == MB_FC_READ_DISCRETE_INPUT) {
    Start = word(MbsByteArray[8],MbsByteArray[9]);
    CoilDataLength = word(MbsByteArray[10],MbsByteArray[11]);
    ByteDataLength = CoilDataLength / 8;
    if(ByteDataLength * 8 < CoilDataLength) ByteDataLength++;      
    CoilDataLength = ByteDataLength * 8;
    MbsByteArray[5] = ByteDataLength + 3; //Number of bytes after this one.
    MbsByteArray[8] = ByteDataLength;     //Number of bytes after this one (or number of bytes of data).
    for(int i = 0; i < ByteDataLength ; i++)
    {
      MbsByteArray[9 + i] = 0; // To get all remaining not written bits zero
      for(int j = 0; j < 8; j++)
      {
        bitWrite(MbsByteArray[9 + i], j, GetBit(Start + i * 8 + j));
      }
    }
    MessageLength = ByteDataLength + 9;
    client.write((uint8_t*)MbsByteArray, MessageLength);
    MbsFC = MB_FC_NONE;
  }
  //****************** Read Registers (3 & 4) ******************
  if(MbsFC == MB_FC_READ_REGISTERS || MbsFC == MB_FC_READ_INPUT_REGISTER) {
    Start = word(MbsByteArray[8],MbsByteArray[9]);
    WordDataLength = word(MbsByteArray[10],MbsByteArray[11]);
    ByteDataLength = WordDataLength * 2;
    MbsByteArray[5] = ByteDataLength + 3; //Number of bytes after this one.
    MbsByteArray[8] = ByteDataLength;     //Number of bytes after this one (or number of bytes of data).
    for(int i = 0; i < WordDataLength; i++)
    {
      MbsByteArray[ 9 + i * 2] = highByte(MbData[Start + i]);
      MbsByteArray[10 + i * 2] =  lowByte(MbData[Start + i]);
    }
    MessageLength = ByteDataLength + 9;
    client.write((uint8_t*)MbsByteArray, MessageLength);
    MbsFC = MB_FC_NONE;
  }
  //****************** Write Coil (5) **********************
  if(MbsFC == MB_FC_WRITE_COIL) {
    Start = word(MbsByteArray[8],MbsByteArray[9]);
    if (word(MbsByteArray[10],MbsByteArray[11]) == 0xFF00){SetBit(Start,true);}
    if (word(MbsByteArray[10],MbsByteArray[11]) == 0x0000){SetBit(Start,false);}
    MbsByteArray[5] = 2; //Number of bytes after this one.
    MessageLength = 8;
    client.write((uint8_t*)MbsByteArray, MessageLength);
    MbsFC = MB_FC_NONE;
  } 
  //****************** Write Register (6) ******************
  if(MbsFC == MB_FC_WRITE_REGISTER) {
    Start = word(MbsByteArray[8],MbsByteArray[9]);
    MbData[Start] = word(MbsByteArray[10],MbsByteArray[11]);
    MbsByteArray[5] = 6; //Number of bytes after this one.
    MessageLength = 12;
    client.write((uint8_t*)MbsByteArray, MessageLength);
    MbsFC = MB_FC_NONE;
  }
  //****************** Write Multiple Coils (15) **********************
  if(MbsFC == MB_FC_WRITE_MULTIPLE_COILS) {
    Start = word(MbsByteArray[8],MbsByteArray[9]);
    CoilDataLength = word(MbsByteArray[10],MbsByteArray[11]);
    MbsByteArray[5] = 6;
    for(int i = 0; i < CoilDataLength; i++)
    {
      SetBit(Start + i,bitRead(MbsByteArray[13 + (i/8)],i-((i/8)*8)));
    }
    MessageLength = 12;
    client.write((uint8_t*)MbsByteArray, MessageLength);
    MbsFC = MB_FC_NONE;
  }  
  //****************** Write Multiple Registers (16) ******************
  if(MbsFC == MB_FC_WRITE_MULTIPLE_REGISTERS) {
    Start = word(MbsByteArray[8],MbsByteArray[9]);
    WordDataLength = word(MbsByteArray[10],MbsByteArray[11]);
    ByteDataLength = WordDataLength * 2;
    MbsByteArray[5] = 6;
    for(int i = 0; i < WordDataLength; i++)
    {
      MbData[Start + i] =  word(MbsByteArray[ 13 + i * 2],MbsByteArray[14 + i * 2]);
    }
    MessageLength = 12;
    client.write((uint8_t*)MbsByteArray, MessageLength);
    MbsFC = MB_FC_NONE;
  }
}