Maker.io main logo

How To Post Data using the Particle Photon

2019-06-24 | By Maker.io Staff

Photon

The Particle Photon is a fantastic prototyping platform for creating IoT projects, and with internet communication being all the rage, there are many different communication methods to choose from. In this article, we will learn how to post data to a simple website using the Particle Photon and learn a bit about HTTP.

What is HTTP?

HTTP stands for HyperText Transfer Protocol and simply involves commands and data that allow users to obtain web pages or submit data to a webpage. HTTP also includes codes depending on the order of the command, as well as plenty of metadata, but this often depends on the server that is sending a response.

Unlike protocols such as MQTT, HTTP is a client-driven communication method where the client initiates all transfers and servers only respond; an HTTP server never forms a connection with a client, nor does it send data if not asked to by the client. HTTP is almost always used on port 80; however, a private system could use any port by a user as long as that port is unused by any other server or service.

The internet is a very complex structure of connections and layers that allow two devices to send messages to each other. The protocol that is used to connect and transfer data between two devices is called IP and often comes in the forms of UDP and TCP.UDP sends a bunch of data packets randomly, hoping that they reach the receiver, while TCP forms a handshake and ensures that all data packets arrive in the correct sequence.

However, from a programmer’s perspective, UDP and TCP are rarely dealt with; instead, when a connection is formed, it appears as a simple serial port. Data can be both sent down and received from the port. For example, a programmer who forms a connection with a server could send the string “Hello world” and the server would receive this exact string. How this data is interpreted and acted upon is what HTTP describes, and using HTTP is simpler than you think!

Basic HTTP structure

Devices communicating over HTTP often use one of two commands: GET and POST. GET is used to get the contents of a file, while POST is used to submit a value to a page (typically a PHP page). GET does not typically take any data, whereas POST takes both a variable (the data that is to be assigned to that variable) and some other metadata describing the nature of the data being sent. When either command is executed, the server responds with a code that indicates if the command was successful. If the command sent was GET, then the server also sends the contents of the file being requested. Below are some of the codes that a server can respond with:

  • 200 – Server understood and has completed the command
  • 403 – Server says its forbidden to access that location
  • 404 – Server could not find the page that is trying to be accessed
  • 500 – Server failed for unknown reasons

All HTTP packets (which include commands, codes, metadata, and data) are all terminated with a double carriage return line feed (\r\n\r\n), and each line in an HTTP message is terminated with a carriage return line feed.

GET

The GET command is used to obtain data from a server. A simple HTTP message is shown below (including carriage return line feeds). Note that the last line is a carriage return line feed, and this is immediately after the previous carriage return line feed, which indicates the end of the HTTP message.

How To Post Data using the Particle Photon

The response for a typical GET command (which returns the contents of a HTML file, for example) is shown below. You will notice that this message has two carriage return line feeds, with the first one indicating the end of the HTTP server message and the second indicating the end of the file contents of dataValue.html. This use of two carriage return line feeds can be used to quickly parse data from the server response message with the use of a string split (where the splitting character is either a double carriage return line feed or an indexOf() function, which can point to where the double carriage lines lie in the message).

How To Post Data using the Particle Photon

POST

The POST message is used to send data to a website, which often involves sending a value to a form or PHP script. The POST message has some additional metadata needed by the server to correctly process the data, including the type of content and how many bytes that content is. The example below shows a typical POST message that sends the string “10” to a variable called “number” on the PHP script found on submit.php.

How To Post Data using the Particle Photon

The PHP script for the submit.php page is below and demonstrates how the variable “number” in the POST message is extracted and then saved to the dataValue.html page.

 

Copy Code
<?php
	$dataValue = $_POST["number"];
	$Write="<h1>#" . $dataValue . "#</h1>";
	file_put_contents('dataValue.html',$Write);
?>

Particle Photon Example

Copy Code
TCPClient client;                           	// Create TCP Client object
byte server[] = { 185, 176, 40, 75 }; 		// http://maker-io-iot.atwebpages.com/
byte dataBuffer[1024];
 
String receivedData;
 
void setup() 
{
    Serial.begin(9600);
}
 
 
void loop() 
{
    // GET Message
    if(client.connect(server, 80))
    {
        // Print some information that we have connected to the server
        Serial.println("**********************************!");
        Serial.println("New GET Connection!");
        Serial.println("Connection OK!");
                
        // Send our HTTP data!
        client.println("GET /dataValue.html HTTP/1.0");
        client.println("Host: maker-io-iot.atwebpages.com");
        client.println();
        
        receivedData = "";
 
        // Read data from the buffer
        
        while(receivedData.indexOf("\r\n\r\n") == -1)
        {
            memset(dataBuffer, 0x00, sizeof(dataBuffer));
            client.read(dataBuffer, sizeof(dataBuffer));
            receivedData += (const char*)dataBuffer;
        }
        
        // Print the string
        Serial.println(receivedData);
 
        // Stop the current connection
        client.stop();
    }  
    else
    {
        Serial.println("Server connection failed. Trying again...");
    }
    
    
    // POST Message
    if(client.connect(server, 80))
    {
        // Print some information that we have connected to the server
        Serial.println("**********************************!");
        Serial.println("New POST Connection!");
        Serial.println("Connection OK!");
                
        // Send our HTTP data!
        client.println("POST /submit.php HTTP/1.0");
        client.println("Host: maker-io-iot.atwebpages.com");
        client.println("Content-Type: application/x-www-form-urlencoded");
        client.println("Content-Length: 9");
        client.println();
        client.print("number=10");
        
        receivedData = "";
 
        // Read data from the buffer
        
        while(receivedData.indexOf("\r\n\r\n") == -1)
        {
            memset(dataBuffer, 0x00, sizeof(dataBuffer));
            client.read(dataBuffer, sizeof(dataBuffer));
            receivedData += (const char*)dataBuffer;
        }
        
        // Print the string
        Serial.println(receivedData);
 
        // Stop the current connection
        client.stop();
    }  
    else
    {
        Serial.println("Server connection failed. Trying again...");
    }    
    
    delay(1000);
}

 

TechForum

Have questions or comments? Continue the conversation on TechForum, DigiKey's online community and technical resource.

Visit TechForum