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

452
LICENSE
View File

@ -1,208 +1,340 @@
Apache License
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Version 2.0, January 2004
Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION,
AND DISTRIBUTION
Preamble
1. Definitions.
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
"License" shall mean the terms and conditions for use, reproduction, and distribution
as defined by Sections 1 through 9 of this document.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
"Licensor" shall mean the copyright owner or entity authorized by the copyright
owner that is granting the License.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
"Legal Entity" shall mean the union of the acting entity and all other entities
that control, are controlled by, or are under common control with that entity.
For the purposes of this definition, "control" means (i) the power, direct
or indirect, to cause the direction or management of such entity, whether
by contract or otherwise, or (ii) ownership of fifty percent (50%) or more
of the outstanding shares, or (iii) beneficial ownership of such entity.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions
granted by this License.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
"Source" form shall mean the preferred form for making modifications, including
but not limited to software source code, documentation source, and configuration
files.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
"Object" form shall mean any form resulting from mechanical transformation
or translation of a Source form, including but not limited to compiled object
code, generated documentation, and conversions to other media types.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
"Work" shall mean the work of authorship, whether in Source or Object form,
made available under the License, as indicated by a copyright notice that
is included in or attached to the work (an example is provided in the Appendix
below).
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
"Derivative Works" shall mean any work, whether in Source or Object form,
that is based on (or derived from) the Work and for which the editorial revisions,
annotations, elaborations, or other modifications represent, as a whole, an
original work of authorship. For the purposes of this License, Derivative
Works shall not include works that remain separable from, or merely link (or
bind by name) to the interfaces of, the Work and Derivative Works thereof.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
"Contribution" shall mean any work of authorship, including the original version
of the Work and any modifications or additions to that Work or Derivative
Works thereof, that is intentionally submitted to Licensor for inclusion in
the Work by the copyright owner or by an individual or Legal Entity authorized
to submit on behalf of the copyright owner. For the purposes of this definition,
"submitted" means any form of electronic, verbal, or written communication
sent to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems, and
issue tracking systems that are managed by, or on behalf of, the Licensor
for the purpose of discussing and improving the Work, but excluding communication
that is conspicuously marked or otherwise designated in writing by the copyright
owner as "Not a Contribution."
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
of whom a Contribution has been received by Licensor and subsequently incorporated
within the Work.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
2. Grant of Copyright License. Subject to the terms and conditions of this
License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
no-charge, royalty-free, irrevocable copyright license to reproduce, prepare
Derivative Works of, publicly display, publicly perform, sublicense, and distribute
the Work and such Derivative Works in Source or Object form.
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
3. Grant of Patent License. Subject to the terms and conditions of this License,
each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
no-charge, royalty-free, irrevocable (except as stated in this section) patent
license to make, have made, use, offer to sell, sell, import, and otherwise
transfer the Work, where such license applies only to those patent claims
licensable by such Contributor that are necessarily infringed by their Contribution(s)
alone or by combination of their Contribution(s) with the Work to which such
Contribution(s) was submitted. If You institute patent litigation against
any entity (including a cross-claim or counterclaim in a lawsuit) alleging
that the Work or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses granted to You
under this License for that Work shall terminate as of the date such litigation
is filed.
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
4. Redistribution. You may reproduce and distribute copies of the Work or
Derivative Works thereof in any medium, with or without modifications, and
in Source or Object form, provided that You meet the following conditions:
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
(a) You must give any other recipients of the Work or Derivative Works a copy
of this License; and
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
(b) You must cause any modified files to carry prominent notices stating that
You changed the files; and
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
(c) You must retain, in the Source form of any Derivative Works that You distribute,
all copyright, patent, trademark, and attribution notices from the Source
form of the Work, excluding those notices that do not pertain to any part
of the Derivative Works; and
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
(d) If the Work includes a "NOTICE" text file as part of its distribution,
then any Derivative Works that You distribute must include a readable copy
of the attribution notices contained within such NOTICE file, excluding those
notices that do not pertain to any part of the Derivative Works, in at least
one of the following places: within a NOTICE text file distributed as part
of the Derivative Works; within the Source form or documentation, if provided
along with the Derivative Works; or, within a display generated by the Derivative
Works, if and wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and do not modify the
License. You may add Your own attribution notices within Derivative Works
that You distribute, alongside or as an addendum to the NOTICE text from the
Work, provided that such additional attribution notices cannot be construed
as modifying the License.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
You may add Your own copyright statement to Your modifications and may provide
additional or different license terms and conditions for use, reproduction,
or distribution of Your modifications, or for any such Derivative Works as
a whole, provided Your use, reproduction, and distribution of the Work otherwise
complies with the conditions stated in this License.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any
Contribution intentionally submitted for inclusion in the Work by You to the
Licensor shall be under the terms and conditions of this License, without
any additional terms or conditions. Notwithstanding the above, nothing herein
shall supersede or modify the terms of any separate license agreement you
may have executed with Licensor regarding such Contributions.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
6. Trademarks. This License does not grant permission to use the trade names,
trademarks, service marks, or product names of the Licensor, except as required
for reasonable and customary use in describing the origin of the Work and
reproducing the content of the NOTICE file.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to
in writing, Licensor provides the Work (and each Contributor provides its
Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied, including, without limitation, any warranties
or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR
A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness
of using or redistributing the Work and assume any risks associated with Your
exercise of permissions under this License.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
8. Limitation of Liability. In no event and under no legal theory, whether
in tort (including negligence), contract, or otherwise, unless required by
applicable law (such as deliberate and grossly negligent acts) or agreed to
in writing, shall any Contributor be liable to You for damages, including
any direct, indirect, special, incidental, or consequential damages of any
character arising as a result of this License or out of the use or inability
to use the Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all other commercial
damages or losses), even if such Contributor has been advised of the possibility
of such damages.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
9. Accepting Warranty or Additional Liability. While redistributing the Work
or Derivative Works thereof, You may choose to offer, and charge a fee for,
acceptance of support, warranty, indemnity, or other liability obligations
and/or rights consistent with this License. However, in accepting such obligations,
You may act only on Your own behalf and on Your sole responsibility, not on
behalf of any other Contributor, and only if You agree to indemnify, defend,
and hold each Contributor harmless for any liability incurred by, or claims
asserted against, such Contributor by reason of your accepting any such warranty
or additional liability. END OF TERMS AND CONDITIONS
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
APPENDIX: How to apply the Apache License to your work.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
To apply the Apache License to your work, attach the following boilerplate
notice, with the fields enclosed by brackets "[]" replaced with your own identifying
information. (Don't include the brackets!) The text should be enclosed in
the appropriate comment syntax for the file format. We also recommend that
a file or class name and description of purpose be included on the same "printed
page" as the copyright notice for easier identification within third-party
archives.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
Copyright [yyyy] [name of copyright owner]
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
Licensed under the Apache License, Version 2.0 (the "License");
NO WARRANTY
you may not use this file except in compliance with the License.
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
You may obtain a copy of the License at
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
http://www.apache.org/licenses/LICENSE-2.0
END OF TERMS AND CONDITIONS
Unless required by applicable law or agreed to in writing, software
How to Apply These Terms to Your New Programs
distributed under the License is distributed on an "AS IS" BASIS,
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
See the License for the specific language governing permissions and
{description}
Copyright (C) {year} {fullname}
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
{signature of Ty Coon}, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
limitations under the License.

View File

@ -1,3 +1,48 @@
# rpi-temp-humid-monitor
Raspberry Pi temperature humidity monitor
This is my implementation of making a Raspberry Pi powered temperature and humidity monitor. The original instructions that I followed were created by wpnsmith at [the instructables website](http://www.instructables.com/id/Raspberry-Pi-Temperature-Humidity-Network-Monitor/)
In this repository are my copies of the th.c code, a thd init script, and two files for creating a Google Chart graph rather than the python based GraphTH.py using matplotlib that wpnsmith used.
The th.c code was modified so that a fourth column in MySQL is used (an auto incrementing id - probably not strictly necessary as the ComputerTime entry is incrementing anyway), as well as having th detect if an incorrect temperature/humidity reading has been made (by checking against the previously recorded value) and silently not adding this to the MySQL database if it is seen to be a big change.
Using a thd init script means that we don't need to modify /etc/rc.local - which is useful for me as this file is used by other projects and can be overwritten at times.
## UPDATED - 10 July 2015
Added a python script, readMysql.py, to read the previous values of temperature and humidity from the MySQL database. This is necessary for the single run python script, as we don't have a previous reading to compare against.
## UPDATED - 24 June 2015
Fixed a typo in a variable name (humiddiff) that could cause the daemon to crash if an erroneous reading was made.
## UPDATED - 23 June 2015
Fixed a bug in the code where the script would crash as I hadn't passed the temperature and humidity difference tolerances allowed to the loop. If an erroneous reading was made, the script would crash.
## UPDATED - 19 June 2015
The updateMysql.py script has been updated to provide a method of retrying failed MySQL updates. Primarily this was added so that when the server is booted up, the daemon version of the code can retry a number of times before giving up, as the MySQL server will not necessarily have finished starting up.
An updated thMonitord init script has been added, and the temp-humid-read-loop and temp-humid-read-single scripts have been altered so that they are currently hardcoded to use a configuration file called /etc/thMonitor.conf
## UPDATED - 18 June 2015
There are now two python scripts (with logging added rather than printing to stdout)
- temp-humid-read-loop.py - this code should loop and run the temperature/humidity readind every 60 seconds. I have tried to add code to ensure that this loops every 60 seconds regardless of how long the actual reading takes. Due to occasional reading errors, the function to read temperature and humidity can vary in length - dependent upon the timeout and number of retries conifgured. The code should time the length of the sensorRead function and subtract this time from the configured reading interval. Tests have shown this is reasonably accurate but some drift has still been observed.
- temp-humid-python-single.py - this code is a simplified python script taken from the looping script. The looping logic has been removed, and a single pass is made reading the temperature and humidity readings. Any errors from a reading during this single pass are retried according to the timeout and retries configured though - so a single read should succeed. This script can be put into a cron job to run on a regularly scheduled basis, which might be less prone to drift than the looped version.
- updateMysql.py - this code has been cleaned up so that it logs to the logfile rather than to stdout by default.
## UPDATED - 17 June 2015
Looking to replace the C code with a python script that takes a configuration file. Added here:
- temp-humid-read-loop.py - python code to continuously loop and read the temperature and humidity settings
- updateMysql.py - python code called by the loop script to update the MySQL database
- temphumid.conf - sample configuration file to be used with the python script
- dhtreader.so - binary shared object file. This has been created from [http://www.airspayce.com/mikem/bcm2835/](http://www.airspayce.com/mikem/bcm2835/)
###Please note this updated python code was heavily inspired by the work done by Adafruit here:###
[https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code/tree/master/Adafruit_DHT_Driver_Python](https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code/tree/master/Adafruit_DHT_Driver_Python)
Raspberry Pi temperature and humidity monitoring code

4
TODO Normal file
View File

@ -0,0 +1,4 @@
## TO DO LIST
- Update the single run python script so that it reads the MySQL database for the previous values of temperature and humidity, as it doesn't loop and therefore doesn't maintain the previous readings.

168
c_code/Makefile Normal file
View File

@ -0,0 +1,168 @@
#
# Makefile:
# wiringPi - Wiring Compatable library for the Raspberry Pi
# https://projects.drogon.net/wiring-pi
#
# Copyright (c) 2012 Gordon Henderson
#################################################################################
# This file is part of wiringPi:
# Wiring Compatable library for the Raspberry Pi
#
# wiringPi is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wiringPi is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with wiringPi. If not, see <http://www.gnu.org/licenses/>.
#################################################################################
#DEBUG = -g -O0
DEBUG = -O3
CC = gcc
INCLUDE = -I/usr/local/include,/usr/include/mysql
CFLAGS = $(DEBUG) -Wall $(INCLUDE) -Winline -pipe -std=c99
LDFLAGS = -L/usr/local/lib,/usr/lib/arm-linux-gnueabihf -lmysqlclient -lpthread -lz -lm -lrt -ldl -lconfig
LDLIBS = -lwiringPi -lwiringPiDev -lpthread -lm
# Should not alter anything below this line
###############################################################################
SRC = blink.c blink8.c blink12.c \
blink12drcs.c \
pwm.c \
speed.c wfi.c isr.c isr-osc.c \
lcd.c lcd-adafruit.c clock.c \
nes.c \
softPwm.c softTone.c \
delayTest.c serialRead.c serialTest.c okLed.c ds1302.c \
lowPower.c \
rht03.c piglow.c
OBJ = $(SRC:.c=.o)
BINS = $(SRC:.c=)
all:
@cat README.TXT
@echo " $(BINS)" | fmt
@echo ""
really-all: $(BINS)
blink: blink.o
@echo [link]
@$(CC) -o $@ blink.o $(LDFLAGS) $(LDLIBS)
blink8: blink8.o
@echo [link]
@$(CC) -o $@ blink8.o $(LDFLAGS) $(LDLIBS)
blink12drcs: blink12drcs.o
@echo [link]
@$(CC) -o $@ blink12drcs.o $(LDFLAGS) $(LDLIBS)
blink12: blink12.o
@echo [link]
@$(CC) -o $@ blink12.o $(LDFLAGS) $(LDLIBS)
speed: speed.o
@echo [link]
@$(CC) -o $@ speed.o $(LDFLAGS) $(LDLIBS)
lcd: lcd.o
@echo [link]
@$(CC) -o $@ lcd.o $(LDFLAGS) $(LDLIBS)
lcd-adafruit: lcd-adafruit.o
@echo [link]
@$(CC) -o $@ lcd-adafruit.o $(LDFLAGS) $(LDLIBS)
clock: clock.o
@echo [link]
@$(CC) -o $@ clock.o $(LDFLAGS) $(LDLIBS)
wfi: wfi.o
@echo [link]
@$(CC) -o $@ wfi.o $(LDFLAGS) $(LDLIBS)
isr: isr.o
@echo [link]
@$(CC) -o $@ isr.o $(LDFLAGS) $(LDLIBS)
isr-osc: isr-osc.o
@echo [link]
@$(CC) -o $@ isr-osc.o $(LDFLAGS) $(LDLIBS)
nes: nes.o
@echo [link]
@$(CC) -o $@ nes.o $(LDFLAGS) $(LDLIBS)
rht03: rht03.o
@echo [link]
@$(CC) -o $@ rht03.o $(LDFLAGS) $(LDLIBS)
pwm: pwm.o
@echo [link]
@$(CC) -o $@ pwm.o $(LDFLAGS) $(LDLIBS)
softPwm: softPwm.o
@echo [link]
@$(CC) -o $@ softPwm.o $(LDFLAGS) $(LDLIBS)
softTone: softTone.o
@echo [link]
@$(CC) -o $@ softTone.o $(LDFLAGS) $(LDLIBS)
delayTest: delayTest.o
@echo [link]
@$(CC) -o $@ delayTest.o $(LDFLAGS) $(LDLIBS)
serialRead: serialRead.o
@echo [link]
@$(CC) -o $@ serialRead.o $(LDFLAGS) $(LDLIBS)
serialTest: serialTest.o
@echo [link]
@$(CC) -o $@ serialTest.o $(LDFLAGS) $(LDLIBS)
okLed: okLed.o
@echo [link]
@$(CC) -o $@ okLed.o $(LDFLAGS) $(LDLIBS)
tone: tone.o
@echo [link]
@$(CC) -o $@ tone.o $(LDFLAGS) $(LDLIBS)
ds1302: ds1302.o
@echo [link]
@$(CC) -o $@ ds1302.o $(LDFLAGS) $(LDLIBS)
piglow: piglow.o
@echo [link]
@$(CC) -o $@ piglow.o $(LDFLAGS) $(LDLIBS)
.c.o:
@echo [CC] $<
@$(CC) -c $(CFLAGS) $< -o $@
clean:
@echo "[Clean]"
@rm -f $(OBJ) *~ core tags $(BINS)
tags: $(SRC)
@echo [ctags]
@ctags $(SRC)
depend:
makedepend -Y $(SRC)
# DO NOT DELETE

BIN
c_code/th Executable file

Binary file not shown.

203
c_code/th.c Normal file
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
c_code/th.c-NOTES Normal file
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.

12
c_code/th.conf Normal file
View File

@ -0,0 +1,12 @@
//config.txt
// Basic Information:
filename = "Temperature and Humidity Monitoring Configuration File";
// Parameters
params =
{
sqlServer = "localhost";
databaseName = "Monitoring";
username = "USERNAME";
password = "PASSWORD";
};

87
c_code/thd Normal file
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

45
getData.php Normal file
View File

@ -0,0 +1,45 @@
<?php
$servername = "localhost";
$username = "USERNAME";
$password = "PASSWORD";
$dbname = "Monitoring";
$rows = array();
$table = array();
$table['cols'] = array(
// Labels for your chart, these represent the column titles
array('label' => 'Date and Time', 'type' => 'number'),
array('label' => 'Temperature', 'type' => 'number'),
array('label' => 'Humidity', 'type' => 'number')
);
// Create connection
//$conn = new mysqli($servername, $username, $password, $dbname);
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ComputerTime, Temperature, Humidity from TempHumid ORDER BY id DESC LIMIT 360";
$result = mysqli_query($conn,$sql);
//if ($result->num_rows > 0) {
// output data of each row
while($row = mysqli_fetch_array($result)) {
$temp = array();
// $datetime = date('d/m/Y H:i', $row[0]);
// $temp[] = array('v' => $datetime);
$temp[] = array('v' => $row[0]);
$temp[] = array('v' => $row[1]);
$temp[] = array('v' => $row[2]);
$rows[] = array('c' => $temp);
}
//} else {
// echo "No current temperature - ERROR?";
//}
$table['rows'] = $rows;
header('Content-type: application/json');
echo json_encode($table);
$conn->close();
?>

35
python_code/readMysql.py Normal file
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

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)

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)

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
python_code/thMonitord Normal file
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

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

68
temp-humid-chart.html Normal file
View File

@ -0,0 +1,68 @@
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "getData.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
// assumes you have timestamps in column 0, and two data series (columns 1 and 2)
var view = new google.visualization.DataView(data);
view.setColumns([{
type: 'datetime',
label: data.getColumnLabel(0),
calc: function (dt, row) {
var timestamp = dt.getValue(row, 0) * 1000; // convert to milliseconds
return new Date(timestamp);
}
}, 1, 2]);
var options = {
title: 'Temperature and Relative Humidity over Time',
width: 900,
height: 500,
vAxis: {title: "Temperature (C) and Humidity (%)"},
hAxis: {title: "Date and Time"},
// chartArea: {'width': '100%', 'height': '80%'},
}
chart.draw(view, options);
}
</script>
<script type="text/javascript" src="jQuery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// First load the chart once
drawChart();
// Set interval to call the drawChart again
setInterval(drawChart, 60000);
});
</script>
</head>
<body>
<!--Div that will hold the line chart-->
<div id="chart_div"></div>
</body>
</html>