# Communicating with private server \[SOLVED?\]

**URL:** <https://community.particle.io/t/communicating-with-private-server-solved/6240>\
**Category:** Firmware\
**Created:** [August 6, 2014, 2:58pm UTC](https://community.particle.io/t/communicating-with-private-server-solved/6240 "2014-08-06T14:58:12Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![daflippymaster](https://avatars.discourse-cdn.com/v4/letter/d/6a8cbe/32.png) [@daflippymaster](https://community.particle.io/u/daflippymaster)\
**Post date:** [August 6, 2014, 2:58pm UTC](https://community.particle.io/t/communicating-with-private-server-solved/6240/1 "2014-08-06T14:58:13Z")

</div>

## See post #5 for solution/final code

Having some trouble getting the spark to talk to a private server (bypassing the spark cloud)

Here’s the code i’m using

```
TCPClient client;
byte serverAddress[] = { 192, 168, 0, 101 };

void setup()
{
    Serial.begin(9600);
    delay(1000);
    Serial.flush();
}

void loop()
{
  client.connect(serverAddress, 80);
  delay(1000);

  if(client.available()){
      Serial.println("connected"); 
  }else{Serial.println("connection failed");}
  
delay(1000);

Serial.println(WiFi.ping(serverAddress));
delay(1000);  
}

```

So I can get the ping to return a value of 4 (some of the time, other times it returns 0) but it always prints out "connection failed"  
Any idea about what is going on here?  
(the server is on the same network the core is connected to)

---

<div class="post-metadata">

**Author:** ![kennethlimcp](https://avatars.discourse-cdn.com/v4/letter/k/c0e974/32.png) [@kennethlimcp](https://community.particle.io/u/kennethlimcp)\
**Post date:** [August 7, 2014, 4:49am UTC](https://community.particle.io/t/communicating-with-private-server-solved/6240/2 "2014-08-07T04:49:03Z")

</div>

It seems like the connection is not closed and `client.connect()` is called every time the loop() repeats.

Maybe that’s an issue? I’m definitely no the best person to answer this. 😉 @bko?

---

<div class="post-metadata">

**Author:** ![daflippymaster](https://avatars.discourse-cdn.com/v4/letter/d/6a8cbe/32.png) [@daflippymaster](https://community.particle.io/u/daflippymaster)\
**Post date:** [August 7, 2014, 5:11pm UTC](https://community.particle.io/t/communicating-with-private-server-solved/6240/3 "2014-08-07T17:11:55Z")

</div>

So i’ve got it to the point where i’m able to connect to server but i’m having trouble calling the php test file

```
TCPClient client;
byte server[] = { 192, 168, 0, 101 }; // Google
void setup(){
  Serial.begin(9600);
  while(!Serial.available()) SPARK_WLAN_Loop();
  Serial.println("connecting...");

  if (client.connect(server, 80)){
    Serial.println("connected");
    client.write("GET /~jkennedy/get_test.php HTTP/1.1");
  }
  else{
    Serial.println("connection failed");
  }
}

void loop(){
 // delay(2);
 if (client.available()){
    char c = client.read();
    Serial.print(c);
 }

if (!client.connected()){
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    for(;;);
  }
}

```

all the php file has in it is

```
ECHO "Hello world";
```

---

<div class="post-metadata">

**Author:** ![daflippymaster](https://avatars.discourse-cdn.com/v4/letter/d/6a8cbe/32.png) [@daflippymaster](https://community.particle.io/u/daflippymaster)\
**Post date:** [August 8, 2014, 8:14pm UTC](https://community.particle.io/t/communicating-with-private-server-solved/6240/4 "2014-08-08T20:14:45Z")

</div>

I’ve got the spark talking to the server and can call the PHP file all right.  
Now I need to set it up so that the spark sends 2 variables for the php file to send to the server, a string and a float.

I’ve gotten the code below to work alright for sending a single string, but i’m not sure how I would go about sending both at the same time (consecutively).

Any suggestions?

```
#define ASLDKFJASLDFJ "tests"

byte server[] = {192, 168, xxx, xxx};
String line1("PUT /~jkennedy/get_test.php HTTP/1.1\r\n");
String line2("User-Agent: A Spark Core\r\n");
String line3("Host: 192.168.xxx.xxx\r\n");
String line4("Connection: close\r\n");
String line5("Content-Type: text/plain\r\n");
String line6("Content-Length: ");
//line7 is added by transmit()
String line8("\r\n");
String line9("\r\n");
String line10("\r\n");

void transmit() { 
    char tmpString[40];
    sprintf(tmpString,ASLDKFJASLDFJ);
    String message = String(tmpString);
    String line7(message.length());
    TCPClient client;
  
  if(client.connect(server, 80)) {
    client.write( (uint8_t*)line1.c_str(), line1.length() );
    client.write( (uint8_t*)line2.c_str(), line2.length() );
    client.write( (uint8_t*)line3.c_str(), line3.length() );
    client.write( (uint8_t*)line4.c_str(), line4.length() );
    client.write( (uint8_t*)line5.c_str(), line5.length() );
    client.write( (uint8_t*)line6.c_str(), line6.length() );
    client.write( (uint8_t*)line7.c_str(), line7.length() );
    client.write( (uint8_t*)line8.c_str(), line8.length() );
    client.write( (uint8_t*)line9.c_str(), line9.length() );
    delay(20);
    client.write( (uint8_t*)message.c_str(), message.length() );
    client.write( (uint8_t*)line10.c_str(), line10.length() );
    delay(20);
    //Serial.println("PUT request sent");
    Serial.print("Data Sent");
}

    client.flush();
    client.stop();
    Serial.println(message);
}

```

---

<div class="post-metadata">

**Author:** ![daflippymaster](https://avatars.discourse-cdn.com/v4/letter/d/6a8cbe/32.png) [@daflippymaster](https://community.particle.io/u/daflippymaster)\
**Post date:** [August 8, 2014, 9:26pm UTC](https://community.particle.io/t/communicating-with-private-server-solved/6240/5 "2014-08-08T21:26:27Z")

</div>

Got everything working pretty much exactly how it should!  
Here’s what I used for whoever’s interested:

Spark Code

```
byte server[] = {192, 168, xxx, xxx};
String line1("PUT /~jkennedy/get_test.php HTTP/1.1\r\n");
String line2("User-Agent: A Spark Core\r\n");
String line3("Host: 192.168.xxx.xxx\r\n");
String line4("Connection: close\r\n");
String line5("Content-Type: text/plain\r\n");
String line6("Content-Length: ");
//line7 is added by transmit()
String line8("\r\n");
String line9("\r\n");
String line10("\r\n");  

//FUNCTION TO TRANSMIT DATA TO DATABASE

void transmit(char Name[20],float temp) {
    char tmpString[40];
    sprintf(tmpString, "%s, %f",Name,temp );
    String message = String(tmpString);
    String line7(message.length()); 
    TCPClient client;
    if(client.connect(server, 80)) {
        client.write( (uint8_t*)line1.c_str(), line1.length() );
        client.write( (uint8_t*)line2.c_str(), line2.length() );
        client.write( (uint8_t*)line3.c_str(), line3.length() );
        client.write( (uint8_t*)line4.c_str(), line4.length() );
        client.write( (uint8_t*)line5.c_str(), line5.length() );
        client.write( (uint8_t*)line6.c_str(), line6.length() );
        client.write( (uint8_t*)line7.c_str(), line7.length() );
        client.write( (uint8_t*)line8.c_str(), line8.length() );
        client.write( (uint8_t*)line9.c_str(), line9.length() );
        delay(20);
        client.write( (uint8_t*)message.c_str(), message.length() );
        client.write( (uint8_t*)line10.c_str(), line10.length() );
        delay(20);
        Serial.print("Data Sent");
    }

    client.flush();
    client.stop();
    Serial.println(message);
}

```

and here’s the php script to handle the data. There’s probably a better way to do this as it involves an intermediary text file to store the data and then read it back to send it. It ain’t pretty but it works!

```
<?php
$dbhost="localhost";
$dbuser=" *************";
$dbpass=" *************";
$targetDB=" ***********";

$handle = fopen("./helloworld.txt", "w+",true);
$content = fopen("php://input","r");
while($data=fread($content,1024)){
fwrite($handle,$data);
}
fclose($content);

$put_vars = file_get_contents("./helloworld.txt",true);
$TestData = str_getcsv($put_vars,",");
$TestName = $TestData[0];
$TestTemp = $TestData[1];

$server = mysqli_connect($dbhost, $dbuser, $dbpass, $targetDB);

if(mysqli_errno()) {
   fwrite( "Could not connect: " . mysqli_connect_error());
}
else{
   fwrite( "connected. \n");
}

$result = "INSERT INTO TestTable(TestName,TestTemp) VALUES ('" . $TestName . "', '" . $TestTemp . "')";

if(!mysqli_query($server, $result)) {
    die('error: ' . mysqli_error($server));
}

if($result){fwrite( "query sent ");}else{fwrite( "oops ");}

fclose($handle);
mysqli_close($server);
?>
```

---

<div class="post-metadata">

**Author:** ![daflippymaster](https://avatars.discourse-cdn.com/v4/letter/d/6a8cbe/32.png) [@daflippymaster](https://community.particle.io/u/daflippymaster)\
**Post date:** [August 11, 2014, 4:28pm UTC](https://community.particle.io/t/communicating-with-private-server-solved/6240/6 "2014-08-11T16:28:42Z")

</div>

So i’ve come across a bit of a bug that i’m not sure how to squash.

The temperature data gets logged to the server fine most of the time, but sometimes values are completely skipped or i’ll get some null data sent in

Could this be a timing issue?

this is the function that reads the temperature data and then calls transmit() to send it to the server

```
void ContinuousRead(){

unsigned long starttime;
char tName[20]={""};
char answer[8]={""};
float fanswer=0;
if(MachineState==0){
  Serial.println("Machine is off");
  
 }else{
   Serial.println("Enter a name for the test :");
   while(!Serial.available());   
   Serial.readBytesUntil('\r',tName,19);
    
   while(uptime<36000000){
    uptime=millis();      
    Serial1.write(RemoteT,3);
    while (Serial1.available()) Serial1.read();
    starttime = millis();
   
   while(!Serial1.available() && millis()<=starttime+TIMEOUT) SPARK_WLAN_Loop();
     if(millis()>=starttime+TIMEOUT){
        Serial.println("TIMED OUT");
        memset(&answer[0], 0, sizeof(answer));
        delay(3000);
        Serial1.write(RemoteT,3);
        while (Serial1.available()) Serial1.read();
      }
      
    Serial1.readBytesUntil('\r',answer,6);
    
    while(answer[0]<45||answer[0]>57){
      memset(&answer[0], 0, sizeof(answer));  
      Serial1.write(RemoteT,3);
      while (Serial1.available()) Serial1.read();

      while(!Serial1.available());
      Serial1.readBytesUntil('\r',answer,6);
    }
    Serial.print((uptime/1000)/60);
    Serial.print(" ");
    Serial.print("Sensor Temperature: ");
    Serial.print(answer);
    Serial.println(" C \n");
    Serial.flush();
    fanswer=atof(answer);

    transmit(tName,fanswer);
    delay(15000);
    }
  }
}

```

EDIT: Solved the printing null data issue, however i’m still gettting skips and jumps in the data  
its supposed to post every 15s, however occasionally it will skip a few periods

---

<div class="post-metadata">

**Author:** ![digixx](https://sea2.discourse-cdn.com/flex026/user_avatar/community.particle.io/digixx/32/2831_2.png) [@digixx](https://community.particle.io/u/digixx)\
**Post date:** [September 18, 2014, 8:01pm UTC](https://community.particle.io/t/communicating-with-private-server-solved/6240/7 "2014-09-18T20:01:22Z")

</div>

Hi Jack

May this is of interest. This is how I transfer sensor data to a php script running on Raspberry Pi

core.cpp

```
void updateDATA() {
    debugPrintln("\nContact server..");
    if (client.connect(server, 80))
    {
        String HTTPreq = "GET /data.php";
        sprintf(szData, "%d", stat); HTTPreq = HTTPreq + "?stat=" + szData;
        
        sprintf(szData, "%.2f", ina219d.voltage); HTTPreq = HTTPreq + "&volt=" + szData;
        sprintf(szData, "%.2f", ina219d.current); HTTPreq = HTTPreq + "&chrg=" + szData;

        sprintf(szData, "%.2f", dhtd.t); HTTPreq = HTTPreq + "&temp=" + szData;
        sprintf(szData, "%.2f", dhtd.h); HTTPreq = HTTPreq + "&hum=" + szData;
        
        sprintf(szData, "%.2f", bmpd.pressure); HTTPreq = HTTPreq + "&baro=" + szData;
        
        sprintf(szData, "%d", tcsd.colortemp); HTTPreq = HTTPreq + "&ctemp=" + szData;
        sprintf(szData, "%d", tcsd.lux); HTTPreq = HTTPreq + "&cbright=" + szData;
        sprintf(szData, "%d", tcsd.r); HTTPreq = HTTPreq + "&cred=" + szData;
        sprintf(szData, "%d", tcsd.g); HTTPreq = HTTPreq + "&cgreen=" + szData;
        sprintf(szData, "%d", tcsd.b); HTTPreq = HTTPreq + "&cblue=" + szData;
        sprintf(szData, "%d", tcsd.c); HTTPreq = HTTPreq + "&cclear=" + szData;
        
        sprintf(szData, "%d", rssi); HTTPreq = HTTPreq + "&rssi=" + szData;
        
        HTTPreq = HTTPreq + "\n";
        HTTPreq = HTTPreq + "Host: 192.168.55.150\n";
        HTTPreq = HTTPreq + "User-Agent: spark.io\nContent-Length: 0\nConnection: close\n";
        
        client.println(HTTPreq);
        delay(250);
        
        while (client.available())
        {
            char c = client.read();
        }
        client.flush();
        client.stop();
        debugPrintln("\nsending data successfully");
    } else {
        debugPrintln("\nsending data failed");
    }
}

```

file.php

```
<?php
$voltage = htmlspecialchars($_GET["volt"]);
$charge = htmlspecialchars($_GET["chrg"]);
$temp = htmlspecialchars($_GET["temp"]);
$humidity = htmlspecialchars($_GET["hum"]);
$baro = htmlspecialchars($_GET["baro"]);
$colortemp = htmlspecialchars($_GET["ctemp"]);
$brightness = htmlspecialchars($_GET["cbright"]);
$red = htmlspecialchars($_GET["cred"]);
$green = htmlspecialchars($_GET["cgreen"]);
$blue = htmlspecialchars($_GET["cblue"]);
$clear = htmlspecialchars($_GET["cclear"]);
$rssi = 0 - htmlspecialchars($_GET["rssi"]);
$status = htmlspecialchars($_GET["stat"]);

// Do something

?>
```

---

<div class="post-metadata">

**Author:** ![daflippymaster](https://avatars.discourse-cdn.com/v4/letter/d/6a8cbe/32.png) [@daflippymaster](https://community.particle.io/u/daflippymaster)\
**Post date:** [September 29, 2014, 5:19pm UTC](https://community.particle.io/t/communicating-with-private-server-solved/6240/8 "2014-09-29T17:19:15Z")

</div>

Hey all,

Sorry for the late reply. The way I got this working was by using a buffer to store the data and then only send it when the connection to the server was good.

```
//FUNCTION TO TRANSMIT DATA TO DATABASE
void transmit(char Name[20],float temp) 
{
String TimeNow = Time.timeStr();
int UnixTime = Time.now();
char tmpString[40];
String TmpCmd("");
float TempBuffer[20]={};
int TimeBuffer[20]={};
int buffer_index=0;

TempBuffer[buffer_index]=temp;
TimeBuffer[buffer_index]=UnixTime;

if(buffer_index>sizeof(TempBuffer))
{
    memset(&TempBuffer[0], 0, sizeof(TempBuffer));  
    memset(&TimeBuffer[0], 0, sizeof(TimeBuffer)); 
}
else
{
    buffer_index++;
}

for(int i=0;i<buffer_index;i++)
{

  sprintf(tmpString, "%s, %f, %i",Name,TempBuffer[i],TimeBuffer[i] );
  String message = String(tmpString);
  String line7(message.length());

  TmpCmd.concat(line1);
  TmpCmd.concat(line3);
  TmpCmd.concat(line4);
  TmpCmd.concat(line5);
  TmpCmd.concat(line6);
  TmpCmd.concat(line7);
  TmpCmd.concat(line8);
  TmpCmd.concat(line9);
  TmpCmd.concat(message);
  TmpCmd.concat(line10);

  TCPClient client;
  if(client.connect(server, 80)) 
  {
      client.write( (uint8_t*)TmpCmd.c_str(), TmpCmd.length() );          
      delay(20);
  }  
  
  while(client.available())
  {
      buffer_index=0;      
  }

  delay(100);
  client.flush();
  delay(100);
  client.stop();  
 }
}
```
