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 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() {  
   request.ip = IPAddress(192,168,1,169);  
   request.port = 8080;  
 void printResponse(http_response_t &response) {  
   Serial.println("HTTP Response: ");  
 void getRequest() {  
   request.path = "/photon/time";  
   request.body = "";  
   http.get(request, response, headers);  
 void putRequest() {  
   request.path = "/photon/measurements";  
   request.body = "{\"measurementType\":\"static\", \"value\": 1000}";  
   http.put(request, response, headers);  
 void postRequest() {  
   request.path = "/photon/measurements";  
   request.body = "{\"measurementType\":\"static\", \"value\": 2000}";, response, headers);  
 void deleteRequest() {  
   request.path = "/photon/measurements/123";  
   request.body = "";  
   http.del(request, response, headers);  
 void loop() {  

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

No comments:

Post a Comment