new file: c_code/th

new file:   c_code/th.c
	new file:   c_code/th.c-NOTES
	new file:   c_code/thd
	new file:   python_code/dhtreader.so
	new file:   python_code/temp-humid-read-loop.py
	new file:   python_code/temphumid.conf
	new file:   python_code/updateMysql.py
	deleted:    dhtreader.so
	deleted:    temp-humid-read-loop.py
	deleted:    temphumid.conf
	deleted:    th.c
	deleted:    th.c-NOTES
	deleted:    thd
	deleted:    updateMysql.py
This commit is contained in:
Jonny Ervine
2015-06-17 12:34:27 +08:00
parent 2a2b02ed6c
commit a772eaeeb6
8 changed files with 517 additions and 0 deletions
Executable
BIN
View File
Binary file not shown.
+203
View File
@@ -0,0 +1,203 @@
/*
* th.c capture Temperature and Humidity readings, write them to sql database
* https://projects.drogon.net/raspberry-pi/wiringpi/
rev 1.0 12/01/2013 WPNS built from Gordon Hendersen's rht03.c
rev 1.1 12/01/2013 WPNS don't retry, takes too long
rev 1.2 12/01/2013 WPNS allow one retry after 3-second delay
rev 1.3 12/01/2013 WPNS make cycle time variable
rev 1.4 12/01/2013 WPNS add mysql stuff in
rev 1.5 12/01/2013 WPNS do 60 second cycle, cleanup, trial run
rev 1.6 12/01/2013 WPNS clean up output format
rev 1.7 12/02/2013 WPNS allow more retries, minor cleanups
rev 1.79 12/04/2013 WPNS release to instructables
rev 1.8 01/06/2015 JDE updated code to try and drop anomolous temperature humidity readings before hitting the database
rev 1.9 04/06/2015 JDE updated to try and read MySQL configuration from /etc/th.conf file rather than hard coding it
rev 1.10 11/06/2015 JDE updated to remove echoing the config options to the th.log file
*/
#include <stdio.h>
#include <wiringPi.h>
#include <maxdetect.h>
#include <time.h>
#include <libconfig.h>
#include <mysql/mysql.h>
#define RHT03_PIN 7
#define CYCLETIME 60
#define RETRIES 3
void finish_with_error(MYSQL *con)
{
fprintf(stderr, "%s\n", mysql_error(con));
mysql_close(con);
exit(1);
}
int main()
{
config_t cfg; /*Returns all parameters in this structure */
config_setting_t *setting;
const char *str1, *sqlServer, *databaseName, *username, *password;
char *config_file_name = "/etc/th.conf";
int temp, rh, oldtemp, difftemp ; // temperature and relative humidity readings
int loop; // how many times through the loop?
time_t oldtime,newtime; // when did we last take a reading?
char SQLstring[64]; // string to send to SQL engine
char TimeString[64]; // formatted time
time_t rawtime;
struct tm * timeinfo;
int status; // how did the read go?
/*Initialization */
config_init(&cfg);
/* Read the file. If there is an error, report it and exit. */
if (!config_read_file(&cfg, config_file_name))
{
printf("\n%s:%d - %s", config_error_file(&cfg), config_error_line(&cfg), config_error_text(&cfg));
config_destroy(&cfg);
return -1;
}
/* Get the configuration file name. */
if (config_lookup_string(&cfg, "filename", &str1))
printf("\nFile Type: %s", str1);
else
printf("\nNo 'filename' setting in configuration file.");
/*Read the parameter group*/
setting = config_lookup(&cfg, "params");
if (setting != NULL)
{
/*Read the server*/
if (config_setting_lookup_string(setting, "sqlServer", &sqlServer));
else
printf("\nERROR: No 'sqlServer' setting in configuration file.");
/*Read the database*/
if (config_setting_lookup_string(setting, "databaseName", &databaseName));
else
printf("\nERROR: No 'databaseName' setting in configuration file.");
/*Read the username*/
if (config_setting_lookup_string(setting, "username", &username));
else
printf("\nERROR: No 'username' setting in configuration file.");
/*Read the password*/
if (config_setting_lookup_string(setting, "password", &password));
else
printf("\nERROR: No 'password' setting in configuration file.");
printf("\n");
}
/* config_destroy(&cfg); */
/*MYSQL *con = mysql_init(NULL);
if (con == NULL) finish_with_error(con);
if (mysql_real_connect(con, sqlServer, username, password, databaseName, 0, NULL, 0) == NULL) finish_with_error(con);
sprintf(SQLstring,"SELECT ComputerTime, Temperature, Humidity FROM TempHumid ORDER BY id DESC LIMIT 1");
if (mysql_query(con, SQLstring)) finish_with_error(con);
MYSQL_RES *result = mysql_store_result(con);
if (result == NULL)
{
finish_with_error(con);
}
int num_fields = mysql_num_fields(result);
MYSQL_ROW row;
row = mysql_fetch_row(result);
for(int i = 0; i < num_fields; i++)
{
printf("%s ", row[i] ? row[i] : "NULL");
}
printf("\n"); */
/* THIS IS WHERE THE Temperautre humidity monitoring Code starts - really untidy and needs tidying up */
temp = rh = loop = 0 ;
oldtime = (int)time(NULL);
wiringPiSetup () ;
piHiPri (55) ;
printf("th.c rev 1.10 11/06/2015 JDE %sCycle time: %i seconds, %i retries\n",ctime(&oldtime),CYCLETIME,RETRIES);
fflush(stdout);
MYSQL *con = mysql_init(NULL);
if (con == NULL) finish_with_error(con);
if (mysql_real_connect(con, sqlServer, username, password, databaseName, 0, NULL, 0) == NULL) finish_with_error(con);
// wait for an interval to start and end
printf("Sync to cycletime...");
fflush(stdout);
while ((((int)time(NULL))%CYCLETIME)) delay(100);
oldtime = (int)time(NULL);
oldtemp = 500;
while (!(((int)time(NULL))%CYCLETIME)) delay(100);
printf("\n");
fflush(stdout);
for (;;)
{
// wait for an interval to start
while ((((int)time(NULL))%CYCLETIME)) delay(100);
/*****************************************************************/
// read new data
temp = rh = -1;
loop=RETRIES;
status = readRHT03 (RHT03_PIN, &temp, &rh);
while ((!status) && loop--)
{
printf("-Retry-");
fflush(stdout);
delay(3000);
status = readRHT03 (RHT03_PIN, &temp, &rh);
}
newtime = (int)time(NULL);
// deltime = newtime-oldtime;
time(&rawtime);
timeinfo = localtime (&rawtime);
strftime (TimeString,64,"%F %T",timeinfo);
fflush(stdout);
oldtime = newtime;
difftemp = temp - oldtemp;
printf("Current Temp: %5.1f, Previous Temp: %5.1f, Temperature Difference: %5.1fC\n",(temp / 10.0),(oldtemp / 10.0),(difftemp / 10.0)) ;
if (temp > oldtemp && difftemp > 100) {
printf("Damn ... the sensor returned a bad reading!\n");
}
else {
sprintf(SQLstring,"INSERT INTO TempHumid VALUES(unix_timestamp(now()),%5.1f,%5.1f,NULL)",(temp / 10.0),(rh / 10.0));
if (mysql_query(con, SQLstring)) finish_with_error(con);
oldtemp = temp;
}
/*****************************************************************/
// wait for the rest of that interval to finish
while (!(((int)time(NULL))%CYCLETIME)) delay(100);
}
return 0 ;
config_destroy(&cfg);
}
+10
View File
@@ -0,0 +1,10 @@
The stucture of th.c is horrible at the moment. Everything is called from main()
At some point I'd like to break out the reading of the configuration into a separate sub-routine. The printing of the configureation
file details into the log file should also be disabled for a live situation.
TODO:
1. Stop printing out config to the log file.
2. Add an option to specify the config file on the command line.
3. Add the option to log to the syslog facility.
4. Maybe add code here to only start up when MySQL is available, and to wait/retry until this works.
+87
View File
@@ -0,0 +1,87 @@
#!/bin/sh
### BEGIN INIT INFO
# Provides: th
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 1
# Short-Description: Temperature and Humidity Monitoring Daemon
### END INIT INFO
set -e
DAEMON="/usr/sbin/th"
NAME="th"
PATH="/sbin:/bin:/usr/sbin:/usr/bin"
LOGFILE="/var/log/th.log"
test -x "${DAEMON}" || exit 0
if [ ! -e "${LOGFILE}" ]
then
touch "${LOGFILE}"
chmod 640 "${LOGFILE}"
chown root:adm "${LOGFILE}"
fi
case "${1}" in
start)
echo -n "Starting Temperature and Humidity Monitoring Daemon: "
sleep 10 # We need to wait until mysqld has started - this is a horrible workaround for now
start-stop-daemon --start --background -m --oknodo --pidfile /var/run/th.pid --startas /bin/bash -- -c "exec ${DAEMON} >> ${LOGFILE} 2>&1"
echo "${NAME}."
;;
stop)
echo -n "Stopping Temperature and Humidity Monitoring Daemon: "
start-stop-daemon --stop --pidfile /var/run/th.pid --oknodo --exec ${DAEMON}
rm -f /var/run/th.pid
echo "${NAME}."
;;
restart)
echo -n "Stopping Temperature and Humidity Monitoring Daemon: "
start-stop-daemon --stop --pidfile /var/run/th.pid --oknodo --exec ${DAEMON}
rm -f /var/run/th.pid
echo "${NAME}."
echo -n "Starting Temperature and Humidity Monitoring Daemon: "
start-stop-daemon --start --background -m --oknodo --pidfile /var/run/th.pid --startas /bin/bash -- -c "exec ${DAEMON} >> ${LOGFILE}"
echo "${NAME}."
;;
status)
PID="$(cat /var/run/th.pid 2>/dev/null)" || true
if [ ! -f /var/run/th.pid ] || [ -z "${PID}" ]
then
echo "${NAME} is not running"
exit 3
fi
if ps "${PID}" >/dev/null 2>&1
then
echo "${NAME} is running"
exit 0
else
echo "${NAME} is not running"
exit 1
fi
;;
*)
echo "Usage: /etc/init.d/${NAME} {start|stop|restart|status}"
exit 1
;;
esac
exit 0
BIN
View File
Binary file not shown.
+139
View File
@@ -0,0 +1,139 @@
#!/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 timedelta
from datetime import datetime
oldtemp = "NULL"
oldhumid = "NULL"
def exec_every_n_seconds(n,f,*args):
first_called=datetime.now()
print args
f(*args)
num_calls=1
drift=timedelta()
time_period=timedelta(seconds=n)
while 1:
time.sleep(n-drift.microseconds/1000000.0)
current_time = datetime.now()
f(*args)
num_calls += 1
difference = current_time - first_called
drift = difference - time_period* num_calls
print "drift=",drift
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):
print('Exception detected! We will retry. Loop number: %d', num)
logging.warning('Exception detected! We will retry. Loop number: %d', num)
time.sleep(timeout)
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.')
else:
if t and h:
print(t, h)
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)
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)
print oldhumid
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))
updateMysql.main(t, h, host, db, username, password)
oldtemp=t
oldhumid=h
break
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))
else:
print("Failed to read from sensor, maybe try again?")
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
print('Configured to use DHT11 device')
logging.info('Configured to use DHT11 device')
elif hwtype == "22":
dev_type = DHT22
print('Configured to use DHT22 device')
logging.info('Configured to use DHT22 device')
elif hwtype == "2302":
dev_type = AM2302
print('Configured to use AM 2302 device')
logging.info('Configured to use AM2303 device')
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.!')
sys.exit(3)
dhtpin = int(pin)
if dhtpin <= 0:
print("Invalid GPIO pin#, correct your configuration file")
logging.warn("Invalid GPIO pin#, correct your configuration file")
sys.exit(3)
print("using pin #{0}".format(dhtpin))
logging.info("using pin #{0}".format(dhtpin))
print('About to enter infinte loop ...')
logging.info("About to enter infinite loop")
exec_every_n_seconds(60,sensorRead,hwtype,pin,retries,timeout,maxtemp,mintemp,maxhumid,minhumid)
+55
View File
@@ -0,0 +1,55 @@
[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
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/python
##
## Script to import the temperature and humidity into a MySQL database
##
import sys
import MySQLdb
#import datetime
#import time
def main(temp, humid, host, db, user, passwd):
print('Temp = {0} *C, Hum = {1} %'.format(temp, humid))
print('Updating MySQL database next ...')
connection = MySQLdb.connect(host,user,passwd,db)
cursor=connection.cursor()
sqltemp=format(temp, '5.1f')
sqlhumid=format(humid, '5.1f')
print(sqltemp, sqlhumid)
sql = """INSERT INTO TempHumid (ComputerTime, Temperature, Humidity, id) VALUES (unix_timestamp(now()), %s, %s, NULL)"""
args = (sqltemp, sqlhumid)
cursor.execute(sql, args)
connection.commit()
cursor.close()
return 0