Wemos D1 Mini Door Contact (plus temperature)

, posted: 16-Nov-2017 07:58

Creating a garage door contact switch for detecting if the door is open.

I had my garage door added to my house alarm. In doing so, it was added to a button on the remote we use for arming and disarming. Well after one morning where my son accidentally opened the garage door (which we can’t see from the house) I looked at adding a reed switch to the door to detect it’s open state.

I hadn’t used a Wemos D1 Mini before but I liked the size of them, and there seemed to be a fair bit of code around to base off.

After buying 3, and finally taking delivery of some DHT shields (DHT12 for temperature), some reed switches and a few other bits and pieces for future projects I started playing in the Arduino IDE.


What most blogs will give you is a schematic breadboard with the Wemos pins, but then it tends to get a little fuzzy in showing how the various components are wired up.


So in actual case with my 2 wire reed switch, I wired 1 wire to the ground header of the wemos, the other wire to the D2 header.


Excuse the soldering, it’s been a long time.  Also I’ve moved these connections to the rear, as I intend to mount in an enclosure and want the DHT Shield on top exposed the the air (not that the temperature on this is important).

But what you should see is the D2 and GND pins being used.  The DHT Shield communicates on D4.

Next the code.

I’ve decided on a framework called Homie.  This is an MQTT enabled framework that allows for over the air (OTA) firmware updates and a consistent messaging protocol for sensors.

There are a number of blog posts aroudn getting a Wemos D1 to work in the Arduino IDE, so I wont cover this.




The simple blink samples are well worth doing if you’ve not played before.

As for Homie.  Here is the quick Start http://marvinroger.github.io/homie-esp8266/2.0.0-beta.1/quickstart/getting-started/

I started with the Version1 stable, but quickly moved to the Version 2 (beta at time of writing) for access to the OTA updates.

Once the D1 Mini was working in the Arduino IDE, and the Homie Framework installed and running on your mini.  You’re now in the position to look at this specific project.

There are two parts we need to think about.  The reed switch and the temperature sensor.  I will mostly concentrate on the reed switch as that’s the least documented.

#include <Homie.h>
#include <WEMOS_DHT12.h>

#define FW_NAME "dhtshield-reed-dht12"
#define FW_VERSION  "1.0.3"

/* Magic sequence for Autodetectable Binary Upload */
const char *__FLAGGED_FW_NAME = "\xbf\x84\xe4\x13\x54" FW_NAME "\x93\x44\x6b\xa7\x75";
const char *__FLAGGED_FW_VERSION = "\x6a\x3f\x3e\x0e\xe1" FW_VERSION "\xb0\x30\x48\xd4\x1a";
/* End of magic sequence for Autodetectable Binary Upload */

/* Reed pin */
#define REED_PIN D2
int doorState = 0;

unsigned long lastTemperatureSent = 0;
DHT12 dht12;

HomieNode reedNode("reed", "state");
HomieNode temperatureNode("temperature", "temperature");
HomieNode humidityNode("humidity", "humidity");

void setupHandler() {
   // Do what you want to prepare your sensor

void loopHandler() {
   int lastDoorState = doorState;
   doorState = digitalRead(REED_PIN);
   String doorStateString = "unk";

  if (lastDoorState != doorState) {
     if (doorState == 1) {
       doorStateString = "open";
       Homie.getLogger() << "Door State: OPEN" << endl;
     } else if (doorState == 0){
       doorStateString = "closed";
       Homie.getLogger() << "Door State: CLOSED" << endl;
     } else {
       doorStateString = "unk";
       Homie.getLogger() << "Door State: UNKNOWN" << endl;

  if (millis() - lastTemperatureSent >= TEMPERATURE_INTERVAL * 1000UL || lastTemperatureSent == 0) {
         float temperature = dht12.cTemp;
         float humidity = dht12.humidity;
         Homie.getLogger() << "Temperature: " << temperature << " °C" << endl;
         Homie.getLogger() << "Humidity: " << humidity << " %" << endl;
     lastTemperatureSent = millis();

void setup() {
   // put your setup code here, to run once:
   Serial << endl << endl;
   Homie_setFirmware(FW_NAME, FW_VERSION);



void loop() {
   // put your main code here, to run repeatedly:



Lets break some of it down, include statements for the Homie framework, and the DHT shield. 

#include <Homie.h>
#include <WEMOS_DHT12.h>


The name and definition of the firmware (used when there is an OTA server).

#define FW_NAME "dhtshield-reed-dht12"
#define FW_VERSION  "1.0.3"

/* Magic sequence for Autodetectable Binary Upload */
const char *__FLAGGED_FW_NAME = "\xbf\x84\xe4\x13\x54" FW_NAME "\x93\x44\x6b\xa7\x75";
const char *__FLAGGED_FW_VERSION = "\x6a\x3f\x3e\x0e\xe1" FW_VERSION "\xb0\x30\x48\xd4\x1a";
/* End of magic sequence for Autodetectable Binary Upload */



The pin number for the reed switch and a variable to hold the door state.

/* Reed pin */
#define REED_PIN D2
int doorState = 0;


Variables to the DHT shield, the important one is the DHT12 which is the object that will perform the reading.

unsigned long lastTemperatureSent = 0;
DHT12 dht12;


This is the Homie Property that will hold the reed switch state.

HomieNode reedNode("reed", "state");


And two more for the temperature and humidity readings from the DHT Shield.

HomieNode temperatureNode("temperature", "temperature");
HomieNode humidityNode("humidity", "humidity");


Here is all your specific code for your sensors.  So in this case I’m setting the reed property type (eg on off), and defining the pin that is read.  For the DHT I’m setting the unit type for the temperature and humidity.

void setupHandler() {
   // Do what you want to prepare your sensor


I’ve skipped over the main loop handler and will cover that last, as it’s the bit that does the work.

The setup function sending the firmware name and version, sets up the looping function (loophandler) and tells all the nodes to advertise their properties.

void setup() {
   // put your setup code here, to run once:
   Serial << endl << endl;
   Homie_setFirmware(FW_NAME, FW_VERSION);




Here is part of the main loop handler.  This is concerned with the reading of the reed switch.  The current doorState is kept, then the reed switch GPIO port is read.

Then only if the previous door state and current differ does it translate the pin state into an MQTT friendly (OpenHAB Contact) state – of ‘OPEN’ or ‘CLOSED’

void loopHandler() {
   int lastDoorState = doorState;
   doorState = digitalRead(REED_PIN);
   String doorStateString = "unk";

  if (lastDoorState != doorState) {
     if (doorState == 1) {
       doorStateString = "open";
       Homie.getLogger() << "Door State: OPEN" << endl;
     } else if (doorState == 0){
       doorStateString = "closed";
       Homie.getLogger() << "Door State: CLOSED" << endl;
     } else {
       doorStateString = "unk";
       Homie.getLogger() << "Door State: UNKNOWN" << endl;


The line


is what sends the current state to the MQTT broker.


The rest is all concered with reading the state of the DHT shield if the last time the temperature was read is > that the interval set in the settings, eg 300 seconds or 300000 milliseconds.

if (millis() - lastTemperatureSent >= TEMPERATURE_INTERVAL * 1000UL || lastTemperatureSent == 0) {
         float temperature = dht12.cTemp;
         float humidity = dht12.humidity;
         Homie.getLogger() << "Temperature: " << temperature << " °C" << endl;
         Homie.getLogger() << "Humidity: " << humidity << " %" << endl;
     lastTemperatureSent = millis();

Here are all the properties being sent to MQTT


The state of the reed switch is sent regardless on the same interval, if not already set.  Probably not needed as homie defaults each message to retained on the MQTT broker.

Lastly the function is looped each second.


Once this code is uploaded to the D1 via the Arduino IDE.  Open the Serial Monitor to see messages with the connected D1 Mini.  This should show the device attempting to connect to a WIFI network – of which it doesn’t know any.  So you need to post it a config file which tells the device how to connect.  http://marvinroger.github.io/homie-esp8266/2.0.0-beta.1/configuration/json-configuration-file/.  Once the device has figured it there is no known network, it will actually create an AP.  Connect to this and from here navigate to http://setup.homie-esp8266.marvinroger.fr which should take you to the Wemos D1 mini running homie.  Here there are pages to configure the device name (this is the MQTT topic it will use), it’s nice name, the WIFI network and password, the location of your MQTT broker and base topic.  Enter all these and save.

I use a base of sensors/d1mini for my MQTT topic.  And for a device name garage-sensor, I should expect to see mqtt messages appearing in the topic sensors/d1mini/garage-sensor. I use this naming scheme for other devices as well, such as a raspberry pi with a DHT sensor is on sensors/dht/<device>.

At this point the device should reboot.  I found mine do not, so I have to hard reboot (pull power).  Again keep it connected via serial monitor and you should see it come up and connect to your WIFI network.

If you seen the connect to the network, then you can now go to your mqtt broker and check for messages.  Given mine is on a linux, I’ll be using the linux mosquitto commands.  But any MQTT client will work.

To list all entries for this example device I’d enter (assuming that I was running the command on the same server as the mqtt broker.:

mosquitto_sub –v –t sensors/d1mini/garage-sensor/#

sensors/d1mini/garage-sensor/$homie 2.0.0
sensors/d1mini/garage-sensor/$implementation esp8266
sensors/d1mini/garage-sensor/$implementation/config {"name":"Garage","device_id":"garage-sensor","wifi":{"ssid":"IOT"},"mqtt":{"host":"","mDNS":"mqtt","port":1883,"base_topic":"sensors/d1mini/"},"ota":{"enabled":true,"host":"","port":9081,"path":"/custom_ota"}}
sensors/d1mini/garage-sensor/$implementation/version 2.0.0
sensors/d1mini/garage-sensor/$implementation/ota/enabled true
sensors/d1mini/garage-sensor/$mac xx:xx:xx:xx:xx:xx
sensors/d1mini/garage-sensor/reed/$type state
sensors/d1mini/garage-sensor/reed/$properties state
sensors/d1mini/garage-sensor/reed/state closed
sensors/d1mini/garage-sensor/temperature/$type temperature
sensors/d1mini/garage-sensor/temperature/$properties unit,degrees
sensors/d1mini/garage-sensor/temperature/unit c
sensors/d1mini/garage-sensor/temperature/degrees 16.70
sensors/d1mini/garage-sensor/humidity/$type humidity
sensors/d1mini/garage-sensor/humidity/$properties unit,percent
sensors/d1mini/garage-sensor/humidity/percent 68.20
sensors/d1mini/garage-sensor/humidity/unit %
sensors/d1mini/garage-sensor/$name Garage
sensors/d1mini/garage-sensor/$stats/interval 60
sensors/d1mini/garage-sensor/$stats/signal 86
sensors/d1mini/garage-sensor/$stats/uptime 343921
sensors/d1mini/garage-sensor/$fw/name dhtshield-reed-dht12
sensors/d1mini/garage-sensor/$fw/version 1.0.3
sensors/d1mini/garage-sensor/$online true

So if I see this then I know the device is a, working, two, reading my reed switch and DT shield.  It may take a little while for the DHT values to be populated.  The $online tag is really useful for know the device in online and running.

Next we’ll get the values into OpenHAB – but the concept should be similar for Home Assistant.  Here is an items file I have for my D1Mini sensors.  Once thin I like with the new version of OpenHAB2 is that you can (if you wish) segregate items types by technology.

Group g_d1mini "D1 Mini"
Group g_d1mini_garage "Garage"  (g_d1mini)
/* Garage*/
Number   d1mini_garage_temperature  "Temperature [%.1f °C]" <temperature> (g_d1mini_garage) {mqtt="<[mqtt:sensors/d1mini/garage-sensor/temperature/degrees:state:default]"}
Number   d1mini_garage_humidity  "Humidity [%.1f%%]" <humidity>   (g_d1mini_garage) {mqtt="<[mqtt:sensors/d1mini/garage-sensor/humidity/percent:state:default]"}
Number   d1mini_garage_signal  "Signal [%.1f%%]" <signal>   (g_d1mini_garage) {mqtt="<[mqtt:sensors/d1mini/garage-sensor/$stats/signal:state:default]"}
Number   d1mini_garage_uptime  "Uptime [%d]" <humidity>   (g_d1mini_garage) {mqtt="<[mqtt:sensors/d1mini/garage-sensor/$stats/uptime:state:default]"}
String   d1mini_garage_ip  "IP [%s]"   (g_d1mini_garage) {mqtt="<[mqtt:sensors/d1mini/garage-sensor/$localip:state:default]"}
String   d1mini_garage_name  "Name [%s]"    (g_d1mini_garage) {mqtt="<[mqtt:sensors/d1mini/garage-sensor/$name:state:default]"}
Contact  d1mini_garage_door "Door [%s]"  (g_d1mini_garage) {mqtt="<[mqtt:sensors/d1mini/garage-sensor/reed/state:state:MAP(onoff.map)]"}
Contact  d1mini_garage_online "Online [%s]"  (g_d1mini_garage) {mqtt="<[mqtt:sensors/d1mini/garage-sensor/$online:state:MAP(onoff.map)]"}

So this assumes your mqtt broker for OpenHAB is set up and running, and accepting messages.  Here is the config page: http://docs.openhab.org/addons/bindings/mqtt1/readme.html

So a quick run down, here is the garage door reed switch.  It is a contact item (which is a read only switch in openhab) which has a state of OPEN or CLOSED.  Equally a switch will work.

Contact  d1mini_garage_door "Door [%s]"  (g_d1mini_garage) {mqtt="<[mqtt:sensors/d1mini/garage-sensor/reed/state:state:MAP(onoff.map)]"}

The important bits here is that it’s using the MQTT binding, with a defined mqtt server (done as part of the OpenHAB config, and looking at sensors/d1mini/garage-sensor/reed/state for it’s state information.  If we look back at the code, when the reed switch is open (too far from each other) the word “open” will be posted to this topic.  When closed, ”closed” is posted.  As that wasn’t what OpenHAB was actually expecting, it expected OPEN and CLOSED in capitals, the MAP(onoff.map) is a translation table which translates open to OPEN.

So in OpenHAB (basic UI) I see the sensor show up as follows:


RM3's also - but this time with more geek.

, posted: 16-Jul-2017 20:16

Steve just blogged about the great little RM3 device - https://www.geekzone.co.nz/sbiddle/8949 - a small IR capable device with a number of IR transmitters in it.  Capable of controling heatpumps, tvs and stereos.

But using their app, does allow the little device on the internet, as as Steve alluded to, it's not pretty and uses their cloud when you're out an about.  While simple to use, that's not geeky enough for me, and I'm already using the OpenHAB app, why would I want to use another one for one device?  You're right, I wouldn't.

OpenHAB has concept on bindings and services.  These are addons for controlling various aspects or other systems.  Now the RM3 addon can't be written, because there's an element of revers engineering the protocol and including decryption.  So people looked for another method.

If you've read my other Home automation posts, you'd see I'm a big fan on MQTT - Mosquitto.  It's a great little transport system for sending and receiving small messages for receiving status messages (from devices), or sending commands.

Well some bright spark, made a RM3 <-> MQTT bridge, that means that any home automation software and interact with it.  I took this code and forked it to add some more remotes, and are in the process of adding support for multiple RM3 devices.  As, as soon as I had one working, I had to get another one.

Here's the link to github: https://github.com/eschava/broadlink-mqtt - or to follow my version: https://github.com/psyciknz/broadlink-mqtt

Follow the instructions to get it installed, this will mean you've got a script that you can run that will talk to your RM3.  There are some commands (specifically support for some Samsung TVs and a Yahama Amplifier) as part of the package, but you can record any new codes you need.  It's unfortunate the code sequences differ from lirc...but thems the brakes.

So what I'll actually be writing about is getting the MQTT bit going, specifically for OpenHAB, but it should be transportable across any system that has interaction with MQTT.

So if you haven't already got one, you'll need a mosquitto server.  There's servers for linux and windows.  The windows one works, but I prefer to run them on linux.  So I have one machine set up and a mosquitto server.  This will receive and send and mqtt messages.


The process is, that a command is sent from OpenHab to a special topic starting with broadlink.  The rest of the topic, relates to the command to send.


broadlink/tv/samsung/volumedown replay

This is telling the broadlink-mqtt script to send, or replay, the command from tv/samsung/volumedown to the attached RM3 device.

So how do I get OpenHAB to send it's command to the right place.

I use a rollershutter OpenHAB item.  In either OpenHAB 1 or 2.  An Items file is a list of items that can be interacted with.

Rollershutter rm3_lounge_samsung_volume "Volume" (rm3) { mqtt=">[mqttbroker:broadlink/tv/samsung/volumeup:command:UP:replay],>[mqttbroker:broadlink/tv/samsung/volumedown:command:DOWN:replay]"}

 I'll break this up into it's bits.

Rollershutter is the item type.   - It presents an up and down arrow, and as a device sends and UP and DOWN command to the item.

rm3_lounge_samsung_volume is the item name - which is called from a sitemap - the sitemap is what decides what to items to display.

"Volume" is the icon name - there's a bunch of these as presets.

(rm3) is it's group.  Can be used for controlling multiple items as a whole, or for grouping display items.

The MQTT bit is what communicates with MQTT.  This also has a number of parts.

OpenHab has a number of MQTT brokers - which are configured in the settings.  I have an broker called mqttbroker, which exists on a linux machine - lets call it fred.

In the MQTT command > denotes that it is a command being sent.  As opposed to < which is a status being received into OpenHAB.  So in this case we are sending one of two states.  One for when the roller shutter item Up arrow is pressed, and another for when down is pressed.

So for the UP state, we are sending the replay mqtt message to broadlink/tv/samsung/volumeup, which as we know from before the broadlink-mqtt script will see this command, and replay, the volumeup command to the connected RM3 and therefore change the volume up by one increment.  For the DOWN state, a replay to broadlink/tv/samsung/volumedown will be sent.

This configuration can be repeated for each command for each device.  All that differs is the mqtt command that is being sent out, and how it is attached to the various OpenHAB item types.

Hope that helps someone.  I wrote this after trying to explain to Steve how MQTT worked, so figured I'd better write it down.  If need be, I can add other OpenHAB items types for explanation.  And how you can send a different command to a device that has distinct on and off ir commands.  Or switching between multiple sources.




Controlling a 12v fan from a raspberry Pi.

, posted: 17-Jan-2017 07:49

My last post (Here), showed the reading of temperatures via raspberry Pi. The last post it was via a Bluetooth dongle and a BlueMaestro temp disc.

Once you've taken the temperature, or other sensor readings, it's now time to do something with it.

My Comms cabinet is in an external cupboard and wall mounted. It's one disadvantage, that on a sunny day, the sun beats on to the door and warms the room up, so I grabbed two 120mm fans, mounted them on to a bracket, and hooked them up to a 12v AC adapter. It works well, but I realised that it didn't need to be on 24x7. So I started investigating options for tying the fans to the temperature.

Initially I tried an external thermostat. As an idea it was great (12V Digital Thermostat Temperature Alarm Controller). On execution the one I'd bought didn't seem to work, as even though it powered, when triggered I was getting no voltage on the output terminals. Disappointing, but led me to look harder at raspberry Pi based methods. Then I stumbled across some posts on mosfet relays, and the use of Pulse width modulation. 0-24VTop Mosfet Button IRF520 MOS Driver Module For Arduino MCU ARM Raspberry pie.

Upon receiving the relay, I quickly wired a DC 2.1 barrel and socket knowing that I could plug it into the fan that already used that connector and a battery also with a similar connector, or into a voltage regulator as shown below. Then I found some python code that used the PWM pin on the raspberry Pi (pin 18) and controlled an LED light from 0 to 100 and back.


The mosfet relay is wired as follows:

VCC (positive) to pi. 2 (white)
GND (negative) to pin 4 (black)
SIG (signal) to pin 12 (this is a raspberry pi's PWM port GPIO 18) (gray)

After testing with a fan that it would actually drive the two fans, I started the interface to OpenHAB

I'll start with the OpenHAB items, so you can see where the mqtt topics are entered.

Switch gf_cupboard_fan "Fan Control [%s]" <socket>  {mqtt=">[mosquitto:cupboard/fan:command:ON:1],>[mosquit to:cupboard/fan:command:OFF:0],<[mosquitto:cupboard/fanstate:state:default]"}

So this item has a couple of components.

  • First it's a switch
  • Its name (when accessing via sitemap, or as a command) is gf_cupboard_fan.
  • <socket> is the icon to use.

The next bits are the mosquitto bindings. I'll have to assume you know a little about this already.

But in essence this one says that openhab will push (defined by the >) to a subscribed item on the topic cupboard/fan, 1 for ON and 0 for OFF when the switch is acted upon, by the user in the OpenHAB interface. The next part with the < is an input on a topic cupboard/fanstate. This will receive a status back from the fan control script.

Next up is the script that will both subscribe to the control topic (cupboard/fan) and the publish the state back to openhab - cupboard/fanstate.

The script can be found here: Github Link

I'll post the main sections - warning, this isn't as parameterised as some if the other scripts I have. If I install another instance then I'll add a lot more configuration parameters.

After the two callback methods, on_message and on_connect, setup up the mosquito server and gpio ports.

set the loop time
PAUSE_TIME = 60.02

Create the mosquito client, asking the callback messages, and connect to the server.

mqttc = mqtt.Client()
mqttc.on_message = on_message
mqttc.on_connect = on_connect

Here is the main run time loop:

while True:

except Exception,e:
    logging.error("Error in mqtt loop")

except KeyboardInterrupt:

There very little to it, as the work is in the on_message callback.

def on_message(client, userdata, msg):
    logging.info('Topic: ' + msg.topic+' Message: '+str(msg.payload))
    if msg.payload == "1":
        logging.info("Turning Fan on")
        (result1,mid) = client.publish("cupboard/fanstate","ON")
        logging.info("Turning fan off")
        (result1,mid) = client.publish("cupboard/fanstate","OFF")

If "1" is received as the message to the subscribed topic of cupboard/fan, the message is logged, and a ON state is posted back to OpenHAB to update the GUI (if the message has been fired external to the openhab GUI, ie a rule. If 0 received then the reverse.

def on_connect(client, userdata, rc):
    logging.info("Connected with result code "+str(rc))
    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.

The on connect method just subscribes to the topic where openhab will post the on/off command.

The last bit is the control, I have a GUI item for the switch. The is what can receive the state, and push the 1/0 state.

I also have a rule that runs whenever a specified temperature sensor is updated. The temperature is analysed, and when above a threshold the fan switch is sent an ON command. When below a minimum, an OFF is sent.

OpenHAB and Bluetooth beacons for temperature (Blue Maestro Tempo Disc)

, posted: 19-Dec-2016 21:39

Recently I've dipped my toes in the home automation pool.

I started out with an OpenHab installation on linux, then started adding some sensors.

The easy ones were existing items already compatible and computer based, NUT for UPS, Plex and with a bit of effort server load, temp and memory usage.

I had a couple of raspberry Pis floating around, so after some reading I added a 1 or 2 DHT22 sensors (http://bit.ly/2gR7wcP).  Including one raspberry pi with 2 sensors.  These work well with MQTT and feed in both temperature and humidity.

But doing that required a fair bit of wiring, and a raspberry pi with power costs around the $80 NZD mark, so I start looking a iBeacons, as some include temperature sensors.  The idea being I would have a central device (a Rasbperry Pi most likely), with a bluetooth receiver, and it would take a feed from a number of bluetooth based sensors.

I received one, but could never get the temperature sensor to activate and the support was a little lacking.

Then I stumbled across Blue Maestro (http://bluemaestro.com) .  They sell "smart" pacifiers and environmental sensors, all using Bluetooth LE.  After some back and forth discussing how they work and their intended use, I purchased a Tempo Disc (https://www.bluemaestro.com/temp-disc-bluetooth-sensors-data-loggers/).

It came with a link to an IOS app for pulling the internal data via bluetooth. 

So after looking at it on and off for a couple of months, and with a release on an updated API document, I finally found a set of commands for reading the raw data off the unit without having to make a proper connection.

For some background a bluetooth device will push out advertising packets at defined intervals.  These include the MAC address, the UDID of the device and version numbers.  But also hidden in another packet is some of the specific manufacturer information and specific instructions, in this case temperature, humidity and dewpoint numbers.

After a lot of trial and error I finally found that wireshark would read a bluetooth dump.


sudo hcidump -w btle.cap

On one SSH session and

sudo hcitool lescan --duplicates

on a second would create a dump file that you could then load into to wireshark.  The 2nd command is a bluetooth scan.  Its sends out requests for all devices in range and the response from each device is generally 1 or 2 advertising packets (SCAN_RSP - defined by the hex 04 at the start).

Before I found wireshark, at this point all I would see was a dump of hex:

04 3e 2a 02 01 04 01 xx xx xx xx xx xx 1e 1d ff 33 01 00 d9 02 ae 00 c0 02 41 00 d9 02 ae 00 93 00 c0 02 41 00 80 00 d0 02 82 00 89 b8

A blog post a read said that Wireshark could load a dump file from hci dump and interrogate the packets.  This made life so much easier to decode the packets, as you saw the hex and ascii.

This is the first packet (above).  It contains the mac address (in reverse).  There's no specific sensor information in this packet though.

The interesting one is the 2nd one:

04 3e 2b 02 01 00 01 xx xx xx xx xx xx 1f 02 01 06 11 ff 33 01 16 5e 0e 10 00 08 00 bf 02 b0 00 81 01 00 09 09 54 65 6d 70 48 75 6d 33 b3

This one also contains the mac address, and at the far right is actually the devices' name, Preceded by the length of the name.  In this case it's 9 characters and is 54, 65, 6d, 70, 48, 75, 6d, which when you convert to ASCII is "TempHum3"

The interesting data is in the middle though. 00 bf (28-29) is the temperature in hex. so 00 bf converting to decimal is 191 - or 19.1 Degrees.  Following, the 02 bf, is the humidity, or 688 decimal, or 68.8% and lastly is the dewpoint, 00 81 or 129 = 12.9 Degrees.

Once I had that then I knocked together a quick python program which will pull the advertising packets and put the mac address, temperature, battery, humidity and dewpoint into an object.

Company: 3301
UDID: a700d0025e00820100090954656d
MAJOR: 70 48 None
MINOR: 75 6d None
Temp: 00d0
Temp: 20.8
Humidity: 02 5e None
Humidity: 60.6
Dewpoint: 13.0
NameLength: 9
Name: TempHum3 9
Battery: 57 None
Battery: 87.3411764706

I also tested for the company id, which which is the blue maestro company identifier for this specific packet.

Then a send python script calls this one every 10 mins, if the packets are returned then I use MQTT to push the data to openhab.  At this point I used the mac address as a main topic...and push the name also.  Meaning what ever name I give the device is independent to the mac address and can be use for defining the room.

When it's all complete it looks as follows in OpenHAB;

So now that it's in OpenHab I can move to centralise the collection of environmental data to a couple of raspberry pis.

 I'm intending to put the code on github and will link to it when done.  The outer is generic, but the inner class is specific to these Blue Maestro discs.  But could be adapted for any type of similar device as long at it also used the advertising packets.

 UPDATE: Here's a link to github.  Both python files in this folder are required. Link Here


The New Age of Online Television

, posted: 19-Jun-2013 20:27

I've been watching with interest the announcements over the past few days regarding broadcasting of the English premier league football.

In a nutshell, the incumbant broadcaster - sky television, New Zealand's primary pay TV broadcaster - lost broadcast rights to the EPL.

What subsequently came out, was the set up of http://premierleaguepass.com, a subscription based online service for watching all 380 games of the league.

Quite a way down in the press releases and articles that were released it noted that subscriber would be able to watch all the games on PC, Mac, iPhone, iPads,  Androids and Apple TV devices.

This is where I think the service will fall down.  Yes watching a footy match on your iPhone or android phone will be great - for a highlights package, while on the train or bus. But do they seriously expect people to watch all the games on these small screens?

What about those with their 50" televisions and surround sound audio? Will they connect a laptop to the TV every time they want to watch a game? Standing up by the TV to navigate the desktop designed web site?

Where is the ability to pause or rewind the game, via remote, from the comfort of their couch?

While I applaud the break from Sky TV, the online, ondemand model in New Zealand is not mature enough yet for mainstream use. To transition for the average joe, a device is needed, a set top box, connected to the TV as is the sky decoder, with a connection to the Internet, a remote, and the ability to load user selected channels.  The reason for the user selected channels is becuase one single sport would not be able to sustain the costs of such a device by itself.  It would take colaboration by a number of networks and services to be viable (TVNZ, TV3, C4, Prime for example).

Such a device already exists, in the US, a roku. The roku combines the simplicity of use with the ability to add user selected channels -  either free or paid. 

The Apple TV is another solution, but short of adding each game as an "episode" or persuading apple to host premier league site for the New Zealand region (of which apple would take a cut of the subscription as they do with Netflix and Hulu) then this would not happen either.   To date apart from a number of US based services, only one other non US subscription based service has been added to the Apple TV (http://www.imore.com/apple-tv-gains-subscription-service-watchever-germany)

The other potential solution, is some of the smart TVs that currently sport App Stores.  The Samsung Smart TVs allow for the loading of a TVNZ Ondemand App and a Quickflix App.

Exciting times, and hopefully this will be the start of a new model of ondemand television in this country.

TVNZ Ondemand App behind UnblockUS Service - part II

, posted: 1-Mar-2013 07:14

Update, based on a commend @bagheera made, I reversed the process, put telecoms DNS servers in my router and used DNSMasq.conf to put all the overseas services to http://www.unblock-us.com

Here's the config I'm currently running:


I've confirmed netflix, bbc, itv and ABC.com. 

The version posted yesterday included mylifetime.com which included the brightcove domain name - this stopped TVNZ Ondemand from working.  I've never heard of that network so don't really mind losing it.


TVNZ Ondemand App behind UnblockUS Service

, posted: 27-Feb-2013 19:39

Recently TVNZ brought out an Ondemand App for IOS.  Whoohoo!!

Happily I downloaded it and gave it a spin but to my dismay nothing would show up.  

I had a thought though, I use the http://www.unblock-us.com  service for accessing overseas media services.  A quick change to my iPhone to set the DNS to my ISPs DNS servers confirmed that this was the problem.

The router I use is a TP-Link WR1043ND - but using the Gargoyle-Router.com firmware (v1.4.7) - in this I have the unblockUS DNS servers which means all traffic is generally sent through them.  They confirmed that TVNZ was not a service they deal wtih and so it was best to not use their DNS servers if trying to access them.

That meant I was up for changing my phones DNS settings everytime I wanted to try using the TVNZ Ondemand app.  

Screw that I thought.

So a bit of googling revealed I should be able to use different DNS servers depending on the client doing the accessing - ok I thought, before stumbling upon being able to use different DNS servers based on the domain trying to be accessed - perfect!!

I'm not entirely sure of the full mechanics of it, but essentially on the router I was able to say, if accessing any domain that contains brightcove.com (the video provider used by TVNZ) then use my Telecom domain servers.

This is done by editing the dnsmasq.conf file in the /etc/ directory of my router.

I went for a pretty broad bruch stroke approach and inserted at the bottom:

# add entries to use telecom DNS servers for brightcove.com domain.

After restarting the router I tried the app and off it went.  

There's a couple of refinements possible, that is defining the servers down to a lower level.  I turned on dnsmap logging:
and this showed the domains being accessed and the name servers being used. 

So your homework dear reader is to try and limit the domains further.  That said, I had a look through BrightCove's customers and the only one I saw was ITV (accessible via UnblockUS) -and it didn't seem to be affected, so I've left mine as it.

Update, based on a commend @bagheera made, I reversed the process, put telecoms DNS servers under my router and used DNSMasq.conf to put all the overseas services to unblock-us.com - see the post at http://www.geekzone.co.nz/davidcole/8355

PDF Forms - why you no boxes?

, posted: 26-Jun-2012 09:04

I recently had a number of claims to make for insurance purposes. Both companies had PDF forms to download, print and send away.

Neither had and online claim system, but I guess that could be forgiven with the number of supporting documents (originals only) that had to be supplied.

But my handwriting is truly doctor-worthy. And upon having Adobe Acrobat Professional on my work laptop I used their form wizard to get 70% of the form fields, and then quickly ran through drawing the form

Now I didn't put in formatting, pretty drop down boxes, just pure text boxes - all that is really available to me if I was using a pen, but honestly it only took me about 20 minutes.  The result was a form that could be easily read by a human or OCR technology upon receipt by the insurance company.

I thought about this as I walked to work. For an extra 30 - 60 minutes on these forms, these companies could supply a forms enabled PDF file for those inclined to fill out via computer. I'm not expecting electronic delivery, as I'm still expecting to print it out to sign it and supply the supporting documents (that is a whole other conversation), but means that the form I fill out is more legible, has had more corrections made to it (rather than crossing out or reprinting), could include descriptions on fields, notes, prompting fields (via drop down boxes, lists, enforced date formats, enforced character limits and more.

Example form - this is from the New Zealand Passport Adult renewal form - PDFs a available readily from www.passports.govt.nz/Downloading-and-printing-forms

The instructions clearly state to write in CAPITAL letters, so "that our computer software can accurately capture your information" - well why not enforce the use of captials by using a form, and use a computer to enter the information?

For those not inclined to fill out via computer, then another version of the PDF, or in fact the same one (the forms text boxes will not print out when empty).
Example 2 - passport form with boxes - these display in Adobe reader - but do not print - what is the harm in having them?

Example 3 - Filled in by hand - being in capitals - my doctor worthy scribbling is not so evident.

Example 4 - which would you rather receive?

Seems like a win-win to me.  Why don't companies do this? Lack of knowledge? Lack of forethought? Antiquated thinking? Or just laziness?  I think it's antiquated thinking. Companies are so used to designing the forms for printing out and later using the same form on a web site for download, they didn't take it that one step further and forms enable the PDF files.

eReceipts - Why don't we have them yet?

, posted: 12-Jan-2012 10:01

An offhand comment yesterday to an owner of a Cafe about digital (or electronic) receipts got me thinking, why don't we have these already?

We've probably all seen the emailed receipts that some retailers seem to send out.  Apple sends your receipt as an email.  Some retailer send PDF files with an invoice/receipt for online purchases.

But I was thinking about what can we do to rid ourselves of all this paper you collect in your wallet.

A quick browse around the internet last night brought me to this page: http://www.thehotiron.com/index.php/site/comments/ideas_to_eliminate_and_automate_retail_receipts/

I really liked the idea of a iCalendar/vCard type implementation rather than a formatted email/PDF file.  The reasons are as follows:
  • It's data, can be loaded to a smart phone app, finance program, or just saved somewhere as a file.
  • It could be generated as a QR code - you can create a vCard QR Code that contains contact information - why not a receipt.  The QR code could be printed on the bottom of a paper receipt - meaning those that want electronic and possess a smart phone can scan it (rather than the current standard of taking a photo and OCR or manually entering the data)
  • It could be transmitted via NFC/Email/SMS or presented as a QR code on an LCD screen (this might be a bit slow though at a POS terminal).
So the next bit to look at is a standard.  Guess what, someone has already thought of one.... The Association for Retail Technology Standards (ARTS) already has an xml specification for a Digital Receipt: Here

Next I thought quickly about implementation.  It would be hard, and very unlikely, for every retailer to set up LCD screens/email gateways etc to send these receipts out....so I thought why not think a bit higher up the food chain...what do all the retailers have (well most of them here in NZ) - EFT POS terminals.  All leased or bought through one or two companies. 

With a bit of modification, the EFT POS receipts that are currently printed could include a QR code of a Digital receipt, or on authorisation the EFT POS merchants could send out receipts via email/sms (obviously this last idea would be a subscription based system), or include NFC technology (terminals which include this technology are already being implemented with the likes of snapper, Visa's PayWave or Mastercards PayPass).

It seems like we have most of the pieces they just need to be connected...

Do you like the idea of digital receipts?  Do you keep your paper ones?  Do you throw everything away?

How do we deal with the fact that a receipt is proof or purchase, and is used for your warranty claim?  Those that scan receipts, have you used one of those to validate your purchase?  Did the store accept it?

Sure there are some kinks to work out, but I don't think they're insurmountable.




Contactless Payments - part 2

, posted: 21-Sep-2011 15:12

Yesterday I blogged about feeling uneasy with the no-authentication-for-under-$80-transactions on MasterCards PayPass implementation for ASB Bank.  See here http://www.geekzone.co.nz/davidcole/7804

A number of the comments I received said "any fraud will be reimbursed", "its the bank or merchants taking the risk, not you", "they have insurance to cover that".  Yes they probably do.  I've been rung by ASB as a current customer to notify me of transaction found on a credit card I do use for internet transactions, and the process was remarkably simple and painless.  So I know it works.

But the issue is, why should something be implemented, that requires insurance and fraud protection.  Why not design it to lessen this risk.

I'm going to pull out of context some of the PCI DSS (link) requirements that service providers, merchants and banks have to adhere to:

8.2 Employ at least one of these to authenticate all users: something you know, such as a password or
passphrase; something you have, such as a token device or smart card; or something you are, such
as a biometric.

8.5 Ensure proper user identification and authentication management for non-consumer users and
administrators on all system components.

Ok, so these requirements really relate to the handling of card holder data, but why not apply this to your card.  The main piece of card holder data is your Card number, your PAN (Primary Account Number). To use the PayPass system you only have to supply one piece of card holder data - the physical card with the PAN embossed on it, why shouldn't requirement 8.2 also be applied, and a 2nd authentication criteria be used.

Pin numbers work, but can be slow when people miskey - but the really slow factor for these on EFT POS terminals is the time it takes to authenticate to the Auth Center - why not move the PIN authentication onto the chip, much faster (does potentially bring up the issue of cards being brute forced for pins).

Use biometrics - a thumbprint reader as part of the card, only a person with an authorised thumbprint can use the card - probably a little expensive, but hey it's my blog and I'm just spit balling here.

My point is, why implement something that needs some kind of fraud insurance to cover the banks and ultimately the consumer.  As the consumer you're paying for this in your bank fees and card fees.

davidcole's profile

davidcole Cole
Lower Hutt
New Zealand

Been thinking it would be nice to have a blog but not sure if I have enough to say.

I'm an I.T worker from Wellington New Zealand.

I like my toys so this will probably have posts about my dealings with those.

My Cellphone is an iPhone 5s

I run a NextPVR based PVR at home to replace my video recorder, DVD player and to host all my music. I'm also really big on Plex, for centralising all my music, videos and I've written a plugin or two for it for accessing live TV and for storing recordings with metadata.

TVNZ Ondemand App behind Unblo...
(27-Feb-2013 19:39, 12070 views)
Wemos D1 Mini Door Contact (pl...
(16-Nov-2017 07:58, 11628 views)
OpenHAB and Bluetooth beacons ...
(19-Dec-2016 21:39, 9911 views)
Controlling a 12v fan from a r...
(17-Jan-2017 07:49, 9890 views)
eReceipts - Why don't we have ...
(12-Jan-2012 10:01, 9420 views)
PDF Forms - why you no boxes?...
(26-Jun-2012 09:04, 8304 views)
Free $80 - come and get ur mon...
(20-Sep-2011 13:11, 8061 views)
RM3's also - but this time wit...
(16-Jul-2017 20:16, 7090 views)
Contactless Payments - part 2...
(21-Sep-2011 15:12, 5657 views)
Little Boys and their Sewing M...
(27-Dec-2009 11:09, 5520 views)