Lelylan Lab

Learn how to control and monitor your lights from mobile, tablet and desktop.
15 minutes | $36 (eth) or $44 (WiFi) in hardware | basic level

Hardware

For this tutorial you need a Raspberry Pi connected to the Internet, either via ethernet (Model B) or via WiFi using a compatible WiFi USB dongle. To configure the network access on your Raspberry Pi have a look at this tutorial.

To complete this tutorial you need the following components.

Components Buy Price Quantity
Raspberry Pi (Model B+) Farnell $35.00 1
Edimax EW-7811Un (optional) Amazon $8.00 1
Push button Component packs $0.35 1
Led Component packs $0.35 1
10K Ohm resistor Resistor kit $0.25 1

Software

To program your Raspberry Pi you need to install a compatible GNU/Linux distribution from the Raw Images list section (if new to this checkout this guide) and the following libraries.

Library Notes
paho-mqtt This library enables the communication between Lelylan and the Rasp by creating a MQTT client in Python.
pip install paho-mqtt

Hardware Setup

This schema represents the led, resistor and pushbutton setup. With this setup each time you press the button, the LED is turned on and off.

Lelylan Setup

Open Lelylan Dashboard and create a new device by following 3 simple steps (if you are new to Lelylan, you can sign up for free).

1) Set a meaningful name (e.g. bedroom light).

2) Choose the device type. For this tutorial choose Basic Light.

What is a type? A type defines what a device is by defining its properties, functions and statuses. For this tutorial you do not need to now more about.

3) Choose "Connect with MQTT" as connectivity option.

In this tutorial we'll use MQTT, a publish subscribe protocol for the Internet of Things.

4) Get the Device ID and Device Secret.

Once the device is created, click the settings link (placed under the device name) and get the device ID and device secret. You'll need them in the next section.

Code

Once the (virtual) device is defined on Lelylan you need to make it communicate with the Raspberry Pi. Copy the Python sketch below and change <DEVICE-ID>, <DEVICE-SECRET> and <CLIENT-ID> with your device credentials. Save the sketch in a file named lelylan_light.py and run it as super user: $ sudo python lelylan_light.py.

import paho.mqtt.client as paho
import RPi.GPIO as GPIO
import json, time
# device credentials
device_id = '<DEVICE_ID>' # * set your device id (will be the MQTT client username)
device_secret = '<DEVICE_SECRET>' # * set your device secret (will be the MQTT client password)
random_client_id = '<CLIENT_ID>' # * set a random client_id (max 23 char)
# -------------- #
# Board settings #
# -------------- #
buttonPin = 7
ledPin = 12
GPIO.setmode(GPIO.BOARD) # use P1 header pin numbering convention
GPIO.cleanup() # clean up resources
GPIO.setup(ledPin, GPIO.OUT) # led pin setup
GPIO.setup(buttonPin, GPIO.IN) # button pin setup
# --------------- #
# Callback events #
# --------------- #
# connection event
def on_connect(client, data, flags, rc):
print('Connected, rc: ' + str(rc))
# subscription event
def on_subscribe(client, userdata, mid, gqos):
print('Subscribed: ' + str(mid))
# received message event
def on_message(client, obj, msg):
# get the JSON message
json_data = msg.payload
# check the status property value
print(json_data)
value = json.loads(json_data)['properties'][0]['value']
if value == 'on':
led_status = GPIO.HIGH
GPIO.output(ledPin, GPIO.HIGH)
else:
led_status = GPIO.LOW
GPIO.output(ledPin, GPIO.LOW)
# confirm changes to Leylan
client.publish(out_topic, json_data)
# ------------- #
# MQTT settings #
# ------------- #
# create the MQTT client
client = paho.Client(client_id=random_client_id, protocol=paho.MQTTv31) # * set a random string (max 23 chars)
# assign event callbacks
client.on_message = on_message
client.on_connect = on_connect
client.on_subscribe = on_subscribe
# device topics
in_topic = 'devices/' + device_id + '/get' # receiving messages
out_topic = 'devices/' + device_id + '/set' # publishing messages
# client connection
client.username_pw_set(device_id, device_secret) # MQTT server credentials
client.connect("178.62.108.47") # MQTT server address
client.subscribe(in_topic, 0) # MQTT subscribtion (with QoS level 0)
# ------------ #
# Button logic #
# ------------ #
prev_status = GPIO.LOW
led_status = GPIO.LOW
updated_at = 0 # the last time the output pin was toggled
debounce = 0.2 # the debounce time, increase if the output flickers
# Continue the network loop, exit when an error occurs
rc = 0
while rc == 0:
rc = client.loop()
button = GPIO.input(buttonPin)
if button != prev_status and time.time() - updated_at > debounce:
prev_status = button
updated_at = time.time()
if button:
led_status = not led_status
button_payload = 'off'
if led_status == GPIO.HIGH:
button_payload = 'on'
# effectively update the light status
GPIO.output(ledPin, led_status)
payload = { 'properties': [{ 'id': '518be5a700045e1521000001', 'value': button_payload }] }
client.publish(out_topic, json.dumps(payload))
print('rc: ' + str(rc))

You are done

Access Lelylan Dashboard and control your connected light from mobile, tablet and desktop. If any problem occours, let @lelylan know.

Code Explained

To better understand how the Raspberry Pi sketch works, follows a brief description of what most important sections do.

GPIO Setup

Set GPIO mode to BOARD and set pin mode for the led and the button pins. This will import the necessary libraries in the GPIO namespace and set the pin numbering to correspond to your breakout board.

GPIO.setmode(GPIO.BOARD) # use P1 header pin numbering convention
GPIO.cleanup() # clean up resources
GPIO.setup(7, GPIO.OUT) # led pin setup
GPIO.setup(12, GPIO.IN) # button pin setup
view raw gistfile1.py hosted with ❤ by GitHub

MQTT Callbacks

When a user updates a device status using Lelylan Dashboard a message is published to the topic devices/<DEVICE-ID>/get (in topic) and it's received from the Raspberry PI through the on_message function.

Every message exchanged with Lelylan is made up by a list of properties where each of them contains the property ID and the property value. For the "basic light" type we only have the light status property which has ID 518be5a700045e1521000001 and accepts the values on and off.

What we do is to check the received message and parse the JSON to see if the status property is on or off. Based on this value, the light is turned on or off and a message is sent back to Lelylan to confirm that the physical changes were successfully applied (if not, the device will keep being pending).

def on_message(obj, msg):
# get the JSON message
json_data = msg.payload
# check the status property value
value = json.loads(json_data)['properties'][0]['value']
if value == 'on':
led_status = GPIO.HIGH
GPIO.output(7, GPIO.HIGH)
else:
led_status = GPIO.LOW
GPIO.output(7, GPIO.LOW)
# confirm changes to Leylan
client.publish(out_topic, json_data)
view raw gistfile1.py hosted with ❤ by GitHub

Device Credentials

To make the Raspberry PI communicate with Lelylan create a new MQTT client passing a MQTT client ID as param, a random string not longer than 23 bytes used to identify your Raspberry Pi.

client = mosquitto.Mosquitto('<CLIENT-ID>') # * set a random string (max 23 chars)
view raw gistfile1.py hosted with ❤ by GitHub

The device_id and device_secret are used to authenticate the physical object (Raspberri PI) with Lelylan. To get the device credentials open the Dashboard, select the desired device, click on settings and copy the Device ID and the Device Secret.

device_id = '<DEVICE-ID>' # * set your device id (will be the MQTT client username)
device_secret = '<DEVICE-SECRET>' # * set your device secret (will be the MQTT client password)
view raw gistfile1.py hosted with ❤ by GitHub

Lelylan uses MQTT, a publish subscribe protocol for the Internet of Things. To make Lelylan communicate with Raspberry Pi you need to set two topics: one receiving messages from Lelylan (in_topic) and one sending messages to Lelylan (out_topic). These topics are unique and identified by the device id.

in_topic = 'devices/' + device_id + '/get' # receiving messages
out_topic = 'devices/' + device_id + '/set' # publishing messages
view raw gistfile1.py hosted with ❤ by GitHub

MQTT Connection

Set the Lelylan MQTT server credentials and the MQTT server IP where to connect. Once the connection is completed, the MQTT client subscribes to the in_topic. This way the on_message callback function is called every time a message is received from Lelylan.

client.username_pw_set(device_id, device_secret) # MQTT server credentials
client.connect('178.62.108.47') # MQTT server address
client.subscribe(in_topic, 0) # MQTT subscribtion (with QoS level 0)
view raw gistfile1.py hosted with ❤ by GitHub

Button logic

Here we define the loop function where we use a pushbutton as a switch. Each time you press the button the led is turned on or off. To make it work we need to add a debounce, otherwise everytime you press the button a single press would be recognized as multiple press.

Once the push button is pressed (the led status changes) we publish a message to Lelylan with the updates.

prev_status = GPIO.LOW # init previous status to off
led_status = GPIO.LOW # init led status to off
updated_at = 0 # the last time the output pin was toggled
debounce = 0.2 # the debounce time, increase if the output flickers
# Continue the network loop, exit when an error occurs
rc = 0
while rc == 0:
rc = client.loop()
button = GPIO.input(12)
if button != prev_status and time.time() - updated_at > debounce:
prev_status = button
updated_at = time.time()
if button:
led_status = not led_status
button_payload = 'off'
if led_status == GPIO.HIGH:
button_payload = 'on'
# effectively update the light status
GPIO.output(7, led_status)
payload = { 'properties': [{ 'id': '518be5a700045e1521000001', 'value': button_payload }] }
client.publish(out_topic, json.dumps(payload))
view raw gistfile1.py hosted with ❤ by GitHub

Troubleshooting

Everything should work just fine. If any problem occours mail or Tweet us.

Get inspired

Did you like this tutorial? You could be interested in the following ones.




If you want to learn more check out the Lelylan Dev Center and Lelylan Lab.

Social

If you like our work, let us know on twitter or by sharing the tutorial with anyone you think might find it useful.

Facebook Twitter Google Digg Reddit LinkedIn Pinterest StumbleUpon Email

Thanks

This article is brought to life from the following people. Mail or Tweet us for any idea that can improve the project.