Pages: [1] 2   Go Down
Author Topic: Sending Data to a Mysql WebServeur using POST method  (Read 6682 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 3
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hi everyone,

I would need so help. I am trying to send data to a php page using an arduino with Ethernet Shield.
I manage to send data using the GET method but it is not a safe way. So I am now trying the POST method but I have no idea why it won't work.

Here is the arduino code.

Code:
#include <SPI.h>
#include <Ethernet.h>

long randNumber;
//Affectation d'une adresse MAC
byte mac[] = {  0xB8, 0x27, 0xEB, 0xFE, 0xB2, 0x49 };

// Serveur avec Mysql
IPAddress server(192,168,0,100);

bool connected = false;

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

void setup()
{
Serial.begin(9600);

        randomSeed(analogRead(0));

if (Ethernet.begin(mac) == 0)
{
Serial.println("Impossible de configurer Ethernet en utilisant DHCP"); 
    // Attente perpétuelle
    for(;;);
        }
    Serial.println("Configuration Ethernet DHCP : OK \n@IP : ");
      for (byte thisByte = 0; thisByte < 4; thisByte++)
      {
// print the value of each byte of the IP address:
            Serial.print(Ethernet.localIP()[thisByte], DEC);
            Serial.println(".");
       }
    delay(1000);
}

int val=0;

void loop()
{
int val = random(300);
        String DatatoSend ="";
        DatatoSend += "Data=";
        DatatoSend += (val);
       
        Serial.println("DatatoSend :" + DatatoSend );
       
     
       
if (client.connect(server, 80))
{
    Serial.println("\nconnected...");
    Serial.println("ARDUINO: forming HTTP request message");
    client.println("POST /Test/PhpPost.php HTTP/1.1");
    client.println("From: Arduino1 ");
    client.println("User-Agent: HTTPTool/1.0");
    client.println("Content-Type: application/x-www-form-urlencoded");
                client.print("Content-Length:");
                client.println(DatatoSend.length());
                client.println("Connection: close");
                client.println(DatatoSend);
                client.println();

    Serial.println("ARDUINO: HTTP message sent");
    delay(3000);
    if(client.available())
    {
    Serial.println("ARDUINO: HTTP message received");
    Serial.println("ARDUINO: printing received headers and script response...\n");
   
    while(client.available())
    {
    char c = client.read();
    Serial.print(c);
    }
    }
    else
    {
    Serial.println("ARDUINO: no response received / no response received in time");
    }
   
    client.stop();
    }
    else
    {
    Serial.println("connection failure");
    }
    delay(2000);

}


and the Php Page :

Code:
<?php 
  $Variable 
$_POST['Data'];
  echo 
$Variable ;
?>

Thanks in advance for your Help  smiley-wink
Logged

0
Offline Offline
God Member
*****
Karma: 39
Posts: 986
Get Bitlash: http://bitlash.net
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

When you say it won't work, what do you mean exactly?

The place to start debugging is the access and error logs for the web server that is serving the PHP page.

The URL in the code uses mixed upper and lower case.  Not all file systems support this correctly, and for this reason URLs are usually not mixed case.  This is one possible cause of bugs like the one you are seeing. 

But the (presumably Apache) error log should be your next stop.

-br
Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 3
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Thanks you for this 1st answers. I will try what you say tomorrow and I will post the log of the server.
Logged

Earth
Offline Offline
Full Member
***
Karma: 2
Posts: 111
Webmaster
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

try reading this http://www.w3schools.com/php/php_post.asp
Logged

Webmaster living off grid in a camper with 300watts of solar panels charging 9 absorbed glass mat 12V batteries. i own about 40 dot coms. i

Offline Offline
Newbie
*
Karma: 0
Posts: 26
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

$_POST is used to get values from a HTML form element with a name that corresponds to the value inside the square brackets.

For example, this:
Code:
<?php 
  $Variable 
$_POST['Data'];
  echo 
$Variable ;
?>

Is now looking for a HTML element that has the name "Data", which doesn't exist.
Try writing your data into a separate text file from the arduino (remember to chmod the file) and then do something like;

Code:
<? php
$var = include 'youfilenamehere.txt';
echo $var;
 ?>
Logged

Tasmania - Australia
Offline Offline
Sr. Member
****
Karma: 10
Posts: 298
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
iDroid wrote:
$_POST is used to get values from a HTML form element with a name that corresponds to the value inside the square brackets.
This is partly true, in that what you say is a method often used, but it is not the definition of the POST method.

Using the POST method, you simply place the data, not on the url, but within the body of the http request, whether that be a html form, or for example, json encoded data from an external server/client system like an Arduino. And as such it is possible to send what ever data you have from the Arduino to a server using this method. Using the POST method also allows you to send more data than the GET method.

Quote
royalldonkey wrote:
I manage to send data using the GET method but it is not a safe way
How is using the GET method an issue with safety when using an Arduino?
I can understand the safety issues using the GET method from a html request from a browser on a computer, but I am not sure that you have this issue when sending data using the GET method from the Arduino?
How could the data be intercepted and viewed if it is sent from the Arduino?
If there is any chance of data snooping, the POST method I believe offers no extra protection, as the data is simply shifted to a different location in the http request.

Why do you have the following?
Code:
randomSeed(analogRead(0));

Do you know that the Arduino is setting up the IP configuration correctly using DHCP according to your program?
The Arduino will display this on the serial console at startup.

royalldonkey, have you had any success yet, let us know?

Santé
Paul
Logged


Tasmania - Australia
Offline Offline
Sr. Member
****
Karma: 10
Posts: 298
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Bonjour royalldonkey,

I have taken a section of my Arduino code out that deals with the transfer of data from my Arduino to my SQL database on my hosted site.
I use the Eclipse IDE, and make use of headers files, so file.cpp and header.h
The code below is part of an include file I use.

File sqlData.cpp
Code:
#include    "sqlData.h"                                 // include my own header file oui!
#include    "Ethernet.h"
#include    "Local_files/sensor.h"                      // header file to link to my data in other areas of Arduino:
#include    "Local_files/pidControl.h"                  // same as above:

        uint16_t    okCountPOST         = 0;            // number of successful POST connects:
        uint16_t    fltCountPOST        = 0;            // number of unsuccessful POST connects:
        boolean     fatcowConnected     = false;

        EthernetClient    clientFatCow;

//-----------------------------------------
//    Prepare POST data to SQL table live
//
//
void postLive() {
    char postData[128];

//    reference vars and scaling of integer data below
//    vB_pv        = vdcBattery.pv / 100
//    vT_pv        = vacHydro.pv / 10
//    iT_pv        = idcHydro.pv / 50
//    iS_pv        = idcSolar.pv / 50
//    fT_pv        = frqHydro_pv / 100
//    vT_cvPID     = hydroPID.cvPID / 10.23
//    vS_cvPID     = solarPID.cvPID / 10.23

    sprintf(postData, "{\"id\":\"live\",\"vB_pv\":%1i,\"vT_pv\":%2i,\"iT_pv\":%3i,\"iS_pv\":%4i,\"fT_pv\":%5i,\"vT_cvPID\":%6i,\"vS_CVPID\":%7i}",
            vdcBattery.pv, vacHydro.pv, idcHydro.pv, idcSolar.pv, frqHydro_pv ,hydroPID.cvPID, solarPID.cvPID);

    if(!postPage(postData)) {
        Serial.println("Error Post live");
        ++fltCountPOST;
    }
    else {
//        Serial.println("Post live");
    }
    ++okCountPOST;
}



//-----------------------------------------
//    POST data to server host
//
//
bool postPage(char* thisData) {
    int inChar;
    char outBuf[32];

//    Serial.print("postData: ");
//    Serial.print(thisData);
//    Serial.print("Len: ");
//    Serial.println(strlen(thisData));

    if (!fatcowConnected) {                       // if not connected then connect:
        fatcowConnect();
    }

    if (fatcowConnected) {
//    if(clientFatCow.connect("www.paulalting.com", 80)) {               // www.mydomain.com:
//        sprintf(outBuf,"POST %s HTTP/1.1",page);                       // DEBUG print:
        clientFatCow.println("POST /yourphp.php HTTP/1.1");              // send the header:
//        sprintf(outBuf,"Host: %s",domainBuffer);                       // DEBUG print:
        clientFatCow.println("Host: www.paulalting.com");
        clientFatCow.println("Connection: close\r\nContent-Type: application/json");
        sprintf(outBuf,"Content-Length: %u\r\n",strlen(thisData));       // DEBUG print:
        clientFatCow.print(thisData);                                    // send the data:
    }
    else {
        Serial.println("Heck, were're not connected!");                  // what gives here:
        return false;
    }

    int connectLoop = 0;
    while(clientFatCow.connected()) {
        while(clientFatCow.available()) {
            inChar = clientFatCow.read();
            Serial.write(inChar);                         // serial print reply from host:
            connectLoop = 0;
        }

        delay(1);
        connectLoop++;
        if(connectLoop > 2500) {                          // wait up to 2500mSec for reply:
//            Serial.println();
            Serial.println("Timeout");
            clientFatCow.stop();
            fatcowConnected = false;
        }
    }

    Serial.print("Post Count : ");
    Serial.print(okCountPOST);
    Serial.print("  Fails : ");
    Serial.println(fltCountPOST);
    Serial.println();
//    Serial.println("disconnecting");
    clientFatCow.stop();
    fatcowConnected = false;
    return true;
}

//-----------------------------------------
//    Connect to Server as Client
//
//
void fatcowConnect() {
    uint16_t    retry = 3;                                // retry count, normally 3:
//    Serial.println("Connecting..");
    while (retry) {
        if (clientFatCow.connect("www.paulalting.com", 80)) {
            Serial.print("Connect to host ok, retry: ");
            Serial.println(retry);
            fatcowConnected = true;
            break;
        }
        else {
            Serial.print("Connect to host failed, retry: ");
            Serial.println(retry);
            fatcowConnected = false;
        }
//        delay(10);                                      // delay before retry:
        --retry;
    }
}

//-----------------------------------------
//    Disconnect from Server as Client
//
//
void fatcowClose() {
    if (clientFatCow) {
        clientFatCow.stop();
        fatcowConnected = false;
    }
}


What the routines do;

void postLive(), simply pre-formats some real-time data into json formatted style. You can do this a different way as you please. You just need the php script on your server to understand your format. It then calls the main posting routine below, if successful, it increments a success counter else increments a un-successful counter which I use for debug stats.
I have other functions for other data.

bool postPage(char* thisData), does the hard work of actually using the POST method to send data to my host, where a php script pulls out the data and puts it into a SQL database.

void fatcowConnect(), makes a connection avec retries.
void fatcowClose(), closes the connection.

Be sure not to mix http_1.0 and http_1.1 requests together, as I see you do in your code section.

Then, from your main routine, all you need to do is set up a time based trigger that will call postLive(); and it all happens after that.
If you want some php with SQL code, let me know.

Hope this helps you out.

A bientôt,
Paul
« Last Edit: February 02, 2013, 01:55:25 am by rockwallaby » Logged


Lab
Offline Offline
Newbie
*
Karma: 0
Posts: 38
Arduino rocks
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Hi Rockwallaby,

It would be great if you could also post some parts of your PHP listener.

Thanks
Logged


Offline Offline
Newbie
*
Karma: 0
Posts: 26
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
iDroid wrote:
$_POST is used to get values from a HTML form element with a name that corresponds to the value inside the square brackets.
This is partly true, in that what you say is a method often used, but it is not the definition of the POST method.

Using the POST method, you simply place the data, not on the url, but within the body of the http request, whether that be a html form, or for example, json encoded data from an external server/client system like an Arduino. And as such it is possible to send what ever data you have from the Arduino to a server using this method. Using the POST method also allows you to send more data than the GET method.


Oh, never knew that. Thanks.
If that isn't the problem... Then what is?
Logged

Tasmania - Australia
Offline Offline
Sr. Member
****
Karma: 10
Posts: 298
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
iDroid wrote:
Oh, never knew that. Thanks.
If that isn't the problem... Then what is?

No problems, even I learn new things each day, much from other users here on the forum and from way too much googling  smiley-eek-blue

The other parts of the code royalldonkey has put together will be the problem.
His 'Type Content', mixing of http versions, and also I wonder about the following;
Code:
client.println(DatatoSend.length());
I am unsure if that will work, it looks like nice oop style, but I think you need to use the length function.
Also, the use of the 'String' data type is discouraged due to some issues, use a char array instead.

The code I have placed above is in my working Arduino and POST's to my sql database each 60 seconds.
The code I used is based on code developed by SurferTim.

@H2SO4
I will post a section of php with sql code up here shortly, just having first morning coffee  smiley-sleep

Regards,
Paul
Logged


Offline Offline
Full Member
***
Karma: 4
Posts: 209
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I've been wrestling with this (the OP's code), and all the standard examples, trying to get a connection established to a webserver.  The connection never succeeds.

I have found that this bit of code (at line 61 in EthernetClient.cpp) hangs up, getting a status of 21 instead of the SnSR::ESTABLISHED (17) it is looking for:

  while (status() != SnSR::ESTABLISHED) {
    delay(1);
    if (status() == SnSR::CLOSED) {
      _sock = MAX_SOCK_NUM;
      return 0;
    }
  }

I have tried changing SnSR::ESTABLISHED to have a value of 21 but still no luck getting connected.  Looking deeper, I can see the SPI code in W5100Class::read(uint16_t _addr) is indeed reading '21' from the W5100.

Beats me what's going wrong.  Accepting incoming connections from my browser--  communicating with the WebServer example code -- work just fine.

Looking at WireShark traces, there is evidence of the DHCP request being fufilled and an IP address being handed out.  THEN, a couple 'blackjack' port 1025 messages are sent from the arduino and that's it.

No idea what is going awry or what else to try to troubleshoot it.
« Last Edit: February 02, 2013, 10:56:17 pm by JohnHoward » Logged

Tasmania - Australia
Offline Offline
Sr. Member
****
Karma: 10
Posts: 298
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

John,

What are you attempting to do, to issue a GET or a POST to push data to a server?
From what you say, it seems you are using DHCP, and that the Arduino seems to be getting an IP address and then falls over, but have you tried not using DHCP and instead, specifying the IP parameters?
Could putting debug points (serial prints) in at strategic places help you, even in the library?
Could it be something in your router's configuration?

Are you using the latest version of the IDE together with the supplied libraries, not mixing compiler version with library versions?

It appears you have delved deeply into the problem and have an understanding of the EthernetClient library.
You mention;
Quote
Accepting incoming connections from my browser
Can you explain this more clearly, as I don't really understand what you mean here?

I am not sure what else to suggest at this time.

Paul
Logged


0
Offline Offline
Tesla Member
***
Karma: 114
Posts: 8919
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
I've been wrestling with this (the OP's code), and all the standard examples, trying to get a connection established to a webserver.  The connection never succeeds.

Below is some client test code you can try. Send an e from the serial monitor to make the get request.

Code:
//zoomkat 9-22-12
//simple client test
//for use with IDE 1.0.1
//with DNS, DHCP, and Host
//open serial monitor and send an e to test
//for use with W5100 based ethernet shields

#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address

char serverName[] = "web.comporium.net"; // zoomkat's test web page server
EthernetClient client;

//////////////////////

void setup(){

  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // no point in carrying on, so do nothing forevermore:
    while(true);
  }

  Serial.begin(9600);
  Serial.println("Better client test 9/22/12"); // so I can keep track of what is loaded
  Serial.println("Send an e in serial monitor to test"); // what to do to test
}

void loop(){
  // check for serial input
  if (Serial.available() > 0) //if something in serial buffer
  {
    byte inChar; // sets inChar as a byte
    inChar = Serial.read(); //gets byte from buffer
    if(inChar == 'e') // checks to see byte is an e
    {
      sendGET(); // call sendGET function below when byte is an e
    }
  } 
}

//////////////////////////

void sendGET() //client function to send/receive GET request data.
{
  if (client.connect(serverName, 80)) {  //starts client connection, checks for connection
    Serial.println("connected");
    client.println("GET /~shb/arduino.txt HTTP/1.0"); //download text
    client.println("Host: web.comporium.net");
    client.println(); //end of get request
  }
  else {
    Serial.println("connection failed"); //error message if no client connect
    Serial.println();
  }

  while(client.connected() && !client.available()) delay(1); //waits for data
  while (client.connected() || client.available()) { //connected or data available
    char c = client.read(); //gets byte from ethernet buffer
    Serial.print(c); //prints byte to serial monitor
  }

  Serial.println();
  Serial.println("disconnecting.");
  Serial.println("==================");
  Serial.println();
  client.stop(); //stop client

}

Logged

Consider the daffodil. And while you're doing that, I'll be over here, looking through your stuff.   smiley-cool

Tasmania - Australia
Offline Offline
Sr. Member
****
Karma: 10
Posts: 298
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Firstly, royalldonkey can you let us know of your progress, have you some success as yet?
@JohnHoward, please be mindful not to highjack the thread of royalldonkey, but if some of this helps out for you, that is good.

Here is a little bit of the php script I use to collect the data sent by the Arduino with the code posted a few posts up.
It listens with a switch statement depending on the type of http request, POST, GET, PUT or DELETE methods.

The following code details the workings for a POST message and decodes the JSON formatted data as sent by the Arduino and stores certain values to a real time single record database table as well as storing other values to a standard mult-record incrementing database table. Again, you don't need to use JSON, it is just that I do for pushing data around. I use CSV for pulling the data out for trends on the client side of things.

I have altered any specific information, and as such you need to specify SQL username, password and database and table names as for your own configuration.

Basic PHP code to run on a server with PHP and SQL installed.
Code:
<?php
//  date_default_timezone_set("Australia/Tasmania");
//  date_default_timezone_set('UTC');
//  echo date_default_timezone_get(), "\r\n";

    
$today date("Y-m-d H:i:s");        // 2001-03-10 17:16:18 (the MySQL DATETIME format)
    
echo $today"\r\n";
    
    
$data null;
    
//  Here we work out if we received a POST, GET, PUT or DELETE request from the client:
    
switch($_SERVER['REQUEST_METHOD']) {
        case 
'POST':
            
// post method
            
POST_sql();
            break;
        case 
'GET':
            
// get method
            
break;
        case 
'PUT':
            
// update method
            
break;
        case 
'DELETE':
            
// delete method
            
break;
    }
//-------------------------------------------------------------------
//  Arrive here if we received a POST message from the client:
//  And decide which POST message we received from the Arduino:
//  Data from Arduino is JSON encoded, so use php JSON decode:
//
    
function POST_sql() {
        
$rawdata file_get_contents('php://input');
        
$data json_decode($rawdatatrue);
//      echo "Raw: ", $rawdata,"\r\n";   // we can echo back the raw data received from Arduino:
        
        
$table $data['id'];
        
        switch(
$table) {
            case 
"live";
                
// update live:
                
liveTable($data);        // update live and trend tables:
                
break;
            case 
"stat";
                
// update live:
                
statTable($data);        // update stat table:
                
break;
            case 
"debug";
                
// update debug:
                
debugTable($data);       // update debug table:
                
break;
        }
    }
//-------------------------------------------------------------------
//  function liveTable updates two databases;
//  first is the real-time 'live' table,
//  second is 'trendSensor' table:
//
    
function liveTable($dataLive) {
//      vars from Arduino sent as integer, divided by scaling factor to store as floating point:
        
$vB_pv        $dataLive['vB_pv'] /100;        // Battery Voltage VDC:
        
$vT_pv        $dataLive['vT_pv'] / 10;        // Turbine Voltage VAC:
        
$iT_pv        $dataLive['iT_pv'] / 50;        // Turbine Charge Current in Amps:
        
$iS_pv        $dataLive['iS_pv'] / 50;        // Solar Charge Current in Amps:
        
$fT_pv        $dataLive['fT_pv'] / 100;       // Turbine Frequency in Hz:
        
$vT_cvPID     $dataLive['vT_cvPID'] / 10.23;  // Turbine PID Dump Load %:
        
$vS_cvPID     $dataLive['vS_cvPID'] / 10.23;  // Solar PID Dumpl Load %:

        
$myConnection mysql_connect('mydomain.mySqlHost.com''username''password');
        if (!
$myConnection) {
            die(
'mysql connect error: ' mysql_error() . "\r\n");
        }

//      update first database table, 'live', a single record table:    
//      Select the database 'live':
        
mysql_select_db(live$myConnection);
        
//      Prepare $sql_Live var for update of data into 'live' table:
        
$sql_Live="UPDATE live SET vB_pv = $vB_pv, vT_pv = $vT_pv, iT_pv = $iT_pv, iS_pv = $iS_pv, fT_pv = $fT_pv, vT_cvPID = $vT_cvPID, vS_cvPID = $vS_cvPID";

        if (!
mysql_unbuffered_query($sql_Live,$myConnection)) {
            die(
'mysql update live error: ' mysql_error() . "\r\n");
        }
        else {
            echo 
"mysql update live ok \r\n";
        }

//      update second database table, 'trendSensor', a multi-record table:
//      reference for the insert command - INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,...)
        
$t time() + 36000 3600;    // get current server time, add offset for AEST + DST, crude must do this better:
        
$sql_Trend="INSERT INTO trendSensor (time, vB_pv, vT_pv, iS_pv) VALUES ($t$vB_pv$vT_pv$iS_pv)";
        if (!
mysql_unbuffered_query($sql_Trend,$myConnection)) {
            die(
'mysql update trend error: ' mysql_error() . "\r\n");
        }
        else {
            echo 
"mysql update trend ok \r\n";
        }
        
mysql_close($myConnection);
    }

?>


With the above code and with the code for the Arduino installed, one can view the responses received by the Arduino on the serial monitor.
Have fun peeps.

Kind regards,
Paul
« Last Edit: February 03, 2013, 06:48:06 am by rockwallaby » Logged


Offline Offline
Full Member
***
Karma: 4
Posts: 209
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Royalldonkey, and others:  I continued to play with this, using the code from zoomkat to build something that would POST as you were POSTing.  I came up with this, which does work -- with a caveat (see below):

Code:
//zoomkat 9-22-12
//simple client test
//for use with IDE 1.0.1
//with DNS, DHCP, and Host
//open serial monitor and send an e to test
//for use with W5100 based ethernet shields

#include <SPI.h>
#include <Ethernet.h>

byte mac[] = {
  0xAA, 0xBB, 0xCC, 0xDD, 0xEF, 0x02 };  // Arduino MAC address
byte ip[] = {
  192, 168, 0, 11 };  // Arduino IP address
byte server[] = {
  192,168,0,13 }; // Directly address the web server
char serverName[] = "localhost.at-home";  // If used, will initiate a DNS lookup of web server
//String response;

EthernetClient client;

//////////////////////

void setup(){

  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // no point in carrying on, so do nothing forevermore:
    while(true);
  }

  Serial.begin(9600);
  Serial.println("Even better client test 02/03/13"); // so I can keep track of what is loaded
  Serial.println("Send a g to GET or a p to POST in serial monitor to test"); // what to do to test
}

void loop(){
  // check for serial input
  if (Serial.available() > 0) //if something in serial buffer
  {
    byte inChar; // sets inChar as a byte
    inChar = Serial.read(); //gets byte from buffer
    switch (inChar) {  // checks to see byte is an e
      case 'e': // Backwards compatibility
      case 'g': sendGET(); // call sendGET function below when byte is an e (or g)
                break;
      case 'p': sendPOST();
                break;
    }
  } 
}

//////////////////////////

void sendGET() //client function to send/receive GET request data.
{
  if (client.connect(serverName, 80)) {  //starts client connection, checks for connection
    Serial.println("connected");
    client.println("GET /arduino.php?test=data HTTP/1.0"); //download text
    client.println("Host: localhost.at-home");
    client.println(); //end of get request
  }
  else {
    Serial.println("connection failed"); //error message if no client connect
    Serial.println();
  }

  while(client.connected() && !client.available()) delay(1); //waits for data
  while (client.connected() || client.available()) { //connected or data available
    char c = client.read(); //gets byte from ethernet buffer
    Serial.print(c); //prints byte to serial monitor
  }

  Serial.println();
  Serial.println("disconnecting.");
  Serial.println("==================");
  Serial.println();
  client.stop(); //stop client

}//////////////////////////

void sendPOST() //client function to send/receive POST request data.
{
  if (client.connect(serverName, 80)) {  //starts client connection, checks for connection
    Serial.println("connected");
   
    Serial.println("POST /arduino.php HTTP/1.1"); //download text
    Serial.println("From: Arduino1");
    Serial.println("Host: localhost.at-home");
    Serial.println("User-Agent: HTTPTool/1.1");
    Serial.println("Connection: close");
    Serial.println("Cache-Control : no-cache");
    Serial.println("Pragma: no-cache");
    Serial.println("Expires: -1");
    Serial.println("Content-Type: application/x-www-form-urlencoded");
    Serial.print("Content-Length: ");
    Serial.println(31);
    Serial.println();
    Serial.println("data=ABCDEFGHIJKLMNOPQRSTUVWXYZ");
    Serial.println();

    client.println("POST /arduino.php HTTP/1.1"); //download text
    client.println("From: Arduino1");
    client.println("Host: localhost.at-home");  // Will be needed if apache is configured for VHOSTS
    client.println("User-Agent: HTTPTool/1.1");
    client.println("Connection: close");
    client.println("Cache-Control : no-cache");
    client.println("Pragma: no-cache");
    client.println("Expires: -1");
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.print("Content-Length: ");
    client.println(31);
    client.println();
    client.println("data=ABCDEFGHIJKLMNOPQRSTUVWXYZ");
    client.println();

    Serial.println("ARDUINO: HTTP message sent");
    delay(3000);
    if(client.available())
    {
      Serial.println("ARDUINO: HTTP message received");
      Serial.println("ARDUINO: printing received headers and script response...\n");

      while(client.available())
      {
        char c = client.read();
        Serial.print(c);
      }
    }
    else
    {
      Serial.println("ARDUINO: no response received / no response received in time");
    }

    client.stop();
  }
  else {
    Serial.println("connection failed"); //error message if no client connect
    Serial.println();
  }

  while(client.connected() && !client.available()) delay(1); //waits for data
  while (client.connected() || client.available()) { //connected or data available
    char c = client.read(); //gets byte from ethernet buffer
    Serial.print(c); //prints byte to serial monitor
  }

  Serial.println();
  Serial.println("disconnecting.");
  Serial.println("==================");
  Serial.println();
  client.stop(); //stop client

}
/* arduino.php

<?php
echo 
"hello there\r\n";

foreach ($_POST as $key => $value) {

echo "$key=$value\r\n";
}
?>


*/

What I could never do was talk to a webserver on the same subnet as my Arduino.  It has to be a configuration issue, but I can't figure it out.  I have my Arduino on 192.168.0.11 and webserver on 192.168.0.13.  The Arduino never connects to it.  If I simply change the address of the webserver to 192.168.100.1, it works like a champ.  If I use a serverName and reference something outside my local network, it works fine.

So other than that, my POST above should do what you are trying to do.

I hope someone can chime in a explain the wierdness with same-subnet connections.  I have verified the webserver is running and working.   It is just a normal apache 2.2 server.  Deep inspection of the code and the WireShark traces shows me the wiznet library simply never talks to the same-subnet server.
Logged

Pages: [1] 2   Go Up
Jump to: