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.

eg:

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.

wemos-reed

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.

https://wiki.wemos.cc/tutorials:get_started:get_started_in_arduino

https://www.cnx-software.com/2016/03/22/getting-started-with-wemos-d1-mini-esp8266-board-dht-relay-shields/

https://diyprojects.io/shield-wemos-d1-mini-dht11-dht22-arduino-code-esp-easy/#.WgunAdNL-1s

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;


const int TEMPERATURE_INTERVAL = 300;
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
   reedNode.setProperty("state").send("on");
   pinMode(REED_PIN, INPUT_PULLUP);
   temperatureNode.setProperty("unit").send("c");
   humidityNode.setProperty("unit").send("%");
}

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

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

  if (millis() - lastTemperatureSent >= TEMPERATURE_INTERVAL * 1000UL || lastTemperatureSent == 0) {
     if(dht12.get()==0){
         float temperature = dht12.cTemp;
         float humidity = dht12.humidity;
         Homie.getLogger() << "Temperature: " << temperature << " °C" << endl;
         Homie.getLogger() << "Humidity: " << humidity << " %" << endl;
         temperatureNode.setProperty("degrees").send(String(temperature));
         humidityNode.setProperty("percent").send(String(humidity));
         reedNode.setProperty("state").send(doorStateString); 
     }
     lastTemperatureSent = millis();
   }
   delay(1000);
}

void setup() {
   // put your setup code here, to run once:
   Serial.begin(115200);
   Serial << endl << endl;
   Homie_setFirmware(FW_NAME, FW_VERSION);
   Homie.setSetupFunction(setupHandler).setLoopFunction(loopHandler);

  reedNode.advertise("state");
   temperatureNode.advertise("unit");
   temperatureNode.advertise("degrees");
   humidityNode.advertise("unit");
   humidityNode.advertise("percent");


   Homie.setup();
}

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

}

 

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.

const int TEMPERATURE_INTERVAL = 300;
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
   reedNode.setProperty("state").send("on");
   pinMode(REED_PIN, INPUT_PULLUP);
   temperatureNode.setProperty("unit").send("c");
   humidityNode.setProperty("unit").send("%");
}

 

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.begin(115200);
   Serial << endl << endl;
   Homie_setFirmware(FW_NAME, FW_VERSION);
   Homie.setSetupFunction(setupHandler).setLoopFunction(loopHandler);

   reedNode.advertise("state");
   temperatureNode.advertise("unit");
   temperatureNode.advertise("degrees");
   humidityNode.advertise("unit");
   humidityNode.advertise("percent");


   Homie.setup();
}

 

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";
       //reedNode.setProperty("state").send("open"); 
       Homie.getLogger() << "Door State: OPEN" << endl;
     } else if (doorState == 0){
       doorStateString = "closed";
       //reedNode.setProperty("state").send("closed");
       Homie.getLogger() << "Door State: CLOSED" << endl;
     } else {
       //reedNode.setProperty("state").send("unk");
       doorStateString = "unk";
       Homie.getLogger() << "Door State: UNKNOWN" << endl;
     }
     reedNode.setProperty("state").send(doorStateString); 
   }

 

The line

reedNode.setProperty("state").send(doorStateString); 

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) {
     if(dht12.get()==0){
         float temperature = dht12.cTemp;
         float humidity = dht12.humidity;
         Homie.getLogger() << "Temperature: " << temperature << " °C" << endl;
         Homie.getLogger() << "Humidity: " << humidity << " %" << endl;
         temperatureNode.setProperty("degrees").send(String(temperature));
         humidityNode.setProperty("percent").send(String(humidity));
         reedNode.setProperty("state").send(doorStateString); 
     }
     lastTemperatureSent = millis();
   }
   delay(1000);
}

Here are all the properties being sent to MQTT

temperatureNode.setProperty("degrees").send(String(temperature));
humidityNode.setProperty("percent").send(String(humidity));
reedNode.setProperty("state").send(doorStateString);

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":"192.168.10.41","mDNS":"mqtt","port":1883,"base_topic":"sensors/d1mini/"},"ota":{"enabled":true,"host":"192.168.10.41","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/$localip 192.168.100.21
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:

image



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.

Eg:

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
mqttc.connect(MOSQUITTO_HOST,MOSQUITTO_PORT)

Here is the main run time loop:

while True:
    try:
        mqttc.loop_forever

except Exception,e:
    logging.error("Error in mqtt loop")
    mqttc.disconnect()
    mqttc.connect(MOSQUITTO_HOST,MOSQUITTO_PORT)
    continue

except KeyboardInterrupt:
    print("error")
    GPIO.cleanup()
    exit(0)

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")
        fan.ChangeDutyCycle(100)
        (result1,mid) = client.publish("cupboard/fanstate","ON")
    else:
        logging.info("Turning fan off")
        fan.ChangeDutyCycle(0)
        (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.
    client.subscribe('cupboard/fan',1)

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.

Running

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

 



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, 11612 views)
Controlling a 12v fan from a r...
(17-Jan-2017 07:49, 9419 views)
eReceipts - Why don't we have ...
(12-Jan-2012 10:01, 8973 views)
OpenHAB and Bluetooth beacons ...
(19-Dec-2016 21:39, 8853 views)
PDF Forms - why you no boxes?...
(26-Jun-2012 09:04, 8110 views)
Free $80 - come and get ur mon...
(20-Sep-2011 13:11, 7756 views)
Contactless Payments - part 2...
(21-Sep-2011 15:12, 5406 views)
Little Boys and their Sewing M...
(27-Dec-2009 11:09, 5349 views)
RM3's also - but this time wit...
(16-Jul-2017 20:16, 5190 views)
TVNZ Ondemand App behind Unblo...
(1-Mar-2013 07:14, 4557 views)