Esempio n. 1
0
void Nimbits::createPoint(String pointName)
{
  EthernetClient client;
  if (client.connect(GOOGLE, PORT))
  {
    client.println(F("POST /service/point HTTP/1.1"));
    String content;
    //  writeAuthParams(content);
    content += "email=";
    content += _ownerEmail;
    if (_accessKey.length() > 0)
    {
      content += ("&key=");
      content += (_accessKey);
    }
    content += "&action=create&point=";
    content += (pointName);
    client.println(F("Host:nimbits1.appspot.com"));
    client.println(F("Connection:close"));
    client.println(F("Cache-Control:max-age=0"));
    client.print(F("Content-Type: application/x-www-form-urlencoded\n"));
    client.print(F("Content-Length: "));
    client.print(content.length());
    client.print(F("\n\n"));
    client.print(content);
    while (client.connected() && !client.available())
    {
      delay(1); //waits for data
    }
    client.stop();
    client.flush();
  }

}
/*
 * Sends an HTTP POST request containing the name and the code to the server.
 */
void sendData() {
	Serial.print("attempting to send data (name = ");
	Serial.print(nameBuf);
	Serial.print(", code = ");
	Serial.print(buffer);
	Serial.println(")");


	// if you get a connection, report back via serial:
	if (client.connect(server, port)) {
		Serial.println("connected");
		// Make a HTTP request:
		client.print("POST /barcode");
		client.print("?name=");
		client.print(nameBuf);
		client.print("&code=");
		client.print(buffer);
		client.print("&uptime=");
		client.print(millis());
		client.println(" HTTP/1.0");
		client.println();
		client.flush();
		client.stop();
		Serial.println("request sent");
	}
	else {
		// if you didn't get a connection to the server:
		Serial.println("connection failed");
	}
}
Esempio n. 3
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. 4
0
void DataServeriOS::loop()
{
  _client = _server->available();
  if (_client)
  {
    WaitForRequest();
    ParseReceivedRequest();
    PerformRequestedCommand();
    _client.flush();
    _client.stop();
  }
  else {
    _client.stop();
    _substitudeLoop();
  }
}
Esempio n. 5
0
String Nimbits::recordValue(String point, float value)
{
  EthernetClient client;
  String content;

  if (client.connect(GOOGLE, PORT))
  {
    client.println(F("POST /service/value HTTP/1.1"));
    //  writeAuthParams(content);
    content += ("email=");
    content += _ownerEmail;
    if (_accessKey.length() > 0)
    {
      content += ("&key=");
      content += (_accessKey);
    }

    char buffer[10];

    dtostrf(value, 5, 5, buffer);
    String str = buffer;

    content += ("&value=");
    content += (str);
    content += ("&point=");
    content += (point);
    client.println(F("Host:nimbits1.appspot.com"));
    client.println(F("Connection:close"));
    client.println(F("Cache-Control:max-age=0"));
    client.print(F("Content-Type: application/x-www-form-urlencoded\n"));
    client.print(F("Content-Length: "));
    client.print(content.length());
    client.print(F("\n\n"));
    client.print(content);
    while (client.connected() && !client.available())
    {
      delay(1); //waits for data
    }
    client.stop();
    client.flush();
  }

  return content;
}
void updateDB_Door(){	
	Serial.println("connecting for DB update");
	if (client.connect(server, 80)) {
		client.print("GET http://153.42.193.63/ardi_db_update.php?door=");
		if(clientDoor)
			client.print(clientDoor,BIN);
		else
			client.print("'0'");
			
		client.print(" HTTP/1.0");
		client.println("Host: http://153.42.193.63");
		client.println();
		doorChanged = 1;
	} 
	else {  //connection failed
		Serial.println("connection failed");
		doorChanged = 0;
	}
	client.stop();
	client.flush();
}
void updateDB_Shades(){	
	Serial.println("connecting for DB update");
	if (client.connect(server, 80)) {
		client.print("GET http://153.42.193.63/ardi_db_update.php?shades=");
		if(clientShades)
			client.print(clientShades,BIN);
		else
			client.print("'0'");
			
		client.print(" HTTP/1.0");
		client.println("Host: http://153.42.193.63");
		client.println();
		shadesChanged = 1;
	} 
	else {
		Serial.println("connection failed");
		shadesChanged = 0;
	}

	client.stop();
	client.flush();
}
 void VirtuinoEthernet_WebServer::run(){
    EthernetServer server(serverPort);  
    EthernetClient client = server.available();
  if (client) {
    char c;
   if (DEBUG) Serial.println(clientConnected);
    
    while (client.connected()) {
      if (client.available()) {
        c = client.read();
        lineBuffer.concat(c);
        if (DEBUG)  Serial.write(c);
      }
      if (c == '\n' ) {
              int pos = lineBuffer.indexOf("GET /");
              if (pos!=-1){                                   // We have a GET message
                   if (DEBUG) Serial.println("\n\r LineBuffer="+lineBuffer);
                  String responce = checkNetworkCommand(lineBuffer.substring(pos+5));
                   if (DEBUG) Serial.println("\n\r Responce="+responce);
                  delay(10);
                  client.flush();
                  client.println("HTTP/1.1 200 OK");
                  client.println("Content-Type: text/html");
                  client.println("Connection: close");
                  client.println();
                  client.println(responce);
                  lineBuffer="";
                  break;
                } // if pos
             lineBuffer="";
        } // if c=='\n'
    } // if client.available
    delay(1);
    client.stop();  // close the connection:
    if (DEBUG) Serial.println(clientDisconnected);
  }
  }
void updateDB_Lights(){
	Serial.println("connecting for DB update");
	if (client.connect(server, 80)) {
		client.print("GET http://153.42.193.63/ardi_db_update.php?lights=");
		if(clientLights)
			client.print(clientLights,BIN);
		else
			client.print("'0'");
			
		client.print(" HTTP/1.0");
		client.println("Host: http://153.42.193.63");
		client.println();
		Serial.println("connection successful");
		
		lightsChanged = 1;
		
	} 
	else {
		lightsChanged = 0;
		Serial.println("connection failed");
	}
	client.stop();
	client.flush();
}	
String readPage(){
	int stringPos = 0; // string index counter
	boolean startRead = false; 
    //read the page, and capture & return everything between '?' and '~'

    stringPos = 0;
    memset(inString,' ', 200); //clear inString memory

	while(true){

		if (client.available()) {
		char c = client.read();
		Serial.print(c);

			if (c == '?' ) { 			//'?' is our begining character
				startRead = true; 		//Ready to start reading the part 
			}
			else if(startRead){
				if(c != '~'){ 			//'~' is our ending character
					inString[stringPos] = c;
					stringPos ++;
				}
				else{
					//got what we needed, disconnect
					startRead = false;
					c = 0;
					client.stop();
					client.flush();
					Serial.println("end of poll disconnecting.");
          
				return inString;
				}
			}
		}
	}
}
Esempio n. 11
0
void runExternalCommandsPersistent(EthernetServer* _server, systemState* _state) 
{
	// local variables
	int i, buffer_ptr;
	int room, radiatorState, automaticMode;
	float temperature;
	int commandError = 0;
	
	
	EthernetClient client = _server->available(); // is non-blocking
	if(client.available() > 2)
	{
		#ifdef DEBUG
		Serial.println("Connection established");
		Serial.print("Available: ");
		Serial.println(client.available());
		#endif
		
		char buffer[32];
		
		// read command field
		if( readParam(buffer, 3, client) < 0 ) {commandError = 1; goto errorHandler;}
		
		// switch case on commands
		if(strcmp(buffer, "STM") == 0) // set temperature
		{
			#ifdef DEBUG
			Serial.println("Set temperature command received");
			#endif
			
			// read fisrt param: room number (one digit)
			if( readParam(buffer, 1, client) < 0 ) {commandError = 1; goto errorHandler;}
			room = atoi(buffer);
			
			// read second param: temperature (format xx.y)
			if( readParam(buffer, 4, client) < 0 ) {commandError = 1; goto errorHandler;}
			temperature = atof(buffer);
			
			_state->desiredTemp[room] = temperature;
			
			client.write((unsigned char*)"STM", 3);
			client.write((unsigned char*)"OOK", 3);
		}
		else if(strcmp(buffer, "RTM") == 0) // read temperature
		{
			#ifdef DEBUG
			Serial.println("Read temperature command received");
			#endif
			// read fisrt param: room number (one digit)
			if( readParam(buffer, 1, client) < 0 ) {commandError = 1; goto errorHandler;}
			
			room = atoi(buffer);
			
			temperature = _state->actualTemp[room];
			//buffer_ptr = sprintf(buffer, "%4.1f", temperature);
			ttoa(buffer, temperature);
			
			client.write((unsigned char*)"RTM", 3);
			client.write((unsigned char*)"OOK", 3);
			client.write((unsigned char*)buffer, 4);
		}
		else if(strcmp(buffer, "SRD") == 0) // set radiator
		{
			#ifdef DEBUG
			Serial.println("Set radiator command received");
			#endif
			// read fisrt param: room number (one digit)
			if( readParam(buffer, 1, client) < 0 ) {commandError = 1; goto errorHandler;}
			room = atoi(buffer);
			
			// read second param: radiator state (one digit)
			if( readParam(buffer, 1, client) < 0 ) {commandError = 1; goto errorHandler;}
			radiatorState = atoi(buffer);
			
			_state->radiatorState[room] = radiatorState;
			digitalWrite(radiatorPinByRoom(room), (radiatorState == 1) ? LOW : HIGH);
			
			// set zone valve
			int someoneIsOn = 0;
			for(room = 0; room < 6; room++) 
			{
				if(_state->radiatorState[room] == ON) someoneIsOn = 1;
			}
			digitalWrite(ZONE_VALVE_NO1, someoneIsOn ? LOW : HIGH);
			
			client.write((unsigned char*)"SRD", 3);
			client.write((unsigned char*)"OOK", 3);
		}
		else if(strcmp(buffer, "RRD") == 0) // read radiator
		{
			#ifdef DEBUG
			Serial.println("Read radiator command received");
			#endif
			// read fisrt param: room number (one digit)
			if( readParam(buffer, 1, client) < 0 ) {commandError = 1; goto errorHandler;}
			room = atoi(buffer);

			radiatorState = _state->radiatorState[room];
			sprintf(buffer, "%d", radiatorState);
			
			client.write((unsigned char*)"RRD", 3);
			client.write((unsigned char*)"OOK", 3);
			client.write((unsigned char*)buffer, 1);
		}
		else if(strcmp(buffer, "SAM") == 0) // set automatic mode
		{
			#ifdef DEBUG
			Serial.println("Set automatic mode command received");
			#endif
			// read second param: radiator state (one digit)
			if( readParam(buffer, 1, client) < 0 ) {commandError = 1; goto errorHandler;}
			automaticMode = atoi(buffer);
			
			_state->automaticMode = automaticMode;
			
			client.write((unsigned char*)"SAM", 3);
			client.write((unsigned char*)"OOK", 3);
		}
		else if(strcmp(buffer, "RAM") == 0) // read automatic mode
		{
			#ifdef DEBUG
			Serial.println("Read automatic mode command received");
			#endif
			automaticMode = _state->automaticMode;
			
			sprintf(buffer, "%d", automaticMode);
			
			client.write((unsigned char*)"RAM", 3);
			client.write((unsigned char*)"OOK", 3);
			client.write((unsigned char*)buffer, 1);
		}
		else if(strcmp(buffer, "RDT") == 0) // read desired temperature
		{
			#ifdef DEBUG
			Serial.println("Read desired temperature command received");
			#endif
			// read fisrt param: room number (one digit)
			if( readParam(buffer, 1, client) < 0 ) {commandError = 1; goto errorHandler;}
			room = atoi(buffer);
			
			temperature = _state->desiredTemp[room];
			//buffer_ptr = sprintf(buffer, "%4.1f", temperature);
			ttoa(buffer, temperature);
			
			client.write((unsigned char*)"RDT", 3);
			client.write((unsigned char*)"OOK", 3);
			client.write((unsigned char*)buffer, 4);
		}
		else if(strcmp(buffer, "CLS") == 0) // Close connection
		{
			#ifdef DEBUG
			Serial.println("Close connection command received");
			#endif
			
			client.write((unsigned char*)"CLS", 3);
			client.write((unsigned char*)"OOK", 3);
			
			client.flush(); // NEW to verify ---> it seems not working
			delay(2000);
			while(client.connected())
			{
				client.stop();
				delay(2000);
			}
		}
		else
		{
			#ifdef DEBUG
			Serial.print("Invalid command received: ");
			Serial.print(buffer[0]);
			Serial.print(buffer[1]);
			Serial.print(buffer[2]);
			Serial.println();
			#endif
			client.write((unsigned char*)"ERR", 3);
			client.write((unsigned char*)"INV", 3);
		}
		
		// =============================================
		errorHandler:
		if(commandError)
		{
			
			#ifdef DEBUG
			Serial.print("Invalid command received: ");
			Serial.print(buffer[0]);
			Serial.print(buffer[1]);
			Serial.print(buffer[2]);
			Serial.println();
			#endif
			client.write((unsigned char*)"ERR", 3);
			client.write((unsigned char*)"GEN", 3);
		}
		// =============================================
	}
	
}
Esempio n. 12
0
boolean P098SendCustomHTTPRequest(char* Request, byte ip, unsigned long port, byte varindex)
  {
  byte targetIP[4];
  int InByteCounter,x,y;
  byte InByte;
  unsigned long TimeoutTimer;
  const int TimeOut=5000;
  EthernetClient HTTPClient; // Client class voor HTTP sessie.
  byte State=0;
  char *IPBuffer=(char*)malloc(IP_BUFFER_SIZE+1);

  targetIP[0] = EthernetNodo.localIP()[0];
  targetIP[1] = EthernetNodo.localIP()[1];
  targetIP[2] = EthernetNodo.localIP()[2];
  targetIP[3] = ip;

  strcpy(IPBuffer,"GET ");

  // Alle spaties omzetten naar %20 en toevoegen aan de te verzenden regel.
  y=strlen(IPBuffer);
  for(x=0;x<strlen(Request);x++)
    {            
    if(Request[x]==32)
      {
      IPBuffer[y++]='%';
      IPBuffer[y++]='2';
      IPBuffer[y++]='0';
      }
    else
      {
      IPBuffer[y++]=Request[x];
      }
    }
  IPBuffer[y]=0;

  strcat(IPBuffer," HTTP/1.1");

  if(Settings.Debug==VALUE_ON)
    Serial.println(IPBuffer);

  if(HTTPClient.connect(targetIP,port))
    {
      HTTPClient.println(IPBuffer);
      HTTPClient.println("Host: 192.168.0.123");
      HTTPClient.println("User-Agent: Mozilla/5.0");
      HTTPClient.println(F("Connection: Close"));
      HTTPClient.println();// Afsluiten met een lege regel is verplicht in http protocol/

      TimeoutTimer=millis()+TimeOut; // Als er te lange tijd geen datatransport is, dan wordt aangenomen dat de verbinding (om wat voor reden dan ook) is afgebroken.
      IPBuffer[0]=0;
      InByteCounter=0;
      while(TimeoutTimer>millis() && HTTPClient.connected())
        {
        if(HTTPClient.available())
          {
            InByte=HTTPClient.read();
          
            if(isprint(InByte) && InByteCounter<IP_BUFFER_SIZE)
              IPBuffer[InByteCounter++]=InByte;

            else if(InByte==0x0A)
              {
                IPBuffer[InByteCounter]=0;
                // De regel is binnen

                if(Settings.Debug==VALUE_ON)
                  Serial.println(IPBuffer);

                String line = IPBuffer;

                if (varindex > 0 && line.substring(10, 14) == "Data")
                  {
                    String strValue = line.substring(19);
                    byte pos = strValue.indexOf(',')-1;
                    strValue = strValue.substring(0, pos);
                    strValue.trim();
                    char tmp[80];
                    strValue.toCharArray(tmp,79);
                    float value=0;

                    if (tmp[0]=='O')
                      value = (strValue == "On") ? 1 : 0;
                    else
                      value = atof(tmp);

                    UserVar[varindex-1] = value;
                    if(Settings.Debug==VALUE_ON)
                      {
                        Serial.println(strValue);
                        Serial.println("Succes!");
                      }
                  }

                InByteCounter=0;          
              }
          }
        }
      delay(500);
      HTTPClient.flush();// Verwijder eventuele rommel in de buffer.
      HTTPClient.stop();
    }
  free(IPBuffer);
  return State;
  }
Esempio n. 13
0
void loop() {
  // ESPERA ENTRE CAPTURAS
  delay(5000);
  analogWrite(A2,0);
  analogWrite(A3,255);
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  if (isnan(h) || isnan(t)) {
    Serial.println("ERROR EN LA CAPTURA DEL SENSOR DE HUMEDAD");
    return;
  }
  Serial.print("HUMEDAD: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("TEMERATURA AMBIENTE: ");
  Serial.print(t);
  Serial.print(" *C ");
  // FIN CAPTURA DE DATOS HUMEDAD Y TEMPERATURA AMBIENTE
  //INICIO CAPTURA DE TEMPERATURA CALDERA 1
  Serial.println("TEMPERATURA AMBIENTE TERMO 1= ");
  Serial.println(thermocouple.readInternal());
  double c = thermocouple.readCelsius();
  if (isnan(c)) {
     Serial.println("Something wrong with thermocouple!");
  } else {
     Serial.print("Caldera 1= ");
     Serial.println(c);
  }
  // FIN CAPTURA CALDERA 1
  // INICIO CAPTURA DE TEMPERATURA CALDERA 2
  //Serial.print("ambiente 2= ");
  Serial.println(thermocouple2.readInternal());
  double c2 = thermocouple2.readCelsius();
  if (isnan(c2)) {
     Serial.println("Something wrong with thermocouple!");
  } else {
     Serial.print("Caldera2 = ");
     Serial.println(c2);
  }
  // FIN DE CAPTURA DE TEMPERATURA CALDERA 2
  // INICIO DE SUBIDA A MYSQL SERVER TABLA TEMPERATURA
  Serial.println("Conectando...");
  if (client.connect(server, 80)>0) {  // Conexion con el servidor
    client.print("GET /angu/json/tmprUp.php?estf=1&ambiente=");
    client.print(t);
    client.print("&caldera1=");
    client.print(c2);
    client.print("&caldera2=");
    client.print(c2); // Enviamos los datos por GET
    client.println(" HTTP/1.0");
    client.println("User-Agent: Arduino 1.0");
    client.println();
    Serial.println("Conectado ENVIANDO DATOS TABLA TEMPERATURA");
  } else {
    Serial.println("Fallo en la conexion");
  }
  if (!client.connected()) {
    Serial.println("Desconectado!");
  }
  client.stop();
  client.flush();
  analogWrite(A2,255);
  analogWrite(A3,0);
  delay(2000);
  //FIN DE SUBIDA A MYSQL TABLA TEMPERATURA
  //INICIO SUBIDA A MYSQL SERVER TABLA HUMEDAD
  Serial.println("Conectando...");
  if (client.connect(server, 80)>0) {  // Conexion con el servidor
    client.print("GET /angu/json/hmdaUp.php?estf=1&humedad=");// estufa 1
    client.print(h);
    client.println(" HTTP/1.0");
    client.println("User-Agent: Arduino 1.0");
    client.println();
    Serial.println("Conectado ENVIANDO DATOS TABLA HUMEDAD");
  } else {
    Serial.println("Fallo en la conexion");
  }
  if (!client.connected()) {
    Serial.println("Desconectado!");
  }
  client.stop();
  client.flush();
  analogWrite(A2,0);
  analogWrite(A3,255);
  delay(2000);
  // FIN DE SUBIDA A MYSQL SERVER TABLA HUMEDAD
  //captura datos gases
  float sensor_volt;
  float RS_gas; // Get value of RS in a GAS
  float ratio; // Get ratio RS_GAS/RS_air
  int sensorValue = analogRead(A0);
  sensor_volt=(float)sensorValue/1024*5.0;
  RS_gas = (5.0-sensor_volt)/sensor_volt;


  ratio = RS_gas/0.34;  // ratio = RS/R0

 Serial.print("CO2 = ");//gases calidad
  float co2,calidad;
  co2 = sensor_volt*440;
  Serial.println(co2);
  Serial.print("calidad aire = ");//gases calidad
  calidad = sensor_volt*340;
  Serial.println(calidad);
  Serial.print("NOX = ");//gases nox
  Serial.println(RS_gas);
  Serial.print("CO = ");//gases co
  Serial.println(ratio);
  analogWrite(A2,255);
  analogWrite(A3,0);
  delay(2000);
  delay(5000); // Espero un minuto
  //FIN CAPTURA DE GASES
  //INICIO SUBIDA MYSQL SERVER TABLA GASES
  //INICIO SUBIDA A MYSQL SERVER TABLA HUMEDAD
  Serial.println("Conectando...");
  if (client.connect(server, 80)>0) {  // Conexion con el servidor
    client.print("GET /angu/json/gsesUp.php?estf=1&co2=");
    client.print(co2);
    client.print("&calidad=");
    client.print(calidad);
    client.print("&nox=");
    client.print(RS_gas);
    client.print("&co=");// estufa
    client.print(ratio);
    client.println(" HTTP/1.0");
    client.println("User-Agent: Arduino 1.0");
    client.println();
    Serial.println("Conectado ENVIANDO DATOS TABLA GASES");
  } else {
    Serial.println("Fallo en la conexion");
  }
  if (!client.connected()) {
    Serial.println("Desconectado!");
  }
  client.stop();
  client.flush();
  // FIN DE SUBIDA A MYSQL SERVER TABLA HUMEDAD

}
Esempio n. 14
0
// The loop function is called in an endless loop
void loop() {



	// if there's incoming data from the net connection.
	// send it out the serial port. This is for debugging
	// purposes only:
	if (client.available()) {
		char c = client.read();
		Serial.print(c);
	}

	// if there's no net connection, but there was one last time
	// through the loop, then stop the client:
	if (!client.connected() && wasConnected) {
		Serial.println();
		Serial.println("disconnecting.");
		client.stop();
		wasConnected = false;
	}

	if (PowerSerial::solar.count < 0) {
		int waitTime = millis() - lastupdate;
		if (waitTime > 30000) {
			String jsonResult = PowerSerial::solar.jsonResult;
			Serial.println("transmit Every 30 seconds");
			lastupdate = millis();

			lmillis = tmillis; //timing to determine amount of time since last call
			tmillis = millis();

			delay(1000);
			if (!client.connected()) {
				Serial.println(jsonResult);
				// if there's a successful connection:
				Serial.println("!client.connected() --> 1");

//				DNSClient dns;
//				IPAddress remote_addr;
//				dns.begin(Ethernet.dnsServerIP());
//				int ret = dns.getHostByName(serverName, remote_addr);
//				  if (ret == 1) {
//				    Serial.println(serverName);
//				    Serial.println(remote_addr);
//				  } else {
//					    Serial.println("Fail !!!");
//				  }


				if (client.connect(serverName, 80)) {
					delay(1000);
					Serial.println("!client.connect() --> 2");
					wasConnected = true;
					Serial.println("connecting...");
					// send the HTTP PUT request:
					String str = "GET ";
						str.concat(input);
    					str.concat(apikey);
						str.concat(inputJson);
						str.concat(jsonResult);
						str.concat(" HTTP/1.0");

					client.println(str);
					client.println("Host: emoncms.org");
					client.println("User-Agent: arduino-ethernet");
					client.println("Connection: close");
					client.println();
					client.flush();
					Serial.println(str);
					Serial.println("Respons:");
					Serial.println(client.readString());
					PowerSerial::solar.count = 0;
				} else {
					delay(1000);
					// if you couldn't make a connection:
					Serial.println("connection failed");
					Serial.println();
					Serial.println("disconnecting.");
					client.stop();
				}

			}
		} else {
//			Serial.print("Still waiting: ");
//			Serial.println(waitTime);
		}
	} else {
		Serial.println("Powerserial has no result .... waiting: ");
	}

	if (PowerSerial::solar.count >= 0){
		PowerSerial::parse();
	}

}
Esempio n. 15
0
// ---------------------------------------------------------------------------
// --- Main loop update ------------------------------------------------------
// ---------------------------------------------------------------------------
void PLabFileServer::update() {
	// Main loop.
	// Check if we have any new connections
	EthernetClient client = available();
	if (client) {
		if (out) {
			out->println();
			// Buffer is initially considered empty
			strcpy_P(bigBuf, plabRequest);
			out->println(bigBuf);
			out->println();
		}

		if (filter) {
			filter->start();
		}

		// We should now start parsing our request
		RequestState_t state = REQ_START;
		RequestMethod_t method = METH_NOT_SUPPORTED;
		int indexTracker = 0;
		// While we still have an open connection to the client
		while (client.connected()) {
			if (client.available()) {
				char c = client.read();
				if (out) {
					out->write(c);
				}
				state = reqStateTransition(state, c, indexTracker, method);
			}
			// By default we assume we have answered.
			bool answered = true;
			// Configuring answer, if we have any yet.
			switch (state) {
			case REQ_MESSAGE_BODY:
				if (out) {
					out->println();
					// Safe to overwrite buffer: it should not contain anything
					strcpy_P(bigBuf, plabResponse);
					out->println(bigBuf);
					out->println();
				}
				// GET and HEAD discard request body in this server
				// Currently this (HEAD and GET) covers every possibility.
				if (method == METH_HEAD || method == METH_GET) {
					if (userControlledResponse) {
						if (filter)
							filter->writeResponse(client);
					}
					else {
						// The exact same header
						strcpy_P(bigBuf, plabHeaderHttp);
						if (filter)
							filter->filterResponseHeader(bigBuf, client);
						cPrint(bigBuf, client);
						strcpy_P(bigBuf, plab200OK);
						if (filter)
							filter->filterResponseHeader(bigBuf, client);
						cPrintln(bigBuf, client);
						if (internalMIMEIndex >= 0) {
							strcpy_P(bigBuf, plabContentType);
							if (filter)
								filter->filterResponseHeader(bigBuf, client);
							cPrint(bigBuf, client);
							strcpy_P(bigBuf, (char*)pgm_read_word(&(plabMIMETypeTable[internalMIMEIndex])));
							if (filter)
								filter->filterResponseHeader(bigBuf, client);
							cPrintln(bigBuf, client);
						}
						strcpy_P(bigBuf, plabConnectionClose);
						if (filter)
							filter->filterResponseHeader(bigBuf, client);
						cPrintln(bigBuf, client);
						// TODO Additional user defined header fields
						cPrintln("", client);	// HEADER stop
						if (method == METH_GET) {
							// Rediricting file location
							if (filter)
								filter->redirectReplyFile(sdFile);
#ifdef PLAB_DEBUG
							if (out)
								out->println("GET response");
#endif // PLAB_DEBUG
							// ONLY get has message body
							// TODO User defined body write
							if (sdFile) {
								while (sdFile.available()) {
									char c = sdFile.read();
									if (filter) {
										if (filter->filterResponse(c, client))
											cWrite(c, client);
									}
									else
										cWrite(c, client);
								}
								sdFile.close();
							}
#ifdef PLAB_DEBUG
							else if (out)
								out->println("File not open!");
#endif // PLAB_DEBUG
						}
					}
				}
				break;

				// TODO Better error treatment
			case BAD_REQ_400:
				printDefaultError(400, client);
				break;
			case NOT_FOUND_404:
				printDefaultError(404, client);
				break;
			case METHOD_NOT_ALLOWED_405:
				printDefaultError(405, client);
				break;
			case REQUEST_URI_TOO_LONG_414:
				printDefaultError(414, client);
				break;
			case INTERNAL_SERVER_ERROR_500:
				printDefaultError(500, client);
				break;
			case NOT_IMPLEMENTED_501:
				printDefaultError(501, client);
				break;
			case HTTP_VERSION_NOT_SUPPORTED_505:
				printDefaultError(505, client);
				break;

			default:
				// No other state (as of yet) produces an answer
				answered = false;
			}

			// Clean, if need be
			if (answered) {
				if (sdFile) {
					sdFile.close();
				}

				// Client should have some time to process answer
				delay(1);

				client.stop();
				client.flush();
			}
		}
		if (filter)
			filter->end();
	}
}
Esempio n. 16
0
void ModbusTCP::run(void) {

  int16_t i, iStart, iQty;
  int16_t iTXLen = 0;       // response packet length
  uint8_t *ptr, iFC = MB_FC_NONE, iEC = MB_EC_NONE;
  //
  // Initialize and check for a request from a MODBUS master
  //
#ifdef MB_ETHERNET
  EthernetClient clientrequest = mb_server.available();
  if (clientrequest.available()) {
#endif
#ifdef MB_CC3000
  Adafruit_CC3000_ClientRef clientrequest = mb_server.available();
  if (clientrequest.available()) {
#endif
#ifdef MB_ESP8266
  if (!clientrequest.connected())
    clientrequest = mb_server.available();
  if (clientrequest.available()) {
#endif
    //
    // Retrieve request
    //
    for (i = 0 ; clientrequest.available() ; i++)
      mb_adu[i] = clientrequest.read();
#ifdef MB_ESP8266
    clientrequest.flush();
#endif
#ifdef MB_DEBUG
    printMB("RX: ", word(mb_adu[MB_TCP_LEN], mb_adu[MB_TCP_LEN + 1]) + 6);
#endif
    //
    // Unpack the function code
    //
    iFC = mb_adu[MB_TCP_FUNC];
  }
  //
  // Handle request
  //
  switch (iFC) {
    case MB_FC_NONE:
      break;
    case MB_FC_READ_REGISTERS:
      //
      // 03 (0x03) Read Holding Registers
      //
      // modpoll -m tcp -t 4:float -r 40001 -c 1 -1 192.168.x.x
      //
      //     [TransID] [ProtID-] [Length-] [Un] [FC] [Start--] [Qty----]
      // RX: 0x00 0x01 0x00 0x00 0x00 0x06 0x01 0x03 0x9C 0x40 0x00 0x02
      //
      //     [TransID] [ProtID-] [Length-] [Un] [FC] [Bc] [float------------]
      // TX: 0x00 0x01 0x00 0x00 0x00 0x07 0x01 0x03 0x04 0x20 0x00 0x47 0xF1
      //
      // 123456.0 = 0x00 0x20 0xF1 0x47 (IEEE 754)
      //
      // Unpack the start and length
      //
      ptr = mb_adu + MB_TCP_DATA;
      iStart = word(*ptr++, *ptr++) - 40000;
      iQty = 2 * word(*ptr++, *ptr);
      //
      // check for valid register addresses
      //
      if (iStart < 0 || (iStart + iQty / 2 - 1) > MB_REGISTERS_MAX) {
        iEC = MB_EC_ILLEGAL_DATA_ADDRESS;
        break;
      }
      //
      // Write data length
      //
      ptr = mb_adu + MB_TCP_DATA;
      *ptr++ = iQty;
      //
      // Write data
      //
      for (i = 0 ; i < iQty / 2 ; i++) {
        *ptr++ = highByte(mb_reg[iStart + i]);
        *ptr++ =  lowByte(mb_reg[iStart + i]);
      }
      iTXLen = iQty + 9;
      break;

    case MB_FC_WRITE_REGISTER:
      //
      // 06 (0x06) Write register
      //
      ptr = mb_adu + MB_TCP_DATA;
      iStart = word(*ptr++, *ptr++) - 40000;
      //
      // check for valid register addresses
      //
      if (iStart < 0 || (iStart - 1) > MB_REGISTERS_MAX) {
        iEC = MB_EC_ILLEGAL_DATA_ADDRESS;
        break;
      }
      // Unpack and store data
      //
      mb_reg[iStart] = word(*ptr++, *ptr);
      //
      // Build a response
      //
      iTXLen = 12;
      break;

    case MB_FC_WRITE_MULTIPLE_REGISTERS:
      //
      // 16 (0x10) Write Multiple registers
      //
      // modpoll -m tcp -t 4:float -r 40001 -c 1 -1 192.168.x.x 123456.0
      //
      //     [TransID] [ProtID-] [Length-] [Un] [FC] [Start--] [Qty----] [Bc] [float------------]
      // RX: 0x00 0x01 0x00 0x00 0x00 0x0B 0x01 0x10 0x9C 0x40 0x00 0x02 0x04 0x20 0x00 0x47 0xF1
      //
      // 123456.0 = 0x00 0x20 0xF1 0x47 (IEEE 754)
      //
      // Unpack the start and length
      //
      ptr = mb_adu + MB_TCP_DATA;
      iStart = word(*ptr++, *ptr++) - 40000;
      iQty = 2 * word(*ptr++, *ptr);
      //
      // check for valid register addresses
      //
      if (iStart < 0 || (iStart + iQty / 2 - 1) > MB_REGISTERS_MAX) {
        iEC = MB_EC_ILLEGAL_DATA_ADDRESS;
        break;
      }
      //
      // Unpack and store data
      //
      ptr = mb_adu + MB_TCP_DATA + 5;
      // todo: check for valid length
      for (i = 0 ; i < iQty / 2 ; i++) {
        mb_reg[iStart + i] = word(*ptr++, *ptr++);
      }
      //
      // Build a response
      //
      iTXLen = 12;
      break;

    default:
      iEC = MB_EC_ILLEGAL_FUNCTION;
      break;
  }
  //
  // Build exception response if necessary because we were too
  // lazy to do it earlier. Other responses should already be
  // built.
  //
  if (iEC) {
    ptr = mb_adu + MB_TCP_FUNC;
    *ptr = *ptr++ | 0x80;        // flag the function code
    *ptr = iEC;                  // write the exception code
    iTXLen = 9;
  }
  //
  // If there's a response, transmit it
  //
  if (iFC) {
    ptr = mb_adu + MB_TCP_LEN;    // write the header length
    *ptr++ = 0x00;
    *ptr = iTXLen - MB_TCP_UID;
#ifdef MB_DEBUG
    printMB("TX: ", word(mb_adu[MB_TCP_LEN], mb_adu[MB_TCP_LEN + 1]) + MB_TCP_UID);
#endif
#ifdef MB_ETHERNET
    clientrequest.write(mb_adu, iTXLen); // send it
#endif
#ifdef MB_CC3000
    clientrequest.write(mb_adu, iTXLen); // send it
#endif
#ifdef MB_ESP8266
    clientrequest.write((byte*) mb_adu, iTXLen); // send it
    //clientrequest.stop(); 
#endif
  }
}

#ifdef MB_Float
int ModbusTCP::setFloat(uint16_t iAddress, float fValue) {

  int iRet;
  union {
    float f;
    uint16_t w[2];
  }
  fw;

  for (iRet = 0 ; !iRet ; iRet = 2) {
    if ((iAddress -= 40001) < 0 || (iAddress + 1) >= MB_REGISTERS_MAX) // invalid address
      break;
    fw.f = fValue;
    mb_reg[iAddress++] = fw.w[0];
    mb_reg[iAddress] = fw.w[1];
  }
  return (iRet);
}
Esempio n. 17
0
/**
 *	Process HTTP request
 *
 *	@return EthernetClient client
 **/
EthernetClient uHTTP::available(){
    EthernetClient client;

    memset(__uri, 0, sizeof(__uri));
    memset(__query, 0, sizeof(__query));
    memset(__body, 0, sizeof(__body));
    memset(&__head, 0, sizeof(__head));

    if(client = EthernetServer::available()){
        uint8_t cursor = 0, cr = 0;
        char buffer[uHTTP_BUFFER_SIZE] = {0};
        bool sub = false;

        enum state_t {METHOD, URI, QUERY, PROTO, KEY, VALUE, BODY};
        state_t state = METHOD;

        enum header_t {START, AUTHORIZATION, CONTENT_TYPE, CONTENT_LENGTH, ORIGIN};
        header_t header = START;

		while(client.connected() && client.available()){
      		char c = client.read();

      		(c == '\r' || c == '\n') ? cr++ : cr = 0;
      		
      		switch(state){
      			case METHOD:
            		if(c == ' '){
              			if(strncmp_P(buffer, PSTR("OP"), 2) == 0) __method = uHTTP_METHOD_OPTIONS;
              			else if(strncmp_P(buffer, PSTR("HE"), 2) == 0) __method = uHTTP_METHOD_HEAD;
              			else if(strncmp_P(buffer, PSTR("PO"), 2) == 0) __method = uHTTP_METHOD_POST;
              			else if(strncmp_P(buffer, PSTR("PU"), 2) == 0) __method = uHTTP_METHOD_PUT;
              			else if(strncmp_P(buffer, PSTR("PA"), 2) == 0) __method = uHTTP_METHOD_PATCH;
              			else if(strncmp_P(buffer, PSTR("DE"), 2) == 0) __method = uHTTP_METHOD_DELETE;
              			else if(strncmp_P(buffer, PSTR("TR"), 2) == 0) __method = uHTTP_METHOD_TRACE;
              			else if(strncmp_P(buffer, PSTR("CO"), 2) == 0) __method = uHTTP_METHOD_CONNECT;
              			else __method = uHTTP_METHOD_GET;
              			state = URI; 
              			cursor = 0; 
            		}else if(cursor < uHTTP_METHOD_SIZE - 1){
            			buffer[cursor++] = c; 
            			buffer[cursor] = '\0'; 
            		}
            		break;
            	case URI:
            		if(c == ' '){
            			state = PROTO;
            			cursor = 0;
            		}else if(c == '?'){
            			state = QUERY;
            			cursor = 0;
            		}else if(cursor < uHTTP_URI_SIZE - 1){
            			__uri[cursor++] = c;
            			__uri[cursor] = '\0';
            		}
            		break;
            	case QUERY:
            		if(c == ' '){
            			state = PROTO;
            			cursor = 0;
            		}else if(cursor < uHTTP_QUERY_SIZE - 1){
            			__query[cursor++] = c;
            			__query[cursor] = '\0';
            		}
            		break;
            	case PROTO:
            		if(cr == 2){ state = KEY; cursor = 0; }
            		break;
            	case KEY:
            		if (cr == 4){ state = BODY; cursor = 0; }
            		else if(c == ' '){ state = VALUE; cursor = 0; }
            		else if(c != ':' && cursor < uHTTP_BUFFER_SIZE){ buffer[cursor++] = c; buffer[cursor] = '\0'; }
            		break;
            	case VALUE:
            		if(cr == 2){
            			switch(header){
                			case AUTHORIZATION:
                  				strncpy(__head.auth, buffer, uHTTP_AUTH_SIZE);
                  				break;
                			case CONTENT_TYPE:
                				strncpy(__head.type, buffer, uHTTP_TYPE_SIZE);
                  				break;
                			case ORIGIN:
                  				strncpy(__head.orig, buffer, uHTTP_ORIG_SIZE);
                  				break;
                  			case CONTENT_LENGTH:
                  				__head.length = atoi(buffer);
                  				break;
                  			break;
              			}
            			state = KEY; header = START; cursor = 0; sub = false;
            		}else if(c != '\r' && c!= '\n'){
            			if(header == START){
                			if(strncmp_P(buffer, PSTR("Auth"), 4) == 0) header = AUTHORIZATION;
                			else if(strncmp_P(buffer, PSTR("Content-T"), 9) == 0) header = CONTENT_TYPE;
                			else if(strncmp_P(buffer, PSTR("Content-L"), 9) == 0) header = CONTENT_LENGTH;
              			}

              			// Fill buffer
              			if(cursor < uHTTP_BUFFER_SIZE - 1){
                			switch(header){
                  				case AUTHORIZATION:
                    				if(sub){ buffer[cursor++] = c; buffer[cursor] = '\0'; }
                    				else if(c == ' ') sub = true;
                    				break;
                  				case CONTENT_TYPE:
                  				case CONTENT_LENGTH:
                    				buffer[cursor++] = c; buffer[cursor] = '\0';
                    				break;
                			}
              			}
            		}
            		break;
            	case BODY:
            		if(cr == 2 || __head.length == 0) client.flush();
            		else if(cursor < uHTTP_BODY_SIZE - 1){ __body[cursor++] = c; __body[cursor] = '\0'; }
            		break;
      		}
      	}
	}
	return client;
}