cat << 'EOF' | tee /home/openhabian/USVcontrol.py
#! /usr/bin/python
# -*- coding: UTF-8 -*-
import smtplib
from email.mime.text import MIMEText
import RPi.GPIO as GPIO
import time
import os
def send_msg(title):
SERVER = 'smtp.gmail.com'
PORT = 587
EMAIL = 'user@gmail.com'
PASSWORT = 'xxxxxx'
EMPFAENGER = ['user@gmail.com' , 'user2@gmail.com']
SUBJECT = title
BODY = """
Statusmeldung von OpenHabian, siehe Betreff |
"""
try: # it can easily happen that the network is also down because of the power failure, so we need to catch that error
session = smtplib.SMTP(SERVER, PORT)
session.set_debuglevel(1)
session.ehlo()
session.starttls()
session.ehlo
session.login(EMAIL, PASSWORT)
msg = MIMEText(BODY, 'html')
msg['Subject'] = SUBJECT
msg['From'] = EMAIL
msg['To'] = ", ".join(EMPFAENGER)
session.sendmail(EMAIL, EMPFAENGER, msg.as_string())
session.quit()
except:
print ("SMTP- Fehler - keine Nachricht gesendet:",title)
GPIO.setmode(GPIO.BCM)
# Hier den entsprechden GPIO-PIN auswaehlen
GPIO_TPIN = 24
time.sleep(10) # give the network some time to react at system startup
print ("Sicheres Herunterfahren bei Stromausfall (CTRL-C zum Schliessen)")
# Set pin as input
GPIO.setup(GPIO_TPIN,GPIO.IN,pull_up_down=GPIO.PUD_DOWN)
Current_State = 0
Previous_State = 0
try:
print ("Warte auf Initialisierung der Spannungsversorgung...")
while GPIO.input(GPIO_TPIN)==1:
Current_State = 0
print ("Bereit")
send_msg('OpenHabian USV Kontrolle aktiv')
while True :
Current_State = GPIO.input(GPIO_TPIN)
if Current_State==1 and Previous_State==0:
print ("Spannungsversorgung ausgefallen!")
Previous_State=1
send_msg('OpenHabian STROMAUSFALL!')
os.system("sudo shutdown -h now")
elif Current_State==0 and Previous_State==1:
send_msg('OpenHabian Spannungsversorgung ist wieder zurück!')
print ("Spannungsversorgung ist wieder zurück!")
Previous_State=0
time.sleep(1)
except KeyboardInterrupt:
print ("Quit")
GPIO.cleanup()
EOF
cat << 'EOF' | sudo tee /etc/systemd/system/USVcontrol.service
[Unit]
Description=Shutdown and alert at USV Power loss
Wants=network-online.target
[Service]
Type=simple
ExecStart=/usr/bin/python /home/openhabian/USVcontrol.py
Restart=on-failure
[Install]
WantedBy=default.target
EOF
cat << 'EOF'
As next a editor will open to allow you to adjust your personal Email data
To write the changes, press CTL+o, to exit the editor use CTL+x
EOF
read -p "Press enter to continue"
nano /home/openhabian/USVcontrol.py
sudo systemctl enable USVcontrol
sudo systemctl start USVcontrol
echo "Finished - have fun :-)"