Philips Hue Dimmable Light Remote Control using PocketCHIP (openHAB,Python,MQTT)

Exploring openHAB & openHABian.
rwblinn
Site Admin
Posts: 224
Joined: 07 Oct 2017, 12:16

Philips Hue Dimmable Light Remote Control using PocketCHIP (openHAB,Python,MQTT)

Postby rwblinn » 03 Apr 2018, 10:52

openHAB2 Experiment - Philips Hue Dimmable Light Remote Control using PocketCHIP (openHAB,Python,MQTT)
Version 20180402

Objectives
To remote control Philips Hue Dimmable Lights (Hue Bulbs), via WiFi & MQTT, by using the PocketCHIP with a Python GUI Application.
The GUI Application is controlled by touching the buttons.

Image
Hue Bulb at MakeLab switched on with brightness 25%.

Background
Back in 2016, have bought a PocketCHIP, but was not sure what to do with it.
Whilst developing my HomeAutomation solution, thought about remote controlling Hue Bulbs.
Reading more about the PocketCHIP, got the idea to remote control the Hue Bulbs via the PocketCHIP using MQTT and Python3 with guizero.
The result is shared below.

Hardware
Software
  • Python 3
  • guizero - Python 3 library for creating simple GUIs
  • Mosquitto MQTT Broker
Note
The openHAB server is a Raspberry Pi 3 with openHABian, openHAB 2.2.0 and Mosquitto MQTT Broker.

Download
No download - example openHAB2 configuration and the Python3 source are listed below.

Concept
The brightness of the Hue Bulbs is remote controlled via MQTT. Each Hue Bulb has its own MQTT topics to get or set its brightness.
There are 4 Hue Bulbs used which use following topics (homeautomation/<location>/<huebulbnr>) to get or set the brightness:
  • homeautomation/makelab/huelight1 , homeautomation/makelab/huelight1/set
  • homeautomation/livingroom/huelight2 , homeautomation/livingroom/huelight2/set
  • homeautomation/livingroom/huelight3 , homeautomation/livingroom/huelight3/set
  • homeautomation/livingroom/huelight4 , homeautomation/livingroom/huelight4
The Python GUI application has a ButtonGroup to select the HueBulb and two pushbuttons to switch the Hue Buld ON or OFF.
Example for the Hue Buld located in the MakeLab:
  • Hue ON: set the brightness to 25% by publishing MQTT topic homeautomation/makelab/huelight1/set 25
  • Hue OFF: set the brightness to 0% by publishing MQTT topic homeautomation/makelab/huelight1/set 0
An openHAB number item listens to the MQTT topic and if the value (=state) changes, an openHAB rules triggers setting the value of an openHAB item Dimmer assigned to the Hue Light Thing.
The Hue Light Thing is updated via its Hue Bridge Channel.
The other way around is also implemented, means if the Hue Light brightness is changed via the openHAB Basic-UI, the new value is displayed on the display.

openHAB Configuration
Notes
For the Hue Bulbs, the items, sitemap and rules are extracted from a full openHAB installation.
The Things are defined using the openHAB Basic-UI.
Only one Hue Bulb configuration is shared as an example.

openHAB Thing
The thing defined is named "Hue white lamp 1" with status ONLINE.
It is a Dimmable Light connected to Hue Bridge hue:0100:00178863da1d and has Light ID 1.

openHAB Items
The Dimmer Item uses the brightness channel of the Thing "Hue white lamp 1".

Code: Select all

Dimmer aHA_MakeLab_HueLight1bsl "Brightness" <light> (gHA_MakeLab) { channel="hue:0100:00178863da1d:1:brightness" }


The Number Item contains the brightness by listening to the MQTT topic "homeautomation/makelab/huelight1/set" with payload between 0 - 100.

Code: Select all

Number nHA_MakeLab_HueLight1 { mqtt="<[openhabprod:homeautomation/makelab/huelight1/set:state:default:.*]" }


openHAB Sitemap
The sitemap snippets shows the Dimmer Item as a Slider.

Code: Select all

Frame label="Make Lab" {
   ...
   Slider  item=aHA_MakeLab_HueLight1bsl
   ...
}


openHAB MQTT Broker
The broker is defined in the file mqtt.cfg located on the Raspberry Pi openHAB server /etc/openhabs2/services.

Code: Select all

# Local Mosquitto Broker running on the Raspberry Pi
openhabprod.url=tcp://localhost:1883


openHAB Rules
There are two rules handling the change if the Number Item and the Dimmer Item.

State Change Number Item nHA_MakeLab_HueLight1
As defined in the item, the state will change if the payload of the MQTT message with topic "homeautomation/makelab/huelight1/set" changes.
If a change is made, the Dimmer Item aHA_MakeLab_HueLight1bsl is updated with the value of the Number Item nHA_MakeLab_HueLight1.

Code: Select all

rule "HueLight1 Brightness Set"
when
   Item nHA_MakeLab_HueLight1 changed
then
   logInfo("HUELIGHT1", "*** Brightness set to " + nHA_MakeLab_HueLight1.state.toString)
   aHA_MakeLab_HueLight1bsl.sendCommand(nHA_MakeLab_HueLight1.state.toString)
end


State Change Dimmer Item aHA_MakeLab_HueLight1bsl
If the state of the Dimmer Item changes, by changing the position of the slider in the openHAB Basic-UI, a MQTT message is published with
Broker: openhabprod
Topic: homeautomation/makelab/huelight1
Payload: Value of the Dimmer Item aHA_MakeLab_HueLight1bsl between 0 - 100

Code: Select all

rule "HueLight1 Brightness Changed"
when
   Item aHA_MakeLab_HueLight1bsl changed
then
   // Publish the message to topic using the specified MQTT broker.
   publish("openhabprod", "homeautomation/makelab/huelight1", aHA_MakeLab_HueLight1bsl.state.toString)
end


PocketCHIP Solution
The PocketCHIP uses its own Mosquitto MQTT broker to subscribe & publish to the openHAB server MQTT broker.
A Python script runs on the PocketCHIP and handles the MQTT messaging.
Editing and managing files is done remotely with the tools WinSCP and PuTTy.

PocketCHIP Prepare
Recommend to read the PocketCHIP Documentation.
Notes
  • The PocketCHIP Screen Resolution is 480x272.
  • The Terminal (Linux shell) is used to run commands.
PocketCHIP Update Software
$sudo apt-get update && sudo apt-get upgrade

PocketCHIP Set Static IP Example
Open a Terminal:
$sudo nmtui
Set IP4V connection to manual with IP: 192.168.0.NN and Gateway 192.168.0.N then REBOOT!
Check the IP address after reboot:
$ip addr show wlan0
Example Result: 192.168.0.61

PocketCHIP Mosquitto Installation
$sudo apt-get install mosquitto mosquitto-clients

PocketCHIP Python 3, guizero, MQTT paho Installation
Install Pip3 and Python3:
$sudo apt-get install python3-pip

Install guizero:
$sudo pip3 install guizero

Upgrade guizero:
$sudo pip3 install -U guizero

Install paho-mqtt:
$sudo pip3 install paho-mqtt

PocketCHIP Personalize GUI
To change the applications with their icons displayed on the PocketCHIP GUI First Screen:
$cd /usr/share/pocket-home
$sudo nano config.json
Make the changes:

Code: Select all

{
   "name": "Switch Hue",
   "icon": "appIcons/haswitchhue.png",
   "shell": "python3 /home/chip/python/ha/haswitchhue.py"
}


Notes
  • icon: A new icon has been created and copied as sudo to the folder /usr/share/pocket-home/appIcons
  • shell: python3 is used to start the application. A hourglass is shown when python3 gets started and loads the script haswitchhue.py.
  • The python script is located in folder /home/chip/python/ha/haswitchhue.py with owner chip.

Image

Fullexample of /usr/share/pocket-home/config.json

Code: Select all

{
  "defaultPage" : "Apps",
  "pages": [
    {
      "name": "Apps",
      "items": [
        {
          "name": "Terminal",
          "icon": "appIcons/terminal.png",
          "shell": "vala-terminal -fs 8 -g 20 20"
        },
      {
        "name": "Switch Hue",
        "icon": "appIcons/haswitchhue.png",
        "shell": "python3 /home/chip/python/ha/haswitchhue.py"
      },
        {
          "name": "Get Help",
          "icon": "appIcons/help.png",
          "shell": "surf /usr/share/pocketchip-localdoc/index.html"
        },
        {
          "name": "Browse Files",
          "icon": "appIcons/filebrowser.png",
          "shell": "pcmanfm"
        },
      ],
      "cornerButtons": [
        {
          "location": "TopLeft",
          "name": "Battery",
          "icon": "battery_0.png"
        },
        {
          "location": "TopRight",
          "name": "WiFi",
          "icon": "wifiOff.png"
        },

        {
          "location": "BottomLeft",
          "name": "Power",
          "icon": "powerIcon.png"
        },
        {
          "location": "BottomRight",
          "name": "Settings",
          "icon": "settingsIcon.png"
        }
      ]
    },
    {
      "name": "Settings"
    },
    {
      "name": "Power"
    },
    {
      "name": "WiFi"
    },
    {
      "name": "Battery"
    }
  ]
}


Restart lightdm:
$sudo systemctl restart lightdm

PockerCHIP Python3 Code Switching Hue Bulbs
Image
The GUI Application is controlled by touching the buttons.

Code: Select all

# openHAB Home Automation Project - Hue Remote Control using a PocketCHIP.
# Control Hue Bulbs, via WiFi & MQTT, by selecting a Hue Buld and press push button ON or OFF of the Python GUI.
# There are two buttons: Hue ON which sets the brightness to 25 and Hue OFF sets the brightness to 0.
# If a Hue Buld brightness is changed by another app (i.e. Basic UI or openHAB Android App) then the brightness information is also updated.
# TODO: Use a slider to set the brightness in range between 0 - 100.
# Author Robert W.B. Linn @ www.rwblinn.de
# Version 20180403

# Import mqtt
import paho.mqtt.client as mqtt

# Import the app and the widgets from guizero
from guizero import App, Text, Box, ButtonGroup, PushButton

# Set up and connect to mqtt server.
global broker
broker = "192.168.N.NN"
global broker_port
broker_port=1883
# The client, topic and payload are defined as global to be able to use in the do_hue* functions.
global client
global topic
topic = "homeautomation/makelab/huelight1/set"
global payload

# Callback when client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
   print("MQTT Connected with result code "+str(rc))
   # Subscribing in on_connect() means that if connection lost and reconnect again the subscriptions will be renewed.
   client.subscribe("homeautomation/makelab/huelight1")
   client.subscribe("homeautomation/livingroom/huelight2")
   client.subscribe("homeautomation/livingroom/huelight3")
   client.subscribe("homeautomation/livingroom/huelight4")

# Callback on publish
def on_publish(client,userdata,result):
   print("Data published \n")
   pass

# Callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
   print("Received: " + msg.topic + " " + str(msg.payload))
   messagehuebrightness.value = "Hue Brightness: " + str(int(msg.payload))

def on_log(client, userdata, level, buf):
   print("log: ",buf)

# Button - Close the app
def do_close():
   client.loop_stop()
   client.disconnect()
   app.destroy()

# Set the selected hue: "MakeLab", "Cupboard", "TV", "Rob Place"
def do_sethue():
   print("[INFO] Hue Choice Value: ",huechoice.value)
   # Define the global topic
   global topic
   # hueselected.value = huechoice.value
   if huechoice.value == "1":
      topic = "homeautomation/makelab/huelight1/set"
   elif huechoice.value == "2":
      topic = "homeautomation/livingroom/huelight2/set"
   elif huechoice.value == "3":
      topic = "homeautomation/livingroom/huelight3/set"
   elif huechoice.value == "4":
      topic = "homeautomation/livingroom/huelight4/set"
   else:
      # Do the default
      print("[ERROR] Hue Choice Value: ",huechoice.value)

   print("Topic: " + topic + " ...")

      
# Button - Switch the hue light on
def do_hueon():
   print("Hue ON " + topic)
   payload = "25"
   client.publish(topic, payload)
   print("Publishing " + payload + " to topic: " + topic + " ...")
   
# Button - Switch the hue light off
def do_hueoff():
   print("Hue OFF " + topic)
   payload = "0"
   client.publish(topic, payload)
   print("Publishing " + payload + " to topic: " + topic + " ...")

client = mqtt.Client()
client.on_publish = on_publish
client.on_connect = on_connect
client.on_message = on_message
# client.on_log=on_log
client.connect(broker, broker_port, 60)
# Starts a new thread, that calls the loop method at regular intervals and handles re-connects automatically.
client.loop_start()

# Set up and display guizero objects
app = App(title="HomeAutomation Experiment Switch Hue Bulb ON OFF")
# app = App(title="HomeAutomation Experiment Switch Hue Bulb ON OFF", width=480, height=272, layout="grid")

# Messages
messagehdg = Text(app, text="HomeAutomation Switch Hue Bulbs", grid=[0,0])
messagehdg.font="Helvetica"
messagehdg.bg = "white"
messagehdg.text_color="blue"
messagehdg.text_size = 12

# Buttongroup to select the hue
huechoice = ButtonGroup(app, options=["MakeLab", "Cupboard", "TV", "Rob Place"], selected=1, command=do_sethue, grid=[0,1])
huechoice.text_size = 12

# Pushbuttons to switch the hue
box = Box(app, layout="grid", grid=[0,2])
# box.width=480
button_hueon = PushButton(box, text="Hue ON", command=do_hueon, grid=[0,2])
button_hueon.width = 20
button_hueon.bg = "green"
button_hueon.text_size = 12

button_hueoff = PushButton(box, text="Hue OFF", command=do_hueoff, grid=[1,2])
button_hueoff.width = 20
button_hueoff.bg = "red"
button_hueoff.text_size = 12

# Message showing the value of the hue
global messagehuebrightness
messagehuebrightness = Text(app, text="Hue Brightness", grid=[0,3])
messagehuebrightness.text_size = 10
# hueselected = Text(app, text="MakeLab")

# Pushbutton to close the app
button_close = PushButton(app, text="Close", command=do_close, grid=[0,4])
button_close.width = 15
button_close.bg = "blue"
button_close.text_color = "white"
button_close.text_size = 12

# Who made it
abouthdg = Text(app, text="2018 by rwblinn.de", grid=[0,5])
abouthdg.text_color="blue"
abouthdg.text_size = 9

app.display()


ToDo
  • Experiment completed.

Version
  • 20180403

Return to “Experiments”



Who is online