Temperature monitoring script with email alerts

We have quite a bit of expensive equipment in our server room and we’ve had the A/C fail a couple times. As a result, I’ve installed a raspberry pi zero with a DS18B20 temperature sensor connected to it to monitor the temperature of the room.  If it goes above a set threshold, it will send an email to the engineers so we can log in and shut stuff down until the problem is fixed.


This project branches off from the one I did earlier on monitoring temperature with a raspberry pi and MRTG.  This too uses MRTG but I won’t get into the details of that- you can see how I set that up here.


The big piece here is the alerting logic.  You’d be surprised how fast the temp can go up in a small room with lots of gear putting out a lot of heat.  For that reason, I monitor the temperature every minute.  If the current temperature exceeds the threshold I set in the script, it fires an email and sets an alert flag to true.  The reason I did this is so we don’t get an email every minute while the temperature is above threshold.  How irritating would that be?  So another piece of logic in the script checks to see if the alert flag has been tripped.  If it has, no email is sent until the temperature comes down below the threshold.  Then an all clear email is sent and the cycle repeats itself.


I used the instructions here to set up ssmtp on the pi.  In my case, I used our comcast email relay since we have comcast so the instructions for that are a little different.  You can also use your company’s own mail relay if you have one internally that can be used to send email to external addresses.  As has been my practice lately, I’ve uploaded the code to GitHub here for you to do with as you please.


As always, if you have any constructive criticism or comments, feel free to leave them below and I’ll get back to you ASAP.


What do a Subway sandwich and a computer have in common?

original raspberry-pi-zero-_3510862b


That’s right, you can get either one of them for $5!  Introducing the newest member to the Raspberry Pi family, the Pi Zero.  As you can see by the picture above next to the deck of cards, it’s quite a bit smaller than a foot long sandwich, but that doesn’t stop it from packing quite a punch!  The tiny new SOC (System On a Chip) computer is just that- a full fledged computer capable of running Linux with a desktop environment.  Granted, it’s not the snappiest performer in that capacity but still super cool that it can pull it off!


Here are the specs (gratuitously lifted from raspberry pi’s website):

  • A Broadcom BCM2835 application processor
    • 1GHz ARM11 core (40% faster than Raspberry Pi 1)
  • 512MB of LPDDR2 SDRAM
  • A micro-SD card slot
  • A mini-HDMI socket for 1080p60 video output
  • Micro-USB sockets for data and power
  • An unpopulated 40-pin GPIO header
    • Identical pinout to Model A+/B+/2B
  • An unpopulated composite video header


So- on to the gotcha’s.  With a $5 computer, yo’re gonna to have to make some minor investments in additional hardware to make it functional.  Here’s the list of absolute must have’s to even get up and going:

  • MicroSD Card (preferably 8gb or bigger and class 10 or faster)
  • Micro USB power source capable of providing at least 1A at 5v
  • Micro USB to USB Type A Female converter
  • USB Wi-Fi or ethernet adapter (make sure it’s supported first)

You can technically get up and running with this much hardware, however you have no video out and would have to rely on pre-configuring the OS to somehow get on the network and allow SSH to get in.  Not very functional but a working minimal config once you have it set up the way you want.  Raspberry Pi has taken the Spirit Airlines approach to the Zero.  They give you only what you need to work (the Bare Fare), allowing you to decide what extras you want to pay for and which ones you skip.  In order to configure your Zero initially, you’ll need a couple more things:

  • Mini HDMI to HDMI cable (or Mini HDMI to HDMI converter with an HDMI cable coming out of it)
  • USB Hub for mouse, keyboard and wired or wireless network connectivity
  • Keyboard and Mouse

This will get you connected to a Monitor/TV that has HDMI inputs so you can see what you’re doing.  It also provides for an input method via the keyboard and mouse.  At the end of this article, I’ll post a list of some of the essential hardware, how much I paid for it and where I got it.



One of the reasons I bought one of these is it’s ability to serve as a very capable media center device.  In one of my earlier posts, I talked about something called OpenELEC.  It’s a Linux distribution that includes Kodi which is an open source home theater software package also based on Linux.  The OpenELEC package combines the Linux OS and Kodi into an interface that’s very well suited to a TV and remote control.  Best of all, it runs on the entire line of Raspbery Pi’s!  I’ll be posting soon about one of the other alternatives to OpenELEC called OSMC.  The concept is the same, however OSMC includes a full raspbian Linux OS that isn’t as hands off as OpenELEC is.  As a result, it’s much more easily configured and customized without having to learn all the in’s and out’s of the underlying OpenELEC OS components.



The reason that the Zero can pull this off is mainly due to it’s built in hardware video decoder.  The GPU (Graphics Processing Unit) has discreet hardware functions dedicated for video encoding and decoding (recording and playback).  This means that video playback such as 1080p at 60fps doesn’t rely on the processor to decode and display the video stream, slowing other operations down.  It’s all done in hardware- very similar to the Playstation 4, XBox ONE, or any other gaming platform that has dedicated graphics hardware.  All that’s left for the diminutive Zero to do is render the on-screen menus, take care of assorted housekeeping and perform other OS related stuff.


Pibow_Zero_1_of_3_1024x1024There are a number of “cases” for the Zero out on the market now.  I use the term case rather loosely because as you can see to the left, it’s mainly two layers of plastic sandwiching the Pi Zero between it.  There are also quite a few 3d designs that “makers” can download and print on their 3d printer. Others can be bought in brick and mortar stores like MicroCenter or ordered online from websites like Adafruit, Raspberry Pi’s swag store, or Pimoroni (a popular “maker” website based in the UK) to name just a few.  You don’t technically need a case, but it’s a good idea to keep shorts, static discharge or any other molestation from occurring to your sweet innocent little computer.  With the tiny form factor this device affords, you can easily slap a case on it, connect it to your living room TV and attach it to the back of your set via 2 way adhesive tape- nobody would even know it’s there!


As of this writing, I’m not aware of any MicroSD cards that are bigger than 512gb.  Granted that’s a LOT of storage but that comes at a fairly steep price- about $400 on amazon.com.  I’m sure as higher density chips come out that price will fall, but the better bet would be to cobble together some 4TB hard drives in a desktop computer and use it for network storage of your multimedia files.  This is what I’m doing and it works perfectly!  I have multiple Raspberry Pi’s throughout the house on each TV that can play back my entire collection of movies, pictures, music and any other multimedia I choose to host on my media server.



There are also a number of other things that any of the Raspberry Pi family is capable of doing, including interacting with the physical world via it’s GPIO pins.  The Zero doesn’t come out of the box with the 40pin header required to use the GPIO, however it’s easily soldered onto the board.  I have a couple Pi 2’s that have temperature sensors hooked up to them and I track the temperature via MRTG graphs.  I also hope to set up an animated Christmas light display using a SainSmart 16 Channel relay board that is controlled by the Pi turning on and off each individual circuit.  It could also be used for home automation in that regard.


I could go on and on about all the things that these little buggers can do, but this article is focused on the Zero.  Below I’ll list some of the hardware (with prices and source) that you’ll need in order to put the Zero into service.  Add it all up and you’ll have to purchase at least another $16+ worth of hardware to really get some use out of it.  Granted I went as cheap as I could find online and I didn’t factor in any shipping or tax so your total could very well be north of $20.  For that, you can almost get a Raspberry Pi B+ that has full size HDMI, built in Ethernet and 4 full size Type A USB ports as well.  But c’mon- look how small this thing is- you can hide it in a can of Altoids and have room to spare for cripes sakes!








There are a number of remote control apps that allow your phone/tablet to serve as the remote control for Kodi.  What’s really cool is that Kodi also supports the CEC (Consumer Electronics Control) standard which allows you to control some devices via the HDMI protocol.  This means that in a lot of cases, you can simply use the remote that came with your TV to navigate through Kodi without any additional hardware needed!




openelec_logo_notype_512x512I’ve been playing around with something called OpenELEC.  It’s an open source media center solution based on Linux similar to Myth TV.  The ELEC part of the name stands for Embedded Linux Entertainment Center, appropriately so.  This is the framework container that provides the OS in which the actual media center software runs.


The media software that provides the user interface and media handling ability is called kodi.  Kodi started out as a project to provide a media center environment to the XBox.  Originally in 2002 when it was first developed, it was called XBox Media Player.  In 2004, the development team decided to rename it to XBox Media Center.  Then in 2008 it was renamed to just XBMC as it had moved on from it’s roots in the Xbox.  Shortly after being renamed XBMC, support for the XBox was dropped.  In 2014, XBMC was renamed to Kodi and they had their first release called Helix.  I won’t bore you too much more on the details or history of this media center software, you can fire up your google-fu and do just as good a job as I can.


So I used to have (still do actually) a Western Digital Live TV media player.  It was highly recommended from my good friend Dusty Hudson who works for Dolby Laboratories out in sunny California.  I was looking for a set top box to bring together all of the assorted media I had stored on my file server and be able to access it via the TV interface without having to have a loud bulky computer sitting in the living room like an eyesore.  I used to rock Windows 7 Media Center and that worked pretty well overall.  Still had to have the big ugly and noisy desktop computer sitting in the living room though.  This solution was rather low on the WAF (Wife Acceptance Factor) scale but it worked ok.  Once I stared to get a ton of movies though, the interface just started to choke and became pretty much unuseable.  Back to the WDTV that replaced MCE, it seemed to work pretty well- better than Media Center in a lot of ways.  I picked one up refurbished for $60 and had it for about a year.  It started to flake out on me though- it would freeze up during playback or sometimes I had to power cycle it to get it to turn on.  After dealing with this for months I started to look around for alternatives.


raspberry_pi_logoFast forward to today. I’ve been playing around with Raspberry Pi’s (Pi 2 and B+) lately.  Then I stumbled across this page on OpenELEC.  I don’t recall exactly how I found it, but it seemed very intriguing given that there’s a build that runs on the Raspberry Pi.  At first I thought this would be a non-starter given the relatively limited processing power of the 900MHz quad core ARM Cortex-A7 CPU and 1gb of memory.   Come to find out that the Pi 2 has built in hardware video decoding for the following codecs:


  • H.264 (up to High Profile) encoded videos are supported up to 1080P using hardware video decoding. Note: Hi10P will not work.
  • MPEG-4 encoded videos are supported up to 1080P using hardware video decoding. This includes XviD and recent versions on DivX (but not the older 3.xx DivX).
  • The Raspberry Pi Foundation offers additional video codec licenses for a few dollars. At the moment you can purchase MPEG-2 and VC1, both with support up to 1080P. Read below on how to enable these.
  • MJPEG, VP6, VP8 and OGG Theora are supported as GPU accelerated software decoders. These are limited to DVD resolutions.
  • Codecs without gpu support like DivX 3, msmpeg and sorenson spark will be decoded by dvdplayer on the ARM. Should work for SD resolutions.
  • DVD ISOs with menus should work fine (using dvdplayer).
  • Software DTS audio decode works well in recent builds. TrueHD audio is CPU intensive and may require overclocking.


Quite the little powerhouse for less than $30!  So I loaded OpenELEC on my MicroSD card, threw it in and booted it.  BAM!! right out of the box, everything booted up fine, no errors, no video or audio issues, networking, all good!  A far stretch from my experiences with Myth TV years ago.  I’ve only been running it a few days but so far there are a LOT of features and they’re extremely customizable.  There are builds for windows as well if you want to try it out without actually installing it on a Pi.  I give it a big thumbs up so far!



IOT – temperature sensor project

So I’ve been experimenting with a Raspberry Pi in hopes of eventually creating a project to possibly make one of those really cool animated christmas light displays that synchronize with music.  That’s definitely something for the future but I’d still like to do it.


What I was able to do was access a thermometer sensor connected to the GPIO pins on the pi.  I had a heck of a time even getting some LED’s to turn on and off until I switched to a different unit.  This makes me think the original one is possibly defective or I may have fried the GPIO board. I bought a B+ which is the precursor to the Raspberry Pi 2.  It has the same basic configuration but less powerful than the 2.  It has 256mb of memory and slower CPU but more than adequate for my needs.  I connected a DS18B20 waterproof temperature sensor and was having trouble reading from it until I realized that you have to use a specific GPIO pin.


This particular sensor uses a protocol called 1wire.  It has to be enabled in the kernel and then rebooted to load the drivers.  Once you do that, you should see a directory in /sys/bus/w1/devices/ that starts with 28-XXXXXXXXXXXX.  The X’s represent a hex value that will be different for each sensor.  Then you can cd into the directory and cat the contents of w1_slave.  You should see something like this:


root@garagepi:/sys/bus/w1/devices/28-000006b62cb7# cat w1_slave
3a 01 4b 46 7f ff 06 10 42 : crc=42 YES
3a 01 4b 46 7f ff 06 10 42 t=19625


The number at the end of the second line is the temperature in Celcius.  You have to divide that number by 1000 to get the actual reading (basically just move the decimal point 3 positions to the left):

19625/1000 = 19.625 c

The formula to convert from Celsius to Fahrenheit is T = {temp in Celsius} x 9 / 5 + 32. So here’s the reading in Fahrenheit:

19625/1000 = 19.625 C
19.625 x 9 = 176.625
176.625 / 5 = 35.325
35.325 + 32 = 67.325 F

67 degrees Fahrenheit is the current temperature in my garage.  Then I wrote a quick script to poll the sensor and do the math to convert to Fahrenheit and it spits out just the temperature value:


import os
import glob
import time

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'

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

def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        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
        return temp_f

while True:

It was a python script I found that uses the 1wire protocol to read the contents of the sensor. I modified it to spit out just the one reading. I then configured MRTG to graph out the temperature historically using the following mrtg.cfg:

# Multi Router Traffic Grapher -- Sample Configuration File
# This file is for use with mrtg-2.5.4c

# Global configuration
WorkDir: /var/www/mrtg/

Timezone[temp]: America/Chicago
Target[temp]: `/usr/local/bin/get-temp.py 0`
MaxBytes[temp]: 99
Title[temp]: Garage Temperature
PageTop[temp]: Garage Temperature
ShortLegend[temp]: F 
YLegend[temp]: Farenheit 
Options[temp]: growright,nopercent, nobanner, noinfo, gauge 
Unscaled[temp]: ymd

I’m not going to go into how to set up MRTG, you’ll have to google that or get help from someone if you’re having trouble. Regardless, here’s the output I’ve gotten so far:


Garage Temperature

The statistics were last updated Saturday, 10 October 2015 at 12:35 America/Chicago

`Daily’ Graph (5 Minute Average)


Max Average Current
In 69.0 F 63.0 F 69.0 F
Out 0.0 F 0.0 F 0.0 F

`Weekly’ Graph (30 Minute Average)


Max Average Current
In 68.0 F 61.0 F 65.0 F
Out 0.0 F 0.0 F 0.0 F

`Monthly’ Graph (2 Hour Average)


Max Average Current
In 66.0 F 56.0 F 60.0 F
Out 0.0 F 0.0 F 0.0 F

`Yearly’ Graph (1 Day Average)


Max Average Current
In 0.0 F 0.0 F 0.0 F
Out 0.0 F 0.0 F 0.0 F
GREEN ### Incoming Traffic in Bytes per Second
BLUE ### Outgoing Traffic in Bytes per Second

You can see that MRTG normalizes data as it averages farther out in time by observing the max high and low are different in the year chart than the daily chart.  It’s averaging out the values of the previous level of data.  Once you get to the yearly graph- it’s taking the average of an entire day’s high temperatures to get the high temperature for the year.  I may have to adjust how I tell MRTG what it’s reading so it’s more accurate.  I’d like to see the day’s high, low and current reading.  For now I’m content with what I have so far.


I hope to expand this to gathering humidity as well- I have another sensor that measures both humidity and temp but I haven’t gotten that one working quite yet.  Anyway- I hope you find this interesting and possibly useful in setting up your kit.  Good luck!

Raspbian findings so far

It’s been a couple weeks of playing with the Pi 2 and it’s defacto OS- raspbian.  My installation is based on the debian wheezy build which is also known as Debian 7.  I’m content for now, but would really like to find a RedHat based distribution that works as I’m much more familiar with that.  I tried Pidora but I couldn’t even get a boot screen with that image. I’m also looking into upgrading raspbian to Jessie (aka Debian 8).


Anyway- on to the findings.  So I had a TON of issues with something that really shouldn’t have been an issue.  I was trying to configure a static IP on my eth0 interface and for some ungodly reason it just wouldn’t take across reboots.  I finally wound up configuring the MAC address of the Pi’s NIC in my dhcp server and set the interface to DHCP.  It will always lease the same address this way but it’s a kludge and I’d like to get it working properly.  I did the same for the Ralink wifi usb adapter for the time being.  You’d think that the following config would git ‘r done but for some reason it didn’t:



auto lo
iface lo inet loopback

auto eth0
allow-hotplug eth0
iface eth0 inet static


I don’t see any evidence that NetworkManager is installed in the Raspbian image I’m using so I don’t think it’s that.  If anyone has had issues like this- post a comment and let me know what you did to fix it.


The second thing I’ve been running into is also related to networking.  My Ralink adapter for some reason likes to disconnect every so often:

Jun 8 00:05:10 mypi kernel: [425582.545653] usb 1-1.4: USB disconnect, device number 6
Jun 8 00:05:11 mypi kernel: [425583.546048] usb 1-1.4: new high-speed USB device number 7 using dwc_otg
Jun 8 00:05:11 mypi kernel: [425583.663302] usb 1-1.4: New USB device found, idVendor=148f, idProduct=5370
Jun 8 00:05:11 mypi kernel: [425583.663320] usb 1-1.4: New USB device strings: Mfr=1, Product=2, SerialNumber=3
Jun 8 00:05:11 mypi kernel: [425583.663332] usb 1-1.4: Product: 802.11 n WLAN
Jun 8 00:05:11 mypi kernel: [425583.663343] usb 1-1.4: Manufacturer: Ralink
Jun 8 00:05:11 mypi kernel: [425583.663354] usb 1-1.4: SerialNumber: 1.0
Jun 8 00:05:11 mypi kernel: [425583.756056] usb 1-1.4: reset high-speed USB device number 7 using dwc_otg


When it does this, it drops from the wifi network and doesn’t come back unless I unplug the adapter and plug it back in, or if I reboot the Pi.  To get around this, I’ve done a few things:

  • set wireless-power to off in /etc/network/interfaces
  • created a script that checks every minute to see if wlan0 has an IP address.  If not, it downs and ups the interface.

Here’s my current interfaces file:

auto lo
iface lo inet loopback

#auto eth0
#allow-hotplug eth0
#iface eth0 inet dhcp

auto wlan0
allow-hotplug wlan0
iface wlan0 inet dhcp
wpa-conf /etc/wpa.conf
wireless-power off


Here’s the script I put into cron:


datestamp=`/bin/date '+%D %T'`
result=`/sbin/ifconfig $1 | /bin/grep "inet addr:"`

if [ -z $1 ]
        echo "usage: $0 {interface}"

if [ ! -z "$result" ]
        echo "=== [$datestamp] ===" >> $logfile
        echo "Found an IP on [$1].  No action taken." >> $logfile
        echo "===================================================================" >> $logfile
        echo "=== [$datestamp] ===" >> $logfile
        echo "No IP on interface [$1].  Restarting interface [$1]." >> $logfile
        echo >> $logfile
        echo "Stopping $1." >> $logfile
        /sbin/ifdown $1 &>> $logfile
        echo  >> $logfile
        echo "Starting $1." >> $logfile
        /sbin/ifup $1 &>> $logfile
        echo "===================================================================" >> $logfile


And here’s the crontab entry I used (root crontab):

*/1 * * * * /usr/local/bin/check-wifi.sh wlan0


The script is a bit verbose but I used it to debug the connection so I want to know what’s going on. I’m hoping this will work cause I really like being able to stick this thing anywhere in range of the wifi signal where I can provide power.

Raspberry Pi 2B has arrived!

raspberry_pi_logoSo I finally decided to jump into the world of makers. I got me a Raspberry Pi 2 model B!  I also acquired a 16 port relay board, a 2.4″ TFT touchscreen and some jumper cables. I’m working my way around Debian linux again so have to re-remember all the old commands and file locations (hello ubuntu- I guess you were good for something other than playing around after all). I tried to find a good RedHat distribution that would run on the Pi but Pidora wouldn’t boot out of the box for me and I can’t seem to find a Fidora image to try. Regardless, it seems that most Pi users stick with the very popular debian based Raspian distro, and since I’m a noob in this area I figure it would give me the best chance of finding tutorials based on the OS I’m running.

First off- the specs. The Pi 2 model B is based on a 900MHz quad-core ARM Cortex-A7 CPU (BCM2836) with 1gb of onboard memory. It’s supposedly 6 times faster than the previous model B+ which employed the 700Mhz BCM2835 processor.  It has:

  • 4 USB ports
  • 40 GPIO pins
  • Full HDMI port
  • 10/100 Ethernet port
  • Combined 3.5mm audio jack and composite video
  • Camera interface (CSI)
  • Display interface (DSI)
  • Micro SD card slot
  • VideoCore IV 3D graphics core

It’s still a 32bit OS/CPU but is very capable of basic desktop functions including web browsing and even video gaming (raspbian ships with a Pi version of Minecraft that actually performs pretty damn good).  The coolest part is the size- it’s about as big as a deck of cards!



I’m hoping to educate myself on the 40 pin GPIO interface that allows you to control external devices (like the 16 relay switchboard I got) to do some cool home automation.  There’s even software that allows you to do the synchronized christmas light shows.  So far, I have the OS set up to grab a fixed IP address from my router via DHCP so I can ssh to it.  Gonna try to get the display working first then we’ll see what’s next.