Last active
October 24, 2024 17:19
-
-
Save sigmdel/9d0fbe0c82b2ebb8d3c9fa9b72d185b0 to your computer and use it in GitHub Desktop.
Python script to forward a thermal zone temperature to Domoticz, with e-mail notification when the temperature is over a threshold.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
# coding: utf-8 | |
# Python script to read the CPU temperature and send the results to | |
# a Domoticz server. Meant to be executed by cron at regular intervals. | |
# | |
# | |
# Requires: Python 3 | |
# | |
# Version: 2.1 | |
# Date: 2024-08-20 | |
# License: 0BSD@https://spdx.org/licenses/0BSD.html | |
# Needed module here because LOG_XXX constants are used in parameters | |
from syslog import * | |
# User defined parameters ------------------------------------------------------- | |
alertTemp = 60 # Hot cpu core temperature threshold | |
cpu_zone = "/sys/class/thermal/thermal_zone1/temp" | |
cpu_temp_idx = 211 # Domoticz device index for cpu temperature sensor on vault.local | |
domoticzJson = "http://192.168.1.22:8080/json.htm?type=command¶m=udevice&idx={}&nvalue=0&svalue={}" | |
domoticzTimeout = 15 # HTTP request timeout in seconds | |
alertTitle = 'NAS Temperature Alert' | |
alertMsg = "The temperature of the NAS CPU, {}°C, is above the alert threshold {}°C" | |
verbose = 0 # 0 quiet, 1 to echo log messages with priority | |
consoleloglevel = LOG_ERR # log level for messages printed to the console | |
sysloglevel = LOG_ERR # log level for messages sent to syslog | |
logAlertLevel = LOG_ALERT # priority level for e-mail temperature alerts | |
# ------------------------------------------------------------------------------- | |
# Needed modules in addition to syslog | |
import sys | |
import os | |
from pymail import send_email | |
from urllib.request import urlopen # with python 3.x, use "from urllib2 import urlopen" with python 2.7 | |
if verbose > 0: | |
from datetime import datetime | |
# Routine to send messages to syslog and echo it to the console | |
def log(level, msg): | |
syslog(level, msg) | |
if (verbose) and (level <= consoleloglevel): | |
print(datetime.now().strftime('%Y-%m-%d %H:%M:%S ') + msg) | |
# Setup syslog | |
openlog(ident='NAS') | |
setlogmask(LOG_UPTO(sysloglevel)) | |
# HTTP Get request | |
def httpRequest(url): | |
try: | |
log(LOG_DEBUG, 'CPU: Domoticz GET request: {}'.format(url)) | |
# use context magager which takes care of closing hf | |
with urlopen(url, timeout=domoticzTimeout) as hf: | |
# get Domoticz' response and broadcast it | |
response = hf.read().decode('utf-8') | |
if ('"ERR"') in response: | |
llevel = LOG_ERR | |
else: | |
llevel = LOG_DEBUG | |
log(llevel, 'Domoticz response: {}'.format(response)) | |
except Exception as e: | |
log(LOG_ERR, 'Exception: {}'.format(e)) | |
# Read and report cpu temperature | |
with open(cpu_zone) as f: | |
cpuTemp = "{0:0.1f}".format(int(f.read())/1000.0) | |
log(LOG_DEBUG, 'CPU: temp = {}°C'.format(cpuTemp)) | |
httpRequest(domoticzJson.format(cpu_temp_idx, cpuTemp)) | |
# Raise alert if needed | |
if float(cpuTemp) > alertTemp: | |
message = alertMsg.format(cpuTemp, alertTemp) | |
log(LOG_DEBUG, "Alert, title: '{}', message: '{}'".format(alertTitle, message)) | |
log(logAlertLevel, message) | |
log(LOG_DEBUG, 'Sending email notification') | |
send_email(alertTitle, 'temperature.alert@gmail.com', message) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/bash | |
# Bash script that reads the thermal zone temperatures from the Linux | |
# /sys virtual file system. | |
# | |
# Ref: How to display CPU temperature in bash prompt? | |
# @: https://unix.stackexchange.com/questions/411115/how-to-display-cpu-temperature-in-bash-prompt | |
# | |
# Version 0.2 | |
# (c) Copyright 2024 Michel Deslierres, No rights reseved | |
# This script is in the public domain. In those jurisdictions where this may be a problem, the | |
# BSD Zero Clause License (https://spdx.org/licenses/0BSD.html) applies. | |
CEL=$'\xc2\xb0C' # UTF-8 codepoint for the degree symbol followed by C (celsius) | |
for zone in $(ls -d /sys/devices/virtual/thermal/thermal_zone*); | |
do | |
temp=$(cat $zone/temp) | |
typ=$(cat $zone/type) | |
temp=`expr $temp / 1000` | |
echo $zone: $temp$CEL $typ | |
done |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Import smtplib for the actual sending function | |
import smtplib, ssl | |
# Import the email modules we'll need | |
from email.mime.text import MIMEText | |
SRC = '***me@**host_url****' | |
SMPT = '***mail@**host_url****' | |
PORT = 465 | |
PWD = '****************' | |
def send_email(subject, dest, message): | |
print('send_email({}, {}, {})'.format(subject, dest, message)) | |
# Create the message | |
msg = MIMEText(message) | |
msg['Subject'] = subject | |
msg['From'] = SRC | |
msg['To'] = dest | |
context = ssl.create_default_context() | |
with smtplib.SMTP_SSL(SMPT, PORT, context=context) as server: | |
server.login(SRC, PWD) | |
server.sendmail(SRC, dest, msg.as_string()) | |
print('msg:', msg['Subject'], msg['From'], msg['To']) | |
# ref: https://realpython.com/python-send-email/ # |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment