Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
idcrook committed Jul 14, 2019
1 parent 292b082 commit 4f55495
Show file tree
Hide file tree
Showing 10 changed files with 240 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
!*.example.json
*.secrets.json
/env/
README.html
4 changes: 4 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[submodule "python3-phant"]
path = python3-phant
url = https://github.com/idcrook/python3-phant.git
branch = master
66 changes: 66 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
pitempmon
=========

Log Raspberry Pi CPU temperatures (to phant)

install
-------

```
# clone repo
mkdir ~/projects
cd ~/projects
git clone --recurse-submodules https://github.com/idcrook/pitempmon.git
cd pitempmon
# install requirements (using a virtualenv)
python3 -m venv env
source env/bin/activate
pip install wheel
pip install requests
pip install RPi.GPIO
pip install gpiozero
# install from local submodule clone
cd python3-phant
pip install -e .
```

### systemd service

There is

configure
---------

```
cp app_config.example.json app_config.secrets.json
cp phant-config.example.json phant-config.secrets.json
# EDIT the files
source env/bin/activate
which python
# should be one in ./env/bin/python
python
```

inspired by
-----------

- Adafruit Blog [Logging Raspberry Pi 4 CPU Temperature Data using Adafruit IO #RaspberryPi #IoTuesday #DesktopPiChallenge @AdafruitIO @Raspberry_Pi](https://blog.adafruit.com/2019/07/09/logging-raspberry-pi-4-cpu-temperature-data-using-adafruit-io-raspberrypi-iotuesday-desktoppichallenge-adafruitio-raspberry_pi/)
- https://github.com/darrell24015/tempmon

repo initialization
-------------------

```
git submodule add -b master https://github.com/idcrook/python3-phant.git
git add python3-phant
# on fresh clones
git submodule update --init --recursive
```

example data url
----------------

- https://data.crookster.org/rpif1_cpu_temp
11 changes: 11 additions & 0 deletions app_config.example.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"temperature_range":
{
"min_temp": 0.0,
"max_temp": 100.0
},
"durations":
{
"logging_interval": 120
}
}
1 change: 1 addition & 0 deletions app_config.json
26 changes: 26 additions & 0 deletions etc/pitempmon.service
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# # -*- systemd -*-
# - uses virtualenv python version
# cd /home/pi/projects/pitempmon/etc
# sudo cp -v pitempmon.service /lib/systemd/system/pitempmon@.service
# sudo chmod 644 /lib/systemd/system/pitempmon@.service
# sudo systemctl daemon-reload
# sudo systemctl enable pitempmon@pi.service
# sudo systemctl status pitempmon@pi.service
# sudo systemctl start pitempmon@pi.service
# journalctl -u pitempmon@pi.service

[Unit]
Description=Temperature Logger for Raspberry Pi CPU
Documentation=https://github.com/idcrook/pitempmon
After=network.target time-sync.target
ConditionPathExists=/home/pi/projects/pitempmon/etc

[Service]
Type=simple
WorkingDirectory=/home/pi/projects/pitempmon
ExecStart=/home/pi/projects/pitempmon/env/bin/python \
/home/pi/projects/pitempmon/pitemplog.py
User=pi

[Install]
WantedBy=default.target
7 changes: 7 additions & 0 deletions phant-config.example.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"title": "sensor_stream",
"outputUrl": "https://phant.example.com/output/PUBLIC_KEY",
"inputUrl": "https://phant.example.com/input/PUBLIC_KEY",
"manageUrl": "https://phant.example.com/streams/PUBLIC_KEY",
"publicKey": "PUBLIC_KEY",
}
1 change: 1 addition & 0 deletions phant-config.json
119 changes: 119 additions & 0 deletions pitemplog.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
- read internal Pi CPU temperature
- (OPTIONALLY) log sensor data to a phant server
"""

__author__ = 'David Crook'
__copyright__ = 'Copyright 2019'
__credits__ = []
__license__ = 'MIT'
__maintainer__ = 'David Crook'
__email__ = 'idcrook@users.noreply.github.com'
__status__ = "Development"

import json
from pprint import pprint
import signal
import ssl
import sys
from time import sleep

import requests # so can handle HTTP exceptions
from gpiozero import CPUTemperature
from phant3.Phant import Phant

# Logging sensor readings to Phant
LOGGING = True
# LOGGING = False
LOGGING_COUNT = 0

# Read in config file
with open('app_config.json') as config_file:
config = json.loads(config_file.read())
# pprint(config)
# pprint(config["temperature_range"])
# pprint(config["durations"]["logging_interval"])

# How long to wait (in seconds) between logging measurements.
LOGGING_INTERVAL = config["durations"]["logging_interval"]

if LOGGING:
# Read in Phant config file
phant_json_file = 'phant-config.json'
phant = Phant(jsonPath=phant_json_file)
print('Logging "{0}" every {1} seconds.'.format(phant.title,
LOGGING_INTERVAL))

# create an accessor object using its defaults
cpu = CPUTemperature()


def log_error(error_type='UnknownError'):
"""Record error of passed type (string)."""
global ERROR_TABLES
if error_type not in ERROR_TABLES:
ERROR_TABLES[error_type] = 1
else:
ERROR_TABLES[error_type] = ERROR_TABLES[error_type] + 1


def print_error_tables():
"""Print any recorded errors."""
global ERROR_TABLES
print(ERROR_TABLES, end=' ')
print('number of samples {}'.format(LOGGING_COUNT))
sys.stdout.flush()


def handler_stop_signals(signum, frame):
print_error_tables()
sys.exit(0)


# systemd: time_display.service: State 'stop-sigterm' timed out. Killing.
signal.signal(signal.SIGINT, handler_stop_signals)
signal.signal(signal.SIGTERM, handler_stop_signals)

print('Press Ctrl-C to quit.')
ERROR_TABLES = {}

while True:
try:
temp = cpu.temperature
print('CPU temperature: {}°C - '.format(temp), end='')
if LOGGING:
try:
phant.log(temp)
print('Wrote a row to "{0}" - '.format(phant.title), end='')
# print((phant.remaining_bytes, phant.cap))
except ValueError as errv:
print('-E- Error logging to {}'.format(phant.title))
print('-W- Is phant server down?')
print('ValueError: {}'.format(str(errv)))
log_error(error_type='ValueError')
except requests.exceptions.ConnectionError as errec:
print("Error Connecting:", errec)
print('-W- Is network down?')
log_error(error_type='ConnectionError')
except requests.exceptions.Timeout as errt:
print("Timeout Error:", errt)
log_error(error_type='Timeout')
LOGGING_COUNT = LOGGING_COUNT + 1
print('log count {0}'.format(LOGGING_COUNT))

except KeyboardInterrupt:
log_error(error_type='KeyboardInterrupt')
print_error_tables()
sys.exit(0)

except ssl.SSLError:
# we had a network issue, try again later
log_error(error_type='ssl.SSLError')
print_error_tables()

finally:
print_error_tables()
# pause here
sleep(LOGGING_INTERVAL)
1 change: 1 addition & 0 deletions python3-phant
Submodule python3-phant added at 9d6a22

0 comments on commit 4f55495

Please sign in to comment.