In: Computer Science
Write a Python code that when the temperature of the CPU in the raspberry pi exceeds 40 degrees Celsius you receive an email.
# coding=utf-8
import os
import smtplib
from email.mime.text import MIMEText
critical = False
high = 40
too_high = 45
# At First we have to get the current CPU-Temperature with this defined function
def getCPUtemperature():
res = os.popen('vcgencmd measure_temp').readline()
return(res.replace("temp=","").replace("'C\n",""))
# Now we convert our value into a float number
temp = float(getCPUtemperature())
# Check if the temperature is abouve 60°C (you can change this value, but it shouldn't be above 70)
if (temp > high):
if temp > too_high:
critical = True
subject = "Critical warning! The temperature is: {} shutting down!!".format(temp)
body = "Critical warning! The actual temperature is: {} \n\n Shutting down the pi!".format(temp)
else:
subject = "Warning! The temperature is: {} ".format(temp)
body = "Warning! The actual temperature is: {} ".format(temp)
# Enter your smtp Server-Connection
server = smtplib.SMTP('localhost', 25) # if your using *mail: smtp.*mail.com
server.ehlo()
server.starttls()
server.ehlo
# Login
# server.login("your email or username", "your Password")
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = "Root"
msg['To'] = "root"
# Finally send the mail
server.sendmail("root", "root", msg.as_string())
server.quit()
# Critical, shut down the pi
if critical:
os.popen('sudo halt')
# Don't print anything otherwise.
# Cron will send you an email for any command that returns "any" output (so you would get another email)
# else:
# print "Everything is working fine!"
it will send a mail as soon as it crosses 40'C
I've tweaked it a little bit to also shut down the pi in case the temp is too high (45'C in my case).
To make this as a cronjob running every 30 min do this
mkdir -p ~/scripts
vi ~/scripts/temp.py
paste the code from the script above.
Then crontab -e
and add this:
30 * * * * python ~/scripts/temp.py
close crontab editor (ctrl-x
if nano or
esc
, then :wq
if vim)
That's it