IoT monitor script

As promised here’s the code I’ve currently got watching for incoming messages from the slice of pi.  It’s a hacked up version of the script from Fernando Lourenco’s instructable

The code pulling from Weather Underground is gone and I’ve shuffled things around a bit for my purposes.  No judging what I’ve done to the python if you please, I’m fresh in from years of abusing perl to meet my needs but have shifted to python for pi related stuff since solstice.

https://rockhopper.vom.org.uk/~mark/wirelessthing/monitor_sql.py

#!/usr/bin/env python
# --------------------------------------------------
from time import time, sleep, gmtime, strftime
import logging
import logging.handlers
import serial
import os
import os.path
import datetime
import sys
import MySQLdb as mdb
# --------------------------------------------------
# create table things ( 
#    thistime timestamp, 
#    ID varchar(2), 
#    type varchar(10), 
#    value float );
# --------------------------------------------------
DEVICE = '/dev/ttyAMA0'
BAUD = 9600
ser = serial.Serial(DEVICE, BAUD)
TIMEOUT = 10
# --------------------------------------------------
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.INFO)
handler = logging.handlers.SysLogHandler(address = '/dev/log')
my_logger.addHandler(handler)

#my_logger.debug('this is debug')
#my_logger.critical('this is critical')
# --------------------------------------------------
def dumpResults( thingMsg ):
    print "Message : " + thingMsg
    readValue    = -100
    readID        = "99"
    readType    = "NONE"
    writeMe     = 0

    # Raw mesg logging
    thisTime = strftime("%Y-%m-%d %H:%M", gmtime())
    my_logger.info( "%s,%s\n" % ( thisTime, thingMsg ) )

    readID = thingMsg[1:3]
    if thingMsg[3:7] == "TEMP":
        writeMe = 1
        readType = "TEMP"
        readValue = thingMsg[7:]
    if thingMsg[3:7] == "BATT":
        writeMe = 1
        readType = "BATT"
        readValue = thingMsg[7:11]
        if readValue == "LOW":
            readValue = 0

    if writeMe:
        thisMsg = "%s,%s,%s,%s\n" % ( thisTime, readID, readType, readValue )
        with open( "logfile.txt", "a", 0 ) as thisFile:
            # Dump the information to file and setup the message
            thisTime = strftime("%Y-%m-%d %H:%M:%S", gmtime())
            thisFile.write( thisMsg )
            print( thisMsg )
        try:
            con = mdb.connect('192.168.0.250', 'monitor', 'password', 'houseLogging');
            with con:
                # SQL stuff
                cur = con.cursor()
                cur.execute( "insert into things values ( '%s', '%s', '%s', %s )" % ( thisTime, readID, readType, readValue ) ) 
                con.commit()

        except mdb.Error, e:
            print "Error %d: %s" % (e.args[0],e.args[1])
            my_logger.critical( 'Could not write to db - '+thisMsg )
            #sys.exit(1)    
    return( 1 )

def get_temp():
    global ser
    fim = time()+ TIMEOUT
    my_logger.debug('Attempting to get temp')
    while (time()<fim):
        n = ser.inWaiting()
        if n != 0:
            data = ser.read(n)
            nb_msg = len(data) / 12
            print "Number of message blocks " + str(nb_msg)
            for i in range (0, nb_msg):
                msg = data[i*12:(i+1)*12]
                print ">>" + msg
                dumpResults( msg )
        else:
            sleep(5)
    return {1}

# --------------------------------------------------
# main function
# This is where the program starts 
def main():
    while True:
        temperature = get_temp()


        #else:
        #    print ("temperature=ERROR-Timeout!")
            

if __name__=="__main__":
    main()
# --------------------------------------------------

Wireless Things or “Fighting with IoT”

So I’ve been hunting around for a decent system to build out some initial “smart home” type projects, focusing to start with on temperature, humidity and pressure.

As part of the excessive digging through google and testing out my ability to keep changing search parameters until something good pops up I came across the range of radio sensors from Ciseco (http://www.wirelessthings.net/) which merrily plug into the RPi and an Instructable which at least pointed in the right direction while missing some of the key steps which aren’t entirely clear from the product docs.

2016-01-07 17.28.09 2016-01-07 21.06.42 2016-01-07 21.06.52

Setup

First things first, install the hat onto your RPi of choice, I’ve installed on a RPi B+, but the forum indicates that it should work just as well on a RPi 2.  The hat isn’t stackable so the RPi 2 might be better in the long term by keeping access to some of the GPIO pins.

Pop the lid off the sensor, you’ll need access to the configure button later on.

You must either install the LaunchPad application on the RPi and be able to run an X based display either locally on the RPi or exported back to your working system of choice (I’m using on a Win7 machine running Xming).  This is needed to setup the sensor which arrives in a deep sleep and no hint as to what the device ID is.

Disable the serial console from the raspi-config application, or go through the manual steps to remove /dev/ttyAMA0 from /etc/inittab and /boot/cmdline, reboot as necessary.  Failure to do this blocks the ability to actually access the radio device.

Follow the LaunchPad documentation (PDF Doc from github), first setting up the encryption key for the radio device (I’m using the Slice of Radio for the RPi).  Then run the LaunchPad and follow the instructions for getting the Message Bridge running and setting up the sensor for the first time.

For inital testing purposes I’d recommend setting the reporting interval at 10 seconds so you’re not spending the entire evening waiting for the next poll.

Providing that everything has gone well, you’ve worked out the permission problem on /dev/ttyAMA0 (or are running with root privs) you should be seeing something like the following in minicom

aAATEMP019.0
aAAAWAKE----
aAABATT3.15-
aAASLEEPING-
aAATEMP019.1

The Message Bridge appears to be there to provide a pretty interface into the serial port, however if all you intend to do is listen for information landing on the serial port I would ditch it and just run a script in your language of choice and parse the data as it comes in.

To come

I need to add in some more monitors, work out the range on the sensor and position the monitorPi appropriately in the house, then some graphing to make it actually useful.

I’ll post the script I’m using later.

Links and other useful stuff

Language of things : https://www.wirelessthings.net/language-of-things
LaunchPad : https://www.wirelessthings.net/launchpad
Alternate Instructable

Strike action and Westminster weasels

Some numbers.

Quorum for votes in the House of Commons, 40.
Quorum for votes in the House of Lords, 30.
So respectively votes of 21 and 16 are needed for a motion to pass, this is for legislation which affects the UK.  This is the level at which our politicians think it is ok for them to make decisions on our behalf.

2015 general election, numbers (wikipedia); Overall turnout 66.1%; Conservatives 11.3M votes, 36.9% of the cast votes (~28% of electorate)

Now compare this with what they are proposing for the unions, double standards from our elected lords and masters, yeah.  Not surprised at all.

Election Fact Check

This graphic is doing the rounds, in the interests of getting rid of the bullshit (taking a lesson from the awesome Full Fact & The Last Leg) I detest infographics which do not provide their sources so I can check for bullshit or bias.

18195_820268738065935_4677162186831177814_n

Who From To Party Rebellions Attendance Teller
Clegg 6 May 2010 30 Mar 2015 LDem 1 vote out of 264, 0.4% 264 votes out of 1239, 21.3% 0 times
Cameron 6 May 2010 30 Mar 2015 Con 2 votes out of 202, 1.0% 202 votes out of 1239, 16.3% 0 times
Osborne 6 May 2010 30 Mar 2015 Con 8 votes out of 318, 2.5% 318 votes out of 1239, 25.7% 0 times
May 6 May 2010 30 Mar 2015 Con 6 votes out of 597, 1.0% 597 votes out of 1239, 48.2% 0 times

Based on the information from Public Whip the claim is pretty spot on based on the number of rebellions against votes attended.  Had Clegg found his courage (maybe that’s what the other parties bring to the LDs while they’re providing a heart or brain) and attended more of the votes the rebellion rate might have been higher.

Sources:
Clegg : http://www.publicwhip.org.uk/mp.php?mpn=Nicholas_Clegg&mpc=Sheffield%2C_Hallam&house=commons
Cameron : http://www.publicwhip.org.uk/mp.php?mpn=David_Cameron&mpc=Witney&house=commons
Osborne : http://www.publicwhip.org.uk/mp.php?mpn=George_Osborne&mpc=Tatton&house=commons
May : http://www.publicwhip.org.uk/mp.php?mpn=Theresa_May&mpc=Maidenhead&house=commons

 

We need more encryption and security, not less

http://falkvinge.net/2015/01/14/hilarious-activists-turn-tables-on-political-surveillance-hawks-wiretaps-them-with-honeypot-open-wi-fi-at-security-conference/

The linked article shows just how trivial it is to use metadata to identify the entity associated with the connecting device and start to unpick further details of their life, work and the supposedly secure stuff they’re working on.

Security, a thought for the day

If the ‘good guys’ have a backdoor then so do the criminals
If the ‘good guys’ can crack your encryption, so can the criminals

Having weak encryption would not have stopped the Paris attacks as the security services had already stopped monitoring them.

If you think “I don’t use encryption” then think again, when you bought something online you used encryption, when you made a mobile phone call encryption was needed to protect the setup of the call, your password is stored (or should be) in an encrypted format to prevent hackers from simply downloading a human readable list and so on. Encryption isn’t some dark evil used only by terrorists, it’s used by all of us for good reasons. The government needs to give better reasons for denying it to the public than “terrorists!!”.

Alternatively maybe they’ll be happy that all their governmental and private communications are no longer encrypted to make the job of the press easier in reporting on their deeds and misdeeds, for surely if they have “nothing to hide they have nothing to fear”

Stupid reporting

*sigh*

–[ – ]–
“It’s worrying to see that so many think they’d struggle paying the mortgage should the base rate rise by as little as 2%. What’s also clear is that the understanding of how interest rates affect payments is incredibly low. Simply put, a rise in rates from 1% to 2% is a hundred percent increase, which means a doubling of payment. For example if you were paying £750 per month your new payments would be £1,500,” said Nick Hungerford, CEO and founder of Nutmeg.
–[ – ]–

While ‘accurate’ it’s not a fair representation of the real world unless of course you have a interest only mortgage which is held at BASE + 0%.

A more realistic example is a £181k mortgage at 1.49%+BASE which rises by ~£200/month with a 2% rise in the base rate {not that I have a spreadsheet already setup to track this sort of thing..}

Getting across the risks of interest rate rises is a good thing but seriously guys, bring some reality into the equation so the public can actually properly assess their risk rather than trying to panic the herd.

Link to original article