Raspberry Pi 5 Monitoring code

#!/usr/bin/env python
#!/usr/bin/env python

import stat
import time
import datetime
import os
import RPi.GPIO as GPIO
import subprocess

from time import sleep
from subprocess import *
from smtplib import SMTP
#import date2time

#from datetime
#from time import sleep, strftime

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

GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
GPIO.setup(23, GPIO.IN)
GPIO.setup(24, GPIO.IN)
GPIO.setup(25, GPIO.IN)

LightStatus=False
LightTime=datetime.datetime.now()

CheckTimeStamp=datetime.datetime.now()

debug = True

#############################################################################################
def FlashGreen():
    for x in range(0, 3):
        GPIO.output(18, False)
        sleep(0.2)
        GPIO.output(18, True)
        sleep(0.2)
#############################################################################################
def pdsshutdown():
    FlashGreen()
    print("Shutting Down")
    os.system('sudo init 0')
    sleep(100)

#############################################################################################
def pdsreboot():
    FlashGreen()
    print ("Reboot")
    os.system('sudo reboot')
    sleep(100)

#############################################################################################
def SendStartEmail(Reason):
    cmd = "ip addr show eth0 | grep inet | awk '{print $2}' | cut -d/ -f1"
    ipaddr = run_cmd(cmd)

    pdstemp=pdstemprature('28-00000475129c')
    CPUT=getCPUtemperature()
    debuglevel = 0

    DiskUsage = subprocess.check_output(["df", "-h"]);

    smtp = SMTP()
    smtp.set_debuglevel(debuglevel)
    smtp.connect('mail.com', 26)
    smtp.login('pi@mail.com', 'password')

    from_addr = "Pi <pi@mail.com>"
    to_addr = "frompi@mail.com"

    date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" )
    subj = "Pi 5 " + Reason + " " + ipaddr + "    @ " + date +  "  CPUT-" + str(CPUT) + "  Temp - " + str(pdstemp)

    message_text = "Raspberry Pi 5 " + Reason + " "  + date  + " \nCPUT-" + str(CPUT) + "\nTemp - " + str(pdstemp)
    message_text = message_text + "\n\n" + DiskUsage

    msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( from_addr, to_addr, subj, date, message_text )

    print("Sending Email")
    smtp.sendmail(from_addr, to_addr, msg)
    smtp.quit()

#############################################################################################
def run_cmd(cmd):
        p = Popen(cmd, shell=True, stdout=PIPE)
        output = p.communicate()[0]
        return output
#############################################################################################

#####################################################################

def getCPUtemperature():
    if debug:
        print("Reading CPU Temp")
    res = os.popen('vcgencmd measure_temp').readline()
    tempCPUT=float((res.replace("temp=","").replace("'C\n","")))
    return (tempCPUT)

#####################################################################

##################################################################

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

def read_temp(device_file):
        lines = read_temp_raw(device_file)
        while lines[0].strip()[-3:] != 'YES':
                time.sleep(0.2)
                lines = read_temp_raw(device_file)
        equals_pos = lines[1].find('t=')
        if equals_pos != -1:
                temp_string = lines[1][equals_pos+2:]
                temp_c = float(temp_string) / 1000.0
                return temp_c

def pdstemprature(TempDevice):
    if debug:
        print ("Reading temp "+ str(TempDevice))
    base_dir = '/sys/bus/w1/devices/'
    device_folder = base_dir + TempDevice
    device_file = device_folder + '/w1_slave'
    if(os.path.exists(device_file)):
        if debug:
            print ("Reading temp exists "+ str(TempDevice))
        Temperature = read_temp(device_file)
    else:
        Temperature = 0
    return Temperature

####################################################################

SendStartEmail("Startup")

while True:
    if (LightTime < datetime.datetime.now()):
        if LightStatus:
            LightStatus=False
            GPIO.output(18, LightStatus)
            LightTime=datetime.datetime.now() + datetime.timedelta(seconds=1.8)
        else:
            LightStatus=True
            GPIO.output(18, LightStatus)
            LightTime=datetime.datetime.now() + datetime.timedelta(seconds=0.2)

    if (GPIO.input(23) == False ):
        pdsreboot()
    if (GPIO.input(24) == False ):
        pdsshutdown()
    if (GPIO.input(25) == False ):
        SendStartEmail("On Request")

    sleep(0.2);

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>