Pages

Using Resin.io with Node-RED

I’ve been involved with Oxford Flood Network which is currently one of the showcase projects in the recently opened Digital Catapult Centre. For about a year now I’ve been using Node-RED, including developing the Twilio node for sending SMS. Node-RED is being used on the Raspberry Pi as a gateway between the sensor nodes and the backend systems. Building and managing one or two Raspberry Pi is a fairly simple task, but trying to replicate the build for each individual gateway soon becomes a major challenge.

I was at a recent IoT London meetup 37 where it had moved to a new venue and new sponsors. One of the new sponsors is Resin.io who claim to be Making hardware as easy to hack on as the cloud!. I was interested in seeing how Resin.io could be used to deploy changes to multiple Raspberry pi simultaneously and how it could be used with the Oxford Flood network deployments.

To get started you need to follow the basic getting started guide, I’m not going to repeat these steps here as they are documented well by Resin.io themselves. This will ensure that you have a working system and all your ssh keys are correct. They also provide example projects that demonstrate how to create applications running in Node.Js, Python, Java or .NET. What I am describing here is how you can develop Node-RED flows on one Raspberry Pi and push it to multiple Raspberry Pi with a few commands. It is possible to develop using another linux or windows system providing you don’t use any Pi specific file locations and features. As this project uses both of these, the development platform will be a Raspberry Pi.

Requirements

  • Raspberry Pi for development, Model B or B+ is recommended as we are using Ethernet
  • One or more Raspberry Pi for target deployment testing.
  • Compatible USB WiFi modules. I’ve used the Edimax modules successfully
  • SD and microSD memory cards for all the Pi, min 4GB, preferably Class 10 for speed.
  • Any additional hardware, e.g. wireless modules, LEDs etc that are used by your application

Setup Development environment

To develop your Node-RED flows you need your Raspberry Pi working correctly on your network, either connected via WiFi or Ethernet. If you’ve not got Node-RED installed then the instructions at Node-RED describe how to install it.

The git command is needed to manage the code repository and push the code to the Resin.io repository. If its not installed then install with:

sudo apt-get install git

You need SSH keys to authenticate against the Resin.io repository, again this is documented elsewhere, this time at Github. Skip the part where you add the keys to Github. Instead copy the contents of /home/pi//ssh/id_rsa.pub to the SSH key section of the Resin.io preferences option. If you have other keys on Resin.io, for example your github keys from when you initially registered then these can be either removed or left as is.

Create Resin.io App

Create the Resin.io app, in this case I’ve called it NodeRED. Currently only Raspberry Pi is available as the target device.

createapp

To create your devices you need to download a zip file containing the initial base system. This doesn’t do much other than indicate the device is online and able to talk to the Resin.io systems.

newdevice

The download has two options, Ethernet or WiFi. If WiFi is selected then you need to enter the connection details for your WiFi network.

downloadzip

When the zip files have been downloaded, add wifi or eth to the filename to indicate which version was downloaded. The files need to be written to a FAT32 formatted SD card. I have found using a tool called SDFormatter on Windows (link?) and selecting the resize options will restore previously used cards to the full size. Using something like 7-Zip on Windows you can extract the contents of the zip files to the root of the freshly formatted SD card.

Install to target device

The prepared SD cards should be put into a Raspberry Pi and then it can be powered on. The ACT or OK LEDs should flash occasionally as its preparing the SD card. If using a WiFi adaptor, then the LED in this should start to flash when it is connecting to the network. After a few minutes (upto 10!) a new device should appear on the Resin.io dashboard for your application, provided you entered the correct SSID and passphrase.

newdevices

The devices seem to be given random names which can be changed if you dont like what has been given as a default. Clicking through to the device will show more detail. For some reason its not showing an IP address, this could be because its on a local LAN. Something to check with Resin.io.

devicedetail

The page also has a log window which will show application logs when you have your application loaded onto the device. There is a handy IDENTIFY DEVICE button that causes the LED to flash on the selected device. Useful if you have number of identical looking devices.

devicedetail2

Setup Node-RED for device

The way applications are built is not the traditional package it up and deploy to the target. The scripts presented here are used to build an image that is created on the Resin.io system and transferred to the device once its been built. This is how I understand it to work.

The files to build a node.js application, which is what Node-RED is, are created in a git repository on your development Raspberry Pi. Firstly, create your git repository.

pi@raspberrypi ~ $ mkdir resin
pi@raspberrypi ~ $ cd resin
pi@raspberrypi ~/resin $ mkdir nodered
pi@raspberrypi ~/resin $ cd nodered
pi@raspberrypi ~/resin/nodered $ git init
Initialized empty Git repository in /home/pi/resin/nodered/.git/

Files can then be created in the repository using your favourite text editor.

pi@raspberrypi ~/resin/nodered $ ls
deps.sh flows_raspberrypi.json package.json README.md settings.js

deps.sh – This is basically a series of commands to install all the dependancies and packages required to get Node-RED running on the target device. The commands follow the installation instructions from the Node-RED Raspberry Pi page along with a number of other packages to resolve dependancy issues.

#!/bin/bash

set -o errexit

apt-get -q update
git clone git://git.drogon.net/wiringPi
cd wiringPi
./build
cd ..
git clone https://github.com/node-red/node-red.git
cd node-red
npm install wiring-pi
npm install js2xmlparser
npm install serialport
npm install feedparser
npm install –production

cp -f ../settings.js .
cp -f ../flows_raspberrypi.json .

flows_raspberrypi.json – Copy from your working flows file on your development Pi. The example flow I’ve used is to blink a LED connected to pins 6 and 11, once a second. If you have one connected you should see it start blinking when the application is fully loaded.

package.json – Copy from the Node-RED directory and make the follwoing change:

“scripts” : {
“preinstall”: “bash deps.sh”,
“start”: “node red.js”,
“test”: “./node_modules/.bin/grunt”
},

to

“scripts” : {
“preinstall”: “bash deps.sh”,
“start”: “node node-red/red.js -v”,
“test”: “./node_modules/.bin/grunt”
},

README.md – Simple readme to say what the project is.

settings.js – Copy from the Node-RED directory and make the following change to add the WiringPi functionality:

functionGlobalContext: {
// os:require(‘os’),
// bonescript:require(‘bonescript’),
// arduino:require(‘duino’)
}

to

functionGlobalContext: {
wpi: require(‘wiring-pi’)
// os:require(‘os’),
// bonescript:require(‘bonescript’),
// arduino:require(‘duino’)
}

The files should be added to the git repository:

pi@raspberrypi ~/resin/nodered $ ls
deps.sh flows_raspberrypi.json package.json README.md settings.js
pi@raspberrypi ~/resin/nodered $ git add *
pi@raspberrypi ~/resin/nodered $ git commit -m “First commit” [master (root-commit) 03a4c2d] First commit
5 files changed, 223 insertions(+)
create mode 100644 README.md
create mode 100644 deps.sh
create mode 100644 flows_raspberrypi.json
create mode 100644 package.json
create mode 100644 settings.js
pi@raspberrypi ~/resin/nodered $

The Resin.io remote endpoint needs to be added, the command for this is shown at the top of the Resin.io application page and looks something like this:

git remote add resin git@git.resin.io:yourusername/nodered.git

Next you can push your application to your devices. The first time you use this you may have to confirm the key from the host git.resin.io:

pi@raspberrypi ~/resin/nodered $ git push resin master
The authenticity of host ‘git.resin.io (54.165.162.194)’ can’t be established.
ECDSA key fingerprint is f3:d9:38:97:47.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added ‘git.resin.io,54.165.162.194′ (ECDSA) to the list of known hosts.
Enter passphrase for key ‘/home/pi/.ssh/id_rsa':
Counting objects: 7, done.
Compressing objects: 100% (7/7), done.
Writing objects: 100% (7/7), 3.94 KiB, done.
Total 7 (delta 0), reused 0 (delta 0)

At this point there may be a pause of a few minutes before anything else happens. It then starts to build the image and runs through the deps.sh script which may produce familiar output. Keep an eye out for any errors that could make the build fail. So far with this scripts I’ve not had a failure. If all is successful you should see:

—–> Image created successfully!
—–> Uploading image..
Image uploaded successfully!
To git@git.resin.io:yourusername/nodered.git
* [new branch] master -> master
pi@raspberrypi ~/resin/nodered $

The device status should change to downloading and the log window on the Resin.io device page should start to show that it is installing the application.

When complete you should then be greeted by a unicorn and a LED flashing on your Raspberry Pi!

unicorn

Expanding the device logs should give you a full log of what has been going on. The -v option was added to the node command line in order to output any missing module dependencies.

devicelog

Pushing new version of Node-RED

If you find there is an update to Node-RED but your flows haven’t changed then the easiest way to get the latest Node-RED onto your devices is to fake a change by adding a line to the README.md file, committing it and pushing to resin.io.

pi@raspberrypi ~/resin/nodered $ vi README.md
pi@raspberrypi ~/resin/nodered $ git commit -m “refresh” README.md
[master ffb8ae6] refresh
1 file changed, 2 insertions(+)
pi@raspberrypi ~/resin/nodered $ git push resin master
Enter passphrase for key ‘/home/pi/.ssh/id_rsa':
Counting objects: 5, done.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 300 bytes, done.
Total 3 (delta 2), reused 0 (delta 0)

Then sit back and watch the build happen.

And finally

As a final test, you can locate the IP addresses of your target devices and using a web browser access the IP address and port 1880 to view the Node-RED screen and the flow that was created.

In future, when you develop new flows on your development Raspberry Pi, to deploy them to all the connected devices its just a matter of updating the flows_raspberrypi.json file in the git repository, committing the changes and pushing the new version to Resin.io. If additional Node-RED modules are needed then these can be added to the deps.sh file in the same way as a regular Node-RED installation.

As Resin.io is still being developed, the screen layouts may be slightly different to those shown here.

The files used in my test repository are available on Github

Oxford Flood Network Sensor build

These are the first draft of the detailed build instructions for the V3 Oxford Flood Network river level sensor. The sensor uses an ultrasonic transceiver measure the distance from the sensor to the water. The changes in the water level are registered as changes in the distance measured. This can then be used to calculate the river depth at that point and over time can be used to track changes in the levels.

2014-06-16 19.46.09 2014-06-16 20.55.46
A kit of parts. THis includes the external antenna options and waterproof outdoor sensor. other parts needed are some hookup wire for the temperature sensor. Start by soldering the lowest components first, this is the u.FL connector that is only needed if you are using the external antenna.
2014-06-16 20.58.00 2014-06-16 21.00.33
Solder the R1 which is the 4K7, 1/4W resistor used with the temperature sensor. Followed by 100nF capacitors C4 and C5 (I forgot to renumber the parts before manufacture so some numbers appear missing)
2014-06-16 21.01.19 2014-06-16 21.02.46
The pair of 10 way header sockets should be soldered next. A tip is to only solder one end then make sure that it is straight and upright before soldering the rest of the pins. If not straight, just touch the soldering iron on the joint to re-align it. It should now look like this with the socket for the Ciseco RFu-328 module.
2014-06-16 21.03.28 2014-06-16 21.04.40
To use the external antenna, an additional pin and header must be cut from a spare socket/pin headers. This single pin and header should be fitted together. Insert the Ciseco RFu-328 module then put the header/pin into the PCB so it connects to the antenna pad on the RFu module. Solder the RFu module end first then turn other the PCB to solder the other side. The RFu-328 module can now be removed until assembly has been completed.
2014-06-16 21.05.46 2014-06-16 21.05.55
The new antenna connection header socket should look like this now. Another photo of build so far.
2014-06-16 21.06.59 2014-06-16 21.11.29
Not a clear photo of the new pin on the RFu-328 module. Continue the build soldering the 2N7000 Mosfet, header strip, FTDI connector, 100uF 10V electrolytic capacitor, temperature sensor connector and battery clips.
2014-06-16 20.43.26 2014-06-16 21.28.10
Completed board with RFu-328 fitted. Solder the 7 way right angle header pins to the ultrasonic sensor. It can go in from either side but having it over the label is the way it was done here.
2014-06-16 21.30.13 2014-06-18 21.40.13
Mark which end of the header pins is the GND connection as this should mate with the correct end of the The case, its lid and rubber seal.
2014-06-18 21.40.34 2014-06-18 21.43.54
The inside of the lid has ribs that will need to be partially removed later to allow the sensor to be mounted properly. Marking the centre of the lid ready for drilling. The lower mark is for the temperature sensor and should be towards the edge so as not to foul the ultrasonic sensor mounting nut.
2014-06-18 21.44.49 2014-06-18 21.55.06
A further mark on the side of the box for the external antenna hole. The sensor hole is best made with a 26mm or 27mm hole saw mounted in a pillar drill. I used 27mm as it is what I had available but 26mm would be a better fit.
2014-06-18 21.56.14 2014-06-18 21.56.55
Cutting the main hole. Inside the lid.
2014-06-18 21.58.07 2014-06-18 22.09.14
Both holes made in the lid. The temperature sensor hole is 6mm. The ribs were removed around the hole using a rotary tool with a cutting disk. Appropriate eye and dust protection should be worn as this can be a messy operation.
2014-06-18 22.14.07 2014-06-18 21.59.35
Fit the sensor with the rubber seal on the outside and the O Ring on the inside Fitting the antenna SMA connector. This is a 6mm hole.
2014-06-18 22.18.05 2014-06-18 21.20.05
SMA connector fitted. Use the shakeproof washers provided. (?? May need a spot of silicone sealant around it to make it watertight ??) Almost finished.
2014-06-23 20.14.45 2014-06-23 20.28.44
Parts to build the temperature sensor probe Solder blue wire to centre pin of DS18B20 temperature sensor and cover with heatshrink tubing then shrink using your preferred method (lighter, heat gun etc). Bend one of the outer pins over to meet the other and snip off a piece of pin.
2014-06-23 20.29.35 2014-06-23 20.31.39
Soler the two outer pins together and solder on the brown wire. Use the wider heatshrink tubing to cover all exposed pins and soldered joints.
2014-06-23 20.36.04 2014-06-23 20.38.42
Strip 3mm from the other end of the wires, crimp then solder the connections. Insert into the JST plug housing as shown.
2014-06-23 20.39.10  
When plugged in, the brown wore goes to - and the blue wire to +.  

Still to do:

  • Wiring and mounting Temperature sensor.
  • Alternative antenna options – Integrated and whip antennas
  • Alternative power options – 2AA cells with power pod or Single Tadiran cell
  • Mounting options – Internal magnets for steel bridges, brackets for bolting/screwing.
  • Configuring the sensor node address using the jumper links
  • Publish all the design files – Eagle schematic, PCB layout, Gerbers and Bill of materials.

What to do with surplus dev boards

I’ve been using Arduino boards for a few years now and it re-kindled my interest in microcontroller systems after having worked in the field quite a few years ago. Since then I’ve also used various Arduino compatible boards, shields and d-i-y boards, I’ve created libraries, published code and generally had a lot of fun with them. I’ve also used the ethernet connected Arduino compatible Nanode, dabbled with 32bit ARM architectures of the mbed products, tried the BeagleBone Black, had a brief affair with the Raspberry Pi and other development boards. With all these dev boards I’ve acquired quite a collection. With new boards coming along almost monthly and a change in my focus to more wireless connected devices, there is always something new to try. A lot of the older boards that I have stopped using still have a lot more life in them and would make ideal tools for a novice to learn about embedded micros if they find the purchase of new kit is outside of their means. Or for a small community group providing educational services based on Arduino and similar hardware. This is no way an attempt to undermine any sales of new boards but a way to provide new life for surplus boards. I’d urge everyone to buy at least one original Arduino board if you can afford it to show your support and enable them to continue the good work they are doing.

In the past year I’ve already given away at least 2 Arduino compatibe boards, the most recent was to a fellow attendee of the Thingmonk conference last year.

I’m sure I’m not the only one that has a large collection of boards that are feeling unloved and gathering dust in a box or drawer. After a few exchanges on Twitter I started to have an idea.

The Idea

After seeing the replies to my initial tweet it was going to be a difficult choice of what to do with the boards, who to send them to and what was a deserving cause. The replies included donating them to:

  • Local Hackspaces or Makerspace list of UK based spaces here
  • Schools for extra-curriculum clubs
  • Arduino workshops
  • Community projects
  • Just sell them on eBay
  • Give them to the first person who puts their hand in the air and says Me…Me…Me…

I’ve no idea if this is already being done anywhere in the UK or even the world. So lets see how much interest there is.

As it’s Arduino Day on 29th March 2014, celebrating 10 years of the Arduino I’d like to propose a global Donate a Dev Board scheme or event. The name probably needs work as I’m no marketing expert. There are numerous events going on around the world so this would be an ideal opportunity to share your used boards. If organisers of these events, or even if the Arduino ‘management’ would give the OK or even promote the donation of used boards to worthy causes this would help encourage less privileged people and especially youngsters to take an interest in this exciting world of Arduino and embedded micro controller boards. Although the idea is not limited to Arduino boards, they are ideal for teaching novices the basics and beyond. The range of mbed boards I would say are aimed more towards the more experienced user and are ideal for someone who has experience of the Arduino platform and wants to expand their knowledge and create bigger and better things with a more powerful platform.

The only rules I’d suggest for the dev boards being donated is that they must be fully functional, come with their original bootloader and sockets must not be damaged. Any shields donated must also include a link to where the new user can obtain the required library if it is not part of the core IDE.

I’m not sure if I’ll be able to attend an event, as much as I’d like to, so in support of this I have a number of boards that I’d like to donate. These are listed below.


Arduino Day 2014

My Boards

I have a number of Arduino, Arduino compatible and non-Arduino boards including:

2014-03-11 20.07.33

  • Arduino Due (not pictured)
  • Arduino Bluetooth
  • Mbed FRDM-KL25Z
  • Mbed NXP LPC800-MAX
  • ENC28J60 based ethernet shields for Arduino (x3)
  • 2.4″ TFT LCD Touchscreen
  • LPCXpresso 1768 board, not mbed abut uses version of eclipse ide
  • FEZ Mini .NET micro framework based

I’m sure I have more if I start digging deeper!

What’s next?

I’ve presented my idea, other ideas and suggestions are welcome. There are still a lot to work out, like who gets what, how to send or deliver it, who would run a scheme locally (hackspaces?), support etc. What’s the best way to continue this? Create a google group?

Comments appreciated.

Remote controlled LED Kitchen lights

Introduction

Over the Christmas and New year holiday I’ve been doing a little kitchen refurbishment. This included the usual repaint and replacement of cabinet doors and handles. As an extra I decided to add some additional lighting above the cabinets to illuminate the ceiling. This is achieved using a more than 5m of 12V RGB LED strips. This is the variety that produces the same colour for each LED and as a result is a much cheaper option than the individually addressable LED strips I have used previously. There are two parts to this project, the first being the LED driver, the second being the controller that sends new colour to the LED driver.

2014-01-04 20.54.25

Hardware

Prototype testing on breadboard with lots of jumper wires, IFRZ44N MOSFETs to drive the individual LED colours and 1K resistors for a bit of current limiting on the gate of the MOSFETs. The controller is a Ciseco XinoRF Arduino UNO compatible board with built in wireless transceiver module.
The LED strip is a commonly available on eBay, search for 5050 SMD RGB LED Strip. The ones I used are 5m in length with 150 RGB LEDs in total. It came with a small controller which can be used to test the strip is functioning.
2014-01-04 16.30.10
A quick layout done using Fritzing

Kitchen_LEDs_bb

Once the prototype was working on the breadboard, it was time to make it permanent on an Arduino compatible proto-shield from Ciseco. This sits on top of the Ciseco XinoRF board. As the LED strip required 12V I only wanted to use a single power supply. The XinoRF has a 3.3V regulator and 12V was at the top end of its range, to lower the voltage two IN4001 diodes were used to connect the 12V to the Xino RF VIN pin. This is then regulated by the 3.3V voltage regulator onboard. 2014-01-04 18.15.42
The device used to control the colour of the LED strip is yet another use of my wireless LCD display. This has software that described below. 2014-01-06 21.22.34

Control Commands

The communication between the LED Controller and the LED Driver is done using the Ciseco LLAP protocol. The commands implemented in the LED driver are:

Set new colour
Request:

aXXRGBrrggbb

Response:

aXXRGBOK—-

Request current colour
Request:

aXXRGB——

Response:

aXXRGBrrggbb

In the above, XX is the ID of the LED Driver, rrggbb is the hex value for the colour with each pair of values being in the hex range 00 to FF and representing the colours red, green and blue in that order.

Software

The software is in two parts, the LED driver and the LED controller.

LED Driver

The LED driver software receives commands wirelessly and sets the colour of the LEDs. The main features are:

  • Send starting message so that main hub knows this device is active
  • Responds to colour change commands by acknowledging them and changing the LED colour
  • Responds to current colour request command so that LED controller can determine what the current colour is
  • Saves the current colour in EEPROM and sets this colour when next powered on

LED Controller

The LED controller displays a set of 3 bars representing the three colours of the RGB LEDs. The colour is selected by moving the mini joystick up and down. The currently selected colour is highlighted. Moving the joystick left and right will increase or decrease the length of the coloured bar. This represents the intensity of the colour to be set on the LED driver. The colour change command is only sent to the LED driver when the joystick is released. The main features of the LED controller are:

  • Uses existing wireless hardware platform
  • Query LED Driver for current colours and set bars appropriately
  • Allow new colours to be selected and send them to the LED Driver

In use

A quick video showing the controller changing the colour of the LED strip.

Code

The code is not yet in a releasable state, there are a couple of things to tidy up such as the layout on the controller screen needs a few tweeks and the code needs clean up before I publish it.

Disclaimer

I use a lot of products from Ciseco but I don’t work for them, I’m just a customer who appreciates a good range of products that are developed in the UK. However I have over the years had a few freebies and samples from them. If you do want to get free stuff from their shop then check out this blog post.

2013 – Personally a great year!

Out with the old, in with the new. I’ll be sad to see 2013 go as for me personally it was a great year. I did a bunch of cool stuff, met loads of cool and interesting people and generally I’ve been living the freelancer dream!

Some of the things I have done or achieved this year, that I can remember, in no particular order:

  • Cleared all my loans and credit card debts and kept them clear, except mortgage.
  • Attended my first weekend music festival – Download2013 you were awesome!
  • Flying over the Download main arena on a zip-wire shouting Mother*****rs to the people below.
  • Had a great family holiday touring through France.
  • Dolphin watching in the Bay of Biscay while heading down to Bilboa.
  • A few weekends away in London with wifey and no kids – Quality time!
  • Visited UK MakerFaire in Newcastle.
  • Visited Elephant and Castle Mini MakerFaire.
  • Saw a couple of good cover band gigs.
  • Iron Maiden at the O2 were excellent second time seeing them this year!
  • Saw Avenged Sevenfold and Five Finger Death Punch at the LG Arena, Birmingham.
  • Saw Meatloaf – Like a Bat out of Hell!
  • Had a day of off-road motorcycling for the first time, must do it again.
  • Attended Over The Air 2013 at Bletchley Park, won IoT prize for the hack challenge.
  • Attended Thinkmonk IoT conference.
  • My parents celebrated 50 years of marriage.
  • Celebrated 19 years of marriage to my lovely wife.
  • My eldest turned 18 and still hasn’t bought me a pint yet!
  • My mother-in-law turned 80.
  • Built my first 3D printer – its the future!
  • Started to learn to use OpenSCAD to create 3D models for printing.
  • Made significant progress on my CNC cutter, but still not finished, one for 2014!
  • Celebrated the first anniversary of my company!
  • Attended the first SusHack hackday to kick off the Oxford Flood network – continuing this in 2014.
  • Did a brewery tour at the Wadworth brewery.
  • Drank a lot of beer, some good, lots great.
  • Drank a lot of wine but not much spirit this year.
  • Got a taste for Margaritas!
  • Successfully grew sweetcorn for the first time – those plants are tall.
  • Took over 40 days leave during the year, some to work on other projects. The joy of being a freelancer!
  • Contributed to the excellent Node-RED.
  • Learnt to use EagleCAD to design schematics and PCB layouts.
  • Had a lot of my PCBs professionally manufactured.
  • Bought a Quadcopter, now need to learn to fly it without crashing.
  • Had my first sit in an ambulance while being checked over after coming off bicycle.
  • Built lots of cool things including what could be most annoying IoT device – Bellduino!
  • …and anything else I’ve forgotten!

Many thanks to all the great people I’ve met along the way on my journey that was called 2013, you know who you are!

I’ll be raising a glass of something, beer, wine, cocktail or spirit to say “Here’s to 2014!”

Bellduino – The Internet connected handbell

I’ve recently been looking at alternative notification after seeing things like Bubblino created by Adrian McEwen, co-author of Designing the Internet of Things and the Cheerlights project from ioBridge labs. I had a gift ‘Ring for Beer’ bell that has been hanging around my desk for a couple of years now and decided to use this as the notification device. The first job was to decide how to ring it, the obvious solution would be a servo motor connected to an Arduino Ethernet or equivalent. The prototype uses a basic ATMega328 board and a shield containing a Wiznet Wiz820io module as this is what I had available to me at the time.

Update
I have also successfully used an old Nanode board (Arduino compatible ATmega328 with ENC28J60 Ethernet controller) to drive Bellduino. This was achieved using the Arduino_UIP library with a few minor modifications to the original sketch. So far this seems to be working quite well as a lower cost solution.

The following describes how I built Bellduino, but first, lets see it inaction:

Building the Frame

OpenBeam parts used for the frame:

  • 4 x 150mm extrusion
  • 2 x 90mm extrusion
  • 1 x 45mm extrusion
  • 4 x Corner joining plates
  • 5 x T joining plates
  • 4 x Feet
  • 1 x NEMA17 Stepper motor mount and 608 Bearing mount
  • 1 x Servo motor mount
  • 1 x Big bag of M3 nuts and screws
2013-12-28 11.27.48
The frame is made up as a rectangle with the bottom and top as shown below. Remember to insert enough M3 nuts into the extrusion for the various inner brackets and mounts if the ends of the extrusion are blocked by other pieces. The parts that need extra nuts adding are:

  • Bottom – 3 nuts for T-piece, same side as corner pieces
  • Top – 3 nuts in front slot for servo mounting plate, 3 on rear for T-Piece
  • Right – 3 nuts in rear slot for T-piece to mount Arduino
  • Left – 3 nuts in front slot for NEMA17 mounting plate
  • Right and Left – 2 nuts in outer slot for frame feet
2013-12-28 11.42.46
The support feet are attached using T-joining pieces. The plastic OpenBeam feet are fitted underneath to provide protection to the surface that Bellduino stands on. 2013-12-28 18.45.57
The Arduino or equivalent electronics are mounted using two T-joining pieces taking care to ensure the screws are not shorting any tracks, if in doubt, use fibre washers between the screw head and board. 2013-12-28 18.47.45

Bell Clamp

Using my 3D printer I printed out a clamp and actuator arm that I designed using OpenSCAD. This clamps to the bell, providing a hole at the back that was threaded after printing to take a M8 bolt. The clamp also provides an arm that can then be attached via a rod to the servo motor in order to ring the bell. 2013-12-28 18.33.30
The pivot for the bell is made up from a M8 bolt, 2 nuts and an old 608 skateboard bearing robbed from one of my kids skateboards (Must remember to put it back and source a replacement bearing!). This just sits in the bearing mount and as there isn’t a lot of weight on it a single bearing does the job adequately. 2013-12-28 18.35.28
Close up of the bell pivot. 2013-12-28 18.36.01
The actuating rod connecting the bell to the servo motor is made up from a 140mm strip of 8mm wide aluminium with a hole drilled in each end. Washers and double nuts locked together provide a smooth motion when the servo operates. 2013-12-28 19.16.10
I found that the bell wouldn’t ring properly due to the spring supporting the hammer being too strong. To fix this, a lump of blu-tak (or similar) was added to provide additional weight to the hammer. This solved the problem and it now rings on command. 2013-12-28 18.34.24
The finished Bellduino 2013-12-28 18.31.05

Software

The software runs on an Arduino Ethernet or equivalent and is basically an Arduino sketch that subscribes to a specific MQTT topic on my local server listening for any requests. It uses the Arduino MQTT client library created by Nick O’Leary, one of the co-creators of Node-RED.

As Bellduino subscribes to a MQTT topic, its just a matter of publishing to this topic in order to get it to ring. The easiest way to do this is to use Node-RED to produce the required MQTT publish request based on whatever input you want to use. The example I have at present is a twitter node that responds to the word ringmybell. A rate limiting delay node is included so that the bell is not continuously ringing.

ToDo

  • Publish bell clamp design files
  • Publish sketch for Bellduino – still a work in progress
  • Example Node-RED flows

Using Node-RED with Twilio

For a while now I’ve been using the most excellent Node-RED to provide a way of integrating my various sensors and devices around the house. One thing that was lacking is a general mobile control or status update facility. This could be achieved using browsers on smartphones or custom made Android or iOS apps. These have the problem that they take up resources, are platform specific and may not always work if there is no data signal available. Using SMS to receive notification and perform simple control and status request operations would therefore seem to be the ideal solution. There are a number of providers that provide an API to send SMS but this is all they do. Having a service that enabled both sending and receiving SMS plus the ability, if needed to use voice calls would be ideal. Such a service is provided by Twilio. You can sign up for free and try a limited version of the service. Once you upgrade and start paying for the service you can choose your own number instead of the number allocated originally. You can also have multiple numbers, there is no Twilio banner at the start of your SMS and no Twilio announcement at the start of each call.

Twilio

Twilio already provide extensive documentation and a number of libraries to use their service. They conveniently provide a helper library for Node.js so this was a perfect starting point for the Twilio node. The node I created is a basic output only node as this is what uses the helper library. The input side can be implmented using existing Node-RED nodes.

The Twilio node is currently not yet pary of the Node-RED package, but this is in progress.

The Node-RED Twilio output node

The Twilio output node is configured with a twiliokey.js file located in the directory (or folder) above node-red. This includes your Account-SID, Auth-Token and the telephone number that you will be sending SMS from.

2013-11-08 10.41.20

To send a SMS to a number, the topic parameter of the msg object must be set to the number, e.g. +4416358000xx and the payload parameter is the actual message that is to be sent.

In a simple test, you would use an inject node to create the msg topic and payload, this would feed directly into the Twilio node to send the SMS. How this is used would be up to your own imagination and requirements.

Receiving SMS

To receive and process SMS from Twilio is a little more involved, however there isnt a node for this and it can be easily implemented using the available Node-RED nodes. Input is handled using a http input node. This URL must be available to the Twilio servers so you may have to set up a dynamic dns service such as dyn.com to point to your IP address. Fortunately my BT HomeHub supports this service. in addition to this, you’ll also need to setup port forwarding to your internal Node-RED server. This URL mus then be configured in the Twilio Messaging Request URL field. The purpose of this URL is that it returns a TwiML XML file to tell Twilio what to send as a response.

The basic function to create the response message could be:

var messageObj = { "Message": "You sent: " + msg.req.query.Body } ;
msg.payload = messageObj;
return msg;

The JSON msg object must be converted to XML format using the json2xml node and specify a root element of Response. The final node is the http response node that then sends the reply to Twilio. Once Twilio receive the XML they will read the message and send the reply to the originator of the SMS. This could be as simple as a status update or an acknowledgement that the command had been processed.

The received message can be processed to look for key words and commands to perform actions such as returning the status of a switch or sensor or just acknowledging that a light was switched on as requested.

Example usage:
2013-11-08 17.16.56

The usage described here only relates to sending and receiving SMS, however it is possible with little more effort to use voice calls instead. I’ve done a simple test where the number is called and a voice reads a custom message. Other examples include having your computer call you up and tell you that a window has been opened on your property. The possibilities for communication with mobile devices in this way is only limited by your imagination.

Over The Air Hackday challenge

I recently attended the Over The Air mobile development conference at the historic Bletchley Park, Home of the Codebreakers. This was a superb event including talks and hackday challenges covering a variety of categories. The challenge lasted just over 24 hours and in this time teams and individuals had to come up with something that was fun, useful, clever or just plain stupid! I had decided to enter the Internet of Things category and here is a description of what I came up with during that time. The photos included here were taken at the time of the event and subsequently used in my 90 second presentation for the audience favourite.

The venue: Bletchley Park
2013-09-27 13.51.49

The hack idea

By the evening of the first day I still didn’t have nay idea as to what I was going to do, other than using Node-Red as a way of interconnecting a number of devices. I had taken a large box of Arduino, mbed boards, cables, components, sensors, pcbs, tools and devices. I was looking to do something with wireless sensors that I had taken with me but what, I wasn’t sure. I eventually came up with the idea to use the TFT LCD display I had built previously. This would become a display for the temperature and also the number of tweets detected with the hashtag #ota13. As an added feature I added some very bright addressable RGB pixel strips as everybody likes flashing lights!

Implementing the hack

The Hardware

The temperature sensor node is a pcb and Ciseco SRF module running the LLAP thermistor firmware. For demo purposes it was set to send the temperature reading every 60s. Full details of the sensor node are in a previous post.

2013-09-28 13.31.45

The display is based on a Ciseco RFu-328 which is basically a tiny Arduino with a SRF radio module in a surface mount form factor. The display is a cheap 128×160 SPI display. Its all put together on a PCB that I’d previously designed and had manufactured by Ragworm. A recent post describes the display. As an additional feature I decided to add a pair of Adafruit NeoPixel strips to provide an indication of the number of tweets seen. The connections for these had already been designed into the PCB, but up until this point, no sockets had been soldered on. The sketch used is available for download.

2013-09-28 13.31.36

To be able to receive temperature readings from the sensor and to send updates to the display I used a USB SRF Stick plugged into my laptop.

2013-09-28 13.32.02

The Software

The obvious choice for integrating the various bits of hardware and other systems is the new Node-Red, Node.JS application. The screen capture of the nodes may look like there are a lot of nodes in there but this includes many debug and inject nodes used for debugging and testing the application. I’d pre-installed Node-Red onto my Windows7 laptop and installed all the required libraries, making sure it actually ran too. So during the hack day, it was only a matter of dragging the appropriate nodes into place, linking them up and writing the functions to do all the clever bits.

node-red

The two main input nodes receive the LLAP input from the temperature sensor and search for new tweets with the hashtag #ota13. The input from the temperature sensor is formatted into a single message then directed to three (there is a fourth shown but this was not used in the hack) nodes that reformatted the data to a Xively datastream, sent it via the pushbullet.com api to my mobile phone and the third was to re-broadcast the temperature reading to the wireless display module. The second input node reads a twitter stream and filters on the hashtag #ota13. A count is incremented and the new value is sent to the wireless display. The code for the main nodes is shown at the end of this post.

The twitter input node was configured with my usual twitter name and I’d put ota13 into both the tags and topic boxes. I’m not sure this made much different as it didn’t seem to catch every tweet with the hashtag.

2013-09-28 13.33.11

The Xively output was setup to send the request to a newly created feed and datastream using the MQTT API. This is easy to setup using a MQTT output node, entering the hostname api.xively.com and using a topic of api_key/v2/feeds/feed_number/datastreams/0.csv. Where api_key is the API key for the feed with write permissions and feed_number is the number of the feed.

xively

Node-Red functions

These can be pasted into the function nodes to perform the given action. For some reason the code tags are not preserving the format.

Parse LLAP – input from temperature sensor


// name: Parse LLAP message
// outputs: 1
// anything stored in context is kept available for next time we get called
context.buff = context.buff || "";
context.count = context.count || 0;

// wait for an a and reset the buffer and counter
if (msg.payload == "a") { context.count = 0; context.buff = ""; } // this does mean the a must NOT appear elsewhere in the message

// add payload to the buffer and increase the count
context.buff = context.buff + msg.payload;
context.count += 1;
// when we reach 11 then output the whole message, assumes length is the a plus 11 - may need to tweak...
if (context.count == 12) {
msg.topic = context.buff.slice(1,3); // return the first two chars as the topic
msg.payload = context.buff.slice(3); // return rest of the buffer as the payload
return msg;
}
return null;

Format Xively – Output to Xively for logging


var msgType = msg.payload.substr(0,4);
if( msgType == "TMPA") {
// Create message
var value = msg.payload.substr( 4, 5);
// Strip any - chars
value = value.replace(/-/g,"");
var msgPayload = value;
var newMsg = { payload: msgPayload };

return newMsg;
}
return null;

Format Temperature for Pushbullet


var msgType = msg.payload.substr(0,4);
if( msgType == "TMPA" || msgType == "LVAL" || msgType == "BATT" ) {
// Create message
var value = msg.payload.substr( 4, 5);
// Strip any - chars
value = value.replace(/-/g,"");
var msgPayload = "Temperature is " + value + "C";
var newMsg = { payload: msgPayload };

if(msgType == "TMPA" && msg.topic == "T4" )
context.global.tempt4 = value;
else if( msgType == "TMPA" && msg.topic == "T2" )
context.global.tempt2 = value;

return newMsg;
}
return null;

Format LLAP to send to wireless display


var msgType = msg.payload.substr(0,4);
if( msgType == "TMPA" ) {
// Create message
var msgPayload = "aNPTMPR" + msg.payload.substr( 4, 5) + "-----";
var newMsg = { payload: msgPayload.slice( 0, 12 ) };

return newMsg;
}
return null;

Extract Hashtag to count tweets and send count to wireless display


var entities = msg.tweet.entities;
var hashtags = entities.hashtags;
var newMsg;
try {
var numTags = hashtags.length;
if( numTags > 0 ) {
var tagName = hashtags[0].text.toUpperCase();
else if( tagName == "OTA13" || tagname == "OTA2013" || tagName == "TESTOTA13" ) {
context.global.tweetcount++;
var count = context.global["tweetCount"] || 1;

var llap = "aNPTWOA" + count + "-----";
// Extract first 12 chars
newMsg = { payload: llap.slice(0,12) };
count += 1;
context.global["tweetCount"] = count;
return newMsg;
}

return null;

} else {
newMsg = { payload: "No tags" };
return null;
}
} catch(e) {
newMsg = { payload: e };
}
return null;

That’s it, the hack was entered into the Internet of Things category and won first prize, winning a Fez Spider starter kit worth about £200.
Look out for some .NET Gadgeteer posts!

My slides from the Over the Air presentation are available at SlideShare.

Using Node-Red with OpenRemote for basic home automation

I’ve recently been using a new tool that describes itself as “A visual tool for wiring the Internet of Things“. More details are available at their website http://nodered.org/. The idea is that ‘things’ can be brought together in a visual manner without any programming, although a little coding in JavaScript is needed in places. I’ve also been looking at OpenRemote to provide a tablet based front-end for home automation and monitoring. For this project I selected the D-I-Y approach using the open source version available from http://www.openremote.org/. MQTT is also being used as a message passing mechanism. The broker I use is the most excellent Mosquitto. This post described a basic setup for using Node-Red and OpenRemote to produce a simple tablet based control and monitor application. Full details of Node-Red, OpenRemote and Mosquitto are available on their websites and should be referred to for installation and configuration of these packages.

The components

I have a number of components that need to be linked together, these are on the hardware side:

  • 2 Channel wireless relay board, based on Ciseco SRF module
  • Linux server to run the stuff on
  • Ciseco XRF with FTDI interface connected to Linux server
  • Nexus 7 tablet

And on the software side:

  • Node-Red
  • OpenRemote controller and Android app
  • Mosquitto MQTT broker

Communications

Wireless communications is being done by the Ciseco SRF modules using the LLAP protocol described in detail here.

The relay boar id controlled by sending the command aRLRELAYAON- to turn on relay A on board with an ID of RL. The relay board will respond to indicate the state of the relay.

Within the server, the messaging broker will have topics that the various parts of the Node-Red application can subscribe and publish to. For example, to send new LLAP message, I would publish to a topic llap/send. Received messages from sensor nodes would publish to their own topics, for example llap/T4/TMPA or llap/T4/BATT which would be for the sensor node T4 where the temperature and battery voltage are published to.

One final part of the communications is to provide a basic HTTP interface to control the relays and provide feedback to the OpenRemote application.

Building the Node-Red application

Interfaces to wireless devices

The first part is to receive LLAP messages from the module plugged into the Linux server, this uses the Serial input node then builds up the complete 12 character message. The LLAP message is then split up by the second function before it is finally published to a MQTT topic. A number of debug nodes are included for debugging purposes and can be turned on and off at runtime to display messages being passed between the nodes. A number of values are also stored in the Node-Red global context variables for retrieval later.

NR-llap-receive

Code for the LLAP Parse function:

// name: Parse LLAP message
// outputs: 1
// anything stored in context is kept available for next time we get called
context.buff = context.buff || "";
context.count = context.count || 0;

// wait for an a and reset the buffer and counter
if (msg.payload == "a") { context.count = 0; context.buff = ""; } // this does mean the a must NOT appear elsewhere in the message

// add payload to the buffer and increase the count
context.buff = context.buff + msg.payload;
context.count += 1;
// when we reach 11 then output the whole message, assumes length is the a plus 11 - may need to tweak...
if (context.count == 12) {
msg.topic = context.buff.slice(1,3); // return the first two chars as the topic
msg.payload = context.buff.slice(3); // return rest of the buffer as the payload
return msg;
}
return null;

Code for LLAP to MQTT function:

// Topic is part set, now see if TMPA, LVAL or BATT msg

var msgType = msg.payload.substr(0,4);
if( msgType == "TMPA" || msgType == "LVAL" || msgType == "BATT" ) {
var newTopic = "llap/" + msg.topic + "/" + msgType;
var value = msg.payload.substr( 4, 5);
// Strip any - chars
value = value.replace(/-/g,"");
var newMsg = { topic: newTopic, payload: value };

if(msgType == "TMPA" && msg.topic == "T4" )
context.global.tempt4 = value;
else if( msgType == "TMPA" && msg.topic == "T2" )
context.global.tempt2 = value;

return newMsg;
}
return null;

The second part is to subscribe to the topic llap/send and pass the message out through the Serial out node and onto the wireless devices that would be listening for it.

NR-llap-send

The code for the LLAP format function:

var newMsg = { payload: "a" + msg.payload };
return newMsg;

I have additional nodes that take received LLAP messages, parse them and store the values in the global context for later retrieval.

Interface to Openremote

Next I provided a way to read the previously stored values in the Node-Red global context, this takes a URL of the form http://ip_address:1880/sensor?name=varname where varname is the name of one of the variables. The value is returned without any other formatting or markup. The values I’ve setup this way include temperature measurements, electricity usage and relay states.

readsensor

The code for the Get Reading function:

var name = msg.req.query.name;
var reading = context.global[name];
var newMsg = { payload: reading };

// Send http response
msg.res.send(200, reading );

return newMsg

In order to control the relay board I’ve setup another node to receive http requests of the form http://ip_address:1880/relaycontrol?relay=a&action=on. This will post a message to the MQTT Topic llap/send that will in turn be picked up by the nodes previously described and turn on the relay. Other options are to select either relay a or b and to turn them on, off or tog (toggle).

RelayControl

Code for the Relay To MQTT function:

var deviceId = "RL";
var cmd = "RELAY";
var id = msg.req.query.relay.toUpperCase();
var origAction = msg.req.query.action;
var action = msg.req.query.action.toUpperCase();
if(action == "ON") action="ON-";
var llap = deviceId + cmd + id + action;
var newMsg = { payload: llap };

// Send http response
msg.res.send(200, origAction );

return newMsg;

Building the OpenRemote Application

The OpenRemote Android or iPad application connects to the local controller to retrieve the details needed to draw the panels on the screen that perform the control actions defined using the OpenRemote designer. To start with, OpenRemote needs a number of components defining. These are the building blocks that provide the functionality for a particular device. In the example presented here, I have associted them with a device called Node-Red which is my linux server with Node-Red running on it. The components are:

  • Commands – Perform communication with a device using a variety of different protocols and methods and polling intervals
  • Sensors – Define asensor that uses a command to read a value, range of values or custom data
  • Switches – Select the commands to turn the device on, off and determine its state
  • Slider – Select a command to send a range of values depending on slider position

In the example below, I’m setting the http command to access the relay control node that was previously defined using Node-Red.If this was a slider command then parameters could be passed in the URL using parameter notation ${param}.

or-1

Once the commands, sensors and switches have been defined, you can start on the panel layout by adding labels, buttons and images to create your panel. Multiple panels can be created and accessed via a series of tabs or sliding from left to right. An background image can be used to create different effects and styles.

or-3

When using switches, you need to select both an ON image and an OFF image to show the switch or button state. The community version of the designer doesn’t come with any images so you need to provide your own. I used a couple of images found on the net but for my final design I’m looking to employ a graphic designer to work on new images and the user interface. But for now its not pretty but is functional. The switches are defined as shown in the image below, they need the name, sensor selected from the drop down of available sensors and the images to use for the on/off states.

or-2

Adding labels that have a sensor associated with them will draw the received value where the label is positioned. You need to remember to set a polling interval in the command setup otherwise your readings wont be updated.

This is only a small selection of what OpenRemote can do. I’ve not even explored the many protocols and devices it can control or the macros and rules that can help automate tasks. I’ll leave this for another time.

Testing the application

When the panels have been designed and you are happy with it then you need to sync the design with your controller. This can be done in an online or offline mode. Online is the most convenient method as you just need to select the controller url of the form http://server_ip:8080/controller then enter your OpenRemote designer username and password and click the Sync with Online Designer button.

The Android app is available in Google Play, however this is an old version, following the links on download page will get you the latest version. If you use your tablet and have the option to install software from non-marketplace sites then you should be able to download and install directly.
If all is well then you should see your panel appear on the tablet. The buttons should be selectable as shown in the demo video below.
If the switches fail to operate correctly then it could be down to the sensor part not working correctly as it appears the state of the switch needs to be correct for it to change the image and command used.

Quick Demo video

Listen for the Exterminate as its triggered by the relay board when the second round button is pressed.

Have fun if you decide to try this yourself.

Programming Ciseco SRF LLAP Firmware

I’ve been using a number of Ciseco SRF Radio modules recently, including designing my own PCBs to produce temperature sensors and button sensors. The firmware used is for the XRF range of devices, but as they use the same chip, the firmware will mostly work. There are one or two exceptions, plus the fact the XRF firmware is not supported by Ciseco when programmed onto the SRF modules. Firmware is available from Github repository.

The SRF is hooked up to my SRF programming jig. This is basically a number of spring loaded pins that provide power and the serial rx/tx signals for the SRF module.
2013-09-10 20.32.49

A FTDI cable was used to connect to my programming jig. The Ciseco XCM software is available from Openmicros.org, the Ciseco support site. The SRF are shipped with serial pass through firmware loaded, running at 9600 baud. Using the Download config option you can verify that the SRF is responding to commands.
2013-09-10 20.44.23

Once you are happy that the XCM software is communicating with the SRF, you can re-program the firmware. Select the Upload Firmware tab, select the image to use then press the 3 buttons in turn to Program, Verify and Commit the new firmware. Once the firmware has been committed, the SRF will restart. When the SRF starts, it will send a a–STARTED– message 5 times.

2013-09-10 20.47.24

Using the Download config option again should confirm the firmware has been uploaded.

Once the firmware has been uploaded, the SRF can be soldered onto your board.

TODO: On board re-programming.