Initial commit

This commit is contained in:
Jonathan Ervine
2020-09-03 09:40:05 +08:00
parent 58573d9086
commit 54cca78018
17 changed files with 1379 additions and 161 deletions
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/python
##
## Script to read the last temperature and humidity readings from a MySQL database
##
import sys
import MySQLdb
def main(host, db, user, passwd, logging, sql_retries, sql_timeout):
logging.debug('Reading MySQL database next ...')
connection = MySQLdb.connect(host,user,passwd,db)
cursor=connection.cursor()
sql = """SELECT Temperature, Humidity FROM TempHumid ORDER BY ComputerTime DESC LIMIT 1"""
success = False
attempts = 0
while attempts < sql_retries and not success:
try:
cursor.execute(sql)
data = cursor.fetchall()
for row in data :
temp = row[0]
humid = row[1]
oldtemp = float(temp)
oldhumid = float(humid)
logging.debug('The MySQL database was successfully read.')
connection.commit()
cursor.close()
logging.debug('The previous temperature was: {0}C and the previous humidity was {1}%'.format(oldtemp, oldhumid))
success = True
except MySQLdb.Error, e:
logging.warn('The MySQL database could not be read and returned the following error %d: %s', (e.args[0], e.args[1]))
attempts += 1
if attempts == sql_retries:
logging.error('All configured attempts to read the MySQL database have failed. We are going to skip this attempt.')
time.sleep(sql_interval)
return oldtemp, oldhumid
+141
View File
@@ -0,0 +1,141 @@
#/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
import dhtreader
import updateMysql
import ConfigParser
import time
from time import strftime
from threading import Timer,Thread,Event
import logging
from datetime import datetime
from datetime import timedelta
oldtemp = "NULL"
oldhumid = "NULL"
def exec_every_n_seconds(n,f,*args):
waitInterval = timedelta(seconds=n)
logging.debug('We should read the sensor every {0} seconds'.format(waitInterval))
duration=f(*args)
offset = waitInterval - duration
logging.debug('Running the loop again in {0} seconds (printed as datetime)'.format(offset))
offset2 = offset.total_seconds()
logging.debug('Running the loop again in {0} seconds (printed as float)'.format(offset2))
while 1:
logging.debug('We are in the loop now ...')
initTime=time.time()
logging.debug('Start time is {0}'.format(initTime))
#time.sleep(offset2)
logging.debug('We are about to run the sensor read again')
duration=f(*args)
offset2 = (60.0 - (time.time() - initTime))
time.sleep(60.0 - ((time.time() - initTime) % 60.0))
logging.debug('Duration of sequence was: {0}'.format(duration))
offset = waitInterval - duration
logging.debug('Running the loop again in {0} seconds (printed as dateime)'.format(offset))
#offset2 = offset.total_seconds()
logging.debug('Running the loop again in {0} seconds (printed as float)'.format(offset2))
def sensorRead(hwtype, pin, retries, timeout, maxtemp, mintemp, tempdiff, maxhumid, minhumid, humiddiff):
global oldtemp
global oldhumid
startTime=datetime.now()
logging.debug('This round of results started at {0}'.format(startTime))
for num in range(retries):
try:
t, h = dhtreader.read(dev_type, dhtpin)
except:
if ((num + 1) < retries):
logging.warning('Exception detected! We will retry. Loop number: %d', num)
time.sleep(timeout)
else:
logging.error('Exception detected - we are out of retries. Skipping the measurement in this cycle.')
else:
if t and h:
logging.debug('Temperature and humidity read as {0} and {1}'.format(t, h))
logging.debug('Temperature and Humidity differences allowed: {0} and {1}'.format(tempdiff, humiddiff))
if (oldtemp != "NULL") and ((t - oldtemp < tempdiff) or (oldtemp - t < tempdiff)) and ((h - oldhumid < humiddiff) or (oldhumid - h < humiddiff)):
logging.debug('Current temperature close enough to previous temperature and previous temperature is not NULL, it is: %s', oldtemp)
logging.debug('Current humidity close enough to previous humidity and previous humidity is not NULL, it is: %s', oldhumid)
if (t < maxtemp) and (t > mintemp) and (h < maxhumid) and (h > minhumid):
logging.debug('Temperature is less than {0} and greater than {1}, humidity is less than {2} and greater than {3}'.format(maxtemp,mintemp,maxhumid,minhumid))
updateMysql.main(t, h, host, db, username, password, logging, sql_retries, sql_timeout)
oldtemp=t
oldhumid=h
break
else:
logging.error('Temperature {0} or humidity {1} is outside of allowable values - error! Check your configuration.'.format(t, h))
else:
logging.warning('Failed to read from sensor, maybe try again?')
endTime=datetime.now()
logging.debug('This round of results ended at {0}'.format(endTime))
duration = endTime - startTime
logging.debug('This round of results took {0} to complete'.format(duration))
return duration
DHT11 = 11
DHT22 = 22
AM2302 = 22
config = ConfigParser.ConfigParser()
config.read('/etc/thMonitor.conf')
hwtype=config.get('hardware', 'DHT')
pin=config.get('hardware', 'PIN')
retries=int(config.get('software', 'retries'))
timeout=int(config.get('software', 'timeout'))
interval=int(config.get('software', 'interval'))
maxtemp=int(config.get('software', 'maxtemp'))
mintemp=int(config.get('software', 'mintemp'))
tempdiff=int(config.get('software', 'tempdiff'))
maxhumid=int(config.get('software', 'maxhumid'))
minhumid=int(config.get('software', 'minhumid'))
humiddiff=int(config.get('software', 'humiddiff'))
logfile=(config.get('software', 'logfile'))
loglevel=(config.get('software', 'loglevel'))
host=(config.get('database', 'host'))
db=(config.get('database', 'db'))
username=(config.get('database', 'username'))
password=(config.get('database', 'password'))
sql_retries=int((config.get('database', 'sql_retries')))
sql_timeout=(config.get('database', 'sql_timeout'))
if loglevel == "debug":
logging.basicConfig(filename = logfile, format='%(asctime)s %(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.DEBUG)
elif loglevel == "info":
logging.basicConfig(filename = logfile, format='%(asctime)s %(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO)
elif loglevel == "warn":
logging.basicConfig(filename = logfile, format='%(asctime)s %(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.WARNING)
elif loglevel == "error":
logging.basicConfig(filename = logfile, format='%(asctime)s %(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.ERROR)
else:
logging.basicConfig(filename = logfile, format='%(asctime)s %(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.CRITICAL)
dhtreader.init()
dev_type = None
if hwtype == "11":
dev_type = DHT11
logging.info('Configured to use DHT11 device')
elif hwtype == "22":
dev_type = DHT22
logging.info('Configured to use DHT22 device')
elif hwtype == "2302":
dev_type = AM2302
logging.info('Configured to use AM2303 device')
else:
logging.warn('Invalid hardware type, only DHT11, DHT22 and AM 2302 are supported for now.!')
sys.exit(3)
dhtpin = int(pin)
if dhtpin <= 0:
logging.warn("Invalid GPIO pin#, correct your configuration file")
sys.exit(3)
logging.info("using pin #{0}".format(dhtpin))
logging.info('Multiple (infinte looped) run temperature and humidity reading. [version: 1.0, Jonathan Ervine, 2015-06-17]')
logging.debug("About to enter infinite loop")
exec_every_n_seconds(60,sensorRead,hwtype,pin,retries,timeout,maxtemp,mintemp,tempdiff,maxhumid,minhumid,humiddiff)
+111
View File
@@ -0,0 +1,111 @@
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
import dhtreader
import updateMysql
import readMysql
import ConfigParser
import logging
import time
from time import strftime
from datetime import datetime
from datetime import timedelta
oldtemp = "NULL"
oldhumid = "NULL"
def sensorRead(hwtype, pin, retries, timeout, maxtemp, mintemp, tempdiff, maxhumid, minhumid, humiddiff):
global oldtemp
global oldhumid
oldtemp, oldhumid = readMysql.main(host, db, username, password, logging, sql_retries, sql_timeout)
logging.debug('We have returned the following previous temperature {0} and humidity {1} values.'.format(oldtemp, oldhumid))
for num in range(retries):
try:
t, h = dhtreader.read(dev_type, dhtpin)
except:
if ((num + 1) < retries):
logging.warning('Exception detected! We will retry. Loop number: %d', num)
time.sleep(timeout)
else:
logging.error('Exception detected - we are out of retries. Skipping the measurement in this cycle.')
else:
if t and h:
logging.debug('The temperature and humidity have been read as {0} and {1}'.format(t, h))
if (oldtemp != "NULL") and ((t - oldtemp < tempdiff) or (oldtemp - t < tempdiff)) and ((h - oldhumid < humiddiff) or (oldhumid - h < humiddiff)):
logging.debug('Current temperature close enough to previous temperature and previous temperature is not NULL, it is: %s', oldtemp)
logging.debug('Current humidity close enough to previous humidity and previous humidity is not NULL, it is: %s', oldhumid)
if (t < maxtemp) and (t > mintemp) and (h < maxhumid) and (h > minhumid):
logging.debug('Temperature is less than {0} and greater than {1}, humidity is less than {2} and greater than {3}'.format(maxtemp,mintemp,maxhumid,minhumid))
updateMysql.main(t, h, host, db, username, password, logging, sql_retries, sql_timeout)
oldtemp=t
oldhumid=h
break
else:
logging.error('Temperature {0} or humidity {1} is outside of allowable values - error! Check your configuration.'.format(t, h))
else:
logging.warning('Failed to read from sensor, maybe try again?')
return 0
DHT11 = 11
DHT22 = 22
AM2302 = 22
config = ConfigParser.ConfigParser()
config.read('/etc/thMonitor.conf')
hwtype=config.get('hardware', 'DHT')
pin=config.get('hardware', 'PIN')
retries=int(config.get('software', 'retries'))
timeout=int(config.get('software', 'timeout'))
interval=int(config.get('software', 'interval'))
maxtemp=int(config.get('software', 'maxtemp'))
mintemp=int(config.get('software', 'mintemp'))
tempdiff=int(config.get('software', 'tempdiff'))
maxhumid=int(config.get('software', 'maxhumid'))
minhumid=int(config.get('software', 'minhumid'))
humiddiff=int(config.get('software', 'humiddiff'))
logfile=(config.get('software', 'logfile'))
loglevel=(config.get('software', 'loglevel'))
host=(config.get('database', 'host'))
db=(config.get('database', 'db'))
username=(config.get('database', 'username'))
password=(config.get('database', 'password'))
sql_retries=int((config.get('database', 'sql_retries')))
sql_timeout=(config.get('database', 'sql_timeout'))
if loglevel == "debug":
logging.basicConfig(filename = logfile, format='%(asctime)s %(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.DEBUG)
elif loglevel == "info":
logging.basicConfig(filename = logfile, format='%(asctime)s %(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO)
elif loglevel == "warn":
logging.basicConfig(filename = logfile, format='%(asctime)s %(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.WARNING)
elif loglevel == "error":
logging.basicConfig(filename = logfile, format='%(asctime)s %(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.ERROR)
else:
logging.basicConfig(filename = logfile, format='%(asctime)s %(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.CRITICAL)
dhtreader.init()
dev_type = None
if hwtype == "11":
dev_type = DHT11
logging.info('Configured to use DHT11 device')
elif hwtype == "22":
dev_type = DHT22
logging.info('Configured to use DHT22 device')
elif hwtype == "2302":
dev_type = AM2302
logging.info('Configured to use AM2303 device')
else:
logging.warn('Invalid hardware type, only DHT11, DHT22 and AM 2302 are supported for now.!')
sys.exit(3)
dhtpin = int(pin)
if dhtpin <= 0:
logging.warn("Invalid GPIO pin#, correct your configuration file")
sys.exit(3)
logging.info("using pin #{0}".format(dhtpin))
logging.info('Single run temperature and humidity reading. [version: 1.0, Jonathan Ervine, 2015-06-17]')
sensorRead(hwtype,pin,retries,timeout,maxtemp,mintemp,tempdiff,maxhumid,minhumid,humiddiff)
+61
View File
@@ -0,0 +1,61 @@
[hardware]
## The hardare settings of the temperature humidity monitor
# The hardware type - valid values are: 11 (DHT11 sensor), 22 (DHT22 sensor), and 2302 (AM2302 sensor)
DHT=22
# The pin number used on the Raspberry Pi board
PIN=4
[software]
# The monitoring software will retry reading the temperature and humidity readings if the sensor returns an error. The number of retries is configured here. If no valid reading is made with all attempts, no reading will be recorded in this particular monitoring cycle.
retries=3
# If the monitoring software returns an error from the temperature humidity sensor, it will wait before attempting to re-read the values. The timeout to wait between reading attempts is configured here. This value shoul dnot be set too low.
timeout=5
# The interval between reading cycles is configured here. This is sually set to 1 minute (60 seconds).
interval=60
# The maximum temperature that will be recorded by the monitoring software. Sometimes, the sensor can return an erroneous (too high) temperature reading. If the temperature returned is greater than this value, then it will be discarded, and the software will retry the sensor reading. If all readings are too high, no reading is recorded in this monitoring cycle.
maxtemp=50
# The minimum temperature that will be recorded by the monitoring software. Sometimes, the sensor can return an erroneous (too low) temperature reading. If the temperature returned is less than this value, then it will be discarded, and the software will retry the sensor reading. If all readings are too low, no reading is recorded in this monitoring cycle.
mintemp=15
# This is the maximum difference between the currently read temperature and the previously recorded temperature. If the difference is greater than this value, the reading is discarded and the software will retry the sensor reading. This should ensure that any erroneous readings are not used.
tempdiff=10
# The maximum humidity that will be recorded by the monitoring software. Sometimes, the sensor can return an erroneous (too high) humidity reading. If the humidity returned is greater than this value, then it will be discarded, and the software will retry the sensor reading. If all readings are too high, no reading is recorded in this monitoring cycle.
maxhumid=80
# The minimum humidity that will be recorded by the monitoring software. Sometimes, the sensor can return an erroneous (too low) humidity reading. If the humidity returned is less than this value, then it will be discarded, and the software will retry the sensor reading. If all readings are too low, no reading is recorded in this monitoring cycle.
minhumid=20
# This is the maximum difference between the currently read humidity and the previously recorded humidity. If the difference is greater than this value, the reading is discarded and the software will retry the sensor reading. This should ensure that any erroneous readings are not used.
humiddiff=10
# The name and location of the logfile
logfile=/var/log/th-python.log
# The logging level (available: debug, info, warn, error, or critical). The default is critical.
loglevel=debug
[database]
## MySQL Database connectivity settings
# The hostname of the MySQL database server
host=localhost
# The name of the database
db=Monitoring
# The username to us to connect to MySQL (should have INSERT rights on the database)
username=USRENAME
# The password of the username above
password=PASSWORD
# This is the maximum number of retries made to update the MySQL database with the data. If these all fail, the failure is recorded, but the daemon should continue to run
sql_retries=3
# This is the timeout between retries when updating the MySQL database. It is useful to set this parameter and sql_retries parameter, as the thMonitor daemon frequently starts up before the MySQL daemon has finished starting.
sql_timeout=5
+62
View File
@@ -0,0 +1,62 @@
#!/bin/sh
### BEGIN INIT INFO
# Provides: thMonitor
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Temperature and Humidity Monitor
# Description: Temperature and Humidity Monitoring daemon
### END INIT INFO
# Change the next 3 lines to suit where you install your script and what you want to call it
DIR=/usr/local/bin/thMonitor
DAEMON=$DIR/temp-humid-python-loop.py
DAEMON_NAME=thMonitor
# Add any command line options for your daemon here
DAEMON_OPTS=""
# This next line determines what user the script runs as.
# Root generally not recommended but necessary if you are using the Raspberry Pi GPIO from Python.
DAEMON_USER=root
# The process ID of the script when it runs is stored here:
PIDFILE=/var/run/$DAEMON_NAME.pid
. /lib/lsb/init-functions
do_start () {
log_daemon_msg "Starting system $DAEMON_NAME daemon"
start-stop-daemon --start --background --pidfile $PIDFILE --make-pidfile --user $DAEMON_USER --chuid $DAEMON_USER --startas $DAEMON -- $DAEMON_OPTS
log_end_msg $?
}
do_stop () {
log_daemon_msg "Stopping system $DAEMON_NAME daemon"
start-stop-daemon --stop --pidfile $PIDFILE --retry 10
log_end_msg $?
}
case "$1" in
start|stop)
do_${1}
;;
restart|reload|force-reload)
do_stop
do_start
;;
status)
status_of_proc "$DAEMON_NAME" "$DAEMON" && exit 0 || exit $?
;;
*)
echo "Usage: /etc/init.d/$DAEMON_NAME {start|stop|restart|status}"
exit 1
;;
esac
exit 0
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/python
##
## Script to import the temperature and humidity into a MySQL database
##
import sys
import MySQLdb
def main(temp, humid, host, db, user, passwd, logging, sql_retries, sql_timeout):
logging.debug('Temp = {0} *C, Hum = {1} %'.format(temp, humid))
logging.debug('Updating MySQL database next ...')
connection = MySQLdb.connect(host,user,passwd,db)
cursor=connection.cursor()
sqltemp=format(temp, '5.1f')
sqlhumid=format(humid, '5.1f')
logging.info('Temperature: {0}*C Humidity: {1}% ... updating to MySQL database'.format(sqltemp, sqlhumid))
sql = """INSERT INTO TempHumid (ComputerTime, Temperature, Humidity, id) VALUES (unix_timestamp(now()), %s, %s, NULL)"""
args = (sqltemp, sqlhumid)
success = False
attempts = 0
while attempts < sql_retries and not success:
try:
cursor.execute(sql, args)
connection.commit()
cursor.close()
success = True
logging.debug('The MySQL database was successfully updated.')
except MySQLdb.Error, e:
logging.warn('The MySQL database could not be updated and returned the following error %d: %s', (e.args[0], e.args[1]))
attempts += 1
if attempts == sql_retries:
logging.error('All configured attempts to update the MySQL database have failed. We are going to skip this attempt.')
time.sleep(sql_interval)
return 0