Introduction
HTTP is a protocol that enables communications between clients and servers by setting up a request-response protocol between a client and server.A web browser can be a client, and an application on a computer that hosts a web site could be a server. If this is the case the browser submits an HTTP request to the server; then the server returns a response to the client. The response contains status information about the request and may also contain the requested content.
HTTP Request Methods
- GET - Requests data from a specified resource
- POST - Submits data to be processed to a specified resource
The GET Method
When you use get, you send a query string in the URL (exposing your names/values:/test/demo_form.asp?name1=value1&name2=value2
- GET requests can be cached
- GET requests remain in the browser history
- GET requests can be bookmarked
- GET requests have length restrictions
- GET requests should be used only to retrieve data
Graphing
from community.spark.io- binaryfrost- Core - with sensor(s) - that you expose using a Spark.variable
- Google account, so that you can access Google Drive
-
The following code uses JSON to format the data from the spark Core, so that it was already in a format that's easily parseable by the Google Apps Script.
To test, you can type this:
char resultstr[64]; void setup(){ pinMode(A0, INPUT); // setup A0 as analog input pinMode(A1, INPUT); // setup A1 as analog input // expose your char buffer to the Cloud API Spark.variable("result", &resultstr, STRING); } void loop(){ int data1 = analogRead(A0); // read some data int data2 = analogRead(A1); // some some other data // format your data as JSON, don't forget to escape the double quotes sprintf(resultstr, "{\"data1\":%d,\"data2\":%d}", data1, data2); delay(1000); // wait for a second }
You should see something like this:https://api.spark.io/v1/devices/YOUR-DEVICE-ID/result?access_token=YOUR-ACCESS-TOKEN
{ "cmd": "VarReturn", "name": "result", "result": "{\"data1\":23,\"data2\":26,}", "coreInfo": { "last_app": "", "last_heard": "2014-02-17T20:37:53.300Z", "connected": true, "deviceID": "YOUR-DEVICE-ID" } }
- Open Google Drive
- Create a spreadsheet.
- Open Tools -> Script Editor
- Add the code below, and make the appropriate chanages:
var response = UrlFetchApp.fetch("https://api.spark.io/v1/devices/YOUR-DEVICE-ID/result?access_token=YOUR-ACCESS-TOKEN"); try { var response = JSON.parse(response.getContentText()); // parse the JSON the Core API created var result = unescape(response.result); // you'll need to unescape before your parse as JSON try { var p = JSON.parse( result); // parse the JSON you created var d = new Date(); // time stamps are always good when taking readings sheet.appendRow([d, p.data1, p.data2]); // append the date, data1, data2 to the sheet } catch(e){ Logger.log("Unable to do second parse"); } } catch(e){ Logger.log("Unable to returned JSON"); }
- Select Resources -> Current Project's Triggers
- Select: collectData - Time Driven - Minutes Timer - Every 15 minutes
This connects to your spark Core every 15 minutes, parses the data returned, and appends it to the spreadsheet.
TIP: Don't make the frequency too frequent, otherwise the spreadsheet fills up pretty fast!! - Insert -> Chart, to create a graph that automatically updates as your data comes it.
Web Pages
Local html page
You can poll data from a local web page (you don't want it to be public because then you would expose your ID and access token.Tutorials derived from bko
- Create a web page:
<html> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8"></script> <body> <span id="temp"></span><br> <span id="tstamp"></span><br> <button id="connectbutton" onclick="start()">Read What you want to read</button> <script type="text/javascript"> function start(objButton) { document.getElementById("temp").innerHTML = "Waiting for data..."; document.getElementById("tstamp").innerHTML =""; var deviceID = "Your Device ID"; var accessToken = "Your ACCESS TOKENYour Spark variable"; requestURL = "https://api.spark.io/v1/devices/" + deviceID + "/" + varName + "/?access_token=" + accessToken; $.getJSON(requestURL, function(json) { document.getElementById("temp").innerHTML = json.result + "type of data bpm, °, etc (optional)"; document.getElementById("temp").style.fontSize = "28px"; document.getElementById("tstamp").innerHTML = json.coreInfo.last_heard; }); } </script> </body> </html>
- Save locally
- Preview the page.
Here is an example of how to control a servo motor attached to a core from a web page:
- Here is the core code:
Servo myservo; // create servo object to control a servo int pos = 0; // variable to store the servo position void setup(){ myservo.attach(A0); // attaches the servo on the A0 pin to the servo object Spark.function("setpos", setPosition); Spark.variable("getpos", &pos, INT); } void loop(){ } int setPosition(String posValue) { pos = posValue.toInt(); myservo.write(pos); return 0; }
- Here is a web page. Remember to run it locally!!!
<html> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8"></script> <body> <P>Set Servo Position:<br><br> <input type="range" name="degBox" id="degBoxId" min="0" max="180" step="1" value="90" list="myData" onchange="setValue(this)"> <!-- This adds the tick marks to the range but does not in Safari --> <datalist id="myData"> <option value="0"> <option value="30"> <option value="60"> <option value="90"> <option value="120"> <option value="150"> <option value="180"> </datalist> <br><br> <button id="minusbutton" onclick="fineAdjust(-5)">⇐ -5 °</button> <button id="plusbutton" onclick="fineAdjust(+5)">+5 ° ⇒</button> <br><br> <P>Current Position: <span id="curPos"></span><br> <script type="text/javascript"> var deviceID = " device id "; var accessToken = " access token "; var setFunc = "setpos"; var getFunc = "getpos"; window.setInterval(function() { requestURL = "https://api.spark.io/v1/devices/" + deviceID + "/" + getFunc + "/?access_token=" + accessToken; $.getJSON(requestURL, function(json) { document.getElementById("curPos").innerHTML = json.result + "°"; document.getElementById("curPos").style.fontSize = "28px"; document.getElementById("degBoxId").value = parseInt(json.result); }); }, 1000); function setValue(obj) { var newValue = document.getElementById('degBoxId').value; sparkSetPos(newValue); } function fineAdjust(value) { var currentValue = parseInt(document.getElementById('curPos').innerHTML); var setValue = value + currentValue; sparkSetPos(setValue); document.getElementById("degBoxId").value = setValue; } function sparkSetPos(newValue) { var requestURL = "https://api.spark.io/v1/devices/" +deviceID + "/" + setFunc + "/"; $.post( requestURL, { params: newValue, access_token: accessToken }); } </script> </body> </html>
- Save and test
Using publish()
This allows you to monitor up time. Here is the ino code:// publishme.ino -- Spark Publishing Example unsigned long lastTime = 0UL; char publishString[40]; void setup() { } void loop() { unsigned long now = millis(); //Every 15 seconds publish uptime if (now-lastTime>15000UL) { lastTime = now; // now is in milliseconds unsigned nowSec = now/1000UL; unsigned sec = nowSec%60; unsigned min = (nowSec%3600)/60; unsigned hours = (nowSec%86400)/3600; sprintf(publishString,"%u:%u:%u",hours,min,sec); Spark.publish("Uptime",publishString); } }
<!DOCTYPE HTML> <html> <body> <span id="uptime"></span><br> <span id="tstamp"></span> <br><br> <button onclick="start()">Connect</button> <script type="text/javascript"> function start() { document.getElementById("uptime").innerHTML = "Waiting for data..."; var deviceID = "YOUR DEVICE ID"; var accessToken = "YOUR ACCESS TOKEN"; var eventSource = new EventSource("https://api.spark.io/v1/devices/" + deviceID + "/events/?access_token=" + accessToken); eventSource.addEventListener('open', function(e) { console.log("Opened!"); },false); eventSource.addEventListener('error', function(e) { console.log("Errored!"); },false); eventSource.addEventListener('Uptime', function(e) { var parsedData = JSON.parse(e.data); var tempSpan = document.getElementById("uptime"); var tsSpan = document.getElementById("tstamp"); tempSpan.innerHTML = "Core: " + parsedData.coreid + " uptime: " + parsedData.data + " (h:m:s)"; tempSpan.style.fontSize = "28px"; tsSpan.innerHTML = "At timestamp " + parsedData.published_at; tsSpan.style.fontSize = "9px"; }, false); } </script> </body> </html>
Getting Help
The Spark Core is new, but there is an active community where you can find answers to many of your questions.Check out the Datasheet and the Firmware
Spark Core API
Every Spark Core has a URL, which can be used to GET variables, POST a function call, or PUT new firmware. The variables and functions that you have written in your firmware are exposed as subresources within the Spark Core.- List devices the currently authenticated user has access to.
GET /v1/devices
- Get basic information about the given Core, including the custom variables and functions it has exposed.
GET /v1/devices/{DEVICE_ID}
- Update the Core, including the display name or the firmware (either binary or source).
PUT /v1/devices/{DEVICE_ID}
- Request the current value of a variable exposed by the core
GET /v1/devices/{DEVICE_ID}/{VARIABLE}
- Call a function exposed by the core, with arguments passed in request body
POST /v1/devices/{DEVICE_ID}/{FUNCTION}
- // SYNTAX TO REGISTER A SPARK FUNCTION
Spark.function("funcKey", funcName);
- Spark.sleep() can be used to dramatically improve the battery life of a Spark-powered project by temporarily deactivating the Wi-Fi module, which is by far the biggest power draw.
Spark.sleep() can also be used to put the entire Core into a deep sleep mode.
The Core will automatically wake up and reestablish the WiFi connection after the specified number of seconds.Spark.sleep(int seconds); Spark.sleep(SLEEP_MODE_DEEP, int seconds);
Built in Libraries
Servo
This library allows a Spark Core to control RC (hobby) servo motors. Servos have integrated gears and a shaft that can be precisely controlled. Standard servos allow the shaft to be positioned at various angles, usually between 0 and 180 degrees. Continuous rotation servos allow the rotation of the shaft to be set to various speeds.// EXAMPLE CODE Servo myservo; // create servo object to control a servo // a maximum of eight servo objects can be created int pos = 0; // variable to store the servo position void setup() { myservo.attach(A0); // attaches the servo on the A0 pin to the servo object } void loop() { for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees { // in steps of 1 degree myservo.write(pos); // tell servo to go to position in variable 'pos' delay(15); // waits 15ms for the servo to reach the position } for(pos = 180; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees { myservo.write(pos); // tell servo to go to position in variable 'pos' delay(15); // waits 15ms for the servo to reach the position } }
RGB
This library allows the user to control the RGB LED on the front of the Spark Core.// EXAMPLE CODE // take control of the LED RGB.control(true); // red, green, blue, 0-255 RGB.color(0, 0, 0); // wait one second delay(1000); // resume normal operation RGB.control(false);
Check out some annotated examples
HTTP Server on the Core
Once compiled and flashed the server will be available at http://IP-SPARKCORE (port 80 by default)- Open the WEB IDE and add the following files:
- slre.h
- slre.cpp
- HttpResponse.h
- HttpResponse.cpp
- HttpRequest.h
- HttpRequest.cpp
- http_parser.h
- http_parser.cpp Download repository
- Compile and flash
- Open a browser and pastethe URL: http://IP-SPARKCORE