Exemplo n.º 1
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;
}
Exemplo n.º 2
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()
{
    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();

    }

}
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 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();
  client.flush();
}//void in(char *ptr, uint8_t timeout)
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)
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;
}
Exemplo n.º 9
0
int tcpDisconnect(String param) {
    tcp.flush();
    tcp.stop();
    return 1;
}
Exemplo n.º 10
0
// Called in a loop forever
void loop()
{
	// When you push the button
	if (digitalRead(D0) == HIGH)
	{
		// It might take a couple of loop() iterations to
		// successfully connect to iamresponding.com
		connecting = true;

		// This is how to control the Spark's RGB LED
		RGB.control(true);

		// Red to indicate we're attempting to connect
		RGB.color(255, 0, 0);

		// Push the button once to respond to station.
		// Push it again to cancel.
		if (responding)
		{
			// Do just what the iamresponding.com app does
			data = "{\"keyEntryDesc\":\"CANCELLED\",\"memberIDS\":\"\",\"subscriberID\":\"\",\"userfullname\":\"Jack Bates\"}";
		}
		else
		{
			data = "{\"keyEntryDesc\":\"Station\",\"memberIDS\":\"\",\"subscriberID\":\"\",\"userfullname\":\"Jack Bates\"}";
		}
	}

	// We haven't successfully connected since the button was last
	// pushed, keep trying!
	if (connecting && client.connect(server, 80)) // HTTP is port
	{					      // number 80, FYI
		// We successfully connected, stop trying
		connecting = false;

		// Yellow to indicate we successfully connected and
		// sent the magic words
		RGB.color(255, 255, 0);

		// Again, just ape the iamresponding.com app
		client.println("POST /v3/keyEntries.asmx/AddCallEntry HTTP/1.0");

		client.print("Content-Length: ");
		client.println(strlen(data));

		client.println("Content-Type: application/json");
		client.println("Host: iamresponding.com");
		client.println();

		// Send the magic words
		client.print(data);
	}

	// iamresponding.com sent something back to *us*.
	// (This is our only indication that TCPClient is done
	// transmitting the magic words.  You're welcome to get clever
	// and check if iamresponding.com sent back confirmation or is
	// reporting an error, this just assumes it's confirmation.)
	if (client.available())
	{
		// If we were already responding, then now we aren't
		// (cancelled) and vice versa (if we weren't, then now
		// we are).
		responding = !responding;
		if (responding)
		{
			// Blue to indicate that iamresponding.com
			// knows we're responding to station!
			RGB.color(0, 0, 255);
		}
		else
		{
			// Restore the default RGB LED behavior when
			// we're not responding (cancelled).
			// (By default it shows the Wi-Fi status.)
			RGB.control(false);
		}

		// Tricky: Clean up after transmitting the magic
		// words.  Close the connection to iamresponding.com
		// and discard (flush) anything sent back to us, or
		// else in the next loop() iteration we'll think
		// iamresponding.com sent back something *again*.
		client.stop();
		client.flush();
	}
}