Find the ready-to-edit-and-then-run python program here. Copy and paste the below text into a text editor, format it as plain text and save the file as “genwatch.py”.
#!/usr/bin/python
# These are libraries used by the program.
import smtplib
from gpiozero import Button
from time import sleep
# The “gpiozero” library calls an input a “Button.” If it goes LOW,
# we assume that the input has been turned on. Note that we assign
# the “genrun” Button to GPIO 22, which is actually pin 15 on the
# 40-pin connector.
genrun = Button(22)
# Other values to try might include pin 7 for GPIO 4 (“Button(4)”),
# or pin 13 for GPIO 27 (“Button(27)”).
# These are simple “flag” variables that I use to keep from sending
# the same email over and over.
running = 1
sent1 = 0
sent2 = 0
# IMPORTANT: Change these to your needed values. You’ll need a
# valid email account for the Pi, and a valid recipient. Replace
# “pi” and “recip” below with the correct values.
msg1 = “””From:pi@yourserver.com
Subject: Generator Is RUNNING! \n
To: recip@yourserver.com\n”””
msg2 = “””From:pi@yourserver.com
Subject: Generator Is NOT Running! \n
To: recip@yourserver.com\n”””
# This subroutine takes care of actually sending the email. You
# must edit this with a valid server name; you may need to change
# the port number. Note that this will also need “pi’s” password
# to log in, and that I’m using a secure SSL/TLS connection.
def sendmsg(mstr=””):
server = smtplib.SMTP_SSL(‘mail.yourmailserver.com’,port=465)
server.ehlo()
server.login(‘pi@yourserver.com’,’password’)
server.sendmail(‘pi@yourserver.com’,’recip@yourserver.com\n’,mstr)
server.quit() # exit the connection
# The main program loop, which runs forever, or until you
# press CTRL-C in the terminal that’s running this program.
while(1):
# Check the genrun “Button” object. The “running” flag
# prevents sending the same email if it has already
# been sent.
if genrun.is_pressed:
if( running == 0 ):
running = 1
print(“Gen running.”)
if not sent1:
sent1 = 1
sent2 = 0
sendmsg( msg1 )
# Same, but check for Button “genrun” NOT being pressed —
# i.e., the generator isn’t running.
if not genrun.is_pressed:
if( running == 1 ):
running = 0
print(“Gen idle.”)
if not sent2:
sent2 = 1
sent1 = 0
sendmsg( msg2 )
# Go to sleep for 60 seconds, then run again.
sleep(60.0)
Remember to change the email addresses, password, the email server and port numbers as needed.
Once you’re done, save the file as genwatch.py, then copy it onto your Pi. In a terminal, in the same directory as that file, enter the command
“chmod +x genwatch.py”
to make the file executable. Now you can run it by entering
“./genwatch.py”
at the terminal prompt, while still in the directory containing the file. The program will continuously check the assigned pin at 1-minute intervals, sending an email if the generator’s status changes. Press CTRL-C to stop the program.