Projects Raspberry Pi

Personal Weather Station & RaspberryPi – Part 2

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

When I first installed the Weather Station image to the disk, it worked fine for the intermittent updates (hourly, daily for example). But I wanted to update live statistics to the Weather Underground.

Now, although the script was already there to run, it crashed repeatedly meaning several hours would go by without an update. This was not what I wanted so I searched around and finally came up with the solutions. One was a better script to run the live updates as a “DAEMON” and the other was to put this into “CRON” and run it every minute of every day.

The code to run

#!/bin/bash

# ---------------------------------------------------------------
#
# A script to keep the pywws live data logger running running.
#
# ---------------------------------------------------------------

# Configuration
# -------------
PID_FILE="/tmp/pywws.pid"
DATA_DIR="/home/pi/weather/data"
LOG_DIR="/home/pi/weather/log"
LIVE_LOG="$LOG_DIR/live-weather.log"
LAUNCHER_LOG="$LOG_DIR/live-launcher.log"

# Functions
# ---------

# Log text to the file $LAUNCHER_LOG
function log
{
    local timestamp=`date +%y-%m-%d:%H:%M:%S`
    echo  "$timestamp $@" >> "$LAUNCHER_LOG"
    echo  "$timestamp $@"
}

# Create the log and data directories if they are missing
function setup
{
    if [ ! -d "$LOG_DIR" ]; then
        mkdir -p "$LOG_DIR"
    fi

    if [ ! -d "$DATA_DIR" ]; then
        mkdir -p "$DATA_DIR"
    fi
}

# Check to see if the process with the PID contained in the
# file passed as $1 is currently running. Return 1 if still
# running otherwise return 0.
isRunning()
{
#  log "Checking pid file [$1]"
  [ "$1" = "" ]  && return 0
  [ ! -f "$1" ]  && return 0
  local pywwspid=`pgrep -F $1`
#  log "Found running process [$pywwspid]"
if [ "$pywwspid" = "" ]; then
      return 0;
  else
      return 1;
  fi
}

# Main
# ----

setup
# log "Pywws wrapper script launched by cron..."
isRunning "$PID_FILE"

if [ $? -eq 1 ]; then
#    log "Pywws live logger already running..."
else
    log "Restarting pywws live logger..."
    pywws-livelog.py -v -l ~/weather/data/pywws.log ~/weather/data &
    echo $! >"$PID_FILE"
fi

# log "Pywws wrapper script done."

This code will check to see if the daemon is running using the PID (Process ID). If it finds that is is running, it simply stops and does nothing else.

However if it does not find the PID it will start up the process again and write out to a log file that it has been restarted.

Cron File

@reboot         /home/pi/weather/scripts/pywws-live.sh
* * * * *       /home/pi/weather/scripts/pywws-live.sh

This is the contents of the cron file (Linux Job Schedule) for this script.

@reboot – Tells the Raspberry Pi to run the command when it has finished rebooting

* * * * * – Tells the Raspberry Pi to run the script every minute, of every hour, every day.

Leave a Reply

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