Skip to content

Instantly share code, notes, and snippets.

@ElectricImpSampleCode
Last active June 6, 2017 12:28
Show Gist options
  • Save ElectricImpSampleCode/c3580306bb8fadb7a8f869a4302a749d to your computer and use it in GitHub Desktop.
Save ElectricImpSampleCode/c3580306bb8fadb7a8f869a4302a749d to your computer and use it in GitHub Desktop.
Electric Imp imp API http.poststream() example
// CONSTANTS
const PLOTLY_USERNAME = "<your_username>";
const PLOTLY_KEY = "<your_key>";
const PLOTLY_TOKEN = "<your_token>";
// GLOBAL VARIABLES
// 'stream' will hold the httpstream object we create in initiateStream()
stream <- null;
dataCount <- 0;
// FUNCTIONS
function setupDataObject() {
// Define a Plot.ly Data Object and post it to the Plot.ly REST API
local data = [{ "x": [],
"y": [],
"type": "scatter",
"mode": "markers",
"stream": { "token": PLOTLY_TOKEN } }];
// Define a Plot.ly Layout Object
local layout = { "fileopt": "extend",
"filename": "time plot - staging" };
// Set up the initial request data payload
local payload = { "un": PLOTLY_USERNAME,
"key": PLOTLY_KEY,
"origin": "plot",
"platform": "electricimp",
"args": http.jsonencode(data),
"kwargs": http.jsonencode(layout),
"version": "0.0.1" };
local headers = { "Content-Type" : "application/x-www-form-urlencoded" };
local body = http.urlencode(payload);
local url = "https://plot.ly/clientresp";
local setupRequest = http.post(url, headers, body);
local setupResponse = setupRequest.sendsync();
server.log("Response after sending Plot.ly data object: " + http.jsonencode(setupResponse));
return setupResponse;
}
function initiateStream() {
// Set up the data stream
local headers = { "plotly-streamtoken": PLOTLY_TOKEN };
local url = "http://stream.plot.ly";
stream = http.poststream(url, headers, function(dummy){ server.log("Sent stream headers"); });
}
function streamData() {
// Prepare a data point to send
local now = date();
local seconds = now.sec * 1.0;
local minutes = now.min * 1.0;
local hours = now.hour;
local data = { "x": (hours + (minutes + seconds / 60) / 60),
"y": (minutes + seconds / 60) };
// Stream the data
// NOTE The appended newline is required
stream.send(http.jsonencode(data) + "\n");
// Have we sent 500 points?
dataCount++;
if (dataCount < 500) {
// Send the next data point in 10 seconds' time
imp.wakeup(10, streamData);
} else {
// Close the stream
local response = stream.closesync();
server.log("Response after closing the stream: " + http.jsonencode(response));
}
}
// PROGRAM START
// Set up the Plot.ly data object
local response = setupDataObject();
if (response.statuscode == 200) {
// If the data object was set up correctly, set up the stream
initiateStream();
// Now begin the data stream loop
streamData();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment