void loop() {
  //low power
  WiFi.disconnect();
  System.sleep(D3, RISING, 4);
  if (digitalRead(D3)) {digitalWrite(D6,HIGH);delay(200);digitalWrite(D6,LOW);}

  while (!WiFi.ready()) {
    Particle.process();
    WiFi.connect();
    while(WiFi.connecting()){Particle.process();}
  }// while (!WiFi.ready())

  complete = false;

  //don't unsuccessfully persist beyond 10 secs, just go back to sleep
  lastTime = millis();
  while ((!complete) &&  (millis() - lastTime < 10000)){

  if (client.connect( server, serverPort)) {
    if (client.connected()) {
     sprintf(outmsg,"%c",clientmsg);
     out(outmsg);

    lastTime = millis();
    while ((!client.available()) && (millis() - lastTime < 5000)) { }

    lastTime = millis();
    while ((millis() - lastTime < 300)) {}//plays better with nodejs server?

 //now get confirmation from server that server received msg
    while (client.available()) {
      read_char = client.read();
      if(read_char == replymsg ) { //we got confirmation
        digitalWrite(D7,HIGH);delay(10);digitalWrite(D7,LOW);
        client.read();
        complete = true;
      }//if(read_char == replymsg )
    }//while (client.available())
  }//if (client.connected())
}//if (client.connect( server, serverPort))

  client.read();
  client.flush();
//  client.stop();//apparently unnecessary

}//while (!complete)

// prevent nodejs ECONNRESET, not necessay with another photon??
  lastTime = millis();
  while ((millis() - lastTime < 500)) {}//prevent nodejs ECONNRESET

delay(1);
}//loop
void loop() {
  if (client.connected()) {
    if (client.available()) {
      char pin = client.read() - '0' + D0;
      char level = client.read();
      if ('h' == level) {
        digitalWrite(pin, HIGH);
      } else {
        digitalWrite(pin, LOW);
      }
    }
  }
}
void in(char *ptr, uint8_t timeout) {
  int pos = 0;
  unsigned long lastdata = millis();
  while ( client.available() || (millis()-lastdata < timeout)) {
    if (client.available()) {
      char c = client.read();
      lastdata = millis();
      ptr[pos] = c;
      pos++;
    }//if (client.available())
  }//while ( client.available() || (millis()-lastdata < timeout))
  client.read();
}//void in(char *ptr, uint8_t timeout)
Esempio n. 4
0
void tcpKeepAlive() {
    unsigned long now = millis();
    if (tcp.connected()) {
        if (now > kaTimer) {
            tcp.flush();
            tcpLog("ENQ"); // For logger view 
            tcp.print(ENQ); // Heartbeat signal
            kaWait = now + 500;
            kaWaiting = true;
            tcpKeepAliveReset();
        }
        if (kaWaiting && (kaWait > now)) {
            if (tcp.available()) {
                char read = tcp.read();
                if (read == ACK) {
                    // tcpLog("ACK");
                    kaWaiting = false;
                }
            }
        } else if (kaWaiting && kaWait < now) {
            tcpLog("Timed out");
            kaWaiting = false;
            tcp.flush();
            tcp.stop();
        }
    }
}
void loop() {

    char tmp[3];
    int charPosition = 0;

    // While there is data in the buffer, lets read it.
    while(client.available()) {

        char c = client.read();

        // Check if we reached the end of the data
        if(c == ',') {

            // use the accumulated value
            pData(tmp);

            // Reset
            tmp[0];
            charPosition = 0;

        } else {

            // Save char in to the temp array
            tmp[charPosition] = c;

            // Increment the position of the array
            charPosition++;

        }

    }

}
Esempio n. 6
0
int sendRequest (byte* host, unsigned short port, char* response, unsigned short responseSize, boolean keepAlive)
{
  if (myClient.connected() || myClient.connect(host, port)) {
      uint32_t startTime = millis();

      myClient.write((const uint8_t *)mainbuffer, strlen(mainbuffer));
      myClient.flush();

      while(!myClient.available() && (millis() - startTime) < 5000){
          SPARK_WLAN_Loop();
      };

      while(myClient.available()) {
          readbytes = myClient.read((uint8_t*) response, responseSize);
          if (readbytes == -1) break;
      }

      myClient.flush();

      if(!keepAlive) {
        myClient.stop();
      }

  } else {
      // unable to connect
      return 1;
  }

  return 0;
}
void loop()
{
    if (client.connected())
    {
        while (client.available())
        {
            in(inmsg,1000);
            myInStr =inmsg;
            if (myInStr.indexOf(clientmsg)  >= 0) {
                digitalWrite(D7, 1);
                delay(50);
                digitalWrite(D7, 0);
                sprintf(outmsg,"%c",replymsg);
                out(outmsg);
//THIS WORKS TOO
//                IPAddress myIP = WiFi.localIP();
//                sprintf(outmsg, "%d.%d.%d.%d,%d,2,%d,3,4/e", myIP[0], myIP[1], myIP[2], myIP[3],counter,simulate_temp);
//                out(outmsg); //but don't yet have a tcpclient that can handle such a response
            }//if (myInStr.indexOf("7")  >= 0)
        }//while (client.available())
    }//if (client.connected())
    client.read();
    client.flush();
//    client.stop(); //apparently unnecessary
    client = server.available();
 //keep connection alive long enough for client to receive reply
    lastTime = millis();
    while ( millis()-lastTime < 300) {}
}//loop
void loop() {

    if (clientWww.connected()) {

        int position = 0;
        int canI = 0;

        // echo all available bytes back to the client
        while (clientWww.available()) {

            char c = clientWww.read();
            char url[200];

            // Detect space
            if(c == 32) {

                canI = !canI;

            }

            // Save only data in between spaces
            if(canI) {

                // Discard spaces
                if(c != 32) {

                    url[position++] = c;

                }

            }

            // Detect end of the line
            if(c == 10) {

                // Null terminate our array
                url[position + 1] = 0;

                response(url);

                // Discard the rest of the header
                clientWww.flush();

            }

        }

    } else {

        // if no client is yet connected, check for a new connection
        clientWww = serverWww.available();

    }

}
Esempio n. 9
0
int main()
{
    signal(SIGPIPE, SIG_IGN);
    char buf[BUFSIZ];
    int clientCount = 0;
    try
    {
        TCPServer server(8001);
        int listenfd = server.getfd();
        Epoll epoll;
        // 将监听套接字注册到epoll
        epoll.addfd(server.getfd(), EPOLLIN, true);
        while (true)
        {
            int nReady = epoll.wait();
            for (int i = 0; i < nReady; ++i)
                // 如果是监听套接字发生了可读事件
                if (epoll.getEventOccurfd(i) == listenfd)
                {
                    int connectfd = accept(listenfd, NULL, NULL);
                    if (connectfd == -1)
                        err_exit("accept error");
                    cout << "accept success..." << endl;
                    cout << "clientCount = " << ++ clientCount << endl;
                    setUnBlock(connectfd, true);
                    epoll.addfd(connectfd, EPOLLIN, true);
                }
                else if (epoll.getEvents(i) & EPOLLIN)
                {
                    TCPClient *client = new TCPClient(epoll.getEventOccurfd(i));
                    memset(buf, 0, sizeof(buf));
                    if (client->read(buf, sizeof(buf)) == 0)
                    {
                        cerr << "client connect closed..." << endl;
                        // 将该套接字从epoll中移除
                        epoll.delfd(client->getfd());
                        delete client;
                        continue;
                    }
                    cout << buf;
                    client->write(buf);
                }
        }
    }
    catch (const SocketException &e)
    {
        cerr << e.what() << endl;
        err_exit("TCPServer error");
    }
    catch (const EpollException &e)
    {
        cerr << e.what() << endl;
        err_exit("Epoll error");
    }
}
void in(char *ptr, uint8_t timeout) {
        int pos = 0;
        unsigned long lastTime = millis();
        while( client.available()==0 && millis()-lastTime<timeout) { //timeout
        }  //do nothing
        unsigned long lastdata = millis();
        while ( client.available() || (millis()-lastdata < 500)) {  //500 millisecond timeout
            if (client.available()) {
                char c = client.read();
                lastdata = millis();
                ptr[pos] = c;
                pos++;
            }
            if (pos >= 512 - 1)
            break;
        }
        ptr[pos] = '\0'; //end the char array
        while (client.available()) client.read(); // makeshift client.flush()
        client.flush();  //for safety
       lastdata = millis();
        while ( millis()-lastdata < 200) { }
}//void in(char *ptr, uint8_t timeout)
void loop() {

    if (client.connected()) {

        client.write("I am the server sending you a message.");

        while(client.available()) {

            char c = client.read();
            Serial.print(c);

        }

    } else {

        client = server.available();

    }

}
Esempio n. 12
0
void loop()
{
  // Now open your Serial Terminal, and hit any key to continue!
  if (Serial.available()) {
      char c = Serial.read();
  Serial.println(WiFi.localIP());
  Serial.println(WiFi.subnetMask());
  Serial.println(WiFi.gatewayIP());
  Serial.println(WiFi.SSID());
  }


    if (client.connected()) {
    // echo all available bytes back to the client
    while (client.available()) {
      server.write(client.read());
    }
  } else {
    // if no client is yet connected, check for a new connection
    client = server.available();
  }
}
Esempio n. 13
0
/** Read data from client.
  @param data String to read the received data into.
  @param client TCPClient to get the data from.
*/
bool SparkWebSocketServer::getData(String &data, TCPClient &client)
{
    char buffer[packetLen];

    if(client.connected()) {
        while(client.available() == 0);

        for(int count = 0; client.available() > 0 && count < packetLen; count++) {
            buffer[count] = client.read();
        }

        if(packetHealth(buffer) != 0)
            return false;
        /*int failCount = 0;
        while(packetHealth(buffer) > 0) {
            // make room
            for(int i = 0; i < packetLen-1; i++)
                buffer[i] = buffer[i+1];

            while(client.available() == 0);

            buffer[packetLen-1] = client.read();

            failCount++;
        }

        if(failCount != 0)
            Serial.println(failCount);
        */

        for(int i = 0; i < dataLen; i++) {
            data += (char) (buffer[i+8] ^ buffer[4 + i % 4]);
        }
    }

    return true;
}
Esempio n. 14
0
void loop() {



  if (client.connected()) {

    digitalWrite(D4,HIGH);
    digitalWrite(D0,HIGH);
    delay(200);
    digitalWrite(D4,LOW);
    digitalWrite(D0,LOW);

    while (client.available()) {

      digitalWrite(D4,HIGH);
      digitalWrite(D7,HIGH);
      delay(200);
      digitalWrite(D4,LOW);
      digitalWrite(D7,LOW);



      Serial.println();
      int val = client.read();
      Serial.println(val);

      netapp_ipconfig(&ipconfig);
      char connectedSSID[32];
      sprintf(connectedSSID, "%s", ipconfig.uaSSID);



      digitalWrite(D7,HIGH);
      delay(500);
      digitalWrite(D7,LOW);
      delay(500);

      long err = wlan_ioctl_get_scan_results(0, ucResults);
      int _numEntry = ((uint8_t) ucResults[3] << 24) | ((uint8_t) ucResults[2] << 16) | ((uint8_t) ucResults[1] << 8) | ((uint8_t) ucResults[0]);

      if (err == 0 && _numEntry > 0) {


        digitalWrite(D4,HIGH);
        delay(100);
        digitalWrite(D4,LOW);

        int _stat = ((uint8_t) ucResults[7] << 24) | ((uint8_t) ucResults[6] << 16) | ((uint8_t) ucResults[5] << 8) | ((uint8_t) ucResults[4]);
        bool _valid = (uint8_t) ucResults[8]  & 0x1;
        int _rssi = (uint8_t) ucResults[8] >> 1;
        int _mode = ((uint8_t) ucResults[9] | 0xC0) & 0x3;
        int _ssidlen = (uint8_t) ucResults[9] >> 2;

        char ssid[32];
        int idx = 0;
        while(idx < _ssidlen) {
          ssid[idx] = ucResults[idx+12];
          idx++;
        }
        ssid[_ssidlen] = (char) NULL;

        if (strcmp(connectedSSID, ssid) == 0){

          digitalWrite(D0,HIGH);
          delay(100);
          digitalWrite(D0,LOW);


          Serial.print("WiFi scan status: ");
          server.write("WiFi scan status: ");
          switch (_stat) {
            case 0:
            Serial.print("aged, ");
            server.write("aged, ");
            break;
            case 1:
            Serial.print("valid, ");
            server.write("valid, ");
            break;
            case 2:
            Serial.print("no results, ");
            server.write("no results, ");
            break;
          }

          Serial.print(_numEntry);
          Serial.print(" nets found. ");
          Serial.print(ssid);

          server.write(_numEntry);
          server.write(" nets found. ");
          server.write(ssid);

          if (_valid){
            Serial.print(" is valid, RSSI: ");
            server.write(" is valid, RSSI: ");
          }
          else{
            Serial.print("not valid, RSSI: ");
            server.write("not valid, RSSI: ");
          }

          Serial.print(_rssi);
          Serial.print(", mode: ");

          server.write(_rssi);
          server.write(", mode: ");

          switch (_mode) {
            case 0:
            Serial.println("OPEN");
            server.write("OPEN\n");
            break;
            case 1:
            Serial.println("WEP");
            server.write("WEP\n");
            break;
            case 2:
            Serial.println("WPA");
            server.write("WPA\n");
            break;
            case 3:
            Serial.println("WPA2");
            server.write("WPA2\n");
            break;
          }

        }

        incomingByte = Serial.read();
        //key press 'a' to get data
        if (incomingByte == 97){
          Serial.print("local ip   : ");
          Serial.println(Network.localIP());
          Serial.print("subnet mask: ");
          Serial.println(Network.subnetMask());
          Serial.print("gateway ip : ");
          Serial.println(Network.gatewayIP());
          Serial.print("ssid       : ");
          Serial.println(Network.SSID());
          Serial.println();

        }

        Serial.print(connectedSSID);
        Serial.print( " ");
        Serial.println(ssid);

        server.write(connectedSSID);
        server.write( " ");
        server.write(ssid);
        server.write("\n");

      } else {
Esempio n. 15
0
void loop()
{
    int debug = digitalRead(debug_tx);
    
    if(!digitalRead(waitpin_C)){
        // Skip mode, to ensure bootloader stays available
        char buffer[32];
        sprintf(buffer,"skip state: %d\r\n",state);
        Serial1.print(buffer);
        digitalWrite(led, HIGH);   // Turn ON the LED       
        delay(100);
        return;
    }else{
        digitalWrite(led, LOW);   // Turn OFF the LED  
    }

    delay(1);
    switch(state){
        case 0:
            // Waiting for next time
            wait-=10;
            if(wait<0){
                wait = 0;
                state = 1;
            }
            break;
        case 1:
            // Connecting
            if(debug) Serial1.println("connecting");
            if (client.connect(server, 80)){
                if(debug) Serial1.println("connected");
                state = 2;
            }else{
                if(debug) Serial1.println("connection failed state 1");
                wait = RETRY_INTERVAL;
                state = 0;
            }
            break;
        case 2:
            // Requesting
            tries = 0;
            store = 0;
            hash = 0;
            command_i = 0;
            for(int i=0; i<COMMAND_SIZE; i++) command[i] = 0;
            if(client.connected()){
                if(debug) client.println("GET // HTTP/1.0\r\n\r\n");
                wait = RESPONSE_INTERVAL;
                state = 3;
            }else{
                if(debug) Serial1.println("connection lost state 2");
                wait = RETRY_INTERVAL;
                state = 0;
            }
            break;
        case 3:
            // Receiving
            if(client.connected()){
                if (client.available() > 0) 
                {
                    // Print response to serial
                    char c = client.read();
                    if(debug) Serial1.print(c);
                    
                    // If last expected char found, quit reading
                    if(c =='>') hash = 1;
                    // If first char of data found, start storing the string
                    if(c =='<') store = 1;
                    if(store){
                        command[command_i++] = c;
                    }
                }else{
                    if(debug) Serial1.println("nd s3 ");  
                    delay(100);
                }
                // Quit reading
                if(hash){
                    Serial1.println();
                    state = 4;
                }
            }else{
                // We lost connection
                if(debug) Serial1.println("connection lost state 3");
                wait = RETRY_INTERVAL;
                state = 0;
            }
            break;
        case 4:
            // Disconnecting
            if(client.connected()){
                client.stop();
                if(debug) Serial1.println("connection closed state 4");
                wait = RENEW_INTERVAL;
                state = 5;
            }else{
                if(debug) Serial1.println("connection closed by server state 4");
                wait = RENEW_INTERVAL;
                state = 5; 
            }
            break;
        case 5:
        {
            int code = 0;
            // Parse data read
            client.stop();
            if(debug) Serial1.println("I've got this:");
            for(int i=0; i<COMMAND_SIZE; i++) Serial1.write(command[i]);
            Serial1.println("");
            
            // Control display
            //int code = (command[1]*1000)+(command[2]*100)+(command[3]*10)+(command[4]*1);
            //float temp = atoi((const char*)&command[6]) + (0.1 * atoi((const char*)&command[8]));
            sscanf((const char*)command,"<%d;%f>",&code,&temperature);
            
            if(debug) Serial1.print("Code: ");Serial1.println(code);
            if(debug) Serial1.print("Temp: ");Serial1.println(temperature);
  
            display(temperature);
        
            
            /*
            char tempString[10]; //Used for sprintf
            Serial1.println();
            Serial1.write('v');
            sprintf(tempString, "%4d", temp); //Convert deciSecond into a string that is right adjusted
            Serial1.print(tempString);
            */
            wait = RENEW_INTERVAL;
            state = 0;
        }
            break;
            
    }
}
void loop() {
  if (client.connected()) {
    isConnected = true;

    report();

    a = client.available();
    if (a > 0) {

      #ifdef DEBUG
      Serial.print("Bytes Available: ");
      Serial.println(a, DEC);
      #endif

      action = client.read();

      #ifdef DEBUG
      Serial.print("Action received: ");
      Serial.println(action, DEC);
      #endif

      // is the action valid?
      if (action <= msg_count) {

        // is there enough data left in the buffer to process this action?
        // if not, stop and fix
        if (msgMinLength[action] <= a) {


          int pin, mode, val, type, speed, address, stop, len, i;
          switch (action) {
            case msg_pinMode:  // pinMode
              pin = client.read();
              mode = client.read();
              #ifdef DEBUG
              Serial.print("PIN received: ");
              Serial.println(pin);
              Serial.print("MODE received: ");
              Serial.println(mode, HEX);
              #endif

              if (mode == 0x00) {
                pinMode(pin, INPUT);
              } else if (mode == 0x02) {
                pinMode(pin, INPUT_PULLUP);
              } else if (mode == 0x03) {
                pinMode(pin, INPUT_PULLDOWN);
              } else if (mode == 0x01) {
                pinMode(pin, OUTPUT);
              } else if (mode == 0x04) {
                pinMode(pin, OUTPUT);
                if (servos[ToServoIndex(pin)].attached()) {
                  servos[ToServoIndex(pin)].detach();
                }
                servos[ToServoIndex(pin)].attach(pin);
              }
              break;

            case msg_digitalWrite:  // digitalWrite
              pin = client.read();
              val = client.read();
              #ifdef DEBUG
              Serial.print("PIN received: ");
              Serial.println(pin, DEC);
              Serial.print("VALUE received: ");
              Serial.println(val, HEX);
              #endif
              digitalWrite(pin, val);
              break;

            case msg_analogWrite:  // analogWrite
              pin = client.read();
              val = client.read();
              #ifdef DEBUG
              Serial.print("PIN received: ");
              Serial.println(pin, DEC);
              Serial.print("VALUE received: ");
              Serial.println(val, HEX);
              #endif
              analogWrite(pin, val);
              break;

            case msg_digitalRead:  // digitalRead
              pin = client.read();
              val = digitalRead(pin);
              #ifdef DEBUG
              Serial.print("PIN received: ");
              Serial.println(pin, DEC);
              Serial.print("VALUE sent: ");
              Serial.println(val, HEX);
              #endif
              server.write(0x03);    // could be (action)
              server.write(pin);
              server.write(val);
              break;

            case msg_analogRead:  // analogRead
              pin = client.read();
              val = analogRead(pin);
              #ifdef DEBUG
              Serial.print("PIN received: ");
              Serial.println(pin, DEC);
              Serial.print("VALUE sent: ");
              Serial.println(val, HEX);
              #endif
              server.write(0x04);    // could be (action)
              server.write(pin);
              server.write(val);
              break;

            case msg_setAlwaysSendBit: // set always send bit
              pin = client.read();
              val = client.read();
              reading[pin] = val;
              break;

            // Serial API
            case msg_serialBegin:  // serial.begin
              type = client.read();
              speed = client.read();
              if (type == 0) {
                Serial.begin(SerialSpeed[speed]);
              } else {
                Serial1.begin(SerialSpeed[speed]);
              }
              break;

            case msg_serialEnd:  // serial.end
              type = client.read();
              if (type == 0) {
                Serial.end();
              } else {
                Serial1.end();
              }
              break;

            case msg_serialPeek:  // serial.peek
              type = client.read();
              if (type == 0) {
                val = Serial.peek();
              } else {
                val = Serial1.peek();
              }
              server.write(0x07);
              server.write(type);
              server.write(val);
              break;

            case msg_serialAvailable:  // serial.available()
              type = client.read();
              if (type == 0) {
                val = Serial.available();
              } else {
                val = Serial1.available();
              }
              server.write(0x07);
              server.write(type);
              server.write(val);
              break;

            case msg_serialWrite:  // serial.write
              type = client.read();
              len = client.read();

              for (i = 0; i < len; i++) {
                if (type == 0) {
                  Serial.write(client.read());
                } else {
                  Serial1.write(client.read());
                }
              }
              break;

            case msg_serialRead: // serial.read
              type = client.read();
              if (type == 0) {
                val = Serial.read();
              } else {
                val = Serial1.read();
              }
              server.write(0x16);
              server.write(type);
              server.write(val);
              break;

            case msg_serialFlush: // serial.flush
              type = client.read();
              if (type == 0) {
                Serial.flush();
              } else {
                Serial1.flush();
              }
              break;

            // SPI API
            case msg_spiBegin:  // SPI.begin
              SPI.begin();
              break;

            case msg_spiEnd:  // SPI.end
              SPI.end();
              break;

            case msg_spiSetBitOrder:  // SPI.setBitOrder
              type = client.read();
              SPI.setBitOrder((type ? MSBFIRST : LSBFIRST));
              break;

            case msg_spiSetClockDivider:  // SPI.setClockDivider
              val = client.read();
              if (val == 0) {
                SPI.setClockDivider(SPI_CLOCK_DIV2);
              } else if (val == 1) {
                SPI.setClockDivider(SPI_CLOCK_DIV4);
              } else if (val == 2) {
                SPI.setClockDivider(SPI_CLOCK_DIV8);
              } else if (val == 3) {
                SPI.setClockDivider(SPI_CLOCK_DIV16);
              } else if (val == 4) {
                SPI.setClockDivider(SPI_CLOCK_DIV32);
              } else if (val == 5) {
                SPI.setClockDivider(SPI_CLOCK_DIV64);
              } else if (val == 6) {
                SPI.setClockDivider(SPI_CLOCK_DIV128);
              } else if (val == 7) {
                SPI.setClockDivider(SPI_CLOCK_DIV256);
              }
              break;

            case msg_spiSetDataMode:  // SPI.setDataMode
              val = client.read();
              if (val == 0) {
                SPI.setDataMode(SPI_MODE0);
              } else if (val == 1) {
                SPI.setDataMode(SPI_MODE1);
              } else if (val == 2) {
                SPI.setDataMode(SPI_MODE2);
              } else if (val == 3) {
                SPI.setDataMode(SPI_MODE3);
              }
              break;

            case msg_spiTransfer:  // SPI.transfer
              val = client.read();
              val = SPI.transfer(val);
              server.write(0x24);
              server.write(val);
              break;

            // Wire API
            case msg_wireBegin:  // Wire.begin
              address = client.read();
              if (address == 0) {
                Wire.begin();
              } else {
                Wire.begin(address);
              }
              break;

            case msg_wireRequestFrom:  // Wire.requestFrom
              address = client.read();
              val = client.read();
              stop = client.read();
              Wire.requestFrom(address, val, stop);
              break;

            case msg_wireBeginTransmission:  // Wire.beginTransmission
              address = client.read();
              Wire.beginTransmission(address);
              break;

            case msg_wireEndTransmission:  // Wire.endTransmission
              stop = client.read();
              val = Wire.endTransmission(stop);
              server.write(0x33);    // could be (action)
              server.write(val);
              break;

            case msg_wireWrite:  // Wire.write
              len = client.read();
              uint8_t wireData[len];

              for (i = 0; i< len; i++) {
                wireData[i] = client.read();
              }
              val = Wire.write(wireData, len);

              server.write(0x34);    // could be (action)
              server.write(val);
              break;

            case msg_wireAvailable:  // Wire.available
              val = Wire.available();
              server.write(0x35);    // could be (action)
              server.write(val);
              break;

            case msg_wireRead:  // Wire.read
              val = Wire.read();
              server.write(0x36);    // could be (action)
              server.write(val);
              break;

            case msg_servoWrite:
              pin = client.read();
              val = client.read();
              #ifdef DEBUG
              Serial.print("PIN: ");
              Serial.println(pin);
              Serial.print("WRITING TO SERVO: ");
              Serial.println(val);
              #endif
              servos[ToServoIndex(pin)].write(val);
              break;

            case msg_servoWriteMicroseconds:
              pin = client.read();
              val = client.read();
              #ifdef DEBUG
              Serial.print("PIN: ");
              Serial.println(pin);
              Serial.print("WRITING 'us' TO SERVO: ");
              Serial.println(val);
              #endif
              servos[ToServoIndex(pin)].writeMicroseconds(val);
              break;

            case msg_servoRead:
              pin = client.read();
              val = servos[ToServoIndex(pin)].read();
              server.write(0x43);    // could be (action)
              server.write(pin);
              server.write(val);
              break;

            case msg_servoDetach:
              pin = client.read();
              servos[ToServoIndex(pin)].detach();
              break;

            default: // noop
              break;

          } // <-- This is the end of the switch
        } // <-- This is the end of if (idx+msgMinLength[] < length)
      } // <-- This is the end of the valid action check
    } // <-- This is the end of the length check
  } else {
    // Upon disconnection, reset the state
    if (isConnected) {
      isConnected = false;
      reset();
    }

    // If no client is yet connected, check for a new connection
    client = server.available();
  }
}
Esempio n. 17
0
void loop() {
  if (client.connected()) {

    if (!isConnected) {
      restore();
      #if DEBUG
      Serial.println("--------------CONNECTED");
      #endif
    }

    isConnected = true;

    // Process incoming bytes first
    available = client.available();

    if (available > 0) {

      int received = 0;

      #if DEBUG
      Serial.println("--------------BUFFERING AVAILABLE BYTES");
      Serial.print("Byte Offset: ");
      Serial.println(bytesRead, DEC);
      #endif

      // Move all available bytes into the buffer,
      // this avoids building up back pressure in
      // the client byte stream.
      for (int i = 0; i < available && i < MAX_DATA_BYTES - bytesRead; i++) {
        buffer[bytesRead++] = client.read();
        received++;
      }

      #if DEBUG
      Serial.print("Bytes Received: ");
      Serial.println(received, DEC);

      Serial.print("Bytes In Buffer: ");
      Serial.println(bytesRead, DEC);

      for (int i = 0; i < bytesRead; i++) {
        Serial.print("[");
        Serial.print(i, DEC);
        Serial.print("] ");
        Serial.println(buffer[i], DEC);
      }
      #endif

      processInput();
    }


    // Reporting must be limited to every ~100ms
    // Otherwise the spark becomes unreliable and
    // exhibits a higher crash frequency.
    nowms = millis();
    if (nowms - lastms > sampleInterval && reporters > 0) {
      // possible just assign the value of nowms?
      lastms += sampleInterval;
      report();
    }
  } else {
    // Upon disconnection, restore init state.
    if (isConnected) {
      restore();
    }

    // If no client is yet connected, check for a new connection
    client = server.available();
  }
}
Esempio n. 18
0
void loop () {
    if (!initialised && !connected && (lastCheck + 5000 < millis())) {
        if (WiFi.ready()) {
            connect("www.apple.com", 80);
            if (connected) {
                client.println("GET /library/test/success.html HTTP/1.1");
                client.println("Host: www.apple.com");
                client.println();
                const char *success = "Success";
                unsigned int successLocation = 0;
                while (true) {
                    if (client.available()) {
                        int chr = client.read();
                        if (success[successLocation] == chr) {
                            successLocation ++;
                            if (successLocation == strlen(success)) {
                                initialised = true;
                                Spark.connect();
                                Spark.function("digitalread", tinkerDigitalRead);
                                Spark.function("digitalwrite", tinkerDigitalWrite);
                                Spark.function("analogread", tinkerAnalogRead);
                                Spark.function("analogwrite", tinkerAnalogWrite);
                                client.stop();
                                break;
                            }
                        }
                        else {
                            successLocation = 0;
                        }
                    }
                    else {
                        delay(2);
                    }
                }
            }
        }
        else {
            return;
        }
    }

    if (Serial.available()) {
        if (connected) {
            int bytes = Serial.available();
            for (int i=0; i<bytes; i++) {
                client.write(readSerial());
            }
        }
        else {
            int cmd = readSerial();
            switch (cmd) {
                case 'i':
                    Serial.println("Ready");
                    break;
                case 'c': {
                    char* host;
                    char* stringPort;
                    readWord(); // junk space
                    host = readWord();
                    stringPort = readWord();
                    connect(host, atol(stringPort));
                    free(host);
                    free(stringPort);
                    break;
                }
                case 'w': {
                    char* ssid;
                    char* password;
                    readWord();
                    ssid = readWord();
                    password = readWord();
                    Serial.print("Wifi credentials set to SSID '");
                    Serial.print(ssid);
                    Serial.print("' and password '");
                    Serial.print(password);
                    Serial.println("'");
                    WiFi.setCredentials(ssid, password);
                    break;
                }
                default:
                    Serial.print("Don't know command: ");
                    Serial.write(cmd);
                    Serial.println();
                    break;
            }
        }
    }
    if (connected) {
        int bytes = client.available();
        for (int i=0; i<bytes; i++) {
            Serial.write(client.read());
        }
        
        if (!client.connected()) {
            Serial.println();
            Serial.println("Disconnecting");
            client.stop();
            connected = false;
        }
    }
}
Esempio n. 19
0
/** Read one value from a client. */
int SparkWebSocketServer::checkedRead(TCPClient &client)
{
    while(!client.available());
    return client.read();
}
char * http_get(char const * hostname, String path) {

    int i = 0;
    int j = 0;
    int k = 0;
    bool printOnce = false;

    if (client.connect(hostname, 80)) {
        client.print("GET ");
        client.print(path);
        client.println(" HTTP/1.1");
        client.print("HOST: ");
        client.println(hostname);
        client.println("Connection: close");
        client.println();
        client.flush();
    } else {
        if(DEBUG_SERIAL) Serial.println("\r\n\r\nConnection Failed!");
        client.flush();
        client.stop();
        return NULL;
    }

    // wait 5 seconds or less for the host to respond
    uint32_t startTime = millis();
    while(!client.available() && (millis() - startTime) < 5000);

    if(DEBUG_SERIAL) Serial.println("\r\n\r\nREADING HOST DATA......");
    uint32_t lastRead = millis();
    // If the host doesn't close it's connection, we'll timeout in 10 seconds.
    while (client.connected() && (millis() - lastRead) < 10000) {
        while (client.available()) {
            char c = client.read();
            /*
            if(DEBUG_SERIAL) {
              Serial.print(c);
              if(i++ > 100) {
                delay(5);
                i = 0;
              }
            }
            */
            if(c == -1) {
                Serial.print("\r\n\r\nERROR......\r\n\r\n");
                client.flush();
                client.stop();
            }
            if(j++ >= SKIP_CHARS) { // don't buffer the first X bytes to save memory
                if(DEBUG_SERIAL && !printOnce) {
                    Serial.print("\r\n\r\nSAVING......\r\n\r\n");
                    printOnce = true;
                }
                buffer[k++] = c; // save character to buffer
                Serial.print(c);
                delayMicroseconds(100);
                if(k >= BUFFER_SIZE_MAX) { // if we reach the end of our buffer, just bail.
                    Serial.print("\r\n\r\nOUT OF BUFFER SPACE......\r\n\r\n");
                    client.flush();
                    client.stop();
                }
            }
            // as long as we're reading data, reset the lastRead time.
            lastRead = millis();
        } // END while(client.available())
    } // END while(client.connected())

    client.flush();
    client.stop();

    if(DEBUG_SERIAL) {
        Serial.print("\r\nCHARACTERS RECEIVED: ");
        Serial.println(SKIP_CHARS + k);
    }

    return buffer;
}