Sunday, 5 January 2014

An AirPi - Useful in a Powercut

In March 2013 I built a Raspberry Pi AirPi and I've had it up and running ever since.  The system has proved to be very reliable; I reckon it's only stopped working 2 or 3 times since I set it up.  The Python scripts are setup to run when the Pi starts so the AirPi will automatically start up if there's a power cut or glitch.

I do this by putting scripts in the /etc/init.d folder.  Here's an example:

#Used this as a guide http://myraspberrypiexperience.blogspot.co.uk/2012/08/star
t-vnc-automatically.html
#Run this under the Pi username
export USER='pi'
eval cd ~$USER

#Run the Airpi
su $USER -c 'sudo python /home/pi/Meteoros/pdw_upload_v3.py &'

#End stuff
exit 0

We've had some pretty wet and windy weather in the UK over the Christmas period (it's still poor as I write early in the new year) which has resulted in long power cuts all over the country.  We suffered a power cut at my house for 26 hours from roughly 1300 on 23/12/2013 to 1500 on 24/12/2013.  

Here's my AirPi barometric pressure chart for the period:


On the graph you can see the pressure suddenly drop; the weather conditions that coincided with this were high winds and heavy rain.  This caused trees to be blown over which caused a power cut to the place I live in which you can see on the graph as the horizontal line from the 23rd to the 24th.  A power cut means no power to the RasPi and no ADSL router, hence there are no measurements for this period.

The AirPi came in useful as we were due as a family to travel to my in-laws on the 24th for Christmas.  It's a reasonably long drive so we were due to leave at 0830ish on the 24th.  With the power out we decided to stay put as we didn't know what state the house would be in when the power came back on (i.e. freezer defrosted, lights left on).  However by 1200 the power was still off and with a long drive ahead of us we decided to give a key to neighbour, switch off everything we could, chuck out a load of food from the freezer and then crack on with the drive.

In the end the drive went well and we arrived before 1600.  Then, just after 1600 I got a Twitter direct message from my Raspberry Pi, (more on that later), which let me know that it was up and running again.  Shortly after I got a text from my neighbour to tell me that all was well with the house.

The next question was whether the heating would come on properly after the power cut; it would be a bad thing not to have this on during winter.  My AirPi gave me the answer as I could see the temperature in the house going up and down twice a day.  (I could monitor this remotely via Xixely).


It was interesting to look at the temperature profile, (chart for the 25th shown below):

The heating came on in the early hours of the morning and then early in the afternoon which matched the twice a day timer program I had set.  It heated up to roughly the expected temperature  (the thermostat was in another room and set to 19 Celsius).  It was good to see that the room heated up quicker than it cooled down which shows that the insulation must be doing some good.  What was interesting was the the heating was coming on several hours earlier than expected.  What I assumed (and later proved) was that when the power came on at 1600, the clock on the heating controller must have resumed at the time it held when the power went off(1300).  Hence the clock was running roughly 3 hours fast. 

It's also interesting to compare the fairly regular temperature profile while we were away (two peaks a day, a longer one in the afternoon) with one when we were at home the next week:

The "at home" peak is a lot more messy as we control the heating manually, tinker with the main thermostat and TRVs, open doors and windows etc.

I mentioned earlier that the thing that prompted me that the power was back on was a tweet from the Raspberry Pi. I have the Pi GET a temperature measurement from Xively and send it to me as a Twitter direct message (which I can pick up on my Android handset).  The fact that I get one of these every hour just tells me that the Pi is still up and working and it's also good for inter-geek boasting!

I used this utterly excellent document from the Raspberry Pi Foundation to tell me how to tweet from the Pi using Python (see page 115).  The code is below (secret values edited out) but in simple terms, every hour it picks up the latest temperature reading from Xively and posts it as a Twitter direct message.  It uses the twitter Python module.  Here's a screenshot:


#Using Twitter to communicate COSM values
#Example URL is http://api.cosm.com/v2/feeds/XXXXX.csv?datastreams=0
#This returns the last value for datastream 0
import os
from twitter import *
import time
from datetime import datetime
from httplib import HTTP

#The URL we will use
COSMURL = "api.cosm.com"
FullCOSMURL = "http://api.cosm.com/v2/feeds/104017.csv?datastreams=0"
KeyToUse = <Deleted>

#Make a HTTP request to COSM to get a string
def GetCOSM():
  try:
    #Now do the HTTP magic - Connect to the server
    h = HTTP(COSMURL)

    #Do a get
    h.putrequest('GET',FullCOSMURL)

    # setup the API Key
    h.putheader('X-ApiKey',KeyToUse)

    # we're done with the headers....
    h.endheaders()

    #Get the response
    errcode, errmsg, headers = h.getreply()
    response = h.getfile()
    data = response.read()
    h.close()
    print data
    return data
  #Catch an exception
  except Exception, err:
    #Write a log with the error
    print "Got us an exception: " + str(err)

#MAIN BODY OF CODE
#Go in to a loop sending direct messages
while True:
  #Using the @mrjamesbond account to send tweets
  #Went to https://dev.twitter.com/apps/new to set this up
  CONSUMER_KEY = <Deleted>
  CONSUMER_SECRET = <Deleted>

  # get full pathname of .twitterdemo_oauth file in the
  # home directory of the current user
  oauth_filename = os.path.join(os.path.expanduser('~'),'.twitterdemo_oauth')

  # get twitter account login info
  if not os.path.exists(oauth_filename):
    oauth_dance('Raspberry Pi Twitter Demo', CONSUMER_KEY, CONSUMER_SECRET, oauth_filename)
  (oauth_token, oauth_token_secret) = read_token_file(oauth_filename)

  # log in to Twitter
  auth = OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET)
  twitter = Twitter(auth=auth)
  try:
   #Send a direct message
   MessageToSend = "AirPi Temperature Reading " + GetCOSM()
   #print MessageToSend
   twitter.direct_messages.new(user="pauldavidweeks",text=MessageToSend)

   # Tweet a new status update
   #twitter.statuses.update(status=MessageToSend)

   # Display all my tweets
   #for tweet in twitter.statuses.user_timeline():
     #print('Created at',tweet['created_at'])
     #print(tweet['text'])
     #print('-'*80)
  except:
    print "Got a Twitter error"

  time.sleep(3600) 



No comments:

Post a Comment