From 7095ecd9885bbc351e16a25c8fd6c46f0cc03c59 Mon Sep 17 00:00:00 2001 From: gallery1 Date: Wed, 26 May 2021 13:17:47 +0100 Subject: [PATCH] 26-05-2021 snapshot. --- make-log-files.sh | 9 ++++++ relay.py | 72 +++++++++++++++++++++++++++++++++++++++++++++++ relay.service | 16 +++++++++++ shutdown.sh | 38 +++++++++++++++++++++++++ startup.sh | 50 ++++++++++++++++++++++++++++++++ 5 files changed, 185 insertions(+) create mode 100644 make-log-files.sh create mode 100644 relay.py create mode 100644 relay.service create mode 100755 shutdown.sh create mode 100755 startup.sh diff --git a/make-log-files.sh b/make-log-files.sh new file mode 100644 index 0000000..a15c828 --- /dev/null +++ b/make-log-files.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +# This script creates the log files and the fold they will reside in. +# This script must be executed before you set-up the start-up and +# shutdown cron-jobs on the system. + +mkdir ~/logs/ +touch ~/logs/startup-logs.txt +touch ~/logs/shutdown-logs.txt diff --git a/relay.py b/relay.py new file mode 100644 index 0000000..3b38048 --- /dev/null +++ b/relay.py @@ -0,0 +1,72 @@ +#!/usr/bin/python3 + +import RPi.GPIO as GPIO +import time +import requests +import platform +import datetime + +relay_pin = 11 +#GPIO.setmode(GPIO.BCM) # GPIO numbers instead of board numbers. +GPIO.setmode(GPIO.BOARD) +GPIO.setup(relay_pin, GPIO.OUT) + +device_id = platform.node() # For servers logs. + +def get_api_url(): + # Yes, I know I could do this better. Stop moaning. + if (device_id == "gallery1"): + return "http://ritherdon.abbether.net/api/readings/latest/1" + elif (device_id == "gallery2"): + return "http://ritherdon.abbether.net/api/readings/latest/2" + +# Make sure this is valid. +# api_url = "http://ritherdon.abbether.net/api/readings/add/1" +api_url = get_api_url() # Saves having to do the if-check every call. + +def main(): + try: + s = requests.Session() + while True: + r = s.get(api_url, timeout=5) + # print(r.status_code) # For testing. + data = r.json() + # print(f"{datetime.datetime.now()} -> {data}") # For testing. + the_reading = data.get("reading") + # print(the_reading) # For testing. + if (device_id == "gallery1"): + if (the_reading > 39): + # print(f"[INFO: FACTORY1] Light is on -- {the_reading}.") + GPIO.output(relay_pin, GPIO.HIGH) + else: + # print(f"[INFO: FACTORY1] Light is off -- {the_reading}.") + GPIO.output(relay_pin, GPIO.LOW) + elif (device_id == "gallery2"): + if (the_reading > 48): + # print(f"[INFO: FACTORY2] Light is on -- {the_reading}.") + GPIO.output(relay_pin, GPIO.HIGH) + else: + # print(f"[INFO: FACTORY2] Light is off -- {the_reading}.") + GPIO.output(relay_pin, GPIO.LOW) + time.sleep(0.3) + except KeyboardInterrupt: + print("[INFO] KEYBOARD INTERRUPT: quitting program.") + except requests.exceptions.ConnectionError: + pause = 60 + time.sleep(60) + print(f"[WARNING] MAX. REQUESTS EXCEEDED: Pausing requests for {pause} seconds...") + pass + except requests.exceptions.Timeout: + t_stamp = datetime.datetime.now() + print(f"[WARNING] TIMEOUT EXCEPTION: Request timed-out at {t_stamp}.") + time.sleep(60) + pass + except Exception as e: + print(f"[ERROR] GENERAL EXCEPTION: {e}") + finally: + print("[INFO] Terminating relay.py...") + print("[INFO] Cleaning up GPIO before closing...") + GPIO.cleanup() + +if __name__ == "__main__" : + main() diff --git a/relay.service b/relay.service new file mode 100644 index 0000000..95be2d3 --- /dev/null +++ b/relay.service @@ -0,0 +1,16 @@ +[Unit] +Description=Relay service for Return to Ritherdon project by Nicola Ellis +After=network.service + +[Service] +Type=simple +ExecStart=bash /home/rtrp/repos/relay/startup.sh +WorkingDirectory=/home/rtrp/repos/relay +StandardOutput=inherit +StandardError=inherit +Restart=always +RestartSec=60 +user=rtrp + +[Install] +WantedBy=multi-user.target diff --git a/shutdown.sh b/shutdown.sh new file mode 100755 index 0000000..7ffd1cb --- /dev/null +++ b/shutdown.sh @@ -0,0 +1,38 @@ +#!/bin/bash + +# Shutdown Script +# ==================================================================== +# I wrote this script with the intention of using it as part of a +# cron-job. Before you set up the cron-job, you must make sure you +# have either ran the "make-log-files.sh" script or created the +# appropriate log file and folder at the location specified at +# "logFile" below. +# As an aside, I usually set-up as alias for "shutdown" called, +# "powerdown". When I enter "powerdown" into the terminal, this script +# should run and then the "shutdown" command is ran at the end. + +logDate=$(date '+%Y-%m-%dT%TZ') +logFile="/home/rtrp/logs/shutdown-logs.txt" +mainURL="http://ritherdon.abbether.net/api/status/update" # Make sure this is valid. + +getApiUrl () { + case $HOSTNAME in + (factory1) apiURL="${mainURL}/1";; + (factory2) apiURL="${mainURL}/2";; + (factory3) apiURL="${mainURL}/3";; + (gallery1) apiURL="${mainURL}/4";; + (gallery2) apiURL="${mainURL}/5";; + (gallery3) apiURL="${mainURL}/6";; + esac +} + +logStatusChange () { + cat << EOF >> $logFile +$logDate +EOF +} + +logStatusChange +getApiUrl +curl -X POST --header 'Content-Type: application/json' --header 'Accept: text/html' -d '{"status": "off", "time": "'${logDate}'", "token": "QWERTYuiopasdfghjklzxcvbnm_1234567890"}' "${apiURL}" +/sbin/shutdown -h now diff --git a/startup.sh b/startup.sh new file mode 100755 index 0000000..b53993b --- /dev/null +++ b/startup.sh @@ -0,0 +1,50 @@ +#!/bin/bash + +# Startup Script +# ==================================================================== +# I wrote this script with the intention of using it to start a +# cron-job -- when the Raspberry Pi is turned on. Before you set the +# cron-job up, you must make sure you have either ran the +# "make-log-files.sh" script or created the appropriate log file and +# folder at the location specified at "logFile" below. +# ==== +# Please note: This script calls another (Python) script at the end of +# it. The code in the Python script (relay.py) is an infinite-loop +# so you will need to kill it manually or turn-off the Raspberry Pi. +# ==== +# I put the "sleep 60" call at the start to reduce any errors +# occurring because a part of the system (I.E. curl) has not finished +# loading. 60 seconds is a little excessive but I wrote this script +# with the expectation of it running on an unmanned Raspberry Pi. So, +# reliable/consistent behaviour is my preference over "fast start-up +# times". + +#sleep 60 + +logDate=$(date '+%Y-%m-%dT%TZ') +logFile="/home/rtrp/logs/startup-logs.txt" +mainURL="http://ritherdon.abbether.net/api/status/update" # Make sure this is valid. + +getApiUrl () { + case $HOSTNAME in + (factory1) apiURL="${mainURL}/1";; + (factory2) apiURL="${mainURL}/2";; + (factory3) apiURL="${mainURL}/3";; + (gallery1) apiURL="${mainURL}/4";; + (gallery2) apiURL="${mainURL}/5";; + (gallery3) apiURL="${mainURL}/6";; + esac +} + +logStatusChange () { + cat << EOF >> $logFile +$logDate +EOF +} + +logStatusChange +getApiUrl + +curl -S -X POST --header 'Content-Type: application/json' --header 'Accept: text/html' -d '{"status": "on", "time": "'${logDate}'", "token": "QWERTYuiopasdfghjklzxcvbnm_1234567890"}' "${apiURL}" + +python3 /home/rtrp/repos/relay/relay.py