Main Weather Code – Master6.py


#!/usr/bin/python

from PDS_Adafruit_LCDPlate import Adafruit_CharLCDPlate
from subprocess import *
from time import sleep, strftime
from datetime import datetime
from PDS_Relay import *
from PDS_LEDs import *
from PDS_GetWeather import *
from PDS_Database_Connect import * 

import subprocess
import re
import sys
import time
import datetime
import os
import glob
import RPi.GPIO as GPIO, time, os
import gspread
import os.path
import MySQLdb
import stat
import smbus
import getopt

debug = True

os.system('clear') 
print "Started"

print("File is seconds old - " + str(time.time() - os.stat("/usr/share/adafruit/webide/repositories/my-pi-projects/pds/Master6.py")[stat.ST_MTIME]))

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

GPIO.setmode(GPIO.BCM)


lcd = Adafruit_CharLCDPlate(busnum=0)
NextUploadTime = datetime.datetime.now()
elapsed_time = 0

Humidity = []
Pressure = []
LightLevel = []
Temperature = []
CPUT = 0

Switch = []

Relay = []

BackroundLightStatus=True
GetWetherLoopFailCount=0

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

def main():
    global NextUploadTime
    global elapsed_time
    global NextuploadCountdown
    
    PDSReset()
    initialisevariables()
    
    lcd.backlight(lcd.ON)
    dispip()
    
    while (True):
        if debug:
            print ("############### time " + str(datetime.datetime.now()))
        
        if lcd.buttonPressed(lcd.SELECT):
            break
        
        start_time = time.time()
        
        getWeather()
        PDSLogic()
        
        f = open('/home/pi/pds/WeatherTimeStamp', 'w')
        f.write("File is " + str(datetime.datetime.now()) + " seconds old")
        f.close()
    
        elapsed_time = time.time() - start_time
    
        if (NextUploadTime < datetime.datetime.now()):
            NextUploadTime =  InsertToDB(LightLevel, Humidity, Pressure, Temperature, CPUT, Switch, Relay)
    
        NextuploadCountdown = NextUploadTime - datetime.datetime.now()      
        NextuploadCountdown = CountdownMinSec(NextuploadCountdown)
    
        DisplayWeather()
        
        SleepOrWaitForButton(610)
        
        if lcd.buttonPressed(lcd.SELECT):
            break
    
    PDSReset()
    
    print "finished"
    
#############################################################################################
#############################################################################################
def initialisevariables():
    global Humidity, Pressure, LightLevel, Temperature, CPUT, Switch, Relay
    
    Humidity.append(0)
    Humidity.append(0)
    
    Pressure.append(0)
    
    LightLevel.append(0)
    LightLevel.append(0)
    
    Temperature.append(0)
    Temperature.append(0)
    Temperature.append(0)
    Temperature.append(0)
    Temperature.append(0)
    Temperature.append(0)

    CPUT = 0
    
    Switch.append(0)
    Switch.append(0)
    Switch.append(0)
    Switch.append(0)
    
    Relay.append(0)
    Relay.append(0)
    Relay.append(0)
    Relay.append(0)

#############################################################################################
def dispip():
    cmd = "ip addr show wlan0 | grep inet | awk '{print $2}' | cut -d/ -f1"
    lcd.begin(16,1)
    ipaddr = run_cmd(cmd)
    lcd.message(datetime.datetime.now().strftime('%b %d %H:%M:%S\n'))
    lcd.message('IP %s' % ( ipaddr ) )
    sleep(5)

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

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

def CountdownMinSec(TimeDelataPass):
    seconds = TimeDelataPass.seconds
    minutes = seconds / 60
    seconds %= 60
    if (seconds < 10):
        seconds='0'+str(seconds)
    return str(minutes) + ':' + str(seconds)

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

def trunc(f, n):
    '''Truncates/pads a float f to n decimal places without rounding'''
    slen = len('%.*f' % (n, f))
    return str(f)[:slen]
    
####################################################################

def SleepOrWaitForButton(TimeInSeconds):
    global Relay
    
    LightStatus=False
    LightTime=datetime.datetime.now()
    WaitTillTime = datetime.datetime.now() + datetime.timedelta(seconds=TimeInSeconds)
    if debug:
        print ("Sleeping till " + str(WaitTillTime))
        
    while (WaitTillTime > datetime.datetime.now()):
        if (LightTime < datetime.datetime.now()):
            if LightStatus:
                LightStatus=False
                OutputGreenLED(1, LightStatus)
                LightTime=datetime.datetime.now() + datetime.timedelta(seconds=1.8)
            else:
                LightStatus=True    
                OutputGreenLED(1, LightStatus)
                LightTime=datetime.datetime.now() + datetime.timedelta(seconds=0.1)

        if lcd.buttonPressed(lcd.UP):
            print("Up Button Presses")
            OutputGreenLED(1, False)
            break
        
        if lcd.buttonPressed(lcd.DOWN):
            print("Down Button Presses")
            print ("Fan On")
            Switch_On(1)
            Relay[0] = 1
            DisplayWeather()
            sleep(2)

        if lcd.buttonPressed(lcd.RIGHT):
            print("RIGHT Button Presses")
            ChangeBackroundLightStatus()

        if lcd.buttonPressed(lcd.LEFT):
            print("LEFT Button Presses")
            sleep(2)
            if(Relay[0] < 2):
                Relay[0] = 2
                print ("Fan Disabled")
                Switch_Off(1)
            elif(Relay[0] == 2):
                Relay[0] = 0
                print ("Fan Reset")
                Switch_Off(1)
            DisplayWeather()

        if lcd.buttonPressed(lcd.SELECT):
            print("Select Button Pressed")    
            break
    
        sleep(0.2)
    
    OutputGreenLED(1, False)
 
###################################################################

def ChangeBackroundLightStatus():
    global BackroundLightStatus
    if BackroundLightStatus:
        BackroundLightStatus=False
        lcd.backlight(lcd.OFF)
    else:
        BackroundLightStatus=True
        lcd.backlight(lcd.ON)
    sleep(1)

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

def PDSReset():
    InitialiseRelays()
    ResetLEDs()

    lcd.backlight(lcd.OFF)
    lcd.clear()
    
#######################################################################
def InsertToDB(LightLevel, Humidity, Pressure, Temperature, CPUT, Switch, Relay):
    if debug:
        print ("Starting upload to MySQL....")
    OutputGreenLED(2, True)

    #conn = MySQLdb.connect(host= "localhost",
    #              user="weatheruser",
    #              passwd="Harrison71",
    #              db="Weather")
    
    pdssqlcommand="INSERT INTO `Weather`.`WeatherLog` (`WID`, `LogTime`, `Light`, `Humidity`, `Pressure`, " + \
                    "`T1`, `T2`, `T3`, `T4`, `T5`, `T6`, `CPUT`, `Plug1`) " + \
                    "VALUES (NULL, CURRENT_TIMESTAMP, '"+str(LightLevel[1])+"', '"+str(Humidity[0])+"', '"+str(Pressure[0])+"', '"+str(Temperature[0])+ \
                    "', '"+str(Temperature[1])+"', '"+str(Temperature[2])+"', '"+str(Temperature[3])+"', '"+str(Temperature[4])+"', '"+str(Temperature[5])+ \
                    "', '"+str(CPUT)+"', '" + str(Relay[0]) + "');"

    if debug:
        print (pdssqlcommand)

    try:
        x = conn.cursor()
        x.execute(pdssqlcommand)
        conn.commit()
    except:
       print("SQL Upload failed")
       print(pdssqlcommand)
       conn.rollback()
    
    NextUploadTime = datetime.datetime.now() + datetime.timedelta(minutes=10)
    if debug:
        print ("                Next upload time = " + str(NextUploadTime))

    if debug:
        print ("Finished uploading to  MySQL......")
    
    x.close()
    
    OutputGreenLED(2, False)
    
    return (NextUploadTime)
    
#####################################################################
def getCPUtemperature():
    res = os.popen('vcgencmd measure_temp').readline()
    tempCPUT=float((res.replace("temp=","").replace("'C\n","")))
    return (tempCPUT)
#####################################################################
def getWeather():
    
    global Humidity, Pressure, LightLevel, Temperature, CPUT, Switch, Relay, GetWetherLoopFailCount

    OutputRedLED(0, False)
    
    OutputRedLED(1, True)

    Temperature[0] = pdstemprature('28-000003ebb9fd')
    
    OutputRedLED(2, True)
    OutputRedLED(1, False)    
    Temperature[1] = pdstemprature('28-000003e6cf37')
    
    OutputRedLED(3, True)
    OutputRedLED(2, False)  
    Temperature[2] = pdstemprature('28-000003ebb63d')
    
    OutputRedLED(4, True)
    OutputRedLED(3, False)  
    Temperature[3] = pdstemprature('28-000003ebbbc1')
    
    OutputRedLED(5, True)
    OutputRedLED(4, False)  
    Temperature[4] = pdstemprature('28-000004759c3e')

    OutputRedLED(6, True)
    OutputRedLED(5, False)  
    Temperature[5] = pdstemprature('28-00000474a26b')
    
    OutputRedLED(7, True)
    OutputRedLED(6, False) 
    Humidity[0] = pdshumidity(0)
    Pressure[0] = pdsPressure(0)
    
    OutputRedLED(8, True)
    OutputRedLED(7, False) 
    LightLevel[0] = pdslight(23)
    LightLevel[1] = pdslight(18)

    OutputRedLED(0, False)    
    
    CPUT=getCPUtemperature()

    if(Temperature[0]==0 or Temperature[1]==0 or Temperature[2]==0 or Temperature[3]==0):
        OutputGreenLED(3, True)
        lcd.clear()
        LCDMessage=datetime.datetime.now().strftime('%b %d %H:%M:%S\n')
        LCDMessage=LCDMessage + 'Get Weather Failed\nloop count '+ str(GetWetherLoopFailCount)
        lcd.message(LCDMessage)
        print('Get Weather Failed - loop count \n'+ str(GetWetherLoopFailCount))
        GetWetherLoopFailCount=GetWetherLoopFailCount + 1
        sleep(5)
        getWeather()
    else:
        GetWetherLoopFailCount=0
        OutputGreenLED(3, False)

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

def DisplayWeather():
    global Humidity, Pressure, LightLevel, Temperature, CPUT, Switch, Relay
    global NextuploadCountdown
    global elapsed_time

    #LCDMessage = LCDMessage + 'In-' + str(LightLevel[0]) + ' Out-' + str(LightLevel[1])  + '\n'
    #LCDMessage = str(datetime.datetime.now().strftime('%H:%M')) + '     ' + str(NextuploadCountdown)  + '\n'
    
    LCDMessage = str(datetime.datetime.now().strftime('%H:%M')) + '     ' + str(NextuploadCountdown)  + '  R' + str(Relay[0]) +'\n'
    LCDMessage = LCDMessage + 'H-' + str(trunc(Humidity[0],0)) + ' P-' + str(trunc(Pressure[0],0)) + ' Out-' + str(LightLevel[1])  + '\n'
    LCDMessage = LCDMessage + str(trunc(Temperature[0],1)) + ' ' + str(trunc(Temperature[1],1)) + ' ' + str(trunc(Temperature[2],1)) + ' ' + str(trunc(Temperature[3],1)) + '\n'
    LCDMessage = LCDMessage + str(trunc(Temperature[4],1)) + ' ' + str(trunc(Temperature[5],1)) + ' ' + str(trunc(CPUT,1)) + '\n'

    if debug:
        print(LCDMessage)
        
    lcd.clear()
    lcd.message(LCDMessage)
    
    print ('Light Inside=' + str(LightLevel[0]) + ' Light Ouside=' + str(LightLevel[1]) + ' Humidity=' + str(trunc(Humidity[0],0)) + \
        ' Pressure=' + trunc(Pressure[0],1))
    print ('          T1=' + str(round(Temperature[0],1)) +  ' T2=' + str(round(Temperature[1],1)) + ' T3=' + str(round(Temperature[2],1)) + ' T4=' + str(round(Temperature[3],1)))

    print ('          T5=' + str(round(Temperature[4],1)) +  ' T6=' + str(round(Temperature[5],1))+ ' CPUt='+ str(CPUT))
    print ('             Relay1=' + str(Relay[0]))
    print ('                     ElapsedTime=' + str(trunc(elapsed_time,1)) + ' NextUploadin=' + str(NextuploadCountdown))
        

#####################################################################
def PDSLogic():
    global Relay
    
    #Temp 0 = inside
    #Temp 1 = outside
    
    print("")
    print("Logic - T1-" + str(Temperature[0])+ " T2-" + str(Temperature[1]) + " Relay1-" + str(Relay[0]))
    
    if ((Temperature[0] > 22) and (Temperature[1] < (Temperature[0] - 2)) and (Relay[0] == 0)):
        print ("Fan On")
        Switch_On(1)
        Relay[0] = 1
    elif ((Temperature[0] < 20) and (Relay[0] == 1)):
        print ("Fan Off")
        Switch_Off(1)
        Relay[0] = 0
    elif (((Temperature[1] - 2) > Temperature[0]) and (Relay[0] == 1)):
        print ("Fan Off")
        Switch_Off(1)
        Relay[0] = 0
    else: 
        print ("No Fan Action")
        if (Relay[0] == 1):
            print("         Fan is on")
        else:
            print("         Fan is off")
    print("")    
#####################################################################
############################################################### code

if __name__ == "__main__":
   main()






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>