Get High Temp Alerts via Raspberry Pi

Get High Temp Alerts via Raspberry Pi
Photo by Vishnu Mohanan / Unsplash

Recently we had some electrical work done on the NOC. The Air Conditioning had to be disconnected for a few hours, and we watched the temperature in our Server room slowly creep up. It got us thinking; Is there an easy (and cheap) way for us to get alerts about high ambient temperatures? Well, since we already had a Raspberry Pi (running an NTP server synced via GPS) the answer is yes. It was $9.

I'm going to assume you have a Raspberry Pi lying around, so first thing's first; You need a temperature probe. Searching Amazon for "Raspberry Pi Temperature Sensor" brings up thousands of options. Pretty much any of them will work. Ours looks like this:

There are three wires here, you're going to first check the pinout for your model of Pi then connect VCC to a +5v pin, GND to a Ground pin, and DAT to one of the GPIO pins (Default is GPIO 4)

Now we need to edit /boot/config.txt and add a single line:
dtoverlay=w1-gpio,gpiopin=4
Replace 4 with whatever GPIO pin you chose.

Make sure you have Python installed (sudo apt install python3)

Now copy the following code, and save it wherever convenient, with a .py extension.
For example, /temp_sensor.py

import os
import glob
import time
import smtplib
import ssl

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'

# Configure your EMail server information here.
port = 465  # For SSL
smtp_server = "smtp.gmail.com"
sender_email = "no-reply@example.org"  # Enter your address
receiver_email = "notifications@example.org"  # Enter receiver address
password = "PUTYOURPASSWORDHERE"


def read_temp_raw():
    f = open(device_file, 'r')
    lines = f.readlines()
    f.close()
    return lines

def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000.0
        temp_f = temp_c * 9.0 / 5.0 + 32.0
        # Change this line to return temp_c if you prefer celsius
        return temp_f

def sendmail(temp):
    message = "Subject: Temperature Alert: " + str(temp)
    print(message)  
    context = ssl.create_default_context()
    with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
        server.login(sender_email, password)
        server.sendmail(sender_email, receiver_email, message)


# Buffer_Base is the minimum amount of time, in seconds, between alerts.
# This is so you don't get spammed with emails every second.
buffer_base = 900
buffer = buffer_base
# This is the temperature at which Emails will be sent.
alarm_temp = 75

while True:
    current_temp = read_temp()
    print(current_temp)     
    time.sleep(1)
    if (buffer < buffer_base):
        buffer = buffer + 1
    if (current_temp >= alarm_temp) and (buffer >= buffer_base):
        sendmail(current_temp)
        buffer = 0

Read through the comments in the code, replace the bits that need replacing. This includes the email server settings, minimum time between emails, and the temp at which the alarm is triggered. If using GMail with 2FA enabled (and it had better be!) you'll want to create an app password and use that (remove the spaces).

Remember, this password is stored in plaintext, so make sure you use a dedicated account to send and do not give it any special permissions or access to anything.

Next up we'll create a systemd service to run this script in the background.
Edit /etc/systemd/system/temp-monitor.service and paste the following:
(Make sure to change /temp_sensor.py on line 8 to the location of your script.

[Unit]
Description=Temperature Monitor Alert Service
After=multi-user.target

[Service]
Type=simple
Restart=always
ExecStart=/usr/bin/python3 /temp_sensor.py

[Install]
WantedBy=multi-user.target

Save that, then run:

sudo systemctl enable temp-monitor.service && sudo reboot

Now after your Pi reboots, any time the temperature creeps above alarm_temp, you'll get an email. How cool is that?