Javascript talking to littleBits Cloud API

LittleBits is a set of components that allow kids to build their own electrical circuits. The Cloudbit will send and receive values from the Internet.

For this project we wanted to build some Web pages with Javascript that could interact with the littleBits Cloud API.

littleBits Hardware Setup

cloudbit_setup

The Cloudbit enables an input to be sent to the Internet, and it will receive a value (output) from the Internet. For a test setup we used a dimmer bit to adjust the input value with a number bit to show the value. On the output side we used a bargraph bit. Other combinations of bits are possible. The key is to be able to test and see your input and output values.

Cloudbits Setup

For the Cloudbit setup you will need to create a sign-in on the littleBits web site. For details on how to setup your Cloudbit use the following link.

The Cloud API is a RESTful interface, that uses http requests with some header definitions. Before you get started you’ll need your specific littleBits device ID and authorization token. In your specific Cloudbit definition go to the Settings icon, and get your Device ID and AccessToken.

littlebit_id

Cloudbit Rest API – First Example Testing with curl

The Cloudbit API reference can be found at : http://developers.littlebitscloud.cc/#devices. 

The Cloudbit API is based on the REST API standard, and this means that an HTTP request is made with some extra parameters that are passed in the header. The most important header item is the littleBits authorization token.

Curl is command line software tool that allows you to issue an HTTP request with header and method parameters and it returns the results in a text format. Curl is available for Windows, OSX and Linux. As an example to query the CloudBit API to get all my devices the following command is issued (note you’ll need to enter your own authorization code) :

curl "https://api-http.littlebitscloud.cc/v2/devices" \
-H "Authorization: Bearer 4f3830b44e1d4b2789b50b0xxxxxx"

[
{"label":"twinbit",
"id":"00e04c0379bb",
"subscriptions":[],
"subscribers":[],
"user_id":118217,
"is_connected":true,
"input_interval_ms":200}
]

Javascript Device Monitor

The curl example can be done in Javascript using the Javascript built in XMLHttpRequest object.

A monitor page can be useful if you have a number of Cloudbits and you’re interested is checking their status. Below is a sample web page and the associated HTML/javascript code. It’s important to note that text that is returned needs to have the first few characters removed in order to have a clean JSON string.

js_status

<!DOCTYPE html>
<html>
<body>
<h1 id='title'>Cloudbit Status Monitor</h1>
<h2>
Label : <font color='red' id='LB_label'></font><br>
Is Connected : <font color='red' id='is_connected'></font><br>
</h2>
 
<script>
var xhttp = new XMLHttpRequest();
// change the authtoken to match your settings
var authtoken = "4f3830b44e1dxxxxxxxxxxxxxxxx";
var theURL =  "https://api-http.littlebitscloud.cc/devices/";
xhttp.open("GET", theURL, true);
xhttp.setRequestHeader("Accept","application/vnd.littlebits.v2+json");
xhttp.setRequestHeader("Authorization", "Bearer " + authtoken);
xhttp.onreadystatechange = function() {
  if (xhttp.readyState == 4 ) { // when the response is complete get the data
    // remove leading "[" and trailing ']'
    var theresponse = xhttp.responseText.substring(1, xhttp.responseText.length -1);
    var lb_data = JSON.parse( theresponse );  
    
    document.getElementById('LB_label').innerText =  lb_data.label;
    document.getElementById('is_connected').innerHTML = lb_data.is_connected;
  }
}
xhttp.send();
</script>

</body>


</html>

Read Value Example

Reading a CloudBit value is a little tricky because the data is returned as a stream that updates every second. I saw a lot of people asking for a single point read, so hopefully this will be available soon.

The read value HTTP request is a little more complex than the simple monitor device example because you need to include the device that you are querying and a head parameter of :  Accept: application/json.

A curl example would be:

curl -XGET "https://api-http.littlebitscloud.cc/v2/devices/00e04c0379bb/input" -H "Authorization: Bearer 4f3830b44e1d4b2789b50b09cb493f06750b968cff5d45331c75006025fa0dc9" -H Accept: application/vnd.littlebits.v2+json"

data:{"type":"input","timestamp":1543536039623,"percent":6,"absolute":66,"name":"amplitude","payload":{"percent":6,"absolute":66},"from":{"device":{"id":"00e04c0379bb","mac":"00e04c0379bb"}}}

data:{"type":"input","timestamp":1543536039650,"percent":6,"absolute":65,"name":"amplitude","payload":{"percent":6,"absolute":65},"from":{"device":{"id":"00e04c0379bb","mac":"00e04c0379bb"}}}

...

For an HTML/Javascript single point read the key to check the xhttp.readyState == 3 , this will catch the first streamed response.  Below is a single point example with code.

js_in

<!DOCTYPE html>
<html>
<head>
<title>littleBits Get Input</title>
<script>
var theinput = 0;

function get_input() {
// update with your deviceid and authtoken
  var deviceid = "00e04c0379bb";
  var authtoken = "4f3830b44e1d4b27xxxx";
  var theurl = "https://api-http.littlebitscloud.cc/devices/";
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {

    if (xhttp.readyState == 3 ) {
	  	var datapackage = xhttp.responseText.split("\n\ndata:");
		var lb_data = JSON.parse( datapackage[1] );		 
		document.getElementById("thevalue").innerText =  lb_data.percent;
		xhttp.open("GET","",true);
		xhttp.send();
    }
  }
  xhttp.open("GET", theurl + deviceid + "/input", true);
  xhttp.setRequestHeader("Accept","application/json");
  xhttp.setRequestHeader("Authorization", "Bearer " + authtoken);
  xhttp.send();
}
</script>
</head>
<body>

<h1 id='title'>littleBit Get Input</h1>
The value : <font id="thevalue"> XXXX </font>
<button type="button" onclick="get_input()">Request data</button>
<br>

</body>
</html>

Output Example

A CloudBit output can be either sustained or it can be timed out. The curl command is:

curl "https://api-http.littlebitscloud.cc/v2/devices/yourdevice_id/output" \
  -X POST \
  -H "Authorization: your_auth_code" \
  -H "Content-type: application/json" \
  -d '{ "percent": 100, "duration_ms": 3000 }'

For an HTML/Javascipt web the http response is a POST, and the value’s percent and duration are put into a JSON string:

var params = JSON.stringify({duration_ms: duration,percent: thevalue});

An example page and code is shown below:

js_out

<!DOCTYPE html>
<html>
<body>
<h2>CloudBit Output Test</h2>
<button type="button" onclick="sendoutput()">Send Output</button>
<br>
<pre>
Output Time (ms): <input type="text" id="duration" value="-1"/> (constant = -1)</br>
Output Value	: <input type="text" id="thevalue" value="80"/> (percent 0-100)</br> 
</pre>
<p id="demo"></p>


function sendoutput() {
	var xhttp = new XMLHttpRequest();
        // change to your device id
	xhttp.open("POST", "https://api-http.littlebitscloud.cc/devices/00e04c0379bb/output?", true);
	xhttp.setRequestHeader("Accept","application/vnd.littlebits.v2+json");
	// change to your Auth Token
	xhttp.setRequestHeader("Authorization", "Bearer 4f3830b44e1d4b27xxxx");
	xhttp.setRequestHeader("Content-Type","application/json");

	var duration = document.getElementById("duration").value;
	var thevalue = document.getElementById("thevalue").value;

	var params = JSON.stringify({duration_ms: duration,percent: thevalue});

	xhttp.onreadystatechange = function() {
		document.getElementById("demo").innerHTML = "Result=" +xhttp.responseText;
	}

	xhttp.send(params);
}


</body>
</html>

Gauges

Once you’ve got the basics down it’s possible to start making some more advanced applications. There are lot of Javascript charting libraries. For this example I used the Google  Charts library.

js_gauge

<html>
  <head>
   https://www.gstatic.com/charts/loader.js
   
	  var littleBitinput = 0;
      google.charts.load('current', {'packages':['gauge']});
      google.charts.setOnLoadCallback(drawChart);
      function drawChart() {

        var data = google.visualization.arrayToDataTable([
          ['Label', 'Value'],
          ['littleBits', 100],
        ]);

        var options = { 
          width: 600, height: 600,
          redFrom: 90, redTo: 100,
          yellowFrom:75, yellowTo: 90,
		  greenFrom: 60, greenTo: 75,
          minorTicks: 5
        };

        var chart = new google.visualization.Gauge(document.getElementById('chart_div'));

        chart.draw(data, options);

        setInterval(function() {
		  get_input();
          data.setValue(0, 1, littleBitinput);
          chart.draw(data, options);
        }, 500);
 
      }
	  function get_input() {
	  // change to your deviceid and authtoken
		  var deviceid = "00e04c0379bb";
		  var authtoken = "4f3830b44e1d4b27xxx";
		  var theurl = "https://api-http.littlebitscloud.cc/devices/";		  
		  var xhttp = new XMLHttpRequest();
		  
		  xhttp.onreadystatechange = function() {
			if (xhttp.readyState == 3 ) {
				var datapackage = xhttp.responseText.split("\n\ndata:");
				var lb_data = JSON.parse( datapackage[1] );		 
				littleBitinput =  lb_data.percent;
				xhttp.open("GET","",true);
				xhttp.send();
			}
		  }
		  xhttp.open("GET", theurl + deviceid + "/input", true);
		  xhttp.setRequestHeader("Accept","application/vnd.littlebits.v2+json");
		  xhttp.setRequestHeader("Authorization", "Bearer " + authtoken);
		  xhttp.send();

}
    
  </head>
  <body>

 

Final Comment

There are some great projects that you could do with littleBits and the CloudAPI.

One still project I did was to use smoothie charts http://smoothiecharts.org/ for the real time charts.

lb_chart2

 

 

 

 

Python talking to littleBits Cloud API

LittleBits is a set of components that allow kids to build their own electrical circuits. The Cloudbit will send and receive values from the Internet.

For this project we wanted to build some Python programs that could interact with the littleBits Cloud API.

littleBits Hardware Setup

cloudbit_setup

The Cloudbit enables an input to be sent to the Internet, and it will receive a value (output) from the Internet. For a test setup we used a dimmer bit to adjust the input value with a number bit to show the value. On the output side we used a bargraph bit. Other combinations of bits are possible. The key is to be able to test and see your input and output values.

Cloudbits Setup

For the Cloudbit setup you will need to create a sign-in on the littleBits web site. For details on how to setup your Cloudbit use the following link.

Python Basic Setup

The Cloud API is a RESTful interface, that uses http requests with some header definitions. Before you get started you’ll need your specific littleBits device ID and authorization token. In your specific Cloudbit definition go to the Settings icon, and get your Device ID and AccessToken.

littlebit_id

 

The Cloud API presently does not support a single point read (this might change), instead the input data point value is streamed about once a second.

The basic syntax in Python to get values from the  Cloud API will be:

import requests

requests.packages.urllib3.disable_warnings()

# Change with your Authorization code and deviceID
authToken = "4f3830b44e15fa0d"
deviceId = "00e04c"

headers = {"Authorization": "Bearer " + authToken,"Content-type": "application/json"}

# For a read 
littleBitsUrl = "https://api-http.littlebitscloud.cc/devices/" + deviceId + "/input"
r = requests.get(littleBitsUrl, headers=headers, stream=True)

#  For a write, note: a data body needs to be defined
# littleBitsUrl = "https://api-http.littlebitscloud.cc/devices/" + deviceId + "/output"
# body = {"percent": thevalue , "duration_ms": thetime} 
# thebody = json.dumps(body)
# r = requests.post(littleBitsUrl, data=thebody, headers=headers)

To do a read of the Cloud API an get request is done, to do a write a post request is used.

Python Read Value Example

The cloud API will stream the input value about every second in a format something like:

data: {"type":"input","timestamp":1521587206463,"percent":61,"absolute":629,"name":"amplitude","payload":{"percent":61,"absolute":629},"from":{"device":{"id":"00e04c0379bb","mac":"00e04c0379bb"}}}
{"type":"input","timestamp":1521587206463,"percent":61,"absolute":629,"name":"amplitude","payload":{"percent":61,"absolute":629},"from":{"device":{"id":"00e04c0379bb","mac":"00e04c0379bb"}}}

This data stream will need to be massaged with the following steps:

  • decode the stream (UTF-8)
  • remove the leading data: , (the remain message will be JSON formatted).
  • load the remain string into a JSON object

Below is some example code, for an app with a slider.

lb_tk_input

#
# lb_input.py - read input from a Cloudbit device
#
import json
import requests

requests.packages.urllib3.disable_warnings()

# Change with your Authorization code and deviceID
authToken = "4f3830b44e1d4b27xxxxxx"
deviceId = "00e04c03xxxx"

littleBitsUrl = "https://api-http.littlebitscloud.cc/devices/" + deviceId + "/input"

headers = {"Authorization": "Bearer " + authToken,"Content-type": "application/json"}
r = requests.get(littleBitsUrl, headers=headers, stream=True)

for line in r.iter_lines():
   strmsg = line.decode("utf-8").strip()
 
   print("Str: ",strmsg)
   if len(strmsg) > 0:
      lb_data = strmsg.split('data:')[1]
      print(lb_data)
      result = json.loads(lb_data)
      thevalue = result['percent']
      lb_bar.set(thevalue)
      thetime = str(datetime.datetime.fromtimestamp(result['timestamp']/1000))
      lb_time['text'] = "Time : " + thetime[:-7]
      root.update()

The Cloud API passed the time stamp as a numeric value with microseconds. The time can be cleaned with:

thetime = str(datetime.datetime.fromtimestamp(result['timestamp']/1000)) 
time_no_micro_seconds = thetime[:-7]

Python Output Value Example

The Cloud API output uses a post method and unlike the input example there is no streaming.

The new output value and a pulse time is sent in the post data parameter. The value is from 0-100, and a pulse time is -1 for sustained, otherwise a millisecond pulse time is used.

Below is some sample code for a Tkinter app:

lb_tk_output

from Tkinter import *
import json
import requests

# update your auth Token and device ID
authToken = "4f3830b44e1d4b27xxxx"
deviceId = "00e04c03xxxxx"

littleBitsUrl = "https://api-http.littlebitscloud.cc/devices/" + deviceId + "/output"

headers = {"Authorization": "Bearer " + authToken, "Content-type": "application/json"}

def setvalue():
	thevalue = lb_value.get()
	thetime = lb_duration.get()
	body = {"percent": thevalue , "duration_ms": thetime}
	thebody = json.dumps(body)
	print body, thebody
	r = requests.post(littleBitsUrl,  data=thebody, headers=headers)
	print r
     

root = Tk()
root.title('littleBits Output')

Label(text = "Value (0-100) :",width=30).grid(row=0,column=0)
lb_value = Entry(root, width= 10)
lb_value.grid(row=0,column=1)
Label(text = "Duration (ms) (constant=-1) :",width=30).grid(row=1,column=0)
lb_duration = Entry(root, width= 10)
lb_duration.grid(row=1,column=1)


Button(root, text=' Set Output ', bg='silver', command=setvalue).grid(row=2,column=1)

root.mainloop()

Final Comments

There are a lot of simple applications and projects that can be created with Python and some littleBits. One of the limitations on the Cloudbit is that it only sends 1 value and receives 1 value. If you are dealing with digital signals it would be possible to do some multiplexing.

littleBits Paddleboat

We made a few versions of the littleBits paddleboat, using bluetooth, IR (infrared with TV remotes) and wireless Ethernet (ESP8266) for control.

For sure the easiest approach is to use a litteBits wireless transmitter and receiver. This method is a hardware only solution and no software/coding is required.

For the wireless littleBits approach the following items are required:

  • 1x littleBits mounting plate (comes with base set)
  • 1x littleBits fork module ($12)
  • 2x littleBits dimmer($8) or slide switches ($10)
  • 2x littleBits power module with battery ($6)
  • 2x littleBits DC motors (o5) ($19)
  • 1x ittleBits wireless transmitter (w12) Bit ($40)
  • 1x wireless receiver (w11) Bit ($40)
  • 2x wire Bits
  • duct tape
  • thin card board
  • tupper ware

Paddleboat Circuit

The paddleboat circuit had the two DC motor bits connected to the wireless receiver bit. A power bit was connected to the input of the receiver bit.

motor1

PaddleBoat Construction

We tried a few designs for the paddle boat, so experiment to find out what works best for you. The most important thing about the design is the paddles, they need to be waterproof and long enough to touch the water. The first step is to cut four rectangles out of thin card board (cereal or cracker box). For our design we used 2″x4.745″ (5cm x12cm). We cut even slits half way in each paddle blade, so that the two pieces would fit together. Next we put the paddles into the littleBits motor attachment and covered them in duct tape (you need to make sure the card board is completely covered).

construction_steps

A 6″ (15 cm) wide dish would fit the littleBits mounting plate, and we used duct tape on the bottom and side to secure things in place. We found that our boat floated a little higher than we wanted so you might need to add some weight.

tupperware

Remote Control

We connected the power module to a fork module and then the fork module powered our dimmer modules. We mounted all the components on a littleBits mounting plate, and we taped the battery to the back.

frontremote

backremote

Final Testing

Despite the fact that the motors do not turn very fast we were quite surprised how well the boat worked. The motors have a “left” and “right” toggle switch. This toggle switch is used to set the forward direction.

 

 

littleBits/Pi Temperature Monitor

By using littleBits Proto modules it is possible to create Raspberry Pi projects with littleBits components. On this project we created a temperature monitor with a local indication and a remote Web page using Node-Red.

The parts used were:

  • 1 Raspberry Pi 3
  • 1 Explorer Hat (used for Analog Inputs)
  • 2 littleBits Proto bits
  • 1 littleBits Temperature bit
  • 1 littleBits Number bit
  • 1 littleBits Wire bit (optional, used for easier wiring)

The Wiring

To complete the littleBits circuit the first Proto bit was wired with 5V to the VCC and the data connectors. Pi GND was wired to the module’s GND. The second Proto bit had the data pin with to the Explorer HAT analog input 1.

tempcircuit

Node-Red Logic

On the Pi, the following Node-Red nodes were used:

  • Explorer Hat Node – reads the analog input
  • Function Node – only pass on analog input 1
  • Smooth Node – removes noise and jitter
  • Function Node – converts 0-5V to 0-100 C

temp_logic

The logic for the first function node, (to pass only analog input 1), was:

 if (msg.topic == "explorerhat/analog.1"){
return msg;
} 

We added a smooth node to remove noise in the analog input signal. The configuration that we used for the smooth node was:

temp_smooth

The logic for the second function, (to convert the voltage to a temperature), was:

msg.payload= (100/5)*msg.payload;
return msg;

Finally we used a Chart Dashboard node to show the results on a Web page. Our configuration for this was:

temp_gauge

To view the Web page use the URL of : http://the-pi-address:1880/ui

 

littleBits/Pi Internet Radio

The littleBits Proto bit allows littleBits components to be directly to connected to a Raspberry Pi (or Arduino).

The Goal

The goal of this project was to play Internet Radio and use littleBits to:

  • start the music, (and possibily change the music)
  • control the volume
  • use the littleBits speaker

For this project we used:

  • 2 Proto Bits
  • 1 Fork Bit
  • 1 Button Bit
  • 1 Slide Dimmer Bit
  • 1 Speaker Bit
  • 1 Bargraph Bit (optional)
  • 1 Wire Bit (optional)

The Wiring

music_setup

For the littleBits to Pi wiring, the input to the Fork Bit needs to have 5V on both the power and data pins, the GND pin of the Proto Bit is wired to GND on the Pi.

music_circuit

The output on the littleBits Button bit is wired into GPIO 23 on the Pi.

The Logic

For the logic we used Node-Red, Python would have probably been a better choice, but we wanted to see if it could improve our Node-Red skills.

To play Internet music we need to load the Node-Red mpd node:

cd $HOME/.node-red
npm install node-red-contrib-mpd

The Node-Red logic used only 3 nodes:

  • 1 – Raspberry Pi input node, to read button push
  • 1 – Function node, to do some action on the button push
  • 1 – MPD Output node, to play Internet Radio

radio_logic

There are a lot of possible options for what the littleBits button could do. For this example we simply wanted to load an Internet Radio URL, and then start playing. To find Internet Radio stations go to: https://www.internet-radio.com/.

music_func

The function node had a context variable, issetup,  that was used to load the music for the first time and then start playing.

// create an "is setup" variable
var issetup = context.get('issetup')||0;

if (msg.payload == "1") {
// if the setup hasn't been run, add a radio station playlist
if (issetup === 0) {
context.set('issetup',1);
var msg0 = { payload:"clear"};
var msg1 = { payload:"add http://185.33.21.112:11029" };
var msg2 = { payload:"play" };
return [ [ msg0, msg1, msg2] ];
}
}

littleBits Remote MP3 Player

For the remote MP3 Player project we used:

  • 1 –  power module with battery
  • 1 – littleBits wireless receiver
  • 1 – littleBits MP3 Player ($50)
  • 1 –  littleBits synth speaker ($20)

We created wireless remote to have a dimmer bit to control the volume and a littleBits button ($8) to change the song.

On the MP3 Player module the mode switch needs to be set to next to enable the remote button switch to change the songs. Finally we connected a speaker wire between the MP3 player and the speaker module and we duct taped the batteries to the bottom of the mounting plates.

littleBits Rover

Create a remote control littleBits rover using the littleBits wireless transmitter (w12) Bit ($40) and the wireless receiver (w11) Bit ($40). These wireless bits can also be  found in some of the littleBits kits, (for example the Gizmo and Gadgets kit).

The wireless modules can pass up to 3 signals. Depending on what you are trying to remotely control you could mix and match between dimmers, buttons and toggle switches. If you add some littleBits proto modules you could come up with some interesting designs.

Step 1 : Build the Remote

To create the wireless remote for the a Rover we needed to control the left and right motors , for this we used the following components:

  •  1- littleBits mounting plate (comes with base set)
  • 1 – littleBits fork module ($12)
  • 2 – littleBits dimmer($8) or slide switches ($10)
  • 1 – littleBits wireless transmitter
  • 1-  littleBits power module with battery ($6)

We connected the power module to a fork module and then the fork module powered our dimmer modules. We mounted all the components on a littleBits mounting plate, and we taped the battery to the back.

frontremote

backremote

The littleBits motor circuit is quite simple, the only important thing is to ensure that you have the wheels turning in the same direction.

motor1.png