Wall plug mania

To prevent my coffee pot from being burned every other weekday I had to be able to control wall outlets remotely and automatically via Openhab. For this I looked into into few possible solutions:

  • Build those outlets myself by modifying bunch of Kill-A-Watts, just like what Felix@Moteino Labs has done here with his WattMote or Mike on his Micromania Blog. I must say I was tempted to try experimenting with those, but since I eventually want quite a many of them, assembling those by myself seemed more like a chore. Also it is against the local Electrical Code to make permanent high voltage installations in here without proper license. Even though they are plug-in accessories, let’s be honest, they ARE permanent if one keeps them on 24/7. And besides, I wouldn’t want to sleep in a house full of DIY mains appliances – My sleeping disorder is bad enough as it is 🙂
Few pre-home automation era wall plugs. Don't these just scream for wireless connectivity!

Few pre-home automation era wall plugs. Don’t these just scream for wireless connectivity!

  • There’s a whole family of cheap 433 Mhz sensors, wall sockets/plug-ins, remote controls, doorbells and whatnot. Nexa is one of the manufacturers and their products are sold even here at local Clas Ohlsons. One could then buy for example Tellstick Duo or their more basic Tellstick USB stick, and connect it with RaspBerry Pi. Also Openhab supports Tellsticks natively. For complete device compatibility, see a list here. There’s also Tellstick Net, which is a ethernet connected stand-alone hub that doesn’t require another computer. I do like that modularity aspect, but the down-side is that it connects to their own Telldus Live! service (yuck!) and thus requires constant internet connection (another yuck!). Luckily there’s now an unofficial firmware available which removes that requirement.

    To my disappointment none of these 433 Mhz wall plug-ins (to my knowledge) are able to send their status or output power consumption to the hub i.e. you can only switch them on/off. Now that’s a bummer, since the use-case for turning off the coffee maker after some timeout period explicitly requires power consumption to be measured all the time (how else could the system know when the coffee maker has been manually turned on?)

    However the most concerning thing about these devices is that the security is a joke: all the wireless messages are transmitted without encryption so the attacker is able to just listen to the transmission outside your house and then replay the messages. Anyone still remember Wardriving? I can almost imagine script-kiddies driving around the city, looking for these devices and annoying the hell out of people by switching them on and off 🙂 In fact, there’s an interesting thesis written by students of Linkoping University that examines the security aspect of Tellstick Net. While it mainly concentrates on threats from (wired) network perspective and examines scenarios involving the Telldus Live! service, it’s interesting read. Also what’s funny is that they mention the wireless security only in one paragraph since the security flaw is so obvious they didn’t need the feel to research it more deeply 🙂

  • Wi-Fi 2.4Ghz remote wall plugs are available from D-Link, Belkin and Ankuoo (rebranded Netwjork here) just to name a few. The problem with these is that these look quite nice on brochures but actual user experience has been ranging from so-so to just horrible according to customer reviews on Amazon and other sites. The main annoyances have been flaky connectivity, pairing problems with WiFi router as well as 2.4 Ghz band collisions. I decided to opt out of this mess.

  • Finally there’s Z-Wave, a technology with a family of products that even remotely (pun intended) seemed usable. Using 868 Mhz band here in Europe (908 Mhz in the US) and providing encryption as well as better low-power support (compared to Wi-Fi products), this seemed the best pick out of options mentioned above. The only obvious down-side with Z-Wave devices is that they are quite expensive! Be it a simple flood switch, motion sensor or a wall switch, they all seem to cost a minimum of 40-50 euros / sensor. Since I wasn’t going to lock myself with only Z-Wave by using a proprietary hub, this wouldn’t be a problem. I can begin with wall plugs and then add more devices if needed should their prices come down.

Z-Wave jungle

For wall plugs there are quite many options available just to name a few:

In the end, they all seem quite alike, supporting power measurements beside remote switching. There’s also a new updated standard called Z-Wave Plus (another name for ‘Gen 5’ variety of Z-Wave products, such as the Aeon Smart Switch.)

According to the specs the Z-Wave Plus Features:

  • Significant increased range – up to 150m (clear air)
  • 50% improvement in battery life
  • 250% more bandwidth
  • Three F channels for improved noise immunity and higher bandwidth
  • New Plug-n-Play Network-wide Inclusion feature
  • Improved self-healing and fault tolerance with Explorer Frame feature
  • Standardised method for Over the Air firmware updates (OTA)
  • Improved product information capture for product certification database

This all looks good on paper, but there has been conflicting reports of success with Z-Wave Plus devices and Openhab and other DIY systems, so I decided to pick one older wall plug (AN158 by Everspring) without the Plus support as well as the newer Aeon Smart Switch Gen with Plus capability, both which are readily available here.

To enable communication between Z-Wave devices one needs a main controller that can include and exclude devices to and from the Z-Wave network as well as do bunch of other maintenance and configuration work in the network. When it comes to choosing the Z-Wave controller it all boils down to 2 options: Razberry and Aeon Labs Z-Stick Series 2. Both support Z-Wave Plus devices, but whereas the Z-Stick dangles outside Raspberry and occupies one of the USB slots, Razberry connects to Pis GPIO connector and slides nicely inside the enclosure. I chose the Razberry which seemed a nice idea at that time, but in hindsight Z-Stick maybe would have been better choice should I ever want to migrate away from Raspberry.

In a bit of shopping frenzy I bought also 2 wall switches WALLC_S Secure Wall Switch by Z-Wave.me, since there always will be some occasions when you cannot rely on automated scripts but want to do some manual switching instead. Even though these kind of switches could be easily built using a Moteino and 3.3V coin cell battery, I clearly lack the skill at this stage to create nice enclosures and thus didn’t want to stick any of my frankensteinos (Frankenmotes?) on walls or other visible surfaces 😀

First batch of Z-Wave devices to be tested

First batch of Z-Wave devices to be tested

Connecting with Openhab

For configuring Razberry to be used with Openhab I followed instructions from Home Automation For Geeks. I first tried HAbmin but I didn’t have any luck getting Z-Wave devices detected nor included in the network, so I resorted to the Z-Way server from Z-Wave.me (same manufacturer as Razberry). After fumbling around with the not-so-intuitive settings, all devices were finally set up nicely (or so I thought.. See the next post). After configuring devices the Z-Way server has to be shut down, since it cannot use Razberry simultaneously with Openhab.

First attempt was to use AN158 as coffee maker switch in kitchen. As before, items are defined in .items file (here Z-Wave device #3 is AN158)

Switch Kitchen_Coffee_Switch "Coffee machine" (GF_Kitchen) {zwave="3:command=switch_binary"} 
Number Kitchen_Coffee_Watts "Coffee machine power consumption [%.1f W]" (GF_Kitchen,GF_Energy) { zwave="3:command=meter" }

Then a rule for switching it off after 50 minutes can be set in coffee.rules. It automatically will detect when it has been switched on (consumption goes over pre-defined threshold value) and starts the timer.
import org.openhab.core.library.types.*
import org.openhab.core.persistence.*
import org.openhab.model.script.actions.*

var Integer coffee_watts_threshold = 5
var Integer coffee_timeout = 50
var Timer coffee_timer = null

rule "Coffee switch off"
        Item Kitchen_Coffee_Watts received update
        logInfo("coffee switch", "consumption " + Kitchen_Coffee_Watts.state + " watts. " )         

        if ( ((Kitchen_Coffee_Watts.state as DecimalType).intValue() > coffee_watts_threshold) && (coffee_timer == null) )
            logInfo("coffee switch", "Coffee on. consumption " + Kitchen_Coffee_Watts.state + " watts. Setting switch off timer to " + coffee_timeout + " minutes." )
            coffee_timer = createTimer(now.plusMinutes(coffee_timeout)) [|
                if ((Kitchen_Coffee_Watts.state as DecimalType).intValue() > coffee_watts_threshold)
                    logInfo("coffee switch", "coffee maker still on after timeout period. Switching off.. " )   
        else if ( (Kitchen_Coffee_Watts.state < coffee_watts_threshold) && (coffee_timer != null) ) 
            logInfo("coffee switch", "Coffee off. Canceling switch off timer" )

To my surprise, it started to work out-of-the-box without any additional head scratching. No more burned coffee pots 🙂

Enter Moteino

Having played few days with Arduino Mini and the NRF24L01+ transceiver I came into conclusion that I wanted something more compact with lower power consumption. After some hours of coffee-powered research two top contesters surfaced: Jeenode and Moteino. Also there’s an upcoming ultra-low power arduino clone ULPNode which uses few quite interesting power saving techniques, that makes it possible to reach nanoampere scale basal power consumption when in deep sleep. Unfortunately prototypes are not yet available for purchasing but I will for sure try those out in the future!

Also one thing to consider is that these levels of ultra-low consumption can be implemented on a real-life sensor only when the sensor part itself can be put to sleep (for example with periodical temperature measurements). Since most of my sensor devices in planning will use at least one active sensor (PIR motion sensor mainly), it is irrelevant whether the board uses few microamps vs few dozen nanoamps when the PIR sensor itself uses 50 microamps in standby-mode.

Both Moteino and Jeenode use the low quiescent current MCP1703 voltage regulator and don’t include any kind of LED to indicate power on status (unnecessary power hogs), so low current consumption and long battery life could be obtained even without modifying the hardware.

In the end, I voted for Moteino for following reasons:

  • Compact and quite nice looking
  • RFM69W wireless chip (vs older RFM12B in Jeenode with no HW level encryption)
  • active user base and forum
  • few euros cheaper than JeeNode (not really a deciding factor, but nice to know if you are planning to spread your house full of these sensors..)


Testing Moteino on breadboard with FT232 USB adapter

Testing Moteino on breadboard with FT232 USB adapter

Here’s Moteinos sleep mode consumption after some testing:

  • 23 microamps (16 Mhz, BOD off, 5.0V to Vin)
  • 1.3 milliamps (16 Mhz, BOD off, 3.3V bypassing MCP1703).
    Wow, The regulator sure doesn’t like to be left idle 🙂
  • 22 microamps (16 Mhz, BOD off, 3.3V in, MCP1703 desoldered)
  • 20 microamps (8 Mhz, BOD off, 3.3V in, MCP1703 desoldered)

Note that also the RFM69 needs to be put to sleep (with the transmitter awake but idle I measured 1 milliamp higher values).

Whan transmitting packets the consumption jumps to few dozen milliamps, but this is inconsequential, since the transmitter and CPU will be in deep sleep 99% of the time, awakened only by interrupts from the sensor or hardware watchdog.

So, the setup and assumed current consumption is as follows (values for sensors are from datasheets, I didn’t test sensors separately):
* Moteino @ 16 Mhz: 23 uamps (I didn’t bother with 8 Mhz since at this stage the 2 microamp difference in consumption is negligible)
* 4xAA batteries (calculated later)
* DHT22 temperature and humidity sensor (40-50 uamps)
* PIR sensor (50 uamps)
* Voltage divider setup with a capacitor to measure 4-6V battery voltage (few microamps with 1 Mohm resistor)
* Motion detected LED (0 uamps off)

First prototype

I tossed the parts into left-over junction box. Better looking enclosure would have been nice, but unfortunately I don’t currently have tools nor working area in my current apartment to process suitable materials.

First prototype of bathroom motion sensor. This isn't going to win any beauty contests, but it works :)

First prototype of bathroom motion sensor. This isn’t going to win any beauty contests, but it works :)

Note that the 433 Mhz version of RFM69W seen here needs (or better said, is recommended to have) 17.2 cm antenna and is actually shipped with a 16,5 cm one since the PCB traces make up for the remainder. Now, in my tests I found out that I don’t need that long wire sticking out vertically, but can just route it inside around the edges of the enclosure. Even this gives it plenty of signal strength to transmit through 2 thick walls two rooms across. Good enough.


I measured the current consumption to be 104 microamps @ 5V, which is quite in the ballpark expected! With ideal situation (0% monthly battery discharge) this sensor would last for 4*2000 mAh / 0.104 = 76923 hours = 8.78 years 🙂 Of course now the self-discharge of NiMH batteries start to matter considerably: Cheap NiMH batteries have as high as 20-30% discharge rate, whereas better Sanyo Eneloops (3rd gen) are specified to hold 70% charge after 5 years! Now this would be an almost set-and-forget situation. Actually I just recently ordered a pack of Eneloops, so I think this is going to end up being a field-test lasting for few years 😀

Pairing with Openhab

Now, let’s concentrate on software a bit. Since MySensors supports only the NRF24L01+ and it’s libraries seem to be quite tightly coupled with it’s hardware functionality, I had to find a replacement. After some digging I came across this nicely done pack of libraries for MQTT Gateway and Sensor made by Computourist. With just a few tweaks I was able to fire up (not literally) the sensors and get them to communicate with Openhab. Unlike MySensors MQTT gateway, this one isn’t MQTT server but just normal client so no MQTT server bridging was necessary. Just configure the MQTT server IP address:port in the sketch and Moteino gateway connects automatically and will also keep on trying should it lose the connection to the MQTT server.

MQTT Gatewey will send and receive messages in a fixed notation such like these:

pi@raspberrypi:/opt/openhab# mosquitto_sub -v -t '#'
home/rfm_gw/nb/node02/dev02 -61
home/rfm_gw/nb/node02/dev04 5.2
home/rfm_gw/nb/node02/dev48 24.38

Here nb=northbound (messages from nodes/sensors to the server), sb=southbound (messages from server/openhab to nodes). Devices (items residing inside a node) will be defined per-node basis and could be anything from sensors, actuators to node setting containers. For example commands

pi@raspberrypi:/opt/openhab# mosquitto_pub -t home/rfm_gw/sb/node03/dev00 -m "READ"
pi@raspberrypi:/opt/openhab# mosquitto_pub -t home/rfm_gw/sb/node03/dev04 -m "READ"

could be used to read uptime and battery voltage of node #3.

pi@raspberrypi:/opt/openhab# mosquitto_pub -t home/rfm_gw/sb/node03/dev01 -m 60

Could be used to set periodic transmission interval to 60 seconds. Actual implementation depends on sensor, but these libraries give quite nice framework to work upon.

To accept messages from MQTT Gatewey we just define new items in the Openhab .items file to match the new sensors:

Contact Bathroom_Motion_Sensor {mqtt="<[mosquitto:home/rfm_gw/nb/node03/dev40:state:MAP(switchFromMqtt.map)]"}
Number Bathroom_Temperature  "Bathroom temperature [%.1f C]"   <temperature> {mqtt="<[mosquitto:home/rfm_gw/nb/node03/dev48:state:default]"}
Number Bathroom_Humidity  "Bathroom humidity [%.1f %%]" {mqtt="<[mosquitto:home/rfm_gw/nb/node03/dev49:state:default]"}
Number Bathroom_Sensor_Voltage  "Bathroom sensor voltage [%.1f V]"  {mqtt="<[mosquitto:home/rfm_gw/nb/node03/dev04:state:default]"}

We also need to map the state of the motion sensor (ON/OFF) to a state shat the "Contact" item understands (CLOSED/OPEN). That is done in switchFromMqtt.map (referenced above with MAP(switchFromMqtt.map):


PIR sensor and light rules

Then some timer magic is created to turn on the bathroom light when motion is detected:

import org.openhab.core.library.types.*
import org.openhab.core.library.items.*
import org.openhab.core.persistence.*
import org.openhab.model.script.actions.*

var Timer BathRoomTimer = null
var Integer timeOut = 120

rule "Bathroom Motion Sensor Trip"
        Item Bathroom_Motion_Sensor received update
        logInfo("Bathroom motion Sensor", "sensor changed state")
        if (BathRoomTimer == null ) 
            logDebug("Bathroom Motion Sensor","timer==null")
            logDebug("Bathroom Motion Sensor","timer!=null")
        if(Bathroom_Motion_Sensor.state == CLOSED)
            if (BathRoomTimer == null ) 
                // create timer
                logInfo("Bathroom Motion Sensor", "creating timer: " + timeOut + " sec")
                BathRoomTimer = createTimer( now.plusSeconds(timeOut) )
                        logInfo("Bathroom Motion Sensor", "timer expired, switching off ")
                sendCommand(Bathroom_Light_Toggle, ON)
                sendCommand(Bathroom_Light_CT_Dimm, Light_Temperature.state as DecimalType)
                logInfo("Bathroom Motion Sensor", " rescheduling timer:" + timeOut + " sec" )

Everything seemed to work just fine, but when I took a shower in the morning, PIR sensor couldn't obviously detect any movement behind shower curtain and eventually the light was turned off again, me still in the shower 🙂 Hmm.. Either I could extend that delay period to few minutes (lazy option), OR I could use humidity sensor to detect rise in humidity above a certain threshold (when shower is being used) and extend the delay only then. I chose the latter, more elegant option:

var Integer timeOutWithShower = 300

rule "Bathroom Motion Sensor Humidity"
        Item Bathroom_Humidity received update
        logInfo("Bathroom Humidity Sensor", "bathroom humidity changed")
        if( ( BathRoomTimer != null) && (Bathroom_Humidity.state > 60) )
            logInfo("Bathroom Humidity Sensor", " shower on - rescheduling timer for bathroom in " + timeOutWithShower + "sec" )

This required also changes sensor-side, since in normal mode humidity would be measured only every few minutes. I implemented a "perceptive mode" to start measuring temperature and humidity every few seconds after motion is detected. Mode is then switched back to normal after 1 minute. This gives enough time for humidity sensors to react (in fact humidity goes over 50-60% in just 20 seconds after shower is turned on.)

Next coming: Dash of Z-Wave sorcery!