Esempio n. 1
1
//---------------------------------------------------------------------
void processCommand( uint8_t command )
{
    switch ( command )
    {
        //-------------------------------------------------------------
        case COMMAND_TAG_EMULATE:
        {
#ifdef DEBUG_SERIAL
            Serial.println( "DEBUG: nfc tag emulate" );
#endif
            emulateNfcTag();
            break;
        }
        //-------------------------------------------------------------
        case COMMAND_VIB_MEASUREMENT:
        {
#ifdef DEBUG_SERIAL
            Serial.println( "DEBUG: vibration measurement" );
#endif
            if ( measureVibration() )
                client_.println( VIB_MEASUREMENT_RESP_ON );
            else
                client_.println( VIB_MEASUREMENT_RESP_OFF );
            
            break;
        }
        //-------------------------------------------------------------
        case COMMAND_LIGHT_MEASUREMENT:
        {
#ifdef DEBUG_SERIAL
            Serial.println( "DEBUG: light measurement" );
#endif
            if ( measureLight() )
                client_.println( LIGHT_MEASUREMENT_RESP_ON );
            else
                client_.println( LIGHT_MEASUREMENT_RESP_OFF );
            
            break;
        }
        //-------------------------------------------------------------
        case COMMAND_VIB_CALIBRATE:
        {
#ifdef DEBUG_SERIAL
            Serial.println( "DEBUG: calibrate vibration sensor" );
#endif
            vibrationCalibration();
            break;
        }
        default:
            //handle error
            ;
#ifdef DEBUG_SERIAL
            Serial.println( "WARNING: unknown command" );
#endif
    }
}
Esempio n. 2
0
void MyClientManager::read(EthernetClient client)
{
  int data_size = client.available();
  int x = 0;

  if (headeroffset != 3 && data_size + headeroffset >= HEADER_SIZE)
  {
    while (headeroffset != HEADER_SIZE && x < data_size)
    {
      header[headeroffset] = client.read();
      ++headeroffset;
      ++x;
    }

    if (headeroffset == 3 && header[2] + 1 > BUFFER_SIZE)
      reset();
  }
  else if (headeroffset == 3 && bufferoffset != header[2] && data_size + bufferoffset >= header[2])
  {
    while (bufferoffset != header[2] && x < data_size)
    {
      buffer[bufferoffset] = client.read();
      ++bufferoffset;
      ++x;
    }
  }
  else if (headeroffset == 3 && bufferoffset == header[2] && !checksumisset && data_size > 0)
  {
    checksum = client.read();
    checksumisset = true;
  }
}
size_t ArduinoiDigiInterfaceClass::network_send(idigi_network_handle_t *handle, char *buffer, size_t length)
{
  EthernetClient *client = (EthernetClient *) handle;
  AR_DEBUG_PRINTF("network_send: len = %d\r\n", length);
  size_t sent = client->write((const uint8_t *) buffer, length);
  return sent;
}
Esempio n. 4
0
void getData(char *dst)
{
  Serial.println("Trying to grab data from server:");
  
  // from the server, read them and print them:
  int i = 0;
  
  while (!client.available());

  while (client.available()) {
    char c = client.read();
    Serial.print(c);
    
    if (i < 10)
    {
      dst[i] = c;
      //dst[i+1] = 0;
    }

    i++;
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    while(true);
  }
}
boolean readServerResponse() {
	response = "";
	char inBuf[RESPONSE_BUFFER];

	//response.reserve(RESPONSE_BUFFER);
	int bytesRead = 0;
	if (client.connected()) {
		delay(SERVER_WAIT_TIME);
		Serial.println("awaiting response");
		while (client.available()) {
			char c = client.read();
			Serial.print(c);
			if (bytesRead < RESPONSE_BUFFER) inBuf[bytesRead] = c;
			//else client.flush();
			bytesRead++;
		}
		if (bytesRead > 0) {
			response = inBuf;
			Serial.println("Response Received");
			//if (!client.connected()) client.stop();
			return true;
		}
	}
	return false;
}
//builds the url for the api request, connects to the server, and sends the request
boolean serverRequest() {
	//Serial.print(server);
	//Serial.println(page);
	client.stop();

	Serial.println("connecting...");
	if (client.connect(server, 80)) {
		Serial.println("connected");
		client.print("GET /makermanager/index.php?r=api/toolValidate&badge=");
		client.print(rfid_long);
		client.print("&tool=1");
		client.println(" HTTP/1.1");
		client.print("Host: ");
		client.println(server);
		client.println("User-Agent: arduino-ethernet");
		client.println("Connection: close");
		client.println("");
		
		//Serial.println(cmd);
		//client.println(cmd);
		return true;
	}
	else {
		Serial.println("connection failed");
		return false;
	}
}
Esempio n. 7
0
void Nimbits::recordValue(double value, String pointId) {
  EthernetClient client;

 String json;
 json =  "{\"d\":\"";
 json += floatToString(value, 4);

json +=  "\"}";
  String content;

  content += "&json=";
  content += json;
  content += "&id=";
  content +=  pointId;



  if (client.connect(_hostname.c_str(), _port)) {

    doPost(client, VALUE_API, content);

    String response = getFullResponse(client);


    client.stop();
  }
  else {

    client.stop();
  }

}
Esempio n. 8
0
void MorpheusSlave::receiveEthernet(EthernetClient& incoming) {
	if ( incoming.available() )  {
		char b;
		while ( incoming.available() > 0 ) {
			_lastRX = millis();
			b = incoming.read();
#if DBG
			Serial.print("B: ");
			Serial.println(b);
#endif
			if ( b == '\n' ) {
				endComm();
				break;
			}
			else if ( command == NULL ) {
				command = b;
				data = "";
			}
			else {
				data += b;
			}
		}
    }
	
	if ( _lastRX != -1 && millis() - _lastRX > RX_TIMEOUT ) {
		endComm();
	}
}
Esempio n. 9
0
void loop() {
  // listen for incoming clients
  EthernetClient client = server.available();

  // we get a request
  if (client) {
    Serial.println(F("Client connected"));
    // an http request ends with a blank line
    boolean done = false;
    while (client.connected() && !done) {
      while (client.available () > 0 && !done) {
        done = processIncomingByte (client.read ());
      }
    }  // end of while client connected

    // get ROV status values as json string
    String rovStatus = getRovStatus();

    // send a standard http response header
    client.println(F("HTTP/1.1 200 OK"));
    client.println(F("Content-Type: text/json"));
    client.println(F("Connection: close"));  // close after completion of the response
    client.println();   // end of HTTP header
    client.println(rovStatus);

    // give the web browser time to receive the data
    delay(10);
    // close the connection:
    client.stop();
    Serial.println(F("Client disconnected"));
  }  // end of got a new client
}  // end of loop
Esempio n. 10
0
void setup() {
 // Open serial communications and wait for port to open:
  Serial.begin(9600);
   while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // no point in carrying on, so do nothing forevermore:
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make a HTTP request:
    client.println("GET /search?q=arduino HTTP/1.1");
    client.println("Host: www.google.com");
    client.println("Connection: close");
    client.println();
  }
  else {
    // kf you didn't get a connection to the server:
    Serial.println("connection failed");
  }

}
bool PyrobarHTTPRequestHandler::parseRequest(EthernetClient client) {
  if (client.available()) {
    if(client.readStringUntil(' ') == "GET") {
      if(client.read() == '/') {
        String dataType = client.readStringUntil('/');
        if (DEBUG_REQUEST_HANDLER) {
          Serial.print("Data Type: ");
          Serial.println(dataType);
        }
        if(dataType == pyrobarDataTypeBuffer) {
          return handleBuffer(client);
        } else if(dataType == pyrobarDataTypeFire) {
          return handleFireSequence(client);
        } else if(dataType == pyrobarDataTypeScalar) {
          return handleScalar(client);
        } else if(dataType == pyrobarDataTypeLights) {
          return handleLightsOnOff(client);
        } else {
          return false;
        }
      }
    } else {
      return false;
    }
  }
}
Esempio n. 12
0
// Fonction créant un fichier sur carte mémoire SD
// par X. HINAULT - www.mon-club-elec.fr - GPLv3 - 03/2013
void UtilsSDEthernet::createFile(EthernetClient clientIn, char* nomFichierIn, boolean debug) {
  // La fonction reçoit : 
  // > le client Ethernet à utiliser 
  // > le nom du fichier au format 8.3
  // > un drapeau d'affichage de messages de debug
  
  // la fonction ne renvoie rien 
 
              // création nouveau fichier  
              File dataFile=SD.open(nomFichierIn, FILE_WRITE); // crée / ouvre un objet fichier et l'ouvre en mode écriture - NOM FICHIER en 8.3 ++++
              // > soit en mode : FILE_WRITE: ouvre le fichier pour lecture et écriture, en démarrant au début du fichier. 
              // Important : Si le fichier est ouvert pour écriture, il sera créé si il n'existe pas déjà (cependant le chemin le contenant doit déjà exister)
             
              clientIn.println("------"); 
                
              if (dataFile){ // le fichier est True si créé
                clientIn.println(F("Creation nouveau fichier OK")); 
                dataFile.print(""); // chaine vide
                dataFile.close(); // fermeture du fichier obligatoire après accès 
              } // si fichier existe 
              else { // sinon = si probleme creation
                clientIn.println(F("Probleme creation fichier")); 
              } // fin else datafile
  
} // fin fonction createFile 
Esempio n. 13
0
// Fonction affichant sur le port série le contenu d'un fichier sur carte mémoire SD
// par X. HINAULT - www.mon-club-elec.fr - GPLv3 - 03/2013
void UtilsSDEthernet::read(EthernetClient clientIn, char* nomFichierIn, boolean debug) {
  // La fonction reçoit : 
  // > le client Ethernet à utiliser 
  // > le nom du fichier au format 8.3
  // > un drapeau d'affichage de messages de debug
  
  // la fonction ne renvoie rien 
 
                // lecture du contenu du fichier  
                File dataFile=SD.open(nomFichierIn, FILE_READ); // ouvre le fichier en lecture - NOM FICHIER en 8.3 ++++
                // un seul fichier ne peut etre ouvert à la fois - fermer au préalable tout fichier déjà ouvert
               
                clientIn.println(F("------")); 
                    
                if (dataFile){ // le fichier est True si créé
                  if (debug) clientIn.println(F("Ouverture fichier OK")); 
                
                  while (dataFile.available()) { // tant que des données sont disposnibles dans le fichier
                  // le fichier peut etre considéré comme un "buffer" de données comme le buffer du port série
                
                    char c = dataFile.read(); // lit le caractère suivant
                    clientIn.print(c); // affiche le caractère courant
                    
                    //if (c==10) delay(10); // pause enttre 2 lignes
                  } // fin while available
                
                  dataFile.close(); // fermeture du fichier obligatoire après accès 
                  
                } // si fichier True 
                else { // sinon = si probleme creation
                  clientIn.println(F("Probleme lecture fichier")); 
                } // fin else              
  
} // fin fonction readSerial 
Esempio n. 14
0
static void 
extract_status_code(struct HTTPObject *h, EthernetClient client){
    unsigned int k,multiplier,j;
    j=0;
    char c;
    const byte STATUS_CODE_START_INDEX = 9;
    const byte STATUS_CODE_END_INDEX = 11;

    while(j<=STATUS_CODE_END_INDEX && client.connected()){
        if(client.available()){
            // We want to extract the 200 from "HTTP/1.1 200 OK". The 
            // status code starts at index 9 in the string and ends at 11
            c = client.read();
            if(j<STATUS_CODE_START_INDEX){
                j++;
            }
            else if(j>=STATUS_CODE_START_INDEX && j<=STATUS_CODE_END_INDEX){
                // code = 10^2 * str[9] + 10^1 * str[10] + 10^0 * str[11]
                // Do ghetto exponentiation here.
                multiplier = 1;
                for(k = 1; k <= 2 - (j - STATUS_CODE_START_INDEX); k++){
                    multiplier *= 10;
                }
                // c - '0' => char to int
                h->statusCode += (c - '0') * multiplier;
                j++;
            }
        }
    }
}
Esempio n. 15
0
void printHeader() {

  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: application/json");
  client.println("Connnection: close");
  client.println();
  client.println("{");

}
size_t ArduinoiDigiInterfaceClass::network_recv(idigi_network_handle_t *handle, int timeout_sec, char *buffer, size_t length)
{
  EthernetClient *client = (EthernetClient *) handle;
//  AR_DEBUG_PRINTF("network_recv: timeout_sec = %d\r\n", timeout_sec);
  if (!client->available())
    return 0;
  
  return client->read((uint8_t *) buffer, length);
}
Esempio n. 17
0
void Parser::readStream(EthernetClient client,char* myreadstring) {
  char c = 0; //carctère de lecture
  char tempo[255];
  bool currentLineIsBlank = true;
  int n = 1;
  int flag = 0;

  for (int k = 0; k < 50; k++) tempo[k] = 0;
  c = client.read(); //lecture du premier caractère;
  if (c != (-1)) {
    if ( c == 'G') {
      flag = 1;
      tempo[0] = c;
      while (c != '\n') {
        c = client.read(); //lecture du caractère
        delay(5);
        tempo[n] = c;
        delay(5);
        n++;
      }
    }
    else {
      tempo[0] = '¤';
      tempo[1] = '?';
      while (client.available() > 0) {
        c = client.read();
        if (c == '\n' && currentLineIsBlank) {
          while (c != '\r') { //doute
            c = client.read(); //lecture du caractère

            delay(5);
            if (c == (-1))
              break;
            tempo[n + 1] = c;
            delay(5);
            n++;
          }
        }
        else if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
  }

  if (!flag)n++;

  for (int j = 0; j < n; j++)
    myreadstring[j] = tempo[j] ;

}
bool PyrobarHTTPRequestHandler::handleScalar(EthernetClient client) {
  // E.g. /sclr/sndSens/0.789
  String scalarType = client.readStringUntil('/');
  if (DEBUG_REQUEST_HANDLER) {
    Serial.print("Scalar type: ");
    Serial.println(scalarType);
  }
  float value = client.readStringUntil(' ').toFloat();
  return _lightMap->setScalar(scalarType, value);
}
Esempio n. 19
0
void Nimbits::writeAuthParamsToClient(EthernetClient client)
{
  client.print(F("email="));
  client.print(_ownerEmail);
  if (_accessKey.length() > 0)
  {
    client.print(F("&key="));
    client.print(_accessKey);
  }
}
Esempio n. 20
0
/*
 * Read client response from an HTTP request into a buffer. Return the number of
 * characters written to buf (EXCLUDING null character);
 */
void
extract_client_response(struct HTTPObject *h, EthernetClient client){
    extract_status_code(h, client);
    skip_http_headers(client);
    extract_body(h, client);

    // Clean up the connection
    client.flush();
    client.stop();
}
Esempio n. 21
0
void loop() {
  client = server.available();
  if (client) {                
    while (client.connected()) {
      if (client.available()) {
        if (client.find("GET /")) {
          
          //INICIAR CRONOMETRAGEM
          if (client.find("setCron=")) {
            int charReaded = client.read();
			if(charReaded == 49){
              iniciarCronometragem();
            }
          }
		  
		   //RETORNA O TEMPO DESDE O INICIO		  
          if (client.find("getCron=")) {
            int charReaded = client.read();
			if(charReaded == 49){
              getCronometragem();
			}
          }
        }
      }
      Serial.println();
      break;
    }
    client.println(" HTTP/1.1 200 OK ");
  }
  // give the web browser time to receive the data
  delay(1);
  client.stop();
}
Esempio n. 22
0
void loop() {
  unsigned long time = millis();
  if (next < time) {
    Ethernet.maintain();
    next += send_delay;
    if (next <= time)
      next = time + 1;
    Serial.println("request time !");
    if (client.connected()) {
      Serial.println("already connected");
    } else {
      Serial.print("connecting results : ");
      Serial.println(client.connect("tarzan.info.emn.fr", 80));
    }
    int sent = client.println("GET /ping.php HTTP/1.1");
    sent = client.println(F("Host: tarzan.info.emn.fr"));
    client.println();
  }
  if (client.connected() && client.available() > 0) {
    Serial.println("client received data  : ");
    unsigned char buffer[buff_size + 1];
    while (client.available() > 0) {
      int read = client.read(buffer, buff_size);
      buffer[read] = '\0';
      Serial.println(read);
    }
  }
  if (radio.receiveDone()) {
  }
}
Esempio n. 23
0
// this method makes a HTTP connection to the server:
void sendData(String thisData) {
    // if there's a successful connection:
    if (client.connect("www.pachube.com", 80)) {
        Serial.println("connecting...");
        // send the HTTP PUT request.
        // fill in your feed address here:
        client.print("PUT /api/YOUR_FEED_HERE.csv HTTP/1.1\n");
        client.print("Host: www.pachube.com\n");
        // fill in your Pachube API key here:
        client.print("X-PachubeApiKey: YOUR_KEY_HERE\n");
        client.print("Content-Length: ");
        client.println(thisData.length(), DEC);

        // last pieces of the HTTP PUT request:
        client.print("Content-Type: text/csv\n");
        client.println("Connection: close\n");

        // here's the actual content of the PUT request:
        client.println(thisData);

        // note the time that the connection was made:
        lastConnectionTime = millis();
    }
    else {
        // if you couldn't make a connection:
        Serial.println("connection failed");
    }
}
Esempio n. 24
0
  boolean put_handler(AtMegaWebServer& web_server) {
	const char* length_str = web_server.get_header_value("Content-Length");
	long length = atol(length_str);
	const char *path = web_server.get_path();

	SdFile file;
	if(!file.open(path, O_CREAT | O_WRITE | O_TRUNC)){
		 // maybe the folder must be created
		char *c = strrchr(path, '/');
		if(c){
			*c = 0;
			if(sdfat.mkdir(path)){
#if DEBUG
				Serial << "put_handler make DIR: ok " << path <<'\n';
#endif
				*c = '/';
				if(!file.open(path, O_CREAT | O_WRITE | O_TRUNC)){
#if DEBUG
					Serial << "put_handler open FILE: failed " << path <<'\n';
#endif
				}
			}
			*c = '/';
		}
	}
	if(file.isOpen()){

		EthernetClient client = web_server.get_client();
		long size = 0;
		int read = 0;
		while(size < length && web_server.waitClientAvailable()){
			read = client.read((uint8_t*)buffer, sizeof(buffer));
			file.write(buffer, read);
			size += read;
		}
		file.close();
#if DEBUG
		Serial << "file written: " << size << " of: " << length << '\n';
#endif
		if(size < length){
			web_server.sendHttpResult(404);
		}else{
			web_server.sendHttpResult(200);
			web_server << path;
		}

	}else{
		web_server.sendHttpResult(422); // assuming it's a bad filename (non 8.3 name)
#if DEBUG
		Serial << F("put_handler open file failed: send 422 ") << path <<'\n';
#endif
	}
	return true;
  }
Esempio n. 25
0
char * CosmClient::getFeed(uint32_t feedId) {
    int maxSize = 50;
    char response[maxSize];

    for(int i=0; i<sizeof(response); i++) {
        if (!_client.available()) {
            return response;
        }
        char c = _client.read();
    }
}
Esempio n. 26
0
void loopServer() {
	EthernetClient client = server.available();
	if (client) {
		while (client.connected()) {
			if (client.available()) {
				char c = client.read();

				//read char by char HTTP request
				if (readString.length() < 100) {

					//store characters to string
					readString += c;
					//Serial.print(c);
				}

				//if HTTP request has ended
				if (c == '\n') {

					///////////////
					Serial.print(readString); //print to serial monitor for debuging

					//now output HTML data header
					client.println(F("HTTP/1.1 200 OK")); //send new page on browser request
					client.println(F("Content-Type: text/html"));
					client.println();

					client.println(F("Ok"));

					delay(1);
					//stopping client
					client.stop();

					if (readString.indexOf("R1=1") > 0){
						soldoRelays[0]->On();
//						Serial.println(">>>>>>>>>>>>");
//						Serial.println("R1=1");
					}
					if (readString.indexOf("R2=1") > 0){
						soldoRelays[1]->On();
//						Serial.println(">>>>>>>>>>>>");
//						Serial.println("R2=1");
					}
					if (readString.indexOf("R1=0") > 0){
						soldoRelays[0]->Off();
//						Serial.println(">>>>>>>>>>>>");
//						Serial.println("R1=0");
					}
					if (readString.indexOf("R2=0") > 0){
						soldoRelays[1]->Off();
//						Serial.println(">>>>>>>>>>>>");
//						Serial.println("R2=0");
					}
					readString="";

				}
			}
		}
	}
}
Esempio n. 27
0
/*
 * Read through all the headers of the HTTP Response stored in the client
 */
static void 
skip_http_headers(EthernetClient client){
    char c;
    byte allHeadersRead = 0;
    while(!allHeadersRead && client.connected()){
        if(client.available()){
            c = client.read();
            allHeadersRead = finished_reading_headers(&c, client);
        }
    }
}
Esempio n. 28
0
/* the function reads 'size' bytes from the 'client' 
 * and store them into the 'buffer'. 
 * It is useful to read parameters sent from client
 * */
int readParam(char* buffer, int size, EthernetClient client)
{
	/* TODO return error code if received bytes are less than 'size' */
	int i, buffer_ptr = 0;
	for(i = 0; i < size; i++)
	{
		if(client.available()) buffer[buffer_ptr++] = client.read();
		else return -1;
	}
	buffer[buffer_ptr++] = NULL;
	return 0;
}
bool PyrobarHTTPRequestHandler::handleLightsOnOff(EthernetClient client) {
  String type = client.readStringUntil('/');
  String instruction = client.readStringUntil(' ');
  if (DEBUG_REQUEST_HANDLER) {
    Serial.print("Turning lights ");
    Serial.println(instruction);
  }
  if (instruction == pyrobarLightsOut) _lightMap->turnLights(type, OFF);
  else if (instruction == pyrobarLightsOn) _lightMap->turnLights(type, ON);
  else return false;
  return true;
}
Esempio n. 30
0
void printClient(EthernetClient client){
  int i=0;
    char c = client.read();
    while(c != '\n' && c != '\r'){	
    buffer[i] = c;		
    i++;
    c = client.read();		
  }
  for(int j=0; j<i; j++){
  Serial.write(buffer[j]);
  }
}