Reading Variables in JavaScript (browser)
In this section we will use in browser JavaScript with jQuery to learn how to read variables from our Spark Cores.
Documentation
As promised earlier each section will start with a documentation section. These sections are no different.
We will be accessing data from our Spark Cores using the Spark Cloud API. The Spark Cloud is a REST API which is extremely easy to use.
Also if you need help making requests from jQuery the relevant documentation
for $.get
(the jQuery method we’ll be using to retrieve data from the Spark
Cloud) can be found at:
List Devices
To list devices make a request to https://api.spark.io/v1/devices
and provide
your access token as a GET
variable.
$.get('https://api.spark.io/v1/devices', { access_token: ACCESS_TOKEN })
.then(function(res) {
for (var i in res) {
var device = res[i];
console.log(device.name);
}
});
Here is an example response from this request
[
{
"id": "53ff6f0650723",
"name": "plumber_laser",
"last_app": null,
"last_heard": null,
"connected": false
}
]
List Variables
You can also list the variables you have exposed on your Spark. The URL for this
query is https://api.spark.io/v1/devices/{DEVICE_ID}
. Below is some sample code
making this request
$.get('https://api.spark.io/v1/devices/' + DEVICE_ID, { access_token: ACCESS_TOKEN })
.then(function(res) {
console.log(res);
});
{
id: "54ff6f066678554927290168",
name: "test",
connected: true,
variables: {
"my_var": "int32"
},
functions: [
"digitalread",
"digitalwrite",
"analogread",
"analogwrite"
],
cc3000_patch_version: "1.29",
last_heard: "2015-04-30T03:00:26.870Z"
}
Get Variable’s Value
To actually get the value of a variable you make a request to
https://api.spark.io/v1/devices/{DEVICE_ID}/{VARIABLE_NAME}
. As you probably
expect by now example code is below
$.get('https://api.spark.io/v1/devices/' + DEVICE_ID + '/' + VARIABLE_NAME, { access_token: ACCESS_TOKEN })
.then(function(res) {
console.log(res.name, res.result);
});
And of course an example response from the above code:
{
cmd: "VarReturn",
name: "test",
result: 42,
coreInfo: {
last_app: "",
last_heard: "2015-04-30T03:03:06.718Z",
connected: true,
last_handshake_at: "2015-04-30T03:02:34.107Z",
deviceID: "54ff6f066678574927290167"
}
}
Time To Hook Up A Sensor
Now that we can read variables from our Spark Core it’s time to make those variables interesting by hooking up a sensor.