modified: python_code/temp-humid-read-loop.py
new file: python_code/temp-humid-read-single.py modified: python_code/updateMysql.py
This commit is contained in:
@@ -17,66 +17,57 @@ oldhumid = "NULL"
|
|||||||
|
|
||||||
def exec_every_n_seconds(n,f,*args):
|
def exec_every_n_seconds(n,f,*args):
|
||||||
waitInterval = timedelta(seconds=n)
|
waitInterval = timedelta(seconds=n)
|
||||||
print('We should read the sensor every {0} seconds'.format(waitInterval))
|
logging.debug('We should read the sensor every {0} seconds'.format(waitInterval))
|
||||||
duration=f(*args)
|
duration=f(*args)
|
||||||
offset = waitInterval - duration
|
offset = waitInterval - duration
|
||||||
print('Running the loop again in {0} seconds'.format(offset))
|
logging.debug('Running the loop again in {0} seconds (printed as datetime)'.format(offset))
|
||||||
offset2 = offset.total_seconds()
|
offset2 = offset.total_seconds()
|
||||||
print('Running the loop again in {0} seconds'.format(offset2))
|
logging.debug('Running the loop again in {0} seconds (printed as float)'.format(offset2))
|
||||||
while 1:
|
while 1:
|
||||||
print('We are in the loop now ...')
|
logging.debug('We are in the loop now ...')
|
||||||
time.sleep(offset2)
|
time.sleep(offset2)
|
||||||
print('We are about to run the sensor read again')
|
logging.debug('We are about to run the sensor read again')
|
||||||
duration=f(*args)
|
duration=f(*args)
|
||||||
print('Duration of sequence was: {0}'.format(duration))
|
logging.debug('Duration of sequence was: {0}'.format(duration))
|
||||||
offset = waitInterval - duration
|
offset = waitInterval - duration
|
||||||
print('Running the loop again in {0} seconds'.format(offset))
|
logging.debug('Running the loop again in {0} seconds (printed as dateime)'.format(offset))
|
||||||
offset2 = offset.total_seconds()
|
offset2 = offset.total_seconds()
|
||||||
print('Running the loop again in {0} seconds'.format(offset2))
|
logging.debug('Running the loop again in {0} seconds (printed as float)'.format(offset2))
|
||||||
|
|
||||||
def sensorRead(hwtype, pin, retries, timeout, maxtemp, mintemp, maxhumid, minhumid):
|
def sensorRead(hwtype, pin, retries, timeout, maxtemp, mintemp, maxhumid, minhumid):
|
||||||
global oldtemp
|
global oldtemp
|
||||||
global oldhumid
|
global oldhumid
|
||||||
startTime=datetime.now()
|
startTime=datetime.now()
|
||||||
print('This round of results started at {0}'.format(startTime))
|
logging.debug('This round of results started at {0}'.format(startTime))
|
||||||
for num in range(retries):
|
for num in range(retries):
|
||||||
try:
|
try:
|
||||||
t, h = dhtreader.read(dev_type, dhtpin)
|
t, h = dhtreader.read(dev_type, dhtpin)
|
||||||
except:
|
except:
|
||||||
if ((num + 1) < retries):
|
if ((num + 1) < retries):
|
||||||
print('Exception detected! We will retry. Loop number: %d', num)
|
|
||||||
logging.warning('Exception detected! We will retry. Loop number: %d', num)
|
logging.warning('Exception detected! We will retry. Loop number: %d', num)
|
||||||
time.sleep(timeout)
|
time.sleep(timeout)
|
||||||
else:
|
else:
|
||||||
print('Exception detected - we are out of retries. Skipping the measurement in this cycle.')
|
|
||||||
logging.error('Exception detected - we are out of retries. Skipping the measurement in this cycle.')
|
logging.error('Exception detected - we are out of retries. Skipping the measurement in this cycle.')
|
||||||
else:
|
else:
|
||||||
if t and h:
|
if t and h:
|
||||||
print(t, h)
|
logging.debug('Temperature and humidity 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 < humiddif)):
|
if (oldtemp != "NULL") and ((t - oldtemp < tempdiff) or (oldtemp - t < tempdiff)) and ((h - oldhumid < humiddiff) or (oldhumid - h < humiddif)):
|
||||||
print('Current temperature close enough to previous temperature and previous temperature is not NULL, it is:')
|
|
||||||
logging.debug('Current temperature close enough to previous temperature and previous temperature is not NULL, it is: %s', oldtemp)
|
logging.debug('Current temperature close enough to previous temperature and previous temperature is not NULL, it is: %s', oldtemp)
|
||||||
print oldtemp
|
|
||||||
print('Current humidity close enough to previous humidity and previous humidity is not NULL, it is:')
|
|
||||||
logging.debug('Current humidity close enough to previous humidity and previous humidity is not NULL, it is: %s', oldhumid)
|
logging.debug('Current humidity close enough to previous humidity and previous humidity is not NULL, it is: %s', oldhumid)
|
||||||
print oldhumid
|
|
||||||
if (t < maxtemp) and (t > mintemp) and (h < maxhumid) and (h > minhumid):
|
if (t < maxtemp) and (t > mintemp) and (h < maxhumid) and (h > minhumid):
|
||||||
print('Temperature is less than {0} and greater than {1}, humidity is less than {2} and greater than {3}'.format(maxtemp,mintemp,maxhumid,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))
|
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)
|
updateMysql.main(t, h, host, db, username, password, logging)
|
||||||
oldtemp=t
|
oldtemp=t
|
||||||
oldhumid=h
|
oldhumid=h
|
||||||
break
|
break
|
||||||
else:
|
else:
|
||||||
print('Temperature {0} or humidity {1} is outside of allowable values - error! Check your configuration.'.format(t, h))
|
|
||||||
logging.error('Temperature {0} or humidity {1} is outside of allowable values - error! Check your configuration.'.format(t, h))
|
logging.error('Temperature {0} or humidity {1} is outside of allowable values - error! Check your configuration.'.format(t, h))
|
||||||
else:
|
else:
|
||||||
print("Failed to read from sensor, maybe try again?")
|
|
||||||
logging.warning('Failed to read from sensor, maybe try again?')
|
logging.warning('Failed to read from sensor, maybe try again?')
|
||||||
endTime=datetime.now()
|
endTime=datetime.now()
|
||||||
print('This round of results ended at {0}'.format(endTime))
|
logging.debug('This round of results ended at {0}'.format(endTime))
|
||||||
duration = endTime - startTime
|
duration = endTime - startTime
|
||||||
print('Thiis round of results took {0} to complete'.format(duration))
|
logging.debug('This round of results took {0} to complete'.format(duration))
|
||||||
return duration
|
return duration
|
||||||
|
|
||||||
DHT11 = 11
|
DHT11 = 11
|
||||||
@@ -120,30 +111,24 @@ dhtreader.init()
|
|||||||
dev_type = None
|
dev_type = None
|
||||||
if hwtype == "11":
|
if hwtype == "11":
|
||||||
dev_type = DHT11
|
dev_type = DHT11
|
||||||
print('Configured to use DHT11 device')
|
|
||||||
logging.info('Configured to use DHT11 device')
|
logging.info('Configured to use DHT11 device')
|
||||||
elif hwtype == "22":
|
elif hwtype == "22":
|
||||||
dev_type = DHT22
|
dev_type = DHT22
|
||||||
print('Configured to use DHT22 device')
|
|
||||||
logging.info('Configured to use DHT22 device')
|
logging.info('Configured to use DHT22 device')
|
||||||
elif hwtype == "2302":
|
elif hwtype == "2302":
|
||||||
dev_type = AM2302
|
dev_type = AM2302
|
||||||
print('Configured to use AM 2302 device')
|
|
||||||
logging.info('Configured to use AM2303 device')
|
logging.info('Configured to use AM2303 device')
|
||||||
else:
|
else:
|
||||||
print('Invalid hardware type, only DHT11, DHT22 and AM 2302 are supported for now.!')
|
|
||||||
logging.warn('Invalid hardware type, only DHT11, DHT22 and AM 2302 are supported for now.!')
|
logging.warn('Invalid hardware type, only DHT11, DHT22 and AM 2302 are supported for now.!')
|
||||||
sys.exit(3)
|
sys.exit(3)
|
||||||
|
|
||||||
dhtpin = int(pin)
|
dhtpin = int(pin)
|
||||||
if dhtpin <= 0:
|
if dhtpin <= 0:
|
||||||
print("Invalid GPIO pin#, correct your configuration file")
|
|
||||||
logging.warn("Invalid GPIO pin#, correct your configuration file")
|
logging.warn("Invalid GPIO pin#, correct your configuration file")
|
||||||
sys.exit(3)
|
sys.exit(3)
|
||||||
|
|
||||||
print("using pin #{0}".format(dhtpin))
|
|
||||||
logging.info("using pin #{0}".format(dhtpin))
|
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]')
|
||||||
|
|
||||||
print('About to enter infinte loop ...')
|
logging.debug("About to enter infinite loop")
|
||||||
logging.info("About to enter infinite loop")
|
|
||||||
exec_every_n_seconds(60,sensorRead,hwtype,pin,retries,timeout,maxtemp,mintemp,maxhumid,minhumid)
|
exec_every_n_seconds(60,sensorRead,hwtype,pin,retries,timeout,maxtemp,mintemp,maxhumid,minhumid)
|
||||||
|
|||||||
@@ -0,0 +1,106 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
# -*- coding:utf-8 -*-
|
||||||
|
|
||||||
|
import sys
|
||||||
|
import dhtreader
|
||||||
|
import updateMysql
|
||||||
|
import ConfigParser
|
||||||
|
#import time
|
||||||
|
#from threading import Timer,Thread,Event
|
||||||
|
import logging
|
||||||
|
#from datetime import datetime
|
||||||
|
#from datetime import timedelta
|
||||||
|
|
||||||
|
oldtemp = "NULL"
|
||||||
|
oldhumid = "NULL"
|
||||||
|
|
||||||
|
def sensorRead(hwtype, pin, retries, timeout, maxtemp, mintemp, maxhumid, minhumid):
|
||||||
|
global oldtemp
|
||||||
|
global 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 < humiddif)):
|
||||||
|
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)
|
||||||
|
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('temphumid.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'))
|
||||||
|
|
||||||
|
|
||||||
|
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,maxhumid,minhumid)
|
||||||
@@ -4,17 +4,15 @@
|
|||||||
##
|
##
|
||||||
import sys
|
import sys
|
||||||
import MySQLdb
|
import MySQLdb
|
||||||
#import datetime
|
|
||||||
#import time
|
|
||||||
|
|
||||||
def main(temp, humid, host, db, user, passwd):
|
def main(temp, humid, host, db, user, passwd, logging):
|
||||||
print('Temp = {0} *C, Hum = {1} %'.format(temp, humid))
|
logging.debug('Temp = {0} *C, Hum = {1} %'.format(temp, humid))
|
||||||
print('Updating MySQL database next ...')
|
logging.debug('Updating MySQL database next ...')
|
||||||
connection = MySQLdb.connect(host,user,passwd,db)
|
connection = MySQLdb.connect(host,user,passwd,db)
|
||||||
cursor=connection.cursor()
|
cursor=connection.cursor()
|
||||||
sqltemp=format(temp, '5.1f')
|
sqltemp=format(temp, '5.1f')
|
||||||
sqlhumid=format(humid, '5.1f')
|
sqlhumid=format(humid, '5.1f')
|
||||||
print(sqltemp, sqlhumid)
|
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)"""
|
sql = """INSERT INTO TempHumid (ComputerTime, Temperature, Humidity, id) VALUES (unix_timestamp(now()), %s, %s, NULL)"""
|
||||||
args = (sqltemp, sqlhumid)
|
args = (sqltemp, sqlhumid)
|
||||||
cursor.execute(sql, args)
|
cursor.execute(sql, args)
|
||||||
|
|||||||
Reference in New Issue
Block a user