Ejemplo n.º 1
0
void efail()
{
  byte thisByte = 0;
  int loopCount = 0;

  eth_client.println(F("QUIT"));

  while(!eth_client.available()) {
    #ifdef WATCHDOG
    wdt_reset();
    #endif
    delay(1);
    loopCount++;

    // if nothing received for 10 seconds, timeout
    if(loopCount > 10000) {
      eth_client.stop();
      Serial.println(F("\r\nTimeout"));
      return;
    }
  }

  while(eth_client.available())
  {
    thisByte = eth_client.read();
    Serial.write(thisByte);
  }

  eth_client.stop();

  Serial.println(F("disconnected"));
}
Ejemplo n.º 2
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();
  }

}
Ejemplo n.º 3
0
String Nimbits::login(String email, String password) {
  EthernetClient client;
  _email = email;
  _password = password;
  String content;
  content = "email=";
  content += email;
  content += "&token=";
  content += _password;




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

    doPost(client, SESSION_API, content);
    String response = getFullResponse(client);
    String str = getContent(response);
  Serial.println(str);
    client.stop();

          int str_len = str.length() + 1;

          StaticJsonBuffer<1024> jsonBuffer;
          char char_array[str_len];

          // Copy it over
          str.toCharArray(char_array, str_len);

          JsonObject& root = jsonBuffer.parseObject(char_array);

      if (!root.success()) {
        _authToken = "";
        return "";

      }

      _authToken = root["token"];

  }
  else {

    client.stop();
  }
  return _authToken;



}
Ejemplo n.º 4
0
double Nimbits::getValue(String point) {
  EthernetClient client;

  String content;

  content += "&id=";
  content +=  (_email + "/" + point);

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


    doGet(client, VALUE_API, content);
    String response = getFullResponse(client);


    String str = getContent(response);

      client.stop();


      int str_len = str.length() + 1;
      StaticJsonBuffer<256> jsonBuffer;
      char char_array[str_len];

      // Copy it over
      str.toCharArray(char_array, str_len);

      JsonObject& root = jsonBuffer.parseObject(char_array);

  if (!root.success()) {

    return -1.0;

  }

  double d = root["d"];

  return d;


  }
  else {

    client.stop();
    return 0;
  }

}
String GAE(String link) {
	httpRequest(link);
	delay(10000);

	String readString = ""; //Reset string

	while (client.available() > 0) {

		char s = client.read();
		//Serial.print(s);			//Complete response w/ headers. For dev mode.
		if (s== '\n') {
			char c = client.read();
			//Serial.print(c);			//Parsed response. For dev mode.
			if (c == '\r') {
				while (client.connected()) {
					char z = client.read();
					readString += z;
				}
			}
		}
	}
	client.stop();
	return(readString);

}
Ejemplo n.º 6
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
Ejemplo n.º 7
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();
  }

}
Ejemplo n.º 8
0
void loop() {
  // listen for incoming clients
  EthernetClient client = server.available();
  if (client) 
  {
    Serial.println("new client");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) 
    {
      if (client.available()) 
      {
        char c = client.read();
        Serial.write(c);

        //*******************233333333333333333333333333333333333333333333*******
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) 
        {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: textml");
          client.println("Connection: close");  // the connection will be closed after completion of the response
          client.println("Refresh: 5");  // refresh the page automatically every 5 sec
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("<html>");
          // output the value of each analog input pin
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
            int sensorReading = analogRead(analogChannel);
            client.print("analog input ");
            client.print(analogChannel);
            client.print(" is ");
            client.print(sensorReading);
            client.println("<br />");
          }
          client.println("<ml>");
          break;
        }
        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;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    Serial.println("client disconnected");
  }
}
Ejemplo n.º 9
0
void DataServeriOS::loop()
{
  _client = _server->available();
  if (_client)
  {
    WaitForRequest();
    ParseReceivedRequest();
    PerformRequestedCommand();
    _client.flush();
    _client.stop();
  }
  else {
    _client.stop();
    _substitudeLoop();
  }
}
// this method makes a HTTP connection to the server:
void sendData(String thisData) {
  // if there's a successful connection:
  if (client.connect(server, 80)) {
    Serial.println("connecting...");
    // send the HTTP PUT request:
    client.print("PUT /v2/feeds/");
    client.print(FEEDID);
    client.println(".csv HTTP/1.1");
    client.println("Host: api.xively.com");
    client.print("X-ApiKey: ");
    client.println(APIKEY);
    client.print("User-Agent: ");
    client.println(USERAGENT);
    client.print("Content-Length: ");
    client.println(thisData.length());

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

    // here's the actual content of the PUT request:
    client.println(thisData);
  } 
  else {
    // if you couldn't make a connection:
    Serial.println("connection failed");
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
  }
  // note the time that the connection was made or attempted:
  lastConnectionTime = millis();
}
Ejemplo n.º 11
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);
  }
}
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() && lastConnected) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
  }

  // if you're not connected, and ten seconds have passed since
  // your last connection, then connect again and send data:
  if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
    httpRequest();
  }
  // store the state of the connection for next time through
  // the loop:
  lastConnected = client.connected();
}
Ejemplo n.º 13
0
/*
 * 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");
	}
}
Ejemplo n.º 14
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();
}
Ejemplo n.º 15
0
//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;
	}
}
Ejemplo n.º 16
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="";

				}
			}
		}
	}
}
Ejemplo n.º 17
0
void ProcessClientMessage(){   
    // listen for incoming clients
    EthernetClient client = GetAvailableClient();

    if (client) 
    {  
        // an http request ends with a blank line
        boolean currentLineIsBlank = true;

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

                // if you've gotten to the end of the line (received a newline
                // character) and the line is blank, the http request has ended,
                // so you can send a reply
                if (c == '\n' && currentLineIsBlank) 
                {
                    //Magnetic;Noise;Temperature;Vibration;Voltage

                    String data = "";

                    data += String(GetMagnetic());
                    data += ";";

                    data += String(GetTemperature());
                    data += ";";

                    data += String(GetVibration());
                    data += ";";

                    data += String(GetVoltage());

                    client.println(data);
                    break;
                }

                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;
                }
            }
        }

        // give the web browser time to receive the data
        delay(10);  

        // close the connection:
        client.stop();
    }
}
Ejemplo n.º 18
0
void LeweiTcpClient::listenServer()
{
  EthernetClient clientWeb = server.available();
  if (clientWeb) {
    //Serial.println("new clientWeb");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    String clientStr = "";
    while (clientWeb.connected()) {
      if (clientWeb.available()) {
        char c = clientWeb.read();
        clientStr += c;
        //Serial.write(c);
        
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          clientWeb.println("<html><body><form method='get'>");
          clientWeb.print("KEY<input type='text' name='a' value='");
          clientWeb.print(_userKey);
          clientWeb.print("'>GW<input type='text' name='g' value='");
          clientWeb.print(_gatewayNo);
          clientWeb.println("'><input type='submit'>");
          clientWeb.println("</form></body></html>");
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
          if(clientStr.indexOf(" /?a=")>0)
          {
          	Serial.print(clientStr);
          	String userInfoStr = clientStr.substring(clientStr.indexOf(" /?a=")+5,clientStr.indexOf("&g="));
          	userInfoStr += clientStr.substring(clientStr.indexOf("&g=")+3,clientStr.indexOf(" HTTP/1.1"));
            if(userInfoStr.length()>33)writeRom(userInfoStr);
            Serial.println(userInfoStr);
          }
          //Serial.println(clientStr);
          clientStr = "";
          //checkFreeMem();
        } 
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    clientWeb.stop();
    clientWeb= NULL;
    //Serial.println("clientWeb disonnected");
  }
  
}
Ejemplo n.º 19
0
uint8_t EC_Error(void)
{
#ifndef USE_RS485
	ec_client.stop();
#endif
	// add the two error code to the param_readings
	//sprintf(&param_readings[strlen(param_readings)], ",%u,%u", ec_state, mb_state);
	sprintf_P(&param_readings[strlen(param_readings)], PSTR(",,"));  // add blank values - avoid distorted plotting
	return ec_state;
}
void disconnect_pachube(){
	Serial.println("disconnecting.\n=====\n\n");
	localClient.stop();
	ready_to_update = false;
	reading_pachube = false;
	request_pause = true;
	last_connect = minute();
	found_content = false;
	resetEthernetShield();
}
Ejemplo n.º 21
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();
}
Ejemplo n.º 22
0
//---------------------------------------------------------------------
void terminateConnection()
{
    // flush input buffer
    while ( client_.read() != (-1) )
        delay( STREAM_DELAY_MS );
    
    client_.stop();
#ifdef DEBUG_SERIAL
    Serial.println( "DEBUG: client disconnected" );
#endif
    digitalWrite( PIN_STATUS_LED, LOW );
}
Ejemplo n.º 23
0
// This method makes an HTTP connection to the server
void httpRequest(String link) {
	//if there is a successful connection
	if (client.connect(server, 80)) {
		client.println("Get " + link + " HTTP/1.0 ");
		client.println();

	} else {
		// You couldn't make the connection
		Serial.println("Connection Failed");
		Serial.println("Disconnecting.");
	}
		client.stop(); }
Ejemplo n.º 24
0
void mqttConnect() {
    internetClient.stop(); // Ensure any old connection is closed
    mqtt_response = mqttClient.connect();
    //  DebugSerial.println(F("MQTT connecting"));
    if (mqtt_response == 0) {
        //    DebugSerial.println(F("MQTT connected"));
        publish(F("mqttConnection"), 0);
    } else {
        DebugSerial.print(F("MQTT connection Failed: "));
        DebugSerial.println(mqttClient.connectErrorString(mqtt_response));
    }
}
Ejemplo n.º 25
0
Weather::ReturnVals Weather::GetVals(const char * key, uint32_t zip, const char * pws, bool usePws) const
{
	ReturnVals vals = {0};
	EthernetClient client;
	if (client.connect(m_wundergroundAPIHost, 80))
	{
		char getstring[255];
		trace(F("Connected\n"));
		if (usePws)
			snprintf(getstring, sizeof(getstring), "GET http://%s/api/%s/yesterday/conditions/q/pws:%s.json HTTP/1.1\r\n",m_wundergroundAPIHost, key, pws);
		else
			snprintf(getstring, sizeof(getstring), "GET http://%s/api/%s/yesterday/conditions/q/%ld.json HTTP/1.1\r\n",m_wundergroundAPIHost, key, (long) zip);

		//trace("GetString:%s\n",getstring);
		client.write((uint8_t*) getstring, strlen(getstring));
		
		//send host header
		snprintf(getstring, sizeof(getstring), "Host: %s\r\nConnection: close\r\n\r\n",m_wundergroundAPIHost);
		//trace("GetString:%s\n",getstring);
		client.write((uint8_t*) getstring, strlen(getstring));

		ParseResponse(client, &vals);
		vals.resolvedIP=client.GetIpAddress();

		client.stop();
		if (!vals.valid)
		{
			if (vals.keynotfound)
				trace("Invalid WUnderground Key\n");
			else
				trace("Bad WUnderground Response\n");
		}
	}
	else
	{
		trace(F("connection failed\n"));
		client.stop();
	}
	return vals;
}
Ejemplo n.º 26
0
void api_call_http_register_self(byte amsg_server[]) {


	char path[ 30 ];
	char host[ 30 ];
	strcpy_P(path, msg_server_path);
	strcpy_P(host, msg_server_host);

	EthernetClient client;


	Serial.print("HTTP opening connection to ");
	Serial.println(host);
	/*
	if (!ether.dnsLookup(website))
		  Serial.println("DNS failed");
	else
		  Serial.println("DNS resolution done");
	ether.printIp("SRV IP:\t", ether.hisip);
	*/

	if (!client.connect(amsg_server, pgm_read_word(&msg_server_port))) {
		Serial.println("HTTP failed");
		return;
	}

	char d;
	String netbuf = "GET ";
	netbuf += path;
	netbuf += " HTTP/1.0\nHost: ";
	netbuf += host;
	netbuf += "\nConnection: close\n\n\n";

	Serial.print("HTTP connected to ... ");

	char sockbuf[ netbuf.length() ];
	netbuf.toCharArray(sockbuf, netbuf.length());
	client.write(sockbuf);
	delay(100);
	while(client.connected()) {
		while(client.available())   {
			d = client.read();
			if (d == '\n')
				Serial.print("\r\n");
			else
				Serial.print(d);
		}
	}	  
	client.stop();
	Serial.println();
}
Ejemplo n.º 27
0
void loop(){
  if (dataLesen()==1) {
  //QFF-Berechnung
  x = ((temp + konst1)/(qfe/100)*exp(((temp+konst1+konst2)*11.5526-26821)/(temp+konst1+konst2-1060)));
  qff = (qfe/100)*exp(konst2*10.5152/(x+temp+konst1+konst2));
  //Messwerten abschicken
  if (client.connect(serverName, 80)) {
    //Serial.println("Verbunden ... sende ... fertig!");
    // URL anrufen:
    client.print("GET /upload.php?TEMP=");
    client.print(temp);
    client.print("&TAU=");
    client.print(taupunkt);
    client.print("&QFE=");
    client.print(qfe/100, 1);
    client.print("&QFF=");
    client.print(qff,1);
    client.print("&FEUCHTE=");
    client.print(feuchte);
    client.println("&key=root HTTP/1.0\n");
    client.println("Host: localhost");
    client.println("User-Agent: Arduino");
    client.println();
    client.stop();
  } 
  if (!client.connected()) {
    /*Serial.println();
    Serial.println("disconnecting.");*/
    client.stop();
}    
  delay(899500);
  softReset();
/*  else {
    // 2. Worst-Case-Szenario
    Serial.println("connection failed");
  }*/
}
}
void setup_data_stream(){
  // setup push socket
  Serial.println(F("Setting up PUSH socket..."));
  if( ZMQPush.connect( data_server, mes_port ) ){
    Serial.println(F("oops"));
    client.stop(); // TODO: deal with this better
    frontpanel_set_led( ERR4_LED, 1 );
    for(;;)
      ;
  }
  Serial.println(F("Starting"));
  Serial.println(F("Data"));
  Serial.println(F("Stream"));
}
void register_stream(){
  // setup request socket
  Serial.println(F("Setting up REQ socket"));
  ZMQSocket ZMQReq( client, zmq_buffer, REQ );
  int16_t len;
  do{
    uint8_t err = 0;
    len = -1;
    if( ZMQReq.connect( data_server, reg_port ) ){
      client.stop(); // TODO: deal with this better
      Serial.println("Cant connect to server");
      err = 1;
    }
    if(!err){
      // register datastream with server
      Serial.println(F("Registering data stream..."));
      len = packet.registerIntStream();
      ZMQReq.sendZMQMsg(len);
      len = ZMQReq.recv();
      if( len < 0 ){
        Serial.println(F("negative len returned"));
        client.stop();
      }
    }
  } while( len < 0 );
  // check that we got the expected response from the moitoring server
  if( len != 7 ){
    Serial.println(F("Invalid Response from server, length: "));
    Serial.println(len);
    frontpanel_set_led( ERR4_LED, 1 );
    for(;;)
      ;
  }
  // disconnect from registering port
  Serial.println(F("Disconnecting REQ socket..."));
  client.stop();
}
Ejemplo n.º 30
0
void ModbusIP::task() {
    EthernetClient client = _server.available();

    if (client) {
        if (client.connected()) {
            int i = 0;
            while (client.available()){
                _MBAP[i] = client.read();
                i++;
                if (i==7) break;  //MBAP length has 7 bytes size
            }
            _len = _MBAP[4] << 8 | _MBAP[5];
            _len--;  // Do not count with last byte from MBAP

            if (_MBAP[2] !=0 || _MBAP[3] !=0) return;   //Not a MODBUSIP packet
            if (_len > MODBUSIP_MAXFRAME) return;      //Length is over MODBUSIP_MAXFRAME

            _frame = (byte*) malloc(_len);
            i = 0;
            while (client.available()){
                _frame[i] = client.read();
                i++;
                if (i==_len) break;
            }

            this->receivePDU(_frame);
            if (_reply != MB_REPLY_OFF) {
                //MBAP
                _MBAP[4] = (_len+1) >> 8;     //_len+1 for last byte from MBAP
                _MBAP[5] = (_len+1) & 0x00FF;

                byte sendbuffer[7 + _len];

                for (i = 0 ; i < 7 ; i++) {
                    sendbuffer[i] = _MBAP[i];
                }
                //PDU Frame
                for (i = 0 ; i < _len ; i++) {
                    sendbuffer[i+7] = _frame[i];
                }
                client.write(sendbuffer, _len + 7);
            }

#ifndef TCP_KEEP_ALIVE
            client.stop();
#endif
            free(_frame);
            _len = 0;
        }