Home Automation

Enter Your Electronics & Design Project for a chance to win a $100 Shopping Cart!

Back to The Project14 homepage

Project14 Home
Monthly Themes
Monthly Theme Poll

 

Setting up OpenHAB 2 Exec Binding for the MATRIX Creator

 

Overview

For this Home Automation Project, I elected to use the openHAB 2.4.0 (open Home Automation Bus) which is a open source technology agnostic home automation platform that runs in multiple platforms including Linux(many distributions), Windows,  MacOS, Raspbian, and many other platforms as well as has support for over 1500 devices.  In a previous project I used openHAB 1 to control PiFace devices as well as Smart Home devices for the Pi IoT challenge, some of which is still running, and this project is being used as an opportunity to update to openHAB 2.   To communicate with the devices, the MARTIX Lite Python api was used to retrieve sensor data from the MARTIX Creator as well as control the everLoop LEDS. To communicate with remote devices, MQTT was used implementing the Mosquitto MQTT Broker and Eclipse Paho Client as well as openHAB bindings.

 

Previous posts:

OpenHAB 2 with Matrix Creator and RasPi 3 A+: Intro

OpenHAB 2 with Matrix Creator and RasPi 3 A+: MATRIX Lite Python

OpenHAB 2 with Matrix Creator and RasPi 3 A+: OpenHAB 2 MQTT Binding

OpenHAB 2 with Matrix Creator and RasPi 3 A+: Everloop and demo

OpenHAB 2 with Matrix Creator and RasPi 3 A+: GPIO and Postmortem

 

Related Post:

MKR WiFi 1010 - MQTT Remote Relay Board Control

[Pi IoT] -  Remote Horse Feeder System #6 : OpenHAB, Pi Face and MQTT

 

 

OpenHAB 2 Set-up

 

To install openHAB 2, the manual process was used.  The other option is to use the 'apt-get' tool, however issues were seen with this method of install, so the manual method was used.

    1. Download  'openhab-2.4.0.zip' from the following website.

       NOTE: A Raspberry Pi running Raspbian GNU/Linux 9 (stretch) and currently kernel '4.19.27-v7+'

       Obtain OpenHAB 2 from their web site:

       https://www.openhab.org/

       https://www.openhab.org/docs/installation/linux.html

          Browse to 'Manual Installation' at the following to down load the bits

          https://www.openhab.org/download/

 

    2. Uncompress the zip file to the /opt/openhab folder.

cd /tmp
wget -O openhab-download.zip https://bintray.com/openhab/mvn/openhab-distro
sudo unzip openhab-download.zip -d /opt/openhab2
rm openhab-download.zip

  

 

    3. Change the ownership and permissions of the /openhab folder and files

sudo chown -hR openhab:openhab /opt/openhab2

 

    NOTE: Ensure the following environment variables are configured for the /opt/openhab2 folder before starting openHAB:

    These are found in: /etc/profile.d/openhab2.sh

OPENHAB_HTTPS_PORT=8443
OPENHAB_USERDATA=/opt/openhab2/userdata
OPENHAB_HOME=/opt/openhab2
OPENHAB_CONF=/opt/openhab2/conf
OPENHAB_BACKUPS=/opt/openhab2/backups
OPENHAB_GROUP=openhab
OPENHAB_RUNTIME=/opt/openhab2/runtime
OPENHAB_HTTP_PORT=8080
OPENHAB_USER=openhab
OPENHAB_LOGDIR=/opt/openhab2/userdata/logs

 

    4. Run or create a script with the following to start openHAB 2

# execute as restricted user openhab:
sudo su -s /bin/bash -c '/opt/openhab2/start.sh' openhab

 

 

    5. When openHAB 2 starts successfully, it will look like the following

   

 

    6.  Once openHAB is started, wait a bit and then open a web browser and with the following.

http://<ipaddress>:8080/start/index

 

   

    The openHAB 2 Welcome page has multiple options for various User Interfaces (UI) that can be used to configure openHAB and interface with devices.  For this project, the BASIC UI and PAPER UI were used.  There was an attempt to use the HABPANEL, however issues were seen when running the Exec binding and there was not enough time to debug it.

     What I had found was that it was best to configure some items such as the MQTT Broker binding in the PAPER UI and configure other items in the associated config files as was done in openHAB 1. This gave me more freedom to run scripts and customize message sending.

 

OpenHAB 2 Exec Bindings

 

    One of the cool things about openHAB 2 is the ability to configure and run scripts using the PAPER UI.  This can be used to run local Bash, Python or other command line scripts to collect data or to send a command to a device.  In this project, the Exec Binding was used to collect sensor data from the MATRIX Creator as well as to send commands to it to control features such as the everLoop LEDs.  One issue that was seen was that when the scripts are run from the PAPER UI binging, they run as the openhab user.  This caused an issue since the openhab user did not have permission to access the i2C or SPI bus, so this had to be corrected.  To give the openhab user access to these buses, the openhab user was set up as a sudo user requirig no password.  This is a bit of a security issue, however this is running locally in a non critical environment so it does not pose an immediate threat.

 

  1. The first thing is to add the openhab user to the /etc/sudoers file.

        NOTE: The openhab entry is at the end of the file since the sudo entry would override a previous entry

# User privilege specification
root ALL=(ALL:ALL) ALL

  
# Allow members of group sudo to execute any command
%sudo ALL=(ALL:ALL) ALL

  
# See sudoers(5) for more information on "#include" directives:

  
#includedir /etc/sudoers.d
openhab ALL=(ALL) NOPASSWD: ALL

 

    2. The next step is to add the openhab user to the appropriate groups.

         This can be performed as follows:

         Ex: sudo adduser pi i2c

 

         These are the groups that openhab user was added to:

sudo cat /etc/group |grep openhab
root:x:0:openhab
tty:x:5:openhab
dialout:x:20:pi,openhab
sudo:x:27:pi,openhab
audio:x:29:pi,openhab
video:x:44:pi,openhab
bluetooth:x:111:openhab
spi:x:999:pi,openhab
i2c:x:998:pi,openhab
gpio:x:997:pi,openhab
openhab:x:115:

 

    3.  The openhab user access can be tested using the following:

sudo su -s /bin/bash -c '/usr/bin/python3 /home/pi/development/matrix-lite-py/swigExamples.py' openhab

 

       NOTE: If this results in an error 'can't open any device' then recheck the openhab sudoers user config.

       In a previous post I outlined how to use the MATRIX Lite Python code to interface with the MATRIX Creator:

       OpenHAB 2 with Matrix Creator and RasPi 3 A+: MATRIX Lite Python

 

    3.  Next, from the openHAB 2 PAPER UI, install the Exec Binding by clicking on Add-ons from the left pane and navigate to the BINDINGS heading. Scroll down the list until the listing for Exec Binding is seen and click install. Once installed, the circle with the 'E' should turn blue. Check the openHAB logs for any errors.

 

 

    4. Once installed, click on the Inbox option and the Inbox-> Choose Binding window should appear listing the new Binding.

 

   

 

    5. Click on the Exec Binding option and the Configure Command window should appear where a new Exec command can be configured.

        Add a Name, Thing ID, Location and command to run and an Interval is the command is to run automatically.

   

 

     In this example the following command was used to get the humidity value from the MATRIX Creator.

      NOTE: This is a custom script and not part of the MATRIX Labs code.

/usr/bin/python3 /opt/openhab2/conf/scripts/newTempScript.py -hu "humid"

 

    6.  Once the configuration is saved, the new Exec binding should appear in the Configuration->Things listing.

    This is a list of some of the bindings used in this project.

   

 

    7.  Click on the new Thing to further configure the options for the binding.

        NOTE: Input, Exit Value and Last Execution were disabled in this example by clicking on the associated blue dot.

   

    NOTE: Under the Output option there is a series of values.  These will be used to configure the Thing for the Basic UI:

                Ex: exec:command:digital_humid:output

 

    8.  To view the Thing running, click on the Control option to bring up the Control window and select the appropriate Heading for the Thing that was added.

 

 

    9.  To configure the Thing for the openHAB Basic UI, a few more steps are needed.

         Under the '/opt/openhab/conf' folder, there are few sub folders that can be used to manually configure your Things.

         Here folders items, sitemaps and rules will be used.

 

    10.  Items - A sensors.items files was created under 'items' which is used to define the Things configured in the PAPER UI for use in the Basic UI.   Using the Digital Humid Exec Binding example, add an entry in the .items file.

 

String HTS221Temp "Digital Temp" { channel="exec:command:digital_temp:output" }

String HTS221Humid "Digital Humid" { channel="exec:command:digital_humid:output" }

 

   NOTE: The use of the channel entry from the Thing listing "exec:command:digital_humid:output"

 

    11.  Sitemaps - Once there is an item entry in the .items file, create a .sitemap file under add an sitemap for the sensor item which will define what is displayed in the Basic UI. A sensors.sitemap file was created for this project. Here, both a Temp and Humid entry is made.

 

Frame label="ST HTS221" { 

Text label="Temp/Humid" icon="sun_clouds"{ 

Text item=HTS221Temp label="Temp [%s]" icon="temperature" 

Text item=HTS221Humid label="Humid [%s]" icon="humidity" 

} 

 

    12.  Scripts - Under the /opt/openhab/conf/scripts folder, a Python 3 script was created to send the commands to the MATRIX Creator.  This script acts as an interface into the MATRIX Lite Py script I created since I was having an issue running the original script from the Exec Thing define.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import subprocess as sp
from datetime import datetime

PYTHON_CMD = '/usr/bin/python3'
MATRIX_CMD = "/home/pi/development/matrix-lite-py/matrixSensors.py " 
SUDO_CMD = "sudo -i su -s /bin/bash -c "
GREP_CMD = " grep -v \"INFO\" "

def main(args):
    #today = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    #print(SEND_CMD)
    if args.pressure:
        #TEMP_CMD = " -p \"temp\"" 
        TEMP_CMD = " -p " + "\"" + args.pressure + "\"" 
    elif args.humid:
        TEMP_CMD = " -hu " + "\"" + args.humid + "\"" 
    elif args.imu:
        TEMP_CMD = " --imu " + "\"" + args.imu + "\""  
    elif args.eloop:
        TEMP_CMD = " --eloop " + "\"" + args.eloop + "\""  
    elif args.color:
        TEMP_CMD = " --color " + "\"" + args.color + "\""  
    else:
        TEMP_CMD = " -h" 

    # openhab user is required when running a script with 'sudo -i su -s
    SEND_CMD = SUDO_CMD + "\"" + PYTHON_CMD + " "  + MATRIX_CMD + TEMP_CMD + " | " + GREP_CMD  + "\"" + " openhab" 
    #print(SEND_CMD)
    sp.call(SEND_CMD, shell=True)
    del SEND_CMD

if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description="matrix-lite script")
    parser.add_argument("-g", "--gpio", dest="gpio",

                       action="store_true", default=False,
                       help="run gpio") 
    parser.add_argument("-e", "--eloop", dest="eloop",
                       action="store", help="run eloop")
    parser.add_argument("-c", "--color", dest="color",
                       action="store", help="set eloop")
    parser.add_argument("-i", "--imu", dest="imu",
                       action="store", help="run IMU")
    parser.add_argument("-p", "--press", dest="pressure",
                       action="store", help="run Pressure")
    parser.add_argument("-u", "--uv", dest="uv",
                       action="store_true", default=False,
                       help="run UV") 
    parser.add_argument("-hu", "--humid", dest="humid",
                       action="store", help="run Humidity")

    args = parser.parse_args()
    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit()

    try:
        main(args)
        #user_input = input()
    except KeyboardInterrupt:
        sys.exit(0) 
    finally:
        sys.exit(0)

 

    As was listed previously, the Exec Thing binding runs the following to get the Humidity from the HTS221HTS221 Humidity sensor on the MATRIX Creator.

/usr/bin/python3 /opt/openhab2/conf/scripts/newTempScript.py -hu "humid"

 

    13.  The Basic UI can be accessed from the Welcome openHAB screen or the following url from the system that is running openHAB 2.

http://<ipaddress>:8080/basicui/app 

 

 

Since the Sitemap entry used a Text sub frame in the Frame definition, the ST HTS221HTS221 items can be accessed from the ">" character.

Conclusion

openHAB 2 has Bindings for many of the common Smart Devices as well as a host of other options.  This was just one example to show how to run an executable from the Basic UI.

Next is to add the MQTT Bindings and configurations to send and receive commands to remote devices via MQTT.