#!/usr/bin/env python3
import paho.mqtt.client as mqtt
import os
import sys
client = mqtt.Client()
import time
from time import sleep
import tkinter as tk
from tkinter import *
t = time.time()
set_time_string = time.strftime("%H:%M:%S",time.localtime(t))
Next = 0
pos = 0
fname = os.path.basename(sys.argv[0])
#print("fname=",fname)
fpath = os.getcwd()
#print("fpath=",fpath)
stat = os.stat(fpath)
try:
createdDate= os.stat(fpath).st_birthtime
except AttributeError:
# We're probably on Linux. No easy way to get creation dates here,
# so we'll settle for when its content was last modified.
createdDate= stat.st_mtime
#print("createdDate=",createdDate)
datestring = time.strftime("%d -%H:%M:%S",time.localtime(createdDate))
#print("datestring=",datestring)
#
#print('getcwd: ', os.getcwd())
#print('__file__: ', __file__)
# Path to the file/directory
path = fpath
# Both the variables would contain time
# elapsed since EPOCH in float
ti_c = os.path.getctime(path)
ti_m = os.path.getmtime(path)
# Converting the time in seconds to a timestamp
c_ti = time.ctime(ti_c)
m_ti = time.ctime(ti_m)
#print(f"The file located at the path {path} \
#was created at {c_ti} and was "
# f"last modified at {m_ti}")
import datetime
import os
import threading
rpi=False
try:
import RPi.GPIO as GPIO
rpi=True
except:
rpi=False
today = datetime.datetime.today()
#import csv
#import context
import paho.mqtt.client as mqtt
if rpi == False:
Bwidth=6
Lwidth=9
else:
Bwidth=9
Lwidth=9
client = mqtt.Client()
#import the required modules
import time
from time import sleep
import tkinter as tk
from tkinter import *
root=tk.Tk()
import sys
if os.environ.get('DISPLAY','') == '':
print('no display found. Using :0.0')
os.environ.__setitem__('DISPLAY', ':0.0')
global BREvent
global SREvent
SREvent = tk.Entry(root,width=3)
BREvent = tk.Entry(root,width=3)
SRdelay = 300
BRdelay = 199
BRcount=False
SRcount=False
SREvent.delete(0,END)
SREvent.insert(0,SRdelay)
BREvent.delete(0,END)
BREvent.insert(0,BRdelay)
default_SRdelay = int(SREvent.get())
default_BRdelay = int(BREvent.get())
root.geometry("350x75")
clock = Label(root,font =("arial",62,"bold"),bg = "#005500",fg = "#00aaaa",padx=20)
clock.grid(row=0,column=0,columnspan=3)
visible = TrueLast_Second =0
Lamp_PIR = False
t = time.time()
set_time_string = time.strftime("%H:%M:%S",time.localtime(t))
Next = 0
pos = 0
global sittingroom_Motion_change
global oldsittingroom_Motion
global sittingroom_Motion
global Bedroom_motion_change
sittingroom_Motion_change = False
Bedroom_motion_change = False
global Any_motion_change
Any_motion_change = False
global SRmotion_text
global old_SRmotion_text
old_SRmotion_text = ""
global BRmotion_text
global old_BRmotion_text
old_BRmotion_text = ""
global SRmsg1
global SRmsg2
global BRmsg1
global BRmsg2
global oldBRmsg1
global oldBRmsg2
global oldSRmsg1
global oldSRmsg2
SRmsg1=0
SRmsg2=0
BRmsg1=0
BRmsg2=0
oldSRmsg1=1
oldSRmsg2=1
oldBRmsg1=1
oldBRmsg2=1
global fg,bg
fg = bg = "blue"
SRmotion_text ="unset"
BRmotion_text ="unset"
Light_High=False
BR_Bright_High_Level=False
old_BR_Bright_High_Level=True
old_Light_High = True
Oldmqttmessage=""
Oldnew_mssg=""
broker_address="192.168.0.57"
button_mqttmessage=""
i=0
q=0
start_alarm_list = 0
alarmfound =[list]
OldNextnum="-- -- --"
Nextnum="Nothing yet"
Nextnum2="Nothing following yet"
First_Run = True
message="waiting"
light=False
oldmessage = message
new_mssg = "Nothing yet"
NextAlarm=""
Any_motion = False
NewList =[]
OldAlarm =""
global SRoffTime
global BRoffTime
SRoffTime = 0
BRoffTime = 0
sittingroom_Motion = False
oldsittingroom_Motion = False
old_Bedroom_motion = False
Bedroom_motion = False
Switch = False
days= ['Sat','Sun','Mon','Tue','Wed','Thu','Fri','Sw_All']
time_string=" unsetTime string "
any_day_string=" unsetTime string "
alarmList = []
NewAlarm = ""
switch_set = False
day_set = False
switch = "Sw_1 on"
test_show = True
visible = False
current=""
restart = 0
SRoffTime = 0
BRoffTime = 0
SENT=False
oldSENT=True
mqttmessage="nothing yet"
sw = 0
Dir =1
varSw_1 = False
varSw_2 = False
varSw_3 = False
varSw_4 = False
varSw_All = False
code = "0000"
double_click_flag=False
oldPIR = True
PIR = FALSE
oldSRcountdown =0
SRcountdown =33
oldBRcountdown =0
BRcountdown =33
oneShot=0
Bedroom_Light_State =False
SR_Light_State = False
Lamp = False
BR_PIR = False
SR_PIR = False
oldSR_PIR = True
oldBR_PIR = True
oldSw_2_PIR = True
Sw_2_PIR =False
Any_PIR=False
global Button_off_SRcountdown
global Button_off_BRcountdown
pulseLength = .1
Any_PIR_False = True
def __init__(self, master):
self.master = master
self.master.geometry("250x300")
self.mqtt_client = mqtt.Client()
self._connect_mqtt_client()
self.mqtt_client.on_message = self.on_message
self.mqtt_client.subscribe("frog")
self.message_list = []
self.last_highlighted_index = None
self._create_ui_components()
self.master.after(500, self.check_messages)
def _create_ui_components(self):
self.message_label = ttk.Label(self.master, text="No messages yet")
self.message_label2 = ttk.Label(self.master, text="No messages yet")
self.message_label3 = ttk.Label(self.master, text=" ")
self.message_label4 = ttk.Label(self.master, text=" ")
self.message_label5 = ttk.Label(self.master, text="")
if rpi:
self.message_label3 = ttk.Label(self.master, text=" ")
self.message_label4 = ttk.Label(self.master, text=" ")
self.listbox = tk.Listbox(self.master, height=20 if not rpi else 10)
self.listbox.bind("<Button-1>", self.on_select)
self.message_label.pack(side="top")
self.message_label2.pack(side="top")
self.message_label3.pack(side="left")
self.message_label4.pack(side="right")
self.message_label5.pack(side="bottom")
self.listbox.pack(side="top", expand=True)
def on_message(self, client, userdata, message):
timestamp = time.strftime('%d//%m/%y %H:%M:%S', time.localtime(time.time()))
payload = message.payload.decode("utf-8")
with open("event_list.csv", "a+") as file:
file.write(timestamp + " " + payload + "\n")
print(timestamp + " " + payload)
self.message_label.configure(text=payload + "\n" + timestamp)
# Update the listbox
self._update_listbox(payload)
def _update_listbox(self, payload):
if payload not in self.message_list:
# Add new message to the message list and listbox
self.message_list.insert(0, payload)
self.listbox.insert(0, payload)
self.listbox.itemconfig(0, bg="white", fg="black")
# Reset the background and foreground color of the last highlighted index
if self.last_highlighted_index is not None:
self.listbox.itemconfig(self.last_highlighted_index, bg="white", fg="black")
self.last_highlighted_index = None
else:
# Find the index of the existing message in the message list
index = self.message_list.index(payload)
# Remove the existing message from the message list and listbox
self.message_list.pop(index)
self.listbox.delete(index)
# Add the existing message to the top of the message list and listbox
self.message_list.insert(0, payload)
self.listbox.insert(0, payload)
self.listbox.itemconfig(0, bg="white", fg="black")
# Reset the background and foreground color of the last highlighted index
if self.last_highlighted_index is not None:
self.listbox.itemconfig(self.last_highlighted_index, bg="white", fg="black")
self.last_highlighted_index = None
def check_messages(self):
clock_time_string = time.strftime("%H:%M:%S")
self.message_label2.configure(text=clock_time_string, font=Font(size=40 if not rpi else 25))
try:
self.mqtt_client.loop()
self.master.after(100, self.check_messages)
except BaseException as err:
with open("event_list.csv", "a+") as file:
file.write(timestamp + " An unexpected error occurred: {err}" + payload + "\n")
print(f"An unexpected error occurred: {err}")
pass
def Lamp_on():
sendmqtt("Lamp is on")
global pulseLength
global Lamp
if rpi==True:GPIO.output (40, False)
time.sleep(pulseLength)
if rpi==True:GPIO.output (40, True)
print('Lamp is On ')
Lamp=True
button_Lamp_1 = Button(root,text="Lamp is on",bg="yellow", fg="green",padx=20,width=Bwidth,pady=5,command=Lamp_off)
button_Lamp_1.grid(row=27,column=0)
def Lamp_off():
sendmqtt("Lamp is off")
global Lamp
global pulseLengthclient
if rpi==True:GPIO.output (38, False)
time.sleep(pulseLength)
if rpi==True:GPIO.output (38, True)
print('Lamp is Off ')
Lamp=False
button_Lamp_1 = Button(root,text="Lamp is off",bg="red", fg="black",padx=20,width=Bwidth,pady=5,command=Lamp_on)
button_Lamp_1.grid(row=27,column=0)
def activate_Lamp():
global Lamp
if Lamp:
Lamp_on()
print("Lamp is on")
else:
print("Lamp is off")
Lamp_off()
def setup(): # presets morning radio wakeup
global mqtt
if First_Run == False:
return
print("this should only run ONCE")
#global lastAutoAlarm
global broker_address
alarmList.append ("Sw_1 on:Sun 06:59:54") #Sunday override On
alarmList.append ("Sw_1 on:Sun 07:30:00")
alarmList.append ("Sw_1 off:Sun 08:10:10") #Sunday override On
alarmList.append ("Sw_3 off:Sat 22:20:30")
alarmList.append ("Sw_3 off:Sat 19:59:30")
alarmList.append ("Sw_1 on:Sun 07:59:54")
alarmList.append ("Sw_1 on:Sun 08:59:57")
alarmList.append ("Sw_1 off:Sun 09:06:30")
alarmList.append ("Sw_1 on:Sat 07:30:00")
#alarmList.append ("Sw_2 on:Sat 07:30:00")
alarmList.append ("Sw_1 on:Sat 06:59:57")
alarmList.append ("Sw_1 on:Sat 08:59:57")
alarmList.append ("Sw_1 off:Sat 10:03:01")
alarmList.append ("Sw_2 off:Sat 21:30:00")
alarmList.append ("Sw_2 on:Sun 07:30:30")
alarmList.append ("Sw_2 off:Sun 21:30:01")
alarmList.append ("Sw_All off:Sun 22:00:00")
for day in days[0:]:
alarmList.append ("Sw_1 on:"+day+" 06:59:54")
alarmList.append ("Sw_1 on:"+day+" 07:59:54")
alarmList.append ("Sw_1 on:"+day+" 08:59:54")
alarmList.append ("Sw_All off:"+day+" 22:00:00")
alarmList.append ("Sw_All off:"+day+" 23:00:00")
alarmList.append ("Sw_2 on:"+day+" 07:59:54")
alarmList.append ("Sw_2 off:"+day+" 22:00:00")
alarmList.append ("Sw_4 off:"+day+" 22:00:00")
# alarmList.append ("Sw_4 on:Sat 08:59:50")
alarmList.append ("BR_PIR off:"+day+" 22:30:00")
alarmList.append ("BR_PIR off:"+day+" 23:00:00")
alarmList.append ("Sw_2_PIR on:"+day+" 08:31:30")
alarmList.append ("Sw_2_PIR on:"+day+" 09:00:00")
alarmList.append ("Sw_2_PIR off:"+day+" 22:00:00")
alarmList.append ("Sw_2_PIR off:"+day+" 23:00:00")
alarmList.append ("Br_Light off:"+day+" 22:00:01")
alarmList.append ("Br_Light off:"+day+" 23:00:01")
for day in days[2:]: # Skips Saturday and Sunday
alarmList.append ("Sw_1 off:"+day+" 09:02:10")
if rpi==True:
GPIO.setwarnings(False)
# set the pins numbering mode
GPIO.setmode(GPIO.BOARD)
# Select the GPIO pins used for the encoder K0K3 data inputs
GPIO.setup(11, GPIO.OUT)
GPIO.setup(15, GPIO.OUT)
GPIO.setup(16, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)
GPIO.setup(26, GPIO.IN)#light level input
#Light_High = GPIO.input(26)# BR Light level raw output
GPIO.setup(24, GPIO.IN)
GPIO.setup(18, GPIO.OUT)
GPIO. setup(22, GPIO.OUT)
# Disable the modulator by setting CE pin lo
GPIO.output (22, False)
# Set the modulator to ASK for On Off Keying
# by setting MODSEL pin lo
GPIO.output (18, False)
# Initialise K0K3 inputs of the encoder to 0000
GPIO.output (11, False)
GPIO.output (13, False)
GPIO.output (15, False)
GPIO.output (16, False)
broker_address="192.168.0.57"
#BBSB light pins
GPIO.setup(40, GPIO.OUT)
GPIO.setup(38, GPIO.OUT)
GPIO.output (40, True)
GPIO.output (38, True)
def settle():
global posCol
global mqttmessage
# let it settle, encoder requires this
time.sleep(0.1)
# Enable the modulator
if rpi==True:GPIO.output (22, True)
# keep enabled for a period
time.sleep(0.25)
# Disable the modulator
if rpi==True:GPIO.output (22, False)
global Next
Next-=1
#NextAlarmList()
PrintAlarmList(start_alarm_list+Next)
# mqttmessage=""
wait()
def wait():
time.sleep(0.10)
# mqttmessage=""
def set_button_off_SRcountdown(SRcount,displayedText):
global Button_off_SRcountdown
if SRcount:
Button_off_SRcountdown = Label(root,text=displayedText,bg="yellow", fg="black",padx=20,pady=5, width=Bwidth)
else:
Button_off_SRcountdown = Label(root,text=displayedText,bg="red",width=Lwidth, fg="white",padx=20,pady=5)
Button_off_SRcountdown.grid(row=23,column=2)
def set_button_off_BRcountdown(BRcount,displayedText):
global Button_off_BRcountdown
if BRcount:
Button_off_BRcountdown = Label(root,text=displayedText,bg="yellow", fg="black",padx=20,pady=5, width=Bwidth)
else:
Button_off_BRcountdown = Label(root,text=displayedText,bg="red",width=Lwidth, fg="white",padx=20,pady=5)
Button_off_BRcountdown.grid(row=24,column=2)
def Any_PIR_State_Display():
global Bedroom_Light_State
global SR_Light_State
global SR_PIR
global SRdelay
global BRdelay
global BR_PIR
global oldPIR
global SREvent
global BREvent
global PIR
global Any_PIR
global SENT
global Any_PIR_False
# print("385 SRdelay set to ",SRdelay)
# print("386 BRdelay set to ",BRdelay)
SRoffTime = int(time.time()) + int(SRdelay)
BRoffTime = int(time.time()) + int(BRdelay)
if Any_PIR == False:
Any_PIR_Button = Button(root,text="No PIR is active",bg="red",fg="black",padx=20,pady=5,width=Bwidth)#Noclick action
Any_PIR_Button.grid(row=25,column=0)
sendmqtt("Any_PIR = False")
SENT=True
else:
Any_PIR_Button = Button(root,text="PIR Active",bg="yellow", fg="green",padx=20,pady=5,width=Bwidth,command=Set_Any_PIR_State_Display_False)
sendmqtt("BRdelay\t"+str(BRdelay))
sendmqtt("SRdelay\t"+str(SRdelay))
Any_PIR_Button.grid(row=25,column=0)
def Set_Any_PIR_State_Display_False():
#Action on click - trigger disable all PIR if active - update State
global Any_PIR
global SREvent
global Sw_2_PIR
global SR_PIR
global BR_PIR
global Lamp_PIR
# print("!!Set_Any_PIR_State_Display_False called and current Any_PIR=",Any_PIR,"at ",time.strftime("%A %b %d %H:%M:%S \n"))
button_SRmotion = Label(root,text="SR inactive",bg="red", fg="yellow",padx=20,pady=5,width=Lwidth)
button_SRmotion.grid(row=23,column=1)
button_BRmotion = Label(root,text="BR inactive",bg="red", fg="yellow",padx=20,pady=5,width=Lwidth)
button_BRmotion.grid(row=24,column=1)
set_button_off_SRcountdown(False,"SR inactive")
set_button_off_BRcountdown(False,"BR inactive")
Any_PIR = False
Any_PIR_Button = Button(root,text="No PIR is active",bg="red",fg="black",padx=20,pady=5,width=Bwidth)#Noclick action
Any_PIR_Button.grid(row=25,column=0)
SR_PIR = False
BR_PIR = False
Sw_2_PIR = False
Lamp_PIR = False
Set_BR_PIR()
Set_SR_PIR()
Set_Sw_2_PIR()
set_lamp_PIR()
def set_lamp_PIR():
global Lamp_PIR
global Any_PIR
global Lamp
global SRdelay
global BRdelay
if Lamp_PIR:
Any_PIR=True#sets General PIR State to Active
Any_PIR_State_Display()
button_lamp_PIR = Button(root,text="Lamp PIR on ",bg="yellow", fg="green",padx=20,width=Bwidth,pady=5,command=toggle_Lamp_PIR)
button_lamp_PIR.grid(row=27,column=1)
else:
button_lamp_PIR = Button(root,text="Lamp PIR off",bg="red", fg="black",padx=20,width=Bwidth,pady=5,command=toggle_Lamp_PIR)
button_lamp_PIR.grid(row=27,column=1)
PirDisabledFlag()
def Get_SR_Bright_Level():
global Lamp_PIR
global Any_PIR
global Lamp
global SRdelay
global BRdelay
global Light_High
global old_Light_High
if (old_Light_High != Light_High):
if Light_High ==True:
button_light_level = Label(root,text="SR Light High",bg="yellow", fg="green",padx=20,width=Lwidth,pady=5)
button_light_level.grid(row=27,column=2)
else:
button_light_level = Label(root,text="SR Light Low",bg="red", fg="black",padx=20,width=Lwidth,pady=5)
button_light_level.grid(row=27,column=2)
old_Light_High = Light_High
def Get_BR_Bright_Level():
global Lamp_PIR
global Any_PIR
global Lamp
global SRdelay
global BRdelay
global BR_Bright_High_Level
global old_BR_Bright_High_Level
if (old_BR_Bright_High_Level != BR_Bright_High_Level):
if BR_Bright_High_Level ==True:
button_BR_Bright_High_Level = Label(root,text="Bedroom Bright",bg="yellow", fg="green",padx=20,width=Lwidth,pady=5)
button_BR_Bright_High_Level.grid(row=28,column=2)
else:
button_BR_Bright_High_Level = Label(root,text="Bedroom Dark",bg="red", fg="black",padx=20,width=Lwidth,pady=5)
button_BR_Bright_High_Level.grid(row=28,column=2)
old_BR_Bright_High_Level = BR_Bright_High_Level
def Set_Sw_2_PIR(): #performs Sw_2_button action on current State
global Sw_2_PIR
global Any_PIR
global SRdelay
global BRdelay
if Sw_2_PIR:
Any_PIR=True #sets General PIR State to Active
Any_PIR_State_Display()
button_Sw_2_PIR = Button(root,text="Sw_2_PIR ",bg="yellow", fg="green",padx=20,width=Bwidth,pady=5,command=toggle_Sw_2_PIR)
button_Sw_2_PIR.grid(row=26,column=0)
sendmqtt("Sw_2_PIR = True")
else:
button_Sw_2_PIR = Button(root,text="Sw_2_PIR ",bg="red", fg="black",padx=20,width=Bwidth,pady=5,command=toggle_Sw_2_PIR)
button_Sw_2_PIR.grid(row=26,column=0)
sendmqtt("Sw_2_PIR = False")
PirDisabledFlag()
def toggle_Sw_2_PIR():
global Sw_2_PIR
Sw_2_PIR= not Sw_2_PIR
Set_Sw_2_PIR()
PirDisabledFlag()
def toggle_Lamp_PIR():
global Lamp_PIR
Lamp_PIR= not Lamp_PIR
set_lamp_PIR()
PirDisabledFlag()
def change_message():
global mqttmessage
global new_mssg
new_mssg = mqttmessage
if mqttmessage == "SR_Light_State_is_on":
new_mssg="SR Light is on"
if mqttmessage == "SR_Light_State_is_off":
new_mssg="SR Light is off"
if mqttmessage == "BR PIR = False":
new_mssg="BR PIR is off"
if mqttmessage == "BR PIR = True":
new_mssg="BR PIR is on"
if mqttmessage == "Any_PIR = False":
new_mssg="No PIR is active"
if mqttmessage == "Any_PIR = True":
new_mssg="PIR active"
if mqttmessage == "light_is_True":
new_mssg="SR Light On"
if mqttmessage == "light_is_False":
new_mssg="SR Light Off"
def sendmqtt(mqttmessage):
global Oldmqttmessage
global SENT
global broker_address
global button_mqttmessage
global new_mssg
if mqttmessage=="":return
if Oldmqttmessage == mqttmessage:return
try:
client = mqtt.Client() #create new instance
client.on_message=on_message #attach function to callback
client.connect(broker_address,1883, 60)#connect to broker
client.loop_start()
client.subscribe("frog")
client.publish('frog', payload=mqttmessage, qos=0, retain=True)
# print(f"484 send {mqttmessage} at ",time.strftime("%A %b %d %H:%M:%S \n"+SRcount))
change_message()
button_mqttmessage = Label(root,text=new_mssg,bg="yellow", fg="green",padx=20,width=Lwidth,pady=5)
button_mqttmessage.grid(row=28,column=0)
except Exception as e:
client = mqtt.Client()
# client.loop_stop()
# client.connect(broker_address,1883, 60)#connect to broker
# client.loop_start()
client.subscribe("frog")
client.publish('frog', payload=mqttmessage, qos=0, retain=True)
mqttmessage="lost server"
Oldmqttmessage = mqttmessage
mqttmessage=""
def Sittingroom_Light():
global broker_address
global First_Run
global SR_Light_State
button_SR_Light_State = Button(root,text=" Sittingroom ",bg="red", fg="black",padx=20,width=Bwidth,pady=5,command=Toggle_SR_Light_State)
button_SR_Light_State.grid(row=25,column=1)
if SR_Light_State:
print("S T A R T = ",First_Run," ************************************")
if First_Run == False:
button_SR_Light_State = Button(root,text=" Sittingroom ",bg="yellow", fg="green", padx=20,width=Bwidth,pady=5,command=Toggle_SR_Light_State)
sendmqtt("SR_Light_State_is_on")
button_SR_Light_State.grid(row=25,column=1)
else:
if First_Run == False:
button_SR_Light_State = Button(root,text=" Sitting room ",bg="red", fg="black",padx=20,width=Bwidth,pady=5,command=Toggle_SR_Light_State)
sendmqtt("SR_Light_State_is_off")
button_SR_Light_State.grid(row=25,column=1)
button_SR_Light_State.grid(row=25,column=1)
def Toggle_SR_Light_State():
global SR_Light_State
SR_Light_State= not SR_Light_State
if SR_Light_State:
sendmqtt('SR_Light_State_is_on')
else:
sendmqtt('SR_Light_State_is_off')
Sittingroom_Light()
def Set_SR_PIR():
global Any_PIR
global SR_PIR
if SR_PIR:
button_SR_PIR = Button(root,text="SR PIR ",bg="yellow", fg="green",padx=20,width=Bwidth,pady=5,command=Toggle_SR_PIR)
print("--------------------------------------")
print(button_SR_PIR)
print("--------------------------------------")
Any_PIR=True
Any_PIR_State_Display()
sendmqtt("SR_PIR = True")
else:
button_SR_PIR = Button(root,text="SR PIR ",bg="red", fg="black",padx=20,width=Bwidth,pady=5,command=Toggle_SR_PIR)
button_SR_PIR.grid(row=26,column=1)
PirDisabledFlag()
def PirDisabledFlag():
global BR_PIR
global SR_PIR
global Sw_2_PIR
global Lamp_PIR
if (BR_PIR == False) & (SR_PIR == False) & (Sw_2_PIR == False) & (Lamp_PIR ==False):
Any_PIR = False
Any_PIR_State_Display()
sendmqtt("Any_PIR = False")
def Toggle_SR_PIR():
global SR_PIR
SR_PIR = not SR_PIR
Set_SR_PIR()
PirDisabledFlag()
def Bedroom_Light():
global First_Run
global broker_address
global Bedroom_Light_State
global Bedroom_Light_State_Toggle
global button_Bedroom_Light_State
global client
button_Bedroom_Light_State = Button(root,text="Bedroom ",bg="red", fg="black",padx=20,width=Bwidth,pady=5,command=Set_Bedroom_Light_State)
button_Bedroom_Light_State.grid(row=25,column=2)
if First_Run == True:
return
def Set_Bedroom_Light_State():
global client
global broker_address
global Bedroom_Light_State
global button_Bedroom_Light_State
global client
if Bedroom_Light_State == False:
button_Bedroom_Light_State = Button(root,text="Bedroom ",bg="red", fg="black",padx=20,width=Bwidth,pady=5,command=Toggle_Bedroom_Light_State)
button_Bedroom_Light_State.grid(row=25,column=2)
else:
button_Bedroom_Light_State = Button(root,text="Bedroom ",bg="yellow", fg="green",padx=20,width=Bwidth,pady=5,command=Toggle_Bedroom_Light_State)
button_Bedroom_Light_State.grid(row=25,column=2)
button_Bedroom_Light_State.grid(row=25,column=2)
print(" 585 Bedroom state acted on was =",Bedroom_Light_State)
def Toggle_Bedroom_Light_State():
global Bedroom_Light_State
Bedroom_Light_State = not Bedroom_Light_State
if Bedroom_Light_State:
sendmqtt('Bedroom_is_on')
else:
sendmqtt('Bedroom_is_off')
Set_Bedroom_Light_State()
def Set_BR_PIR():
global Any_PIR
global BR_PIR
if BR_PIR:
BR_PIR_State = Button(root,text="BR PIR ",bg="yellow", fg="green",padx=20,width=Bwidth,pady=5,command=Toggle_BR_PIR)
Any_PIR = True
Any_PIR_State_Display()
sendmqtt("BR PIR = True")
else:
BR_PIR_State = Button(root,text="BR PIR ",bg="red", fg="black",padx=20,width=Bwidth,pady=5,command=Toggle_BR_PIR)
sendmqtt("BR PIR = False")
PirDisabledFlag()
SENT=True
BR_PIR_State.grid(row=26,column=2)
PirDisabledFlag()
def Toggle_BR_PIR():
global BR_PIR
BR_PIR = not BR_PIR
Set_BR_PIR()
def setBRofftime():
try:
BRoffTime = int(time.time())+ int(BRdelay)
except:
BRoffTime = 333
BRcountdown =int(BRoffTime)-int(time.time())
def setSRofftime():
try:
SRoffTime = int(time.time())+ int(SRdelay)
except:
SRoffTime = 321
SRcountdown =int(SRoffTime)-int(time.time())
def get_mqtt():
global mqttmessage
global Bedroom_motion
global Oldmqttmessage
global SENT
global Lamp
global new_mssg
global SREvent
global BREvent
global SR_PIR
global BR_PIR
global BRdelay
global SRdelay
global SRmsg1
global SRmsg2
global BRmsg1
global BRmsg2
global SR_Light_State
global Bedroom_Light_State
global Sw_2_PIR
global button_mqttmessage
global BR_Bright_High_Level
global Light_High
global Any_PIR_False
global Oldnew_mssg
global SRoffTime
global BRoffTime
global sittingroom_Motion
if mqttmessage == Oldmqttmessage:return
print("766 mqttmessage =",mqttmessage,"at ",time.strftime("%A %b %d %H:%M:%S \n"))
SENT= False
updateSENT()
msglist = mqttmessage.split("\t" )
# try:
# oldSRmsg2=SRmsg2
# SRmsg2 = msglist[1]
# if oldSRmsg2 !=SRmsg2:
# sendmqtt("SRdelay\t"+str(SRmsg2))
# print("---------------------------------------------msg2",msglist[1])
# except:
# pass
# SRmsg1 = msglist[0]
if msglist[0] =="SRdelay":
# BRmsg1=SRmsg1
SRmsg2=msglist[1]
if oldSRmsg2!=SRmsg2:
sendmqtt("SRdelay\t"+str(SRmsg2))
SRdelay=int(SRmsg2)
SREvent.delete(0,END)
SREvent.insert(0,SRdelay)
# sendmqtt("BRdelay\t"+str(BRdelay))
SREvent.grid(row=23, column=0,pady = 5)
if msglist[0] =="BRdelay":
# BRmsg1=BRmsg1
BRmsg2=msglist[1]
if oldBRmsg2 != BRmsg2:
sendmqtt("BRdelay\t"+str(BRmsg2))
BRdelay=int(BRmsg2)
BREvent.delete(0,END)
BREvent.insert(0,BRdelay)
oldBRmsg2 = BRmsg2
sendmqtt("BRdelay\t"+str(BRdelay))
BREvent.grid(row=23, column=0,pady = 5)
print("====&=========&=======&===== BRmsg1",BRmsg1,"@", time.strftime("%A %b %d %H:%M:%S \n"))
print("====&=========&=======&===== BRmsg2",BRmsg2)
print("============================= SRmsg1",SRmsg1,"====== SRmsg2",SRmsg2)
if (mqttmessage == "Any_PIR = False"):
Set_Any_PIR_State_Display_False()
if mqttmessage=="Bedroom_MANUAL_on":
Bedroom_Light_State = True
Set_Bedroom_Light_State()
if mqttmessage=="Bedroom_MANUAL_off":
Bedroom_Light_State = False
Set_Bedroom_Light_State()
if mqttmessage=="SRlight Manual On":
SR_Light_State = True
Sittingroom_Light()
if mqttmessage=="SRlight Manual Off":
SR_Light_State = False
Sittingroom_Light()
if mqttmessage== "Bedroom_Motion_is_0":
Bedroom_motion = False
mqttmessage= "Bedroom Still"
BRdelay = BREvent.get()
sendmqtt("BRdelay\t"+str(BRdelay))
print (BRdelay)
setBRofftime()
if mqttmessage== "Bedroom_Motion_is_1":
Bedroom_motion = True
mqttmessage= "Bedroom Mvmnt"
BRdelay = BREvent.get()
sendmqtt("BRdelay\t"+str(BRdelay))
print (BRdelay)
if mqttmessage== "sittingroom_Motion_is_0":
sittingroom_Motion = False
mqttmessage= "Srm Still"
SRdelay = SREvent.get()
sendmqtt("SRdelay\t"+str(SRdelay))
setSRofftime()
if mqttmessage== "sittingroom_Motion_is_1":
sittingroom_Motion = True
mqttmessage= "Srm Motion"
SRdelay = SREvent.get()
sendmqtt("SRdelay\t"+str(SRdelay))
if mqttmessage== "sittingroom_light_is_False":
Light_High = False
mqttmessage="Sr Light OFF"
Get_SR_Bright_Level()
if mqttmessage== "sittingroom_light_is_True":
Light_High = True
Get_SR_Bright_Level()
mqttmessage="Sr Light ON"
if mqttmessage== "Bedroom_light_is_False":
BR_Bright_High_Level = False
Get_BR_Bright_Level()
if mqttmessage== "Bedroom_light_is_True":
BR_Bright_High_Level = True
Get_BR_Bright_Level()
if mqttmessage=="Sw_1_on":
Sw_1_on()
if mqttmessage=="Sw_1_off":
Sw_1_off()
if mqttmessage=="Sw_2_on":
Sw_2_on()
if mqttmessage=="Sw_2_off":
Sw_2_off()
if mqttmessage=="Sw_3_on":
Sw_3_on()
if mqttmessage=="Sw_3_off":
Sw_3_off()
if mqttmessage=="Sw_4_on":
Sw_4_on()
if mqttmessage=="Sw_4_off":
Sw_4_off()
if mqttmessage=="Bedroom_is_off":
Bedroom_Light_State = False
Set_Bedroom_Light_State()
if mqttmessage=="Bedroom_is_on":
Bedroom_Light_State = True
Set_Bedroom_Light_State()
if mqttmessage=="Lamp is on":
Lamp = True
activate_Lamp()
if mqttmessage=="Lamp is off":
Lamp = False
activate_Lamp()
if mqttmessage == "Sw_2_PIR = True":
Sw_2_PIR = True
Set_Sw_2_PIR()
if mqttmessage == "Sw_2_PIR = False":
Sw_2_PIR = False
Set_Sw_2_PIR()
if mqttmessage == "SR_PIR = True":
SR_PIR = True
Set_SR_PIR()
if mqttmessage == "SR_PIR = False":
SR_PIR = False
Set_SR_PIR()
if mqttmessage == "BR PIR = True":
BR_PIR = True
Set_BR_PIR()
if mqttmessage == "BR PIR = False":
BR_PIR = False
Set_BR_PIR()
if mqttmessage =="":return
button_mqttmessage = Label(root,text=mqttmessage,bg="yellow", fg="green",padx=20,width=Lwidth,pady=5)
if rpi == True:
button_mqttmessage = Label(root,text=mqttmessage,bg="yellow", fg="green",padx=20,width=Lwidth,pady=5)
button_mqttmessage.grid(row=28,column=0)
Oldmqttmessage=mqttmessage
Oldnew_mssg = new_mssg
def motion():
global varSw_2
global old_SRmotion_text
global old_BRmotion_text
global SRoffTime
global BRoffTime
global Any_motion_change
global Any_motion
global restart
global sittingroom_Motion_change
global Bedroom_motion_change
global oldsittingroom_Motion
global old_Bedroom_motion
global sittingroom_Motion
global oldsittingroom_Motion
global Bedroom_motion
global Bedroom_Light_State
global SR_Light_State
global SR_PIR
global BR_PIR
global Sw_2_PIR
global SENT
global BRcountdown
global SRcountdown
global SRdelay
global BRdelay
global BRcount
global SRcount
global Any_PIR
global SRmotion_text
global BRmotion_text
global thing
global SRmotion
global BRmotion
global root
global Lamp
global light
global Button_off_SRcountdown
global Button_off_BRcountdown
global button_Bedroom_Light_State
global fg,bg
if (old_Bedroom_motion != Bedroom_motion):
old_Bedroom_motion = Bedroom_motion
print("851 ------Bedroom_motion change state---------------")
Bedroom_motion_change = True
if (sittingroom_Motion != oldsittingroom_Motion ):
oldsittingroom_Motion = sittingroom_Motion
print("860 ------SITTING room change state---------------")
sittingroom_Motion_change = True
else:
sittingroom_Motion_change = False
if ((sittingroom_Motion_change) or (Bedroom_motion_change)):
Any_motion_change = True
if Bedroom_motion_change :
sendmqtt("BR motion\t"+str(Bedroom_motion))
if Bedroom_motion == False:
BRmotion_text="Bedroom Still"
fg="yellow"
bg="red"
if BR_PIR or Sw_2_PIR:
BRcount=True
if Bedroom_motion_change & Bedroom_motion:
print("884 Bedroom motion, state changed to ",Bedroom_motion,"at", time.strftime("%A %b %d %H:%M:%S \n"))
BRmotion_text="Bedroom Motion"
fg="yellow"
bg="green"
BRcount=False
set_button_off_BRcountdown(False,"Waiting")
button_BRmotion = Label(root,text=BRmotion_text, fg=fg,bg=bg,padx=20,pady=5,width=Lwidth)
button_BRmotion.grid(row=24,column=1)
if Sw_2_PIR:
Sw_2_on()
BRdelay = int(BREvent.get())
BRcount=False
if BR_PIR:
Bedroom_Light_State = True
Set_Bedroom_Light_State
sendmqtt('Bedroom_is_on')
BRdelay = int(BREvent.get())
BRcount=False
if sittingroom_Motion_change:
print("sr motion changed --------------------",sittingroom_Motion_change)
sendmqtt("SR motion"+str(sittingroom_Motion))
if sittingroom_Motion:
print("902 Sitting room Motion changed to ",sittingroom_Motion ,"at", time.strftime(" %H:%M:%S \n"))
SRmotion_text="SR Motion"
fg="yellow"
bg="green"
button_SRmotion = Label(root,text=SRmotion_text, fg=fg,bg=bg,padx=20,pady=5,width=Lwidth)
button_SRmotion.grid(row=23,column=1)
if SR_PIR:
SRdelay = int(SREvent.get())
SRcount=False
SR_Light_State=True
Toggle_SR_Light_State
sendmqtt('SR_Light_State_is_on')
set_button_off_SRcountdown(SRcount, "Waiting")
print("911 SR_Light_State ",sittingroom_Motion ,"at", time.strftime("%A %b %d %H:%M:%S \n"))
if sittingroom_Motion == False:
print("913 Sitting room Motion changed to ",sittingroom_Motion ,"at", time.strftime("%A %b %d %H:%M:%S \n"))
SRmotion_text="Sittingroom Still"
SR_Light_State=False
if SR_PIR & (sittingroom_Motion == False):
SRoffTime = int(time.time()) + int(SRdelay)
SRcount=True
SRcountdown =int(SRoffTime)-int(time.time())
set_button_off_SRcountdown(True,SRcountdown)
fg="yellow"
bg="red"
button_SRmotion = Label(root,text=SRmotion_text, fg=fg,bg=bg,padx=20,pady=5,width=Lwidth)
button_SRmotion.grid(row=23,column=1)
Bedroom_motion_change=False
sittingroom_Motion_change=False
Any_motion = False
Any_motion_text="All still"
fg="white"
bg="grey"
if SRmotion_text != old_SRmotion_text:
button_SRmotion = Label(root,text=SRmotion_text, fg=fg,bg=bg,padx=20,pady=5,width=Lwidth)
button_SRmotion.grid(row=23,column=1)
old_SRmotion_text = SRmotion_text
if BRmotion_text != old_BRmotion_text:
button_BRmotion = Label(root,text=BRmotion_text, fg=fg,bg=bg,padx=20,pady=5,width=Lwidth)
button_BRmotion.grid(row=24,column=1)
old_BRmotion_text = BRmotion_text
#
#print("!!END !!!!!!!Any_motion_change state !!!!!!!!!!!!",Any_motion_change)
#
#print(Bedroom_motion,"!!!!!!!!!!!!! A F T E R !!!!!!!!!!!!!!!!!!!!",sittingroom_Motion )
def updateSENT():
global SENT
msgtime = time.strftime("%H:%M:%S ")
if SENT:
button_SENT = Label(root,text="Out @ "+msgtime,padx=20,pady=5,width=Lwidth)
else:
button_SENT = Label(root,text="In @ "+msgtime,padx=20,pady=5,width=Lwidth)
button_SENT.grid(row=28,column=1)
def alarm():
global OldNextnum
global SENT
global mqttmessage
global Nextnum
global NewAlarm
global Sw2Overide
global sittingroom_Motion_is
global SRoffTime
global BRoffTime
global SRdelay
global BRdelay
global varSw_2
global PIR
global oldPIR
global oldSR_PIR
global oldBR_PIR
global SR_PIR
global BR_PIR
global Bedroom_Light_State
global Sw_2_PIR
global client
global Next
timenow=time.strftime("%A %b %d %H:%M:%S")
for alarm in alarmList:
if alarm == ("Lamp on:"+ time_string) or alarm == ("Lamp on:"+ any_day_string):
Lamp = True
Lamp_on()
if alarm == ("Lamp off:"+ time_string)or alarm == ("Lamp off:"+ any_day_string):
Lamp = False
Lamp_off()
if alarm == ("Light PIR on:"+ time_string) or alarm == ("Light PIR on:"+ any_day_string):
Lamp_PIR = True
set_lamp_PIR()
if alarm == ("Light PIR off:"+ time_string)or alarm == ("Light PIR off:"+ any_day_string):
Lamp_PIR = False
set_lamp_PIR()
if alarm == ("Br_Light on:"+ time_string) or alarm == ("Br_Light on:"+ any_day_string):
Bedroom_Light_State = True
Bedroom_Light()
if alarm == ("Br_Light off:"+ time_string)or alarm == ("Br_Light off:"+ any_day_string):
Bedroom_Light_State = False
Bedroom_Light()
if alarm == ("BR_PIR_on:"+ time_string) or alarm == ("BR_PIR_on:"+ any_day_string):
BR_PIR = True
Set_BR_PIR()
if alarm == ("BR_PIR_off:"+ time_string)or alarm == ("BR_PIR_off:"+ any_day_string):
BR_PIR = False
Set_BR_PIR()
if alarm == ("Sw_2_on:"+ time_string) or alarm == ("Sw_2_on:"+ any_day_string):
Sw_2_PIR = True
Set_Sw_2_PIR()
if alarm == ("Sw_2_off:"+ time_string)or alarm == ("Sw_2_off:"+ any_day_string):
Sw_2_PIR = False
Set_Sw_2_PIR()
if alarm == ("Any_PIR off:"+ time_string)or alarm == ("Any_PIR off:"+ any_day_string):
Any_PIR = False
if alarm == ("Sw_1 on:"+ time_string) or alarm == ("Sw_1 on:"+ any_day_string):
Sw_1_on()
if alarm == ("Sw_1 off:"+ time_string)or alarm == ("Sw_1 off:"+ any_day_string):
Sw_1_off()
if alarm == ("Sw_2 on:"+ time_string)or alarm == ("Sw_2 on:"+ any_day_string):
Sw_2_on()
if alarm == ("Sw_2 off:"+ time_string)or alarm == ("Sw_2 off:"+ any_day_string):
Sw_2_off()
if alarm == ("Sw_3 on:"+ time_string)or alarm == ("Sw_3 on:"+ any_day_string):
Sw_3_on()
if alarm == ("Sw_3 off:"+ time_string)or alarm == ("Sw_3 off:"+ any_day_string):
Sw_3_off()
if alarm == ("Sw_4 on:"+ time_string)or alarm == ("Sw_4 on:"+ any_day_string):
Sw_4_on()
if alarm == ("Sw_4 off:"+ time_string)or alarm == ("Sw_4 off:"+ any_day_string):
Sw_4_off()
if alarm == ("Sw_All on:"+ time_string)or alarm == ("Sw_All on:"+ any_day_string):
Sw_All_on()
if alarm == ("Sw_All off:"+ time_string)or alarm == ("Sw_All off:"+ any_day_string):
Sw_All_off()
SENT = True
def add_alarm():
global set_time_string
global e1
global pos
pos = 0
select_switch()
select_day()
select_time()
print("Alarm set for %s - %s:%s" % (switch, day, e1.get()+"\n"))
set_alarm()
global Next
Next = 0 # resets the next alarm counter
PrintAlarmList(0)
def set_alarm():
global set_time_string
t = time.time() + 10
set_time_string = time.strftime("%H:%M:%S",time.localtime(t))
Label(root, text=current).grid(row = 1, column = 2)
show_entry_button=Button(root, text='Set Alarm', command=show_entry_fields).grid(row=2, column=2, pady=4)
select_switch()
select_day()
select_time()
global Next
Next = 0
global start_alarm_list
PrintAlarmList(start_alarm_list+Next)
def select_switch():
global tkvar
tkvar = StringVar(root)
tkvar.set('Sw_1 on') # set the default option
choices = { 'Sw_1 on','Sw_1 off','Sw_2 on','Sw_2 off','Sw_3 on','Sw_3 off','Sw_4 on','Sw_4 off','Sw_All on','Sw_All off','Sw_2_on','Sw_2_off','Any_PIR off','Light on','Light off','Light PIR on','Light PIR off','BR_PIR on','BR_PIR off','Br_Light on','Br_Light off'}
popupMenu = OptionMenu(root, tkvar, *sorted(choices))
Label(root, text="Switch").grid(row = 2, column = 0)
popupMenu.grid(row = 3, column =0)
def change_switch_dropdown(*args):
print( tkvar.get() )
global switch
switch = tkvar.get()
current = switch
tkvar.trace('w', change_switch_dropdown)
def select_day():
global tkvarDay
tkvarDay = StringVar(root)
tkvarDay.set(time.strftime("%a")) # set the default option
popupMenu = OptionMenu(root, tkvarDay, *days)
Label(root, text="Day").grid(row = 2, column = 1)
popupMenu.grid(row = 3, column =1)
global day
day = time.strftime("%a")
# on change dropdown value
def change_day_dropdown(*args):
print( tkvarDay.get() )
global day
day = tkvarDay.get()
tkvarDay.trace('w', change_day_dropdown)
def select_time():
global set_time_string
global e1
e1 = tk.Entry(root,width=7)
#e1.insert(0, time.strftime("%H:%M:%S"))
e1.insert(0, set_time_string)
e1.grid(row=3, column=2,pady = 5)
def show_entry_fields():
global e1
# global e2
# global e3
global start_alarm_list
global Next
Next = 0
alarmList.append (switch+":"+str(day)+" "+e1.get())
print("start_alarm_list = ",start_alarm_list,"@Next =",Next)
print("Alarm added for %s - %s %s" % (switch, day, e1.get()))
PrintAlarmList(Next)
def Sw_1_on():
global varSw_1
sendmqtt("Sw_1_on")
varSw_1 = True
print( "Proc code 1111 Sw_1 on ")
if rpi==True:
GPIO.output (11, True)
GPIO.output (15, True)
GPIO.output (16, True)
GPIO.output (13, True)
button_s1 = Button(root,text="S1 ",bg="green",fg="white",padx=20,pady=5,width=Bwidth,command=toggleS1)
button_s1.grid(row=20,column=0)
settle()
def Sw_1_off():
global varSw_1
sendmqtt("Sw_1_off")
varSw_1 = False
print( "Proc code 0111 Sw_1 off !!!!")
if rpi==True:
GPIO.output (11, True)
GPIO.output (15, True)
GPIO.output (16, True)
GPIO.output (13, False)
button_s1 = Button(root,text="S1 ",bg="red", fg="black",padx=20,pady=5,width=Bwidth,command=toggleS1)
button_s1.grid(row=20,column=0)
settle()
def Sw_2_on():
global p
global varSw_2
sendmqtt("Sw_2_on")
varSw_2 = True
print( "Proc code 1110 Sw_2 on ")
if rpi==True:
GPIO.output (11, False)
GPIO.output (15, True)
GPIO.output (16, True)
GPIO.output (13, True)
button_s2 = Button(root,text="S2 ",bg="green", fg="white",padx=20,pady=5,width=Bwidth,command=toggleS2)
button_s2.grid(row=20,column=1)
settle()
print("Sw_2 turned on \n")
def Sw_2_off():
global varSw_2
sendmqtt("Sw_2_off")
varSw_2 = False
print( "Proc code 0110 Sw_2 off ")
if rpi==True:
GPIO.output (11, False)
GPIO.output (15, True)
GPIO.output (16, True)
GPIO.output (13, False)
button_s2 = Button(root,text="S2 ",bg="red", fg="black",padx=20,pady=5,width=Bwidth,command=toggleS2)
button_s2.grid(row=20,column=1)
settle()
print("Sw_2 turned OFF \n")
def Sw_3_on():
global Sw_3
sendmqtt("Sw_3_on")
varSw_3 = True
print( "Proc code 1001 Sw_3 on ")
if rpi==True:
GPIO.output (11, True)
GPIO.output (15, False)
GPIO.output (16, False)
GPIO.output (13, True)
button_s3 = Button(root,text="S3 ",bg="green", fg="white",padx=20,pady=5,width=Bwidth,command=toggleS3)
button_s3.grid(row=20,column=2)
settle()
def Sw_3_off():
global Sw_3
sendmqtt("Sw_3_off")
varSw_3 = False
print( "Proc code 0001 Sw_3 off ")
if rpi==True:
GPIO.output (11, True)
GPIO.output (15, False)
GPIO.output (16, False)
GPIO.output (13, False)
button_s3 = Button(root,text="S3 ",bg="red", fg="black",padx=20,pady=5,width=Bwidth,command=toggleS3)
button_s3.grid(row=20,column=2)
settle()
def Sw_4_on():
global Sw_4
sendmqtt("Sw_4_on")
varSw_4 = True
print( "Proc code 1100 Sw_4 on ")
if rpi==True:
GPIO.output (11, False)
GPIO.output (15, False)
GPIO.output (16, True)
GPIO.output (13, True)
button_s4 = Button(root,text="S4 ",bg="green", fg="white",padx=20,pady=5,width=Bwidth,command=toggleS4)
button_s4.grid(row=22,column=2)
settle()
def Sw_4_off():
global Sw_4
sendmqtt("Sw_4_off")
varSw_4 = False
print( "Proc code 0100 Sw_4 off ")
if rpi==True:
GPIO.output (11, False)
GPIO.output (15, False)
GPIO.output (16, True)
GPIO.output (13, False)
button_s4 = Button(root,text="S4 ",bg="red", fg="black",padx=20,pady=5,width=Bwidth,command=toggleS4)
button_s4.grid(row=22,column=2)
settle()
def Sw_All_on():
varSw_All = True
print( "Proc code 1011 Sw_All on ")
if rpi==True:
GPIO.output (11, True)
GPIO.output (15, True)
GPIO.output (16, False)
GPIO.output (13, True)
button_sall = Button(root,text="All are on",bg="green", fg="white",padx=20,pady=5,width=Bwidth,command=toggleSall)
button_sall.grid(row=22,column=1)
Sw_1_on()
Sw_2_on()
Sw_3_on()
Sw_4_on()
varSw_All = True
settle()
def Sw_All_off():
Sw_1_off()
Sw_2_off()
Sw_3_off()
Sw_4_off()
global SREvent
global BREvent
global Any_PIR
varSw_All = False
print( "Proc code 0011 Sw_All off ")
if rpi==True:
GPIO.output (11, True)
GPIO.output (15, True)
GPIO.output (16, False)
GPIO.output (13, False)
button_sall = Button(root,text="All are off",bg="red", fg="black",padx=20,pady=5,width=Bwidth,command=toggleSall)
button_sall.grid(row=22,column=1)
Sw_2_PIR = False
Any_PIR = False
Set_Any_PIR_State_Display_False()
def Cycle():
global sw
global Dir
global NewList
AllCodes = ["1000","0000","1001","0001","1010","0010","1011","0011","1100",
"0100","1101","0101","1110","0110","1111","0111"]
global code
code = AllCodes[sw]
print("code ",code)
button_cycle = Button(root,text="Cycle "+code,padx=20,pady=5,width=Bwidth,command=Cycle)
Scode = str(code)
button_cycle.grid(row=22,column=0,columnspan=1)
if rpi==True:
GPIO.output (11, int(Scode[3]))
GPIO.output (15, int(Scode[2]))
GPIO.output (16, int(Scode[1]))
GPIO.output (13, int(Scode[0]))
sw=sw+Dir
if sw==16 :
sw=0
if sw==-1 :
sw=15
settle()
print( "Switch "+str(sw))
Dir=1
def on_message(client, userdata, message):
global mqttmessage
global Light_High
global BR_Bright_High_Level
# print(time.strftime("%A %b %d %H:%M:%S"))
mqttmessage = str(message.payload.decode("utf-8"))
# print (time_string+" "+mqttmessage)
def alarmUpdate(fgcol):
global Nextnum
global Next
if fgcol == "green":
Next = 0
# print("!!!!----------!!!!!!!!",Nextnum)
Label(root, text=" "+ '\n' +" " ).grid(row=1,column=2)
TwoLineAlarmString= " ".join(Nextnum)
posCol=TwoLineAlarmString.find(' ')
TwoLineAlarm = TwoLineAlarmString[:posCol+4] + '\n' + TwoLineAlarmString[posCol+4:]
Label(root, text=TwoLineAlarm).grid(row=1,column=2)
Next_Alarm="Alarm"
DisplayNum= Next_Alarm,Next+1
if Next ==-1:
DisplayNum= "No more today"
button_100 = Button(root, text=DisplayNum,bg="yellow", fg=fgcol,padx=20,pady=5, width=Bwidth, command=NextAlarmList).grid(row = 1, column = 1)
def NextAlarmList():
global alarmfound
nextlist=[]
global Next
global Nextnum
global pos
global i
global q
global start_alarm_list
Now = time.strftime("%H:%M:%S")
Next+=1
for q in alarmfound:
if q[2]>Now:
nextlist.append(q)
print("\nNext Alarm List :-")
for i, q in enumerate(nextlist):
print(i,q)
try:
Nextnum = nextlist[Next]
DisplayText= "Next Alarm->",Next
alarmUpdate("red")
except BaseException as err:
print("reset on Error",err)
Nextnum = ""
start = 0
Next = -1# sets start to array position of next alarm
print ("restart start = ",start," line 1384--Print alarm default")
n=0
alarmUpdate("black")
return Nextnum
def PrintAlarmList(Next):
global First_Run
global start_alarm_list
global NewList
global alarmList
global NextAlarm
global OldAlarm
global Nextnum
global Nextnum2
global alarmfound
global q
global i
NewList2 = []
for n in range(len(alarmList)):
text = alarmList[n]
NewList = text.split()
text = NewList
NewList2.append(NewList)
NewList =[]
NewList2.sort (key=lambda x: x[2])
if First_Run == False:
Now = time.strftime("%H:%M:%S")
Day = time.strftime("%a")
alarmfound.clear()
for q in NewList2:
try: #creates list for today
if q[1] == ("on:"+Day):
alarmfound.append(q)
except:
print("---------error on fail")
try: #creates list for today
if q[1] == ("off:"+Day):
alarmfound.append(q)
except:
print("---------error off fail")
try:
i=0
for i,q in enumerate(alarmfound):
# print(i, end='')
if q[2]>Now:
start_alarm_list = i # sets start_alarm_list to array position of next alarm
Nextnum = alarmfound[i]
break
except BaseException as err:
pass
Next = 0
alarmUpdate("green")
return Nextnum
def toggleS1():
global varSw_1
varSw_1 = not varSw_1
print("toggled S1-varSw_1 to =",varSw_1)
if (varSw_1 == True):
Sw_1_on()
print("S1-varSw_1=",varSw_1)
else:
Sw_1_off()
print("S1-varSw_1=",varSw_1)
def toggleS2():
global varSw_2
global SRoffTime
global BRoffTime
varSw_2 = not varSw_2
print("toggled S2-varSw_2 to =",varSw_2)
# offTime = time.time() + delay
if (varSw_2 == True):
Sw_2_on()
print("Toggle S2-varSw_2=",varSw_2,"\n")
else:
Sw_2_off()
print("Toggle S2-varSw_2=",varSw_2,"\n")
def toggleS3():
global varSw_3
varSw_3 = not varSw_3
print("toggled S3-varSw_3 to =",varSw_3)
if (varSw_3 == True):
Sw_3_on()
print("S3-varSw_3=",varSw_3)
else:
Sw_3_off()
print("S3-varSw_3=",varSw_3)
def toggleS4():
global varSw_4
varSw_4 = not varSw_4
print("toggled S4-varSw_4 to =",varSw_4)
if (varSw_4 == True):
Sw_4_on()
print("S4-varSw_4=",varSw_4)
else:
Sw_4_off()
print("S4-varSw_4=",varSw_4)
def toggleSall():
global varSw_All
varSw_All = not varSw_All
if (varSw_All == True):
Sw_All_on()
else:
Sw_All_off()
print("All-varSws=",varSw_All)
def toggle():
global visible
visible = not visible
if visible:
btnToggle["text"] = ("^")
btnToggle.place(x=9000, y=0)
root.geometry("375x95")
root.geometry("375x95+0+100")
else:
btnToggle["text"] = "V"
btnToggle.place(x=9000, y=245)
root.geometry("375x410")
root.geometry("375x410+0+0")
def prep(event):
event.widget.focus_set() # give keyboard focus to the label
event.widget.bind(toggle())
# Reconnect the MQTT client if an error occurs
#def _reconnect_mqtt_client(self):
# self.mqtt_client.disconnect()
## self.mqtt_client = mqtt.Client()
# client = mqtt.Client()
# self._connect_mqtt_client()
# self.mqtt_client.subscribe("frog")
# self.mqtt_client.on_message = self.on_message
def tick():
# try:
# # Check for new MQTT messages
## self.mqtt_client.loop()
# client.loop_start()
# # Schedule the next check_messages call
## check_messages
# except BaseException as err:
# print(f"An unexpected error occurred: {err}")
# # Reconnect the MQTT client if an error occurs
# self._reconnect_mqtt_client()
global time_string
global SRdelay
global BRdelay
global root
global SRoffTime
global BRoffTime
global BRcount
global SRcount
global SRcountdown
global BRcountdown
time_string=time.strftime("%a %H:%M:%S")
clock_time_string=time.strftime("%H:%M:%S")
clock.config(text=str(clock_time_string))
clock.after(1000,tick)
import gc
# print(gc.get_count())
gc.collect()
# print("---", gc.get_count())
alarm()
get_mqtt()
motion()
if BRcount:
BRcountdown =int(BRoffTime)-int(time.time())
set_button_off_BRcountdown(True,BRcountdown)
if BRcountdown<1:
BRcount=False
if BR_PIR:
BR_Light_State=False
Toggle_Bedroom_Light_State()
sendmqtt('BR_Light_State_is_off')
set_button_off_BRcountdown(False,"Waiting")
if Sw_2_PIR:
Sw_2_off()
set_button_off_BRcountdown(False,"Waiting")
if SRcount:
SRcountdown =int(SRoffTime)-int(time.time())
set_button_off_SRcountdown(True,SRcountdown)
if SRcountdown<1:
SRcount=False
if SR_PIR:
SR_Light_State=False
Toggle_SR_Light_State()
sendmqtt('SR_Light_State_is_off')
set_button_off_SRcountdown(False,"Waiting")
try:
client = mqtt.Client()
client.loop_start()
except Exception as e:
client.loop_start()
client.subscribe("frog")
tick()
alarm()
SREvent = tk.Entry(root,width=3)
SREvent.delete(0,END)
SREvent.insert(0,default_SRdelay)
SREvent.grid(row=23, column=0,pady = 5)
print("1719 SRdelay is ",SREvent.get())
SRcountdown =int(SRoffTime)-int(time.time())
BREvent = tk.Entry(root,width=3)
BREvent.delete(0,END)
BREvent.insert(0,default_BRdelay)
BREvent.grid(row=24, column=0,pady = 5)
print("1652 BRdelay is ",BREvent.get())
BRcountdown =int(BRoffTime)-int(time.time())
setup()
Sw_All_off()
set_alarm()
PrintAlarmList(start_alarm_list+Next)
select_switch()
select_day()
select_time()
print("root poll time =", time.strftime("%A %b %d %H:%M:%S"))
#light = False
button_Light_1 = Button(root,text="Lamp is off",bg="red", fg="black",padx=20,width=Bwidth,pady=5,command=Lamp_on)
button_Light_1.grid(row=27,column=0)
import sys
#title=(os.path.basename(sys.argv[0]))
#root.title(title+" " +time.strftime('%d %H:%M:%S'))
title=(os.path.basename(sys.argv[0]))
root.title(title+" " +time.strftime('%d %H:%M:%S'))
root.title(title+" " +str(createdDate))
root.title(title+" " +m_ti)
filemodtime = time.strftime("%d -%H:%M:%S",time.localtime(ti_m))
root.title(title+" " +filemodtime)
root.geometry("375x95+0+100")
root.geometry("375x505+0+100")
if rpi == False:
root.geometry("390x480+0+400")
print("Sw_1 on:"+ time_string)
button_1 = Button(root,text="Add Alarm",padx=20,pady=5,width=Bwidth,command=add_alarm)
button_1.grid(row=1,column=0)
#setting up initial button display and normalising settings
Any_PIR_State_Display()
SR_PIR = False
BR_PIR = False
Sw_2_PIR = False
Set_Sw_2_PIR()
Set_SR_PIR()
Sittingroom_Light()
Bedroom_Light()
Set_BR_PIR()
Get_SR_Bright_Level()
Get_BR_Bright_Level()
print("___________________BR_Bright_High_Level =",BR_Bright_High_Level)
Cycle()
alarmUpdate("black")
visible = True
btnToggle = tk.Button(text="V", command=toggle)
btnToggle.place(x=9000, y=50)
print("Next alarm found = ",Nextnum)
First_Run = False
PrintAlarmList(start_alarm_list+Next)
def on_select(self, event):
self._reconnect_mqtt_client()
widget = event.widget
selection = widget.curselection()
if selection:
index = selection[0]
payload = widget.get(index)
self.mqtt_client.publish("frog", payload)
#if __name__ == "__main__":
root = tk.Tk()
## MQTT_Client.setup(root)
## mqtt_client = MQTT_Client(root)
root.mainloop()
print("Main loop termination time =", time.strftime("%A %b %d %H:%M:%S"))
if rpi==True:
try:
# Clean up the GPIOs for next time
GPIO.cleanup()
except KeyboardInterrupt:
GPIO.cleanup()