Projects Raspberry Pi

Personal Weather Station & RaspberryPi – Part 3

||||| 0 Like |||||

What it does

This script will find the most recent raw file that PYWWS has produced in its data path, look for the last line and then look for the wind speed value (value 9- or counting from 0 as list arrays do – it is the 8th). Once it has found the value it will go through a check to see if it is mild, windy or gale-force. 1 light = What Wind? 3 lights = rustling the leaves 6 lights = inside out umbrellas 12 lights = inside out houses

The Code

#!/usr/bin/env python2.7
# Python to read pywws raw weather-file and output windspeed
# To the GertBoard LED's based on strength

from collections import deque
import csv
import wiringpi
from time import sleep
import sys
import math
import time
import logging

logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', filename='gertweather.log',level=logging.DEBUG)
board_type = sys.argv[-1]

# pywws puts the raw files in sub-folders by year, then year and month, then the file
# is year, month and day
# This section takes the current date and oyts this into the filename string for the script
folder = time.strftime("%Y/%Y-%m")
file = time.strftime("%Y-%m-%d.txt")
filename = '/home/pi/weather/data/raw/' + folder + '/' + file

def pi_rev_check():      # Function checks which Pi Board revision we have
    # make a dictionary of known Pi board revision IDs
    rev_dict={'0002':1,'0003':1,'0004':2,'0005':2,'0006':2,'000f':2}

    # search the cpuinfo file to get the board revision ID
    revcheck = open('/proc/cpuinfo')
    cpuinfo = revcheck.readlines()
    revcheck.close()

    # put Revision ID line in a variable called matching
    matching = [s for s in cpuinfo if "Revision" in s]

    # extract the last four useful characters containing Rev ID
    rev_num = str(matching[-1])[-5:-1]

    # look up rev_num in our dictionary and set board_rev (-1 if not found)
    board_rev = rev_dict.get(rev_num, -1)
    return board_rev

board_revision = pi_rev_check() # check Pi Revision to set port 21/27 correctly
if board_revision == 1:
    # define ports list Rev 1
    ports = [25, 24, 23, 22, 21, 18, 17, 11, 10, 9, 8, 7]
else:
    # define ports list all others
    ports = [25, 24, 23, 22, 27, 18, 17, 11, 10, 9, 8, 7]

# make a copy of ports list and then reverse it as we need both directions
ports_rev = ports[:]
ports_rev.reverse()

wiringpi.wiringPiSetupGpio()                        # initialise wiringpi

for port_num in ports:
    wiringpi.pinMode(port_num, 1)                   # set up ports for output

def reset_ports():
    for port_num in ports:
        wiringpi.digitalWrite(port_num, 0)          # switches off all LEDs
        wiringpi.pinMode(port_num, 0)               # and reset ports

def led_drive(reps, multiple, direction):           # define function to drive
    for i in range(reps):                      # repetitions, single or multiple
        for port_num in direction:                  # and direction
            wiringpi.digitalWrite(port_num, 1)      # switch on an led
            sleep(0.11)                             # wait for ~0.11 seconds
            if not multiple:                        # if we're not leaving it on
                wiringpi.digitalWrite(port_num, 0)  # switch it off again

def get_last_row(csv_filename):
    with open(csv_filename, 'rb') as f:
        return deque(csv.reader(f), 1)[0]

#Put the results into a list array
weather = get_last_row(filename)
#Wind speed is 9th (so 8th as we count from zero
wind = weather[8]
windspeed = float(wind) # store the windspeed as a float
flatwindspeed = round(windspeed ,0) # round windspeed to an int
#turn off any lights that are currently on
wiringpi.digitalWrite(17, 0)
wiringpi.digitalWrite(18, 0)
wiringpi.digitalWrite(27, 0)
wiringpi.digitalWrite(22, 0)
wiringpi.digitalWrite(23, 0)
wiringpi.digitalWrite(24, 0)
wiringpi.digitalWrite(25, 0)
wiringpi.digitalWrite(4, 0)
wiringpi.digitalWrite(7, 0)
wiringpi.digitalWrite(8, 0)
wiringpi.digitalWrite(9, 0)
wiringpi.digitalWrite(10, 0)

#Turn them on based on the wind speed range
try:
   if windspeed <= 2:       
      logging.debug('slow wind - 1 led')       
      wiringpi.digitalWrite(25, 1) # turn on LED 1    
    elif windspeed >= 6 or windspeed <= 20:       
      logging.debug('mild wind - 3 leds')       
      wiringpi.digitalWrite(25, 1) # turn on LED 1       
      wiringpi.digitalWrite(24, 1) # turn on LED 2       
      wiringpi.digitalWrite(23, 1) # turn on LED 3    
    elif windspeed >= 21 or windspeed <= 50:       
      logging.debug('strong wind - 6 leds')       
      wiringpi.digitalWrite(25, 1) # turn on LED 1       
      wiringpi.digitalWrite(24, 1) # turn on LED 2       
      wiringpi.digitalWrite(23, 1) # turn on LED 3       
      wiringpi.digitalWrite(22, 1) # turn on LED 4       
      wiringpi.digitalWrite(21, 1) # turn on LED 5       
      wiringpi.digitalWrite(18, 1) # turn on LED 6    
    elif windspeed >= 51:
      logging.debug('galefoce or stonger - 12 leds')
      wiringpi.digitalWrite(25, 1) # turn on LED 1
      wiringpi.digitalWrite(24, 1) # turn on LED 2
      wiringpi.digitalWrite(23, 1) # turn on LED 3
      wiringpi.digitalWrite(22, 1) # turn on LED 4
      wiringpi.digitalWrite(21, 1) # turn on LED 5
      wiringpi.digitalWrite(18, 1) # turn on LED 6
      wiringpi.digitalWrite(17, 1) # turn on LED 7
      wiringpi.digitalWrite(11, 1) # turn on LED 8
      wiringpi.digitalWrite(10, 1) # turn on LED 9
      wiringpi.digitalWrite(9, 1) # turn on LED 10
      wiringpi.digitalWrite(8, 1) # turn on LED 11
      wiringpi.digitalWrite(7, 1) # turn on LED 12
except KeyboardInterrupt:           # trap a CTRL+C keyboard interrupt
    reset_ports()                   # reset ports on CTRL-C exit

I then add this to the Cron file so It can run as root (This is required for the GPIO ports)

*/5 * * * * sudo python /home/pi/read.py >> ~/gertweathercron.log 2>&1

This will run it every 5 minutes of every day. If you only wanted to update the lights after 10 minutes, you could use:

*/10 * * * * sudo python /home/pi/read.py >> ~/gertweathercron.log 2>&1

If there are any errors, a cron log file is created and updated with the error details to help you debug the code.

Get the code

If you want my code, you can download it straight to your Raspberry Pi

wget http://talktech.info/wp-content/uploads/2014/01/read1.zip
unzip read1.zip

sudo python read.py

The code is now also on GitHib Gist:

https://gist.github.com/vwillcox/8249000

Finally

Leave a Reply

Your email address will not be published. Required fields are marked *