Saturday 18 June 2016

Particle Photon: Making HTTP requests

One of the best features of the photon is the fact that it is wireless and can connect to the internet to integrate with other devices and services without requiring any extra components. Making HTTP requests from the photon is the most flexible way to send you data somewhere remote.

To make things as simple as possible, Particle have implemented a webhook system to reduce the amount of code you need to write to make an HTTP request. This is nice to have but it's actually not very hard to make requests straight from the photon, without requiring the extra hop into the Particle cloud.

There is a HTTP client available from the official libraries of the Particle Build IDE. You can also get the code from github if you want to write your code locally without using the cloud IDE. Using this library you can easily make requests.

Here is a (quite contrived) example of making a get, post, put and delete request every 10 seconds. I have a little scala web server running on 192.168.1.169:8080 listening for requests. You can find the scala code here.

 #include "application.h"  
 #include "HttpClient.h"  
   
 HttpClient http;  
 http_header_t headers[] = {  
    { "Content-Type", "application/json" },  
    { NULL, NULL }   
 };  
 http_request_t request;  
 http_response_t response;  
   
 void setup() {  
   
   Serial.begin(9600);  
   
   request.ip = IPAddress(192,168,1,169);  
   request.port = 8080;  
 }  
   
 void printResponse(http_response_t &response) {  
   Serial.println("HTTP Response: ");  
   Serial.println(response.status);  
   Serial.println(response.body);  
 }  
   
 void getRequest() {  
   
   request.path = "/photon/time";  
   request.body = "";  
   
   http.get(request, response, headers);  
   printResponse(response);  
 }  
   
 void putRequest() {  
   
   request.path = "/photon/measurements";  
   request.body = "{\"measurementType\":\"static\", \"value\": 1000}";  
   
   http.put(request, response, headers);  
   printResponse(response);  
 }  
   
 void postRequest() {  
   
   request.path = "/photon/measurements";  
   request.body = "{\"measurementType\":\"static\", \"value\": 2000}";  
   
   http.post(request, response, headers);  
   printResponse(response);  
 }  
   
 void deleteRequest() {  
   
   request.path = "/photon/measurements/123";  
   request.body = "";  
   
   http.del(request, response, headers);  
   printResponse(response);  
 }  
   
 void loop() {  
   
   getRequest();  
   postRequest();  
   putRequest();  
   deleteRequest();  
   
   delay(10000);  
 }  
   

If you connect the serial monitor you will see the responses come back:



No comments:

Post a Comment