Skip navigation

Pi IoT

August 25, 2016 Previous day Next day

In these last days I have implemented three new features of Phase 2 that will make DomPi more useful to my family: determine who is at home, welcome the family when we arrive home and send an alert if the average temperature of the apartment is either too high or too low. Let´s have a look at them!


Previous Posts

PiIoT - DomPi: ApplicationPiIoT - DomPi: IntroPiIoT - DomPi 02: Project Dashboard and first steps in the Living room
PiIoT - DomPi 03: Living room, light control via TV remotePiIoT - DomPi 04: Movement detection and RF2.4Ghz commsPiIoT - DomPi 05: Ready for use Living Room and parents and kids´ bedrooms
PiIoT - DomPi 06: Setting up the Command Center - RPI3PiIoT - DomPi 07: Setting up the Command Center (2)PiIoT - DomPi 08: Setting up the Command Center (3) openHAB, mosquitto, RF24
PiIoT - DomPi 09: Presence EmulatorPiIoT - DomPi 10: Garage node (slave)PiIoT - DomPi 11: Ready to use. Garage node (master & slave)
PiIoT - DomPi 12: Ready to use. Control Panel and Garden NodePiIoT - DomPi 13: Ready to use. DomPi Phase 1


Project Status

Project Status

Presence Identification

This feature allows DomPi know, not only know if there is somebody at home, but also who is there. The best solution as of now to implement this, is to check whose mobile phone is at home. I know this has some drawbacks like, what if the phone is off or if we left it at home... To partially sort out this problem, DomPi also leverages the motion sensors to limit the impact of it and make it more reliable. Let´s have a look at all this.


At the beginning, I thought of using the command line (via the executeCommandLine function from openHAB) and then parsing the output of the "ping" in the RPI. While I was working on this, I have come across an existing binding in openHAB that has made the development much easier and faster It is the Network Health Binding, some more details here. This binding connects an item in openHAB with the status of any device or host in general. You could for example check the "network health" of your RPI to communicate with or for instance. For DomPi, I am controlling the network connectivity to the IP´s of our mobile phones. Let´s review the installation and initial config of the binding and have a look then at the implementation.


Installation and initial config

As with any binding, you just need to download the binding in itself (the best approach is to download all of the addons from here as commented in previous posts) and copy the relevant binding (in my case the .jar file is: org.openhab.binding.ntp-1.8.3) into the openhab/addons folder. To perform some fine tune, you just need to modify some of the lines in the openhab.cfg file:

# Cache the state for n minutes so only changes are posted (optional, defaults to 0 = disabled)
# Example: if period is 60, once per hour the online states are posted to the event bus;
#          changes are always and immediately (refresh interval) posted to the event bus.
# The recommended value is 60 minutes.

# refresh interval in milliseconds (optional, default to 60000)


At the end, I modified the line 5 here and uncommented. By allowing the cache, the binding gets the status of the devices as always, and only updates the item if there is a change in the status. This means, there will only be updates if the phones go out or in range. With no cache, there would be updates posted to the openHAB bus every refresh interval (60s as per line 7). I don´t need to overload the bus with this information, but also if you add persistance, there would be a huge volume to store all of these updates in the HDD... In any case, the binding will update the devices status every hour. All in all, with the cache enabled, openHAB will let me know if the devices go from ON to OFF or viceversa and also every hour it will send an update. I kept the networkhealth refresh (line 8) with the default value.


Implementation in DomPi

Potentially, you can connect directly an item to the binding and just display in openHAB its status. Something like this:

Switch Papa_tlf_nh "Papa Network Binding"  <present> (gStatus, gPresencia_casa_nh) nh="" }


This would display a switch showing if the mobile phone is in range or not. However, this would not be optimum. It seems that my mobile phone goes into sleep mode with the Wifi, probably to save up battery. I have not stress-tested but I guess while on sleep mode, it will not reply to pings. The solution I have implemented is to apply a double level of switches: one as above connected directly to the binding and yet another one controlled by an openHAB rule.


The rule will get the updated status from the first level switch. When it is in range, it will directly update the second level. However, when it is out of range, it maybe that the phone is on sleep mode. Therefore, it will wait 8 minutes. If within this time, DomPi has not seen the phone in range, it determines that the user/phone is out from home. The description of the second level switch is this:

Switch Papa_tlf "Papa" <present>    (gStatus, gPresencia_casa)


And the rule is here:

rule "Presence Identification - Father"
    Item Papa_tlf_nh changed
    //If the temporary item Papa_tlf_nh has changed to ON, 
    //we directly update the final item Papa_tlf and cancel the relevant timer if exists
    if (Papa_tlf_nh.state==ON) {
        postUpdate(Papa_tlf, ON)
        if (timer_presenceID_papa!= null) {
            timer_presenceID_papa = null
    } else if (Papa_tlf_nh==OFF) {
        //If it is OFF, it can be that the phone is saving battery on Wifi
        //Let´s allow 8 minutes since the last time it was updated before putting presence to OFF
        if (timer_presenceID_papa == null) {
            //if there was no timer until now, create it
            timer_presenceID_papa = createTimer(now.plusSeconds(480)) [|
                //Allow 8 minutes and modify Papa_tlf item 
                if (Papa_tlf_nh==OFF) postUpdate(Papa_tlf, OFF)
                if (timer_presenceID_papa!= null) {
                    timer_presenceID_papa = null


The drawback of this implementation is that I need a rule per phone to control. In the end I am just planning to monitor two phones so it won´t be a big issue. However, I need to review openHAB's capabilities as I am sure I can condense all the devices to monitor into a single rule. I will look into this when optimizing the code, after the Challenge unfortunately... You can see some snapshots below with this feature. The line Quien esta en casa? => Who is at home? summarizes in the Main Menu how many people are there. It is a clickable item that takes you to the right hand side submenu with the details.




Welcome Home feature

With this, I intend to execute some actions when somebody has arrived home. At this stage, the action is to turn on the lights of the living room and the parents´ bedroom and in the next development it will also turn on the TV and switch it to the TV channel we usually watch. This can be very useful to us, as you can have some light at the end of the corridor without having to walk till there. Also the light in our room takes time to be fully lit, so it is good as well to turn it on some minutes in advance. I have written the code and split it in four openHAB rules.


How it works

It all starts by determining when the apartment is empty. Since it is after the flat is empty when it makes sense to wait for the family and welcome them warmly or at least "lightly". The first rule is quite straightforward:

//This rule determines if there is presence at home
rule "Detect any presence at home"
     Item Nodo09MotionDetected changed from OFF to ON or
     Item Papa_tlf changed from OFF to ON or
     Item Mama_tlf changed from OFF to ON
     if (Someone_at_home.state!=ON) postUpdate(Someone_at_home, ON)


If there is movement, or DomPi discovers any phone at home, then we determine that there is a family member. This assumption has to be fine tuned in the future: what about if we forgot the mobile phones, etc. It may happen that there is motion detected because a burglar broke in... We should not welcome him or her This is controlled by another rule, that checks the status of the Alarm Switch, if it is on, then we won´t trigger the welcome feature:


rule "Welcome home family"
/*If someone has arrived home and there was nobody before inside, let´s do:
 *         Turn on light in the living room if luminosity is low
 *         Turn on light in the parents bedroom if luminosity is low
 *         Improvements: turn on TV and say hello

    Item Someone_at_home changed from OFF to ON
    if (Nodo09AlarmSwitch.state==OFF) {
        //Reconfirm that the alarm switch is off - it can be that rule "Detect any presence at home"
        //has changed Someone_at_home, but alarm is active
        say("Welcome at home!!")    //Let´s be nice to the family even if no lights needs to be turned on ;)
        if (gLuminos.state<50) {
            //Average luminosity is low, lets turn on the lights
            postUpdate(Lampara_2, ON)        //Parents light
            postUpdate(Lampara_3, ON)        //Living room light
    } else if (Nodo09AlarmSwitch.state==ON) postUpdate(Someone_at_home, OFF)
end //We avoid welcoming burglars!


As you can see in lines 15 to 18, before turning on the lights, it checks the average luminosity in the apartment, taking into account only the luminosity from the sensors in the flat: kids, parents and living rooms. If the average is below 50%, it turns on the lights. I will adjust this value after some days testing it.


The last two rules determine whether the family came back home or left home. They will update the item Someone_at_home accordingly:

//This rule determines if there is nobody at home and if so updates item
rule "Did family leave home"
    Item Someone_at_home changed from OFF to ON 
    //Thread launched as soon as we determine someone is at home. 
    //It will start to check the conditions to determine that there is noone at home
    if (timer_presenceat_home!= null) {
        timer_presenceat_home = null
    while (Someone_at_home.state==ON) {
        //if there is no motion detected and all of the members from gPresence_casa (Mama and Papa)
        //are in the state OFF, which means they are not at home, then execute the loop inside
        if (Nodo09MotionDetected.state==OFF && (gPresencia_casa.members.filter(s | s.state==OFF).size==0)) {
            //Wait 30 mins and check again if there was any movement
            //this long delay helps to avoid issues if somebody is in the bath, etc
            timer_presenceat_home = createTimer(now.plusSeconds(1800)) [|
                if (Nodo09MotionDetected.state==OFF && (gPresencia_casa.members.filter(s | s.state==OFF).size==0)) {
                    //Still no movement -> modify item
                    postUpdate(Someone_at_home, OFF)
                if (timer_presenceat_home!= null) {
                    timer_presenceat_home = null
        if (Someone_at_home.state==ON) Thread::sleep(120000) //Every 2 mins determines if someone is at home

rule "Did family come back home"
    Item Someone_at_home changed from ON to OFF
    //Thread launched as soon as we determine nobody is at home
    //It will start checking the conditions to determine that somebody entered home
    //Conditions to determine someone at home:
    //  if there is a mobile phone in the wifi range
        //There is no need to check if any mobile phone appears in range via the Network Binding
        //since there is already a rule ("Detect any presence at home") that would modify the
        //item Someone_at_home to ON
    //  if there is motion detected and 1)the alarm is not active, or 2)alarm is active but 
    //    user turns it off within time limit 
    while (Someone_at_home.state==OFF) {
        if (Nodo09MotionDetected.state==ON) {
            if (Nodo09AlarmSwitch.state==OFF) postUpdate(Someone_at_home, ON)
            else {
                //val t_delay = t_delay_trigger_alarm * 1000 + 200
                Thread::sleep(60200)    //Wait the 60 secs plus 200 ms to allow some updates //Change with t_delay_trigger_familyhome 
                if (Nodo09AlarmSwitch.state==OFF) postUpdate(Someone_at_home, ON)
        if (Someone_at_home.state==OFF) Thread::sleep(10000)        //Sleep for 10s before checking again


Temperature Alarm

This feature notifies me per email if any temperature sensor at home is below 20ºC or above 27 ºC. Many thanks to jkutzsch who gave me the idea back in May, at the very beginning of the Challenge. Finally, I can implement it I have implemented it in a single rule. If the alarm is triggered and the email sent to myself, then the rule launches a timer to wait for 1h before sending again any notification: I want to avoid spamming myself!

 * Rule to send an email warning if temperature at any room is out of a given range
rule "Notify of extreme temperature at home"
//If any room is below 20ºC or above 27ºC send notify per email
    Item gTempers received update
    //First step to check if the timer is not null, this implies that there was an email already sent and 
    //DomPi is waiting some time (1h-2h) before resending the notification

    if (timer_extreme_temperature_alarm==null) {
        //no timer - we can send the email if required
        //check values of the temperature sensors from home (interiors only)
        gTempers?.members.forEach(tsensor| {
                if (tsensor.state>=27) send_alarm_high_t = true
                if (tsensor.state<=20) send_alarm_low_t = true        
        if ((send_alarm_high_t) || (send_alarm_low_t)) {
            //Send email with the alarm and then create the timer
            var String email_subject =""
            var String email_body =""
            if (send_alarm_high_t) {
                email_subject = "Alta temperatura en Casa. Alarma"
                email_body = "Detectada alta temperatura en casa"
            if (send_alarm_low_t) {
                email_subject = "Baja temperatura en Casa. Alarma"
                email_body = "Detectada baja temperatura en casa"
            sendMail("", "DomPi - " + email_subject, email_body)
            timer_extreme_temperature_alarm = createTimer(now.plusSeconds(3600)) [|
                //Wait 1h and then just remove the timer to allow next notification as required
                if (timer_extreme_temperature_alarm!=null) {
                    timer_extreme_temperature_alarm = null


Additional improvements

As I continue to run through the existing rules, I find ways to improve on them. Below a summary of the news this week:

  • Show the internal average temperature and humidity in the main menu - before it was not implemented
  • Create a submenu which quickly shows the temperatures and humidity
  • Alarm - new rule created to turn Alarm Status back to OFF after 2 minutes of no movement being detected to avoid having a false alarm sine die...
Main Menu temp humHumidity


Nodes´ Dashboard

Nodes Dashboard


More items turning into Green!!

Up until now, I built the 'skeleton' of the platform: we have these three nodes in the smart home (Central Node, Sensors Node, User Node), which show the sensors data at different points. However, the platform lacks a nice access point for the residents to interact with the house. Furthermore, the competition module is still to be started! With this post, I will show the improvements in the house GUI as well as the setting up of the central node to start developing a competition system.


The improvements to be included in the Central Node are:

  1. Touch screen integration and GUI development
  2. Server set up to develop the competition system. Central Node will provide:
    • Database storage service - to create a persistent system
    • Web portal/ Web access service - to enable an interface with the competition devices when outside of the home


Touch screen and GUI development

Initial setup: Raspberry Pi 3 - Raspbian SO (Jessie) / SSH Enabled / Mosquitto MQTT Broker installed / MQTT Subsciber client / Console interface


The main GUI of the house is on the Central Node. Since it will make use of the provided touch screen, I introduce a link on how to integrate Raspi and screen as well as a description of the GUI development itself.


Touch screen integration

We will include the touch screen from the kit: '7" Touchscreen Display'. Luckily, this very same elemet14 page offers a very complete description of the product and how to get started

Raspberry Pi 7” Touchscreen Display

The main steps:

1. In the Raspberry Pi 3,  install the matchbox-keyboard (no more need of a keyboard connected via USB)

2. Do the hardware connections (we continue from step 5: attaching the DSI ribbon and then the 5V and GND jumper wires). Then, mount the Raspi to the back of the display.


Here is the final result in my case

IMG_20160721_105121_hdr.jpg  IMG_20160721_105256_hdr.jpg



GUI Design


Using Python, and the GTK library

Full code can be found at Github


This was an interesting project, as it is the first time I use Python to design a graphical interface. In the end, I went for the most basic way, using GTK directly. However, I have the impression there might be higher level libraries which will provide a nice final look (still, it was an exeprience). As far as this project goes, we will have a functional graphical design to display our significant data.


I started from the previous Python scripts, which already implemented an MQTT_Subscriber and a console interface. In the end, I work with three files:

  • - main file
  • - the MQTT client to be connected to the broker. It receives the information for the smart house data
  • - defines the graphical interface, using GTK library, and functions to update its labels

To generate a temperature gauge, there is the additional file


NOTE - An extra file will be required to get the competition house information.


Initial approach for the temperature gauges - Plotly (FAILED)


Plotly is a powerful online tool to generate online graphs and dashboards. It gives enough freedom when creating this charts, and the additional option of exporting to a local directory. I decided to use it to generate a temperature graph which could be updated both in the central node and for a more remote solution. However, I realized this will not work for my case (see the end of this section for a dramatic outcome).


Using plotly

I created a new account in their webpage (as a free user) and started playing. Each account comes with a username and a key, which has to be included in the code using the platform or the environment.




There are two main steps while installing plotly: installation of python library and authentication. The corresponding commands are:

To install the library:

pip install plotly

To authenticate, we have to start python, with the console command


There, the authentication process only requires two commands:

import plotly'DemoAccount', api_key='lr1c37zw81')

(Another option is to include this authentication process in the python files using plotly)


Now, our python scripts are ready to use Plotly!




I included the file in the project, which can generate different temp graph with small modifications. The code defines a chart, with different temperature regions (and some missplacement in the numbers :3, something to fix if using plotly). Depending on the temperature, we should see the pointer signaling the right section. Some examples:


The limits of plotly free account

After the setup and development, I could generate an image with any new temperature sample that emulated the effect of thermometer indicator. Nevertheless, the program will crash after a certain time without any chances of recovery. It is a bit embarrassing, but it took me a long time to realize why:

Free accounts have a limit of requests (kind of obvious). 30 request per hour and a maximum of 50 requests per day. I want to refresh the GUI in a regular basis, and, even if I can regulate and minimize the number of request, I would prefer finding another solution. For now, though, I will keep the static temperature image in the GUI (until I design a better solution!).


A single interface for the smart house and competition system




This interface has three frames:



     Shows whether we are connected to the broker and which local IP we are using

     If connection was not established, we can enter and try a different local IP




  • Temperature as a gauge
  • Pressure and altitude values in real time
  • Door state and alarm

There is a Log button, which will be used to retrieve past data



     Shows a table with the residents and state of the competition

     Results are ordered, with the winning contestants on top

There is a History button, to be used to show past months results.


(*) We have only mock values so far. The real information will be read from our database once the competition system is implemented.


Server setup


The next step for our central node is to host a server. After the setup, it will provide:

  • Remote and local storage, thanks to the MySQL database. The database itself could be built without the webserver, but we want it integrated and accessible form outside too (the competition system will be sending its information mainly outside of the house).
  • Remote access to the node, thanks to a web interface


Next sections describe how to install each of the new capabilities


Installing and starting a database in the Raspberry Pi 3: MySQL


For the MySQL database, I will be  installing the corresponding libraries (mysql as well as  the python related one) it in the Raspberry Pi 3 with the following command:

sudo apt-get install mysql-server python-mysqldb


(*) If during the installation, you are not asked to set the root password you will have to set it after.

  1. Stop the service
    service mysql stop 
  2. Start with disabled grant-table, so that you don't need to enter root password
    sudo mysqld_safe --skip-grant-tables
  3. Access as a root user
    sudo mysql --user=root mysql
  4. Change root password
update user set Password=PASSWORD('new-password') where user='root';

    5.  (Do not forget to stop and restart the server as normal!)


Create a database for the project and also, a user to manage the input data (but not as many privileges as the root)


Again, my main functions will be developed in Python, as scripts. Therefore, I will be using Python commands to:

1. Create table

2. Access table

3. Delete rows/tables


Installing a web server in the Raspberry Pi 3: Apache and PHP5




The command to install the packages is:

sudo apt-get install apache2 php5 libapache2-mod-php5


Afterwards, we will have in the main node:

  • Apache2 - the server.
  • PHP5 - to develop the web portal which communicates with the database.
  • A bridge between the two of them


A usefull command :Activate the service

sudo service apache2 restart



At this point, we can access our web portal using the local IP for the Central node. In the end, we want the web server to be accessible from the outside (it will manage the remote functions). There are two steps needed still:

  1. Port forwarding to our Raspberry Pi 3- the router will redirect the traffic that comes through an specific port to out Central Node. This process depends on the router itself (lucky enough, there are usually plenty of Google entries on how to), but usually there is a "Port Forwarding" menu when accessing the advanced options of the router. Two things we need to keep in mind:
    • External IP address & Start/End Port - which represents the IP address and Port to be access from the outside(START PORT). I leave the IP address to and select an start port (will use it again when sending data to the central node from the competition mobile app) which is the same as the end port
    • Internal IP address & Start/End Port - This Internal IP address should be the local IP of the central node and the start/end port that of the service.

          We will be using this EXTERNAL IP PORT from the mobile application managing the "Competition application" in order to send data back home.


     2. Obtaining a domain - instead of using the IP address, the web will be accessible  using DNS. I obtain the domain from Absolutely Free Dynamic DNS / DDNS (the same page recognizes the public IP of your house network). No more IP memorizing for a while


For an initial web portal we will just forward the port 80 (both, for the external IP and the internal IP). And here it comes!

(Yes, yes... it is still a mock portal)





Services useful commands

Regarding MySQL and Apache servers, here are some useful commands:



sudo service mysql restart


sudo service mysql start


sudo service mysql stop

Developing a web portal

1. Design and content: HTML & CSS


The web will be located in the folder /var/www . The input point is the index.html file, so let's start changing things a bit.


In order to have a nicely designed looked, there are several free templates available. I chose mine from Free Website Templates. With some modifications in the CSS files for a different look as well as in the HTML to include the content, I will make some changes to include the Competition Application:



At this point, I will just display the information related tot he Competition System. It will be a nice feature to also be able to read the information sent from the Sensors Node also in this same web. However, I would include it only with a minimum of security (e.g. users login) so that it is not available to just anybody and everybody.


2. Adding functionalities: PHP5 and mySQL

For the competition system to work, our central node will be receiving each roommate status through the Internet. This information will be then stored on the database so that the main program (the previously developed Python GUI) can access it.

This will be done in PHP:

  1. Receive and decode the user's information to obtain the total distance (from an HTTP POST)
  2. Insert this data in the database (once the local user has open the database, using SQL commands)




With this post, the setting up of our central node is completed!!

  • Smart house GUI is ready to show the house and competition state
  • A mySQL server has been installed, allowing for some future persistence
  • A web server is also installed,opening a bridge for the competition system to enter the house
    • We keep in mind the domain of our Competition smart house (if accessed with a browser, it will show a simple web hosted in the central node) -
    • And the port for our competition service


There is still much development to do on top of that!!

Internet of things is about connecting connecting th things around you in a meaningful way. Last few posts, I showed how to connect and monitor a few sensors inside the home using raspberry pi. Now it's time for a little entertainment. After the basics in home, I believe it's going to be our entertainment systems coming to online. In this post, I'll explore the idea of an internet connected music player with raspberry pi.


Enter Mopidy

Mopidy is much more than a normal music player. I makes your music device accessible from web and also enables it to stream content from web like spotify, Google Play Music etc., The best part - you can access your music player from your smartphone or tab or from PC. This is how it's going to work - Mopidy is going to run on your raspberry pi (I'm using Pi3). It will be working as a daemon(background process) in your pi. And your Pi must be connected to a network. Noe you can access the Mopidy UI using any of you devices - either phone, tab or another PC. It's basically like bluetooth streaming experience except that it won't drain you battery But the catch is your music files should be either available in your rPi or should be played from cloud.


Hardware Setup

The hardware setup is really simply. You have to connect a speaker to your 3.5mm jack. I'm using an USB powered speaker, which I power from the Pi.



Software Installation

Although there is an official apt repository method for installing Mopidy on Pi, I will be following the pip method. The version in apt repo is seems to be old - 0.19, while the one using pip is new - 2.x

First thing to do is to install all the gstreamer dependencies in Pi. Use the following command to install the dependencies:

sudo apt-get install python-gst-1.0 gstreamer1.0-plugins-good gstreamer1.0-plugins-ugly gstreamer1.0-tools gir1.2-gstreamer-1.0 gir1.2-gst-plugins-base-1.0

Now we can go on to install Modpiy using pip. Use the following command to install:

sudo pip install Mopidy

This will install Mopidy music server in your Pi. Before using it, we have to configure Mopidy to be able to access from other devices. This will be particularly helpful if you are running Pi headless. Other thing is, once you configure these access you will be able to control music player from your mobile phone or other PC also. To edit the configuration:

nano ~/.config/mopidy/mopidy.conf

Basic structure of the file is going to be section in square braces ( eg [core] ) and options under it.

First to be able to access mopidy from outside, you need to enable MPD and HTTP section. Navigate to the sections and modify them as given below:

enabled = true 
hostname =
port = 6600
password =
max_connections = 20
connection_timeout = 60
zeroconf = Mopidy MPD server on $hostname
command_blacklist =
default_playlist_scheme = m3u

enabled = true 
hostname =
port = 6680
static_dir =   
zeroconf = Mopidy HTTP server on $hostname

Now you will be able to access your Mopidy from any devices. Next you have to install clients to be able to access them. First we'll configure a webclient so that we can access Mopidy from PC/tablet/phone. You can get a non-exhaustive list of webclients for mopidy from . For this project, I chose to use 'Musicbox_webclient'. To install it, just enter:

sudo pip install Mopidy-MusicBox-Webclient

Now you will be able to access your Mopidy from any of the web clients from any devices.

Now you can go to http://<Pi's IP>:6680 and you will see a page like this:

Screen Shot 2016-08-24 at 10.39.35 pm.png

This page should show all the available webclients for Mopidy. Here I have only one. You can click on it and will be taken to a page like this:

Screen Shot 2016-08-24 at 10.45.24 pm.png

From this point, it will behave as a normal music player. You will be able to browse you local music files and play them using this UI.


Let's Party

Here is a small demo of how I'm using Mopidy using MusicBox client from my android mobile. It is the webclient itself, but I created a shortcut to my home screen so that I can open it easily.


Happy Hacking,



<< Prev | Index | Next >>