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):'Topic: ' + msg.topic+' Message: '+str(msg.payload))
    if msg.payload == "1":"Turning Fan on")
        (result1,mid) = client.publish("cupboard/fanstate","ON")
    else:"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):"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 (  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 ( .  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 (

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, 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 (

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

Here's the config I'm currently running:


I've confirmed netflix, bbc, itv and 

The version posted yesterday included 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  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 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 (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 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 - see the post at

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

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:

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 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

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.

Free $80 - come and get ur moneyz!!

, posted: 20-Sep-2011 13:11

Recently I received a letter from ASB Bank about a replacement credit card with an embedded chip.

"Great" I thought. I'd been wondering when they would come out, as chip cards are supposed to be more secure.

Part of the letter explained about a new contactless payment system incorporated as part of the cards called PayPlus. This is MasterCards implementation of Near Field Communication based payments (see ).  The Visa equivalent I understand is called PayWave.

The letter explained that for transactions of less than $80 no pin was required.  Now of course you do have to find a retailer that would support this, but I would assume these would start appearing, and the concept is similar to my Snapper card I use occasionally for the bus.

But the idea of no pin, no signature linked to my credit card had me a bit worried. 

As snapper is effectively a cash replacement - and in some ways it is more secure than your wallet (where your cash normally resides)* Because of this, the balance kept on my snapper card is akin to what I'd hold in my wallet, not much more than $20.

But the idea of up to $80 payments possible off a household credit card gave me shivers down my spine.  How many people do not check their statements?  Or if they do, only when it's sent to you?  Ok sure, the card has to be out of your possession, and generally you'd cancel the card as soon as you realise it's gone, but it still left me feeling uneasy.  With a regular credit card loss, apart from McDonalds**, there was a modicum of security, someone would have to forge your signature (probably fairly easy to do) or gain access to your pin.

But the thought of someone just having to tap the stolen, or misplaced card on a terminal to have access to your funds seemed to be a lowering security.  I like to think of this contactless technology as a cash replacement...and therefore the value of cash transactions - generally fairly low....not being linked to an account with enough money to cover the household spending for a month.

I saw another user ask @ASBBank on twitter if the limit could be (I assumed) lowered...this was something I'd been thinking of, and I asked if it could it be disabled entirely, the answer was no to both questions.

I'm all for new features, and quite like the idea of contactless payments, don't get me wrong.  But I don't particularly want it attached to a credit card that I've purposely never put on the internet, because it's used for the household, and so it's limit is appropriate for household spending.  I have another card with a $500 limit that I use for internet based transactions.  A separate, opt in, card would have been, in my opinion, the preferable way of implementing this.

BTW this probably isn't so much a dig at ASB Bank, and I think this would be part of their membership to the card schemes, and I'd imagine all the NZ banks would be doing similar.  And all have the same sort of implementation.

* if you lose your snapper and it's registered, it can be stopped and/or refunded.  If you lose your wallet, you've probaby lost your money.

** McDonalds (and maybe others) has allowed no pin or signature on transactions valuing less than $15  Correction, apparently it's $35 - which I think is worse.

Is there an App for that Scam

, posted: 5-Mar-2010 08:20

I had a thought while riding in this morning about a new potential financial scam.


If you're one of these people with one of those fancy new fangled phones that use apps for everything instead of mobile sites, them how do you know it's not stealing your information and sending it to a third party?


Did you check that app when getting it? Just like domain sitters, that sit on a misspelled versions of a popular site, the same could be done with an app. "Nationa1 Bank app", "A5B Bank app", while they show your all of your financial information faithfully, utilising information pulled from their mobile web sites', the app is, in fact, sending your user name and password to a third party that can then log on and play mischief with your financial details.


Now having not actually ever looked at these apps I assume a safe guard such as never storing login details could be used on the official apps, but again, if it's a non official version (and would Apple's vetting process pick this up?) then the user could blindly add in their login details and then wonder why their bank account is emptying....


Just a thought, you be careful out there....

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, 11348 views)
eReceipts - Why don't we have ...
(12-Jan-2012 10:01, 8652 views)
PDF Forms - why you no boxes?...
(26-Jun-2012 09:04, 7856 views)
Free $80 - come and get ur mon...
(20-Sep-2011 13:11, 7484 views)
OpenHAB and Bluetooth beacons ...
(19-Dec-2016 21:39, 5817 views)
Contactless Payments - part 2...
(21-Sep-2011 15:12, 5209 views)
Little Boys and their Sewing M...
(27-Dec-2009 11:09, 5193 views)
Controlling a 12v fan from a r...
(17-Jan-2017 07:49, 5041 views)
TVNZ Ondemand App behind Unblo...
(1-Mar-2013 07:14, 4285 views)
Americans Scare me........
(13-Nov-2008 08:37, 3804 views)