If_i_only_knew101
Posts: 38
Joined: Mon Jul 19, 2021 12:54 am

smart system

Fri Sep 24, 2021 5:40 am

i got a job- (shut down) and start monday (12hr shifts for next 2 months at least) so yippee and bugger at same time...
if someone out there has time to finish this id be greatfull its for a good cause..
background- i have been volunteering at a mens shed (Australia), there are 2 disabled persons here both with PTSD and health issues (one served active duty OS)..
both are homeless- (one just cant live with (fears) people and can not afford rent alone,, the other (the vet) in part can not sleep inside a house or building).
in short the first bought a townace van and converted it to a bedsit complete with hotwater/shower, projector tv, microwave, etc. slowly over the past few years, recently adding air conditioning using a 12volt fridge compressor and a 12v indoor unit (fan/evaporator).
(for those who wish to know how- he stretched the spring in the expansion valve and turned the pin around recessed end in increasing the head pressure and he made it work)...
the vet saw all this realised its could a homebase, with freedom, transport,some mod cons like hot shower etc and copied it (alot of the older persons are watching and doing same as well).
because fear is a factor (in PTSD) i had something experimental in mind (the vet loved that idea. please dont judge me... :D )
They both put alot of thought and effort into the hardware side...
Base .problem was aircon can draw 18Amps on max setting, hotwater pulls 8A, microwave pulls around 200A etc. batteries hate going below 1?2 charge at any stage so its all got to be limited (the less batteries go below 1/2 charge the longer they last).
a batteries half charge is 12.00 volts while under load.
another problem with aircon is duty cycle switching on @ 24*C it will cycle without a break. it needs to cool to 24 then restart at about 26-27 to give compressor time off (help electrical starting surges by- once its on- run it / when its off- stop it, give it a break),
the unfinished code is

Code: Select all

#smartvan.py
from tkinter import Tk
from tkinter.ttk import *
import datetime

import smbus
DEVICE_BUS = 1
#DEVICE_ADDR = 0x12#, 0x11 security, 0x13#, 0x14
bus = smbus.SMBus(DEVICE_BUS)

import RPi.GPIO as GPIO
sensor = 21# gpio 21. pin 40.
GPIO.setmode(GPIO.BCM)
GPIO.setup(sensor, GPIO.IN, GPIO.PUD_DOWN)
previous_state = False
current_state = False

from ads1015 import ADS1015
ads1015 = ADS1015()
ads1015.set_mode('single')
ads1015.set_programmable_gain(2.048)
ads1015.set_sample_rate(1600)
reference = ads1015.get_reference_voltage()            
CHANNELS = ['in0/ref', 'in1/ref', 'in2/ref']

import os
type='Linux'
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

from gpiozero import CPUTemperature

from w1thermsensor import W1ThermSensor
#sensor ID and addresses
sensorID_Cab = "3c01d6070392"#  "28-3c01d6070392"
sensorID_Con = "3c01d60727c8"#  "28-3c01d60727c8"
sensorID_Evap = "3c01d6076a6a"#  "28-3c01d6076a6a"

window = Tk()
window.title("Systems Automatic Mode Rev 1.")
window.geometry('408x340') # ('408x310')
window.resizable(True, True)# expands window both ways x and y.

###################################################################### clock working #######################
def clock():
    date2_time = '  '
    date_time = datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S/%p")
    date,time1 = date_time.split()
    time2,time3 = time1.split('/')
    hour,minutes,seconds =  time2.split(':')
    if int(hour) > 11 and int(hour) < 24:
        time = str(int(hour) - 12) + ':' + minutes + ':' + seconds + ' ' + time3
    else:
        time = time2 + ' ' + time3
    time_label.config(text = time)
    date_label.config(text= date)
    date2_label.config(text = date2_time)
    time_label.after(1000, clock)

##################################################################### alarm error with alarm sound and END statement ###########
def alarm():
    main_time = datetime.datetime.now().strftime("%H:%M %p")
    alarm_time = get_alarm_time_entry.get()
    alarm_time1,alarm_time2 = alarm_time.split(' ')
    alarm_hour, alarm_minutes = alarm_time1.split(':')
    main_time1,main_time2 = main_time.split(' ')
    main_hour1, main_minutes = main_time1.split(':')
    if main_time2 == 'PM':
        main_hour = str(int(main_hour1) - 12)
    else:
        main_hour = main_hour1
    if int(alarm_hour) == int(main_hour) and int(alarm_minutes) == int(main_minutes) and main_time2 == alarm_time2:
        os.system('play -n synth %s sin %s' % (10000/1000, 1000)) ############# 10 sencond alarm at 1kHz ###########################
#        frequency = 1000 # Hertz
#        duration  = 10000 # milliseconds
        alarm_status_label.config(text='Time Is Up')

        get_alarm_time_entry.config(state='enabled')
        set_alarm_button.config(state='enabled')
        get_alarm_time_entry.delete(0,END)######################################## END is not defined  ########################
        alarm_status_label.config(text = '')
    else:
        alarm_status_label.config(text='Alarm Has Started')
        get_alarm_time_entry.config(state='disabled')
        set_alarm_button.config(state='disabled')
    alarm_status_label.after(1000, alarm)

############################################################### voltage display error using a conditional statement with a constant value ###########
def updateVolts():#Iterate over the channels and labels to update them in turn.
    for channel, label in zip(CHANNELS,labels):
        value = ads1015.get_compensated_voltage(channel=channel, reference_voltage=reference)
        current_volts = ('   {}  ---  {:6.3f} volts   '.format(channel, value))
        label.config(text = current_volts)
    window.after(1000,updateVolts)#Wait 1 second before updating again
 
def updateSolar():# in0 used to monitor solar volts of hotwater system.
    for channel in CHANNELS:
        value = ads1015.get_compensated_voltage(channel=channel, reference_voltage=reference)
        if channel == 'in0/ref':
#            current0_channel = ''
            current1_channel = 'Hotwater'
            if True:#using a conditional statement with a constant value ################################
                if value >= 2.000 and value <= 19.000:# voltage range of print solar voltage.
                    current_value = 'HW SOLAR'
                elif value <= 1.999:# voltage range of print no solar input.
                    current_value = 'HW NO SOLAR'
                elif value >= 19.001 and  value <= 22.500:# voltage range of print no solar input.
                    current_value = 'HW SOLAR'                   
                else:
                    current_value = 'WARNING: SOLAR SYSTEM OVERVOLTAGE'# print warning
                solar_label.config(text = current_value)
#                solar2_label.config(text = current0_value)
                power1_label.config(text = current1_channel)
                
            window.after(1000, updateSolar)

def updateMain():
    for channel in CHANNELS:# in1 used to monitor main solar bank. 
        value = ads1015.get_compensated_voltage(channel=channel, reference_voltage=reference)
        if channel == 'in1/ref':
            current2_channel = 'Solar'
            if True:# using a conditional statement with a constant value ##################################
                if value >= 2.000 and value <= 17.500:# voltage range of print solar voltage.
                    main_value = 'MAINS:SOLAR'
                elif value <= 1.999:# voltage range of print no solar input.
                    main_value = 'MAINS:NO SOLAR'
                elif value >= 17.501 and 22.500:# voltage range of print no solar input.
                    main_value = 'MAINS SOLAR'    
                else:
                    main_value = 'WARNING: MAINS SOLAR OVERVOLTAGE'    
                main_label.config(text = main_value)
                power2_label.config(text = current2_channel)
            window.after(1000, updateSolar)

###################################################### insert relay trip voltages for microwave, hotwater etc (high draw units) add relays here###
# bus.write_byte_data( 0x12, 1, 0x00)# condensor fan
# bus.write_byte_data( 0x12, 2, 0x00)# evaporator fan
# bus.write_byte_data( 0x12, 3, 0x00)# compressor
# bus.write_byte_data( 0x12, 4, 0x00)# hotwater
###################################################### note different old blokes have different needs so left blank for now ###################
def updateBattery():# in2 displays battery status.
    for channel in CHANNELS:
        value = ads1015.get_compensated_voltage(channel=channel, reference_voltage=reference)
        if channel == 'in2/ref':
            current3_channel = 'Battery'
            spacer_needed = ' '
            if True:# using a conditional statement with a constant value  #############################
                if value <= 11.000:# range in battery capacity.
                    battery_value = 'SYSTEM DEAD RECHARGE OR BURY NOW'# code stuck here instead of line 169 elif value >= 13.501 and value <= 13.800: 
                    data_value = 'HOTWATER SYSTEM Off'

             
                elif value >= 11.001 and value <= 11.999:# range in battery capacity
                    battery_value = 'SYSTEM DYING RECHARGE NOW'
                    data_value = 'HOTWATERR SYSTEM Off'
                   
                elif value >= 12.000 and value <= 12.200:# range in battery capacity.
                    battery_value = 'SYSTEM LOW RECHARGE NOW'
                    data_value = 'HOTWATER SYSTEM  Off'
       
                elif value >= 12.201 and value <= 13.000:# range in battery capacity.
                    battery_value =  'SYSTEM ON BATTERY'
                    data_value = 'HOTWATER SYSTEM  Off'

                    
                elif value >= 13.001 and value <= 13.250:# range for bulk mode charging
                    battery_value =  'SYSTEM BULK'
                    data_value = 'HOTWATER SYSTEM  Off'
                    
                elif value >= 13.251 and value <= 13.500:# range for bulk mode charging
                    battery_value =  'CHARGING SYSTEM BULK'
                    data_value = 'HOTWATER SYSTEM  On'

                elif value >= 13.501 and value <= 13.800:# range of float mode
                    battery_value = 'CHARGING SYSTEM FLOAT'
                    data_value = 'HOTWATER SYSTEM  On'
  
                elif value >= 13.801 and value <= 14.500:# range of absorbsion mode
                    battery_value = 'CHARGING SYSTEM ABSORBSION'
                    data_value = 'HOTWATER SYSTEM  On'
 
                elif value >= 14.501 and value <= 15.500:# calcium mode thresholds 15.500v restores full battery capacity in heavily discharged batteries
#                   (not calcified or sulphated sla's which require aditional venting and full 16v charge)
                    battery_value = 'CHARGING SYSTEM CALCIUM MODE'
                    data_value = 'HOTWATER SYSTEM  Off'


                elif value >= 15.501 and value <= 16.000:# voltage range to trip following code.
                    battery_value = 'SYSTEMS WARNING: CALCIIUM MODE'
                    data_value = 'TRIP SYSTEM NOW'
                 
                else: #value >= 16.001v trips following code.
                    battery_value = 'SYSTEMS WARNING:'
                    data_value = 'OVERVOLTAGE FAULT <16v'
                   
                battery_label.config(text = battery_value)
                data_label.config(text = data_value)
                power3_label.config(text = current3_channel)
                spacer_label.config(text = spacer_needed)
            window.after(1000, updateBattery)

####################################################### cpu temperature working ###########################################
def update_cpu_temperature():
    cpu1 = 'CPU Teperature'
    cpu = CPUTemperature()
    cpu_temp=(cpu.temperature)
    cpu_label.config(text = cpu1)
    cpu_label1.config(text = cpu_temp)

window.after(1000, update_cpu_temperature)

######################################################### security lights working ######################################### 
def security_lights():
    while True:
        light_button.config(state='enabled')
        bus.write_byte_data(0x11, 3, 0xFF)# security lights
        return

####################################################### security lights off working #####################################
def light_Stop():        
        bus.write_byte_data(0x11, 3, 0x00)# security lights
#        bus.write_byte_data(0x11, 1, 0x00)# light 1
#        bus.write_byte_data(0x11, 2, 0x00)# light 2
        return

######################################################## airconditing section ##########################################
    ################### Errors- switches airconditioner on from start wont turn off ############################
    ########################## grinds program down till clock updates seconds @ 3 second intervals ###############
    ######## note i dont care if temperature updates only update when ac is on ###############
def aircon():
    AC_button.config(state='enabled')
    if True:
        for mySensor in W1ThermSensor.get_available_sensors():# error redefining name 'mySensor' from outer scope (line 15).
            curSensorID = mySensor.id
            curTemp = mySensor.get_temperature()
            curTemp = round(curTemp,2)
    
            if curSensorID == sensorID_Cab:
                myTempCab = curTemp
                cab = ("  Cabin=  " + str(myTempCab) + "*C")
                if curTemp >= 24: #turns compressor on over 24*C
                    bus.write_byte_data(0x12, 3, 0xFF)# turns off compressor
                elif curTemp <= 24:#turns compressor off under 24*C
                    bus.write_byte_data(0x12, 3, 0x00)# turns on compressor
                cab_label.config(text = cab)

            if curSensorID == sensorID_Con:
                myTempCon = curTemp
                con = ("  Condenser=  " + str(myTempCon) + "*C")
                if curTemp >= 65:#turns condenser fan on over 65*C
                    bus.write_byte_data(0x12, 1, 0xFF)# turns on condensor fan
                elif curTemp <= 65:#turns condenser fan off under 65*C
                    bus.write_byte_data(0x12, 1, 0x00)# turns off condensor fan  changed for test.
                con_label.config(text = con)

            if curSensorID == sensorID_Evap:
                myTempEvap = curTemp
                evap = ("  Evaporator=  " + str(myTempEvap) + "*C")
                bus.write_byte_data(0x12, 2, 0xFF)# turns on indoorfan
                evap_label.config(text = evap)
                
            aircon.start()    
    window.after(1000, aircon)
#    return

######################################################## airconditioner stop working ########################################
def acStop():
    while True:
        aircon.stop()
        Stop_button.config(state='enabled')
        bus.write_byte_data(0x12, 1, 0x00)# condensor fan
        bus.write_byte_data(0x12, 2, 0x00)# evaporator fan
        bus.write_byte_data(0x12, 3, 0x00)# compressor
        return

###################################################### this section added but with errors and missing code #######
################################################################ oldies live/travel in high crime area ####################
#################### experimental deturrent ###################################
def Security():#pir sensor time pot set to 3 minutes of output high when tripped (so havent used sleep function) ###########
    while True:
        Security.start()
        try:
            sec_button.config(state='enabled')
            current_state = GPIO.input(sensor)
            if current_state != previous_state:
                previous_state = current_state
                os.system('play -n synth %s sin %s' % (duration/22.275, frequency))#  plays 22.275Hz/sec infrasound for duration sensor is high (2.5+ sconds).
                #sound frequency is through hdmi tvs (note hdmi and pi audio output(video/sound jack) is really neded as option here)######
                # insert code- gpio16* (prefered*) generating frequency output = 7Hz/sec for duration of sensor high (pwr gpio may be required?).
                #gpio16* conected to transistor through resistor to inside led light (load=3W) A x v = W (V=5, W=3, A=0.6(600mA) can gpio16 handle this??. 
                #lights and sounds are experimental and may need adjusting for desired temporary effects (nothing permanent).
                #idea is if you can not stay in a area it makes it hard to rob and 22.275 causes vomitting in most people (good chance of dna evidence left).
        window.after(1000, Security)#unexpected indent#

######################################################## password protection turns security pir off
def pass_word():
    while True:
        UserName = input ("Enter Username: ")
        PassWord = input ("Enter Password: ")
        if UserName == 'bob' and PassWord == 'rainbow123':
            disarm()
        else:
            Security()#this turns pir on but really i want it to trip lights and sound for 3 minutes with every false try.
        password1_label.config(text = UserName)
        password1_labe2.config(text = PassWord)
    window.after(1000, pass_word) 

def disarm():
    while True:
        Security.stop() #code here for: turn Security/PIR off
        disarm_value = 'System Disarmed'
        disarm_label.config(text = disarm_value)
    window.after(1000, pass_word)
            
################################################ tk tabs windows #######################################################
tabs_control = Notebook(window)
clock_tab = Frame(tabs_control)
alarm_tab = Frame(tabs_control)
systems_tab = Frame(tabs_control)
ac_tab = Frame(tabs_control)

tabs_control.add(clock_tab, text='Voltages.')
tabs_control.add(alarm_tab, text='Alarms.')
tabs_control.add(systems_tab, text='Systems.')
tabs_control.add(ac_tab, text='AirConditioner.')

tabs_control.pack(expand = 1, fill ="both")

date2_label = Label(clock_tab, font = 'calibri 5 bold', foreground = 'black')
date2_label.pack(anchor='n') #position (top)
date_label = Label(clock_tab, font = 'calibri 15 bold', foreground = 'black')
date_label.pack(anchor='n') #position (top)
time_label = Label(clock_tab, font = 'calibri 27 bold', foreground = 'black') # added module here
time_label.pack(anchor='center')

power1_label = Label(clock_tab, font = 'Times 13 bold', foreground='black')
power1_label.pack(anchor='s')
volts_label1 = Label(clock_tab, font = 'Times 22 bold', foreground='black')
volts_label1.pack(anchor='s')
power2_label = Label(clock_tab, font = 'Times 13 bold', foreground='black')
power2_label.pack(anchor='s')
volts_label2 = Label(clock_tab, font = 'Times 22 bold', foreground='black')
volts_label2.pack(anchor='s')
power3_label = Label(clock_tab, font = 'Times 13 bold', foreground='black')
power3_label.pack(anchor='s')
volts_label3 = Label(clock_tab, font = 'Times 22 bold', foreground='black')
volts_label3.pack(anchor='s')
labels = [volts_label1, volts_label2, volts_label3]

get_alarm_time_entry = Entry(alarm_tab, font = 'calibri 15 bold')
get_alarm_time_entry.pack(anchor='center')
alarm_instructions_label = Label(alarm_tab, font = 'calibri 12 bold', text = "Enter Alarm Time. Eg -> 01:30 PM, 01 -> Hour, 30 -> Minutes")
alarm_instructions_label.pack(anchor='s')

spacer_label = Label(alarm_tab, font = 'calibri 15 bold', foreground = 'black')
spacer_label.pack(anchor='n') #position

sec_button = Button(alarm_tab, text = "Alarm On", state='active', command=lambda:[Security()])
sec_button.pack(anchor='s')

spacer_label = Label(alarm_tab, font = 'calibri 15 bold', foreground = 'black')
spacer_label.pack(anchor='n') #position

sec_label = Label(alarm_tab, font = 'calibri 15 bold', foreground = 'black')
sec_label.pack(anchor='n') #position

set_alarm_button = Button(alarm_tab, text = "Set Alarm", command=alarm)
set_alarm_button.pack(anchor='s')
alarm_status_label = Label(alarm_tab, font = 'calibri 15 bold')

spacer_label = Label(alarm_tab, font = 'calibri 15 bold', foreground = 'black')
spacer_label.pack(anchor='n') #position

light_button = Button(alarm_tab, text = "Security Lights", state='active', command=lambda:[security_lights()])
light_button.pack(anchor='s')
Stop_button = Button(alarm_tab, text = "Lights Off", state='active', command=lambda:[light_Stop()])
Stop_button.pack(anchor='s')

spacer_label = Label(alarm_tab, font = 'calibri 15 bold', foreground = 'black')
spacer_label.pack(anchor='n') #position

password1_label = Label(alarm_tab, font = 'calibri 15 bold', foreground = 'black')
password1_label.pack(anchor='n') #position
password2_label = Label(alarm_tab, font = 'calibri 15 bold', foreground = 'black')
password2_label.pack(anchor='n') #position

disarm_label = Label(alarm_tab, font = 'calibri 15 bold', foreground = 'black')
disarm_label.pack(anchor='n') #position

alarm_status_label.pack(anchor='s')

spacer_label = Label(ac_tab, font = 'calibri 15 bold', foreground = 'black')
spacer_label.pack(anchor='n') #position
cpu_label = Label(ac_tab, font = 'calibri 15 bold', foreground = 'black')
cpu_label.pack(anchor='n') #position
cpu_label1 = Label(ac_tab, font = 'calibri 15 bold', foreground = 'black')
cpu_label1.pack(anchor='n') #position
spacer_label = Label(ac_tab, font = 'calibri 15 bold', foreground = 'black')
spacer_label.pack(anchor='n') #position

cab_label = Label(ac_tab, font = 'calibri 15 bold', foreground = 'black')
cab_label.pack(anchor='n') #position
con_label = Label(ac_tab, font = 'calibri 15 bold', foreground = 'black')
con_label.pack(anchor='n') #position
evap_label = Label(ac_tab, font = 'calibri 15 bold', foreground = 'black')
evap_label.pack(anchor='n') #position

spacer_label = Label(ac_tab, font = 'calibri 15 bold', foreground = 'black')
spacer_label.pack(anchor='n') #position
AC_button = Button(ac_tab, text = "A/C On", state='active', command=lambda:[aircon()])
AC_button.pack(anchor='s')
Stop_button = Button(ac_tab, text = "A/C Off", state='active', command=lambda:[acStop()])
Stop_button.pack(anchor='s')

spacer_label = Label(systems_tab, font = 'calibri 15 bold', foreground = 'black')
spacer_label.pack(anchor='n') #position
solar_label = Label(systems_tab, font = 'calibri 15 bold', foreground = 'black')
solar_label.pack(anchor='n') #position
main_label = Label(systems_tab, font = 'calibri 15 bold', foreground = 'black')
main_label.pack(anchor='center') #position
spacer_label = Label(systems_tab, font = 'calibri 15 bold', foreground = 'black')
spacer_label.pack(anchor='n') #position
battery_label = Label(systems_tab, font = 'calibri 15 bold', foreground = 'black')
battery_label.pack(anchor='n') #position
spacer_label = Label(systems_tab, font = 'calibri 15 bold', foreground = 'black')
spacer_label.pack(anchor='n') #position
data_label = Label(systems_tab, font = 'calibri 15 bold', foreground = 'black')
data_label.pack(anchor='s') #position

window.after_idle(updateBattery)
window.after_idle(updateVolts) #Call the updateVolts function after the gui has loaded
window.after_idle(updateSolar)
window.after_idle(updateMain)

window.after_idle(aircon)
window.after_idle(update_cpu_temperature)

window.after_idle(security)
window.after_idle(pass_word)
window.after_idle(disarm)

window.after_idle(security_lights)
window.after_idle(Stop)

pass_word()
#Security()
#aircon()
clock()
window.mainloop()
a couple of sections have wrong coding or unfinished as i havent learnt it, and ii really wanted import or add

Code: Select all

import io
import picamera
import logging
import socketserver
from threading import Condition
from http import server

PAGE="""\
<html>
<head>
<title>picamera MJPEG streaming demo</title>
</head>
<body>
<h1>PiCamera MJPEG Streaming Demo</h1>
<img src="stream.mjpg" width="640" height="480" />
</body>
</html>
"""

class StreamingOutput(object):
    def __init__(self):
        self.frame = None
        self.buffer = io.BytesIO()
        self.condition = Condition()

    def write(self, buf):
        if buf.startswith(b'\xff\xd8'):
            # New frame, copy the existing buffer's content and notify all
            # clients it's available
            self.buffer.truncate()
            with self.condition:
                self.frame = self.buffer.getvalue()
                self.condition.notify_all()
            self.buffer.seek(0)
        return self.buffer.write(buf)

class StreamingHandler(server.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/':
            self.send_response(301)
            self.send_header('Location', '/index.html')
            self.end_headers()
        elif self.path == '/index.html':
            content = PAGE.encode('utf-8')
            self.send_response(200)
            self.send_header('Content-Type', 'text/html')
            self.send_header('Content-Length', len(content))
            self.end_headers()
            self.wfile.write(content)
        elif self.path == '/stream.mjpg':
            self.send_response(200)
            self.send_header('Age', 0)
            self.send_header('Cache-Control', 'no-cache, private')
            self.send_header('Pragma', 'no-cache')
            self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=FRAME')
            self.end_headers()
            try:
                while True:
                    with output.condition:
                        output.condition.wait()
                        frame = output.frame
                    self.wfile.write(b'--FRAME\r\n')
                    self.send_header('Content-Type', 'image/jpeg')
                    self.send_header('Content-Length', len(frame))
                    self.end_headers()
                    self.wfile.write(frame)
                    self.wfile.write(b'\r\n')
            except Exception as e:
                logging.warning(
                    'Removed streaming client %s: %s',
                    self.client_address, str(e))
        else:
            self.send_error(404)
            self.end_headers()

class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer):
    allow_reuse_address = True
    daemon_threads = True

with picamera.PiCamera(resolution='640x480', framerate=24) as camera:
    output = StreamingOutput()
    camera.start_recording(output, format='mjpeg')
    try:
        address = ('XYZ IP', 6500) ################################# i need this to be able to be accessed from a 'abc IP' address thats
                                   ######## not on same router of wifi. ie my pi is wifi XYZ, my phone is abc.
        server = StreamingServer(address, StreamingHandler)
        server.serve_forever()
    finally:
        camera.stop_recording()
so they can see the van while away.
the following codes i have got working so i can walk away done but the oldies may have trouble opening programs instead of just booting it all from start as one. and tradesman in me says "if ur gonna screw it, Screw it Proper..."
voltage/relay side by the time i saw it grow into a nightmare it was too late to do init (i hadnt learnt that existed when i started)

Code: Select all

from tkinter import Tk
from tkinter.ttk import *
import datetime

from gpiozero import CPUTemperature
#from w1thermsensor import W1ThermSensor# temp one wire pi config enabled.
#temperature sensor data to pi pin 3, Vin 3.3v pin 1, ground to pin 9.

import smbus
DEVICE_BUS = 1
DEVICE_ADDR = 0x11, 0x12#, 0x13#, 0x14
bus = smbus.SMBus(DEVICE_BUS)
# relay 0x10 unused conflicts with RTC on same addr.
# defult relay 0x11 = security system
# 1 & 4- security lights. # 2- headlights. # 3- flood lights.
# relay 0x12 =  battery systems.
# 1 Air Conditioner. # 2 Hotwater.
# 3 Audio Alarm. #4 Main Battery Bank Isolation (300A slave).
# relay 0x13 = Other Systems.
# 1 Microwave Inverter. # 2 Shower Light (timed for 2 persons @ 4mins each)
# 3 door locks. # 4 engine imobiliser with e paper screen in dash (i2c).

#0x14 is taken by ADS1015.
from ads1015 import ADS1015
ads1015 = ADS1015()
ads1015.set_mode('single')
ads1015.set_programmable_gain(2.048)
ads1015.set_sample_rate(1600)
reference = ads1015.get_reference_voltage()            
CHANNELS = ['in0/ref', 'in1/ref', 'in2/ref']
import os
type='Linux'

window = Tk()
window.title("Systems Automatic Mode Rev 1.")
window.geometry('408x340') # ('408x310')
window.resizable(True, True)# expands window both ways x and y.

def clock():
    date2_time = '  '
    date_time = datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S/%p")
    date,time1 = date_time.split()
    time2,time3 = time1.split('/')
    hour,minutes,seconds =  time2.split(':')
    if int(hour) > 11 and int(hour) < 24:
        time = str(int(hour) - 12) + ':' + minutes + ':' + seconds + ' ' + time3
    else:
        time = time2 + ' ' + time3
    time_label.config(text = time)
    date_label.config(text= date)
    date2_label.config(text = date2_time)
    time_label.after(1000, clock)

def alarm():
    main_time = datetime.datetime.now().strftime("%H:%M %p")
    alarm_time = get_alarm_time_entry.get()
    alarm_time1,alarm_time2 = alarm_time.split(' ')
    alarm_hour, alarm_minutes = alarm_time1.split(':')
    main_time1,main_time2 = main_time.split(' ')
    main_hour1, main_minutes = main_time1.split(':')
    if main_time2 == 'PM':
        main_hour = str(int(main_hour1) - 12)
    else:
        main_hour = main_hour1
    if int(alarm_hour) == int(main_hour) and int(alarm_minutes) == int(main_minutes) and main_time2 == alarm_time2:

        os.system('beep -f 5000')# beep through Linux sys.

        alarm_status_label.config(text='Time Is Up')

        get_alarm_time_entry.config(state='enabled')
        set_alarm_button.config(state='enabled')
        get_alarm_time_entry.delete(0,END)# END is not defined  ########################
        alarm_status_label.config(text = '')
    else:
        alarm_status_label.config(text='Alarm Has Started')
        get_alarm_time_entry.config(state='disabled')
        set_alarm_button.config(state='disabled')
    alarm_status_label.after(1000, alarm)

def update_cpu_temperature():
    cpu1 = 'CPU Teperature'
    cpu = CPUTemperature()
    cpu_temp=(cpu.temperature)
    cpu_label.config(text = cpu1)
    cpu_label1.config(text = cpu_temp)

window.after(1000, update_cpu_temperature)

#def update_sensor():
    
  #     temperature = sensor.get_temperature()
    #    AirCon_sensor = ("Cabin temperature = %s celsius" % temperature)
     #   aircon_label = (text = AirCon_sensor)
    
#window.after(1000, update_sensor)

def updateVolts():#Iterate over the channels and labels to update them in turn.
    for channel, label in zip(CHANNELS,labels):
        value = ads1015.get_compensated_voltage(channel=channel, reference_voltage=reference)
        current_volts = ('   {}  ---  {:6.3f} volts   '.format(channel, value))
        label.config(text = current_volts)
    window.after(1000,updateVolts)#Wait 1 second before updating again
 
def updateSolar():# in0 used to monitor solar volts of hotwater system.
    for channel in CHANNELS:
        value = ads1015.get_compensated_voltage(channel=channel, reference_voltage=reference)
        if channel == 'in0/ref':
#            current0_channel = ''
            current1_channel = 'Hotwater'
            if True:#using a conditional statement with a constant value ################################
                if value >= 2.000 and value <= 19.000:# voltage range of print solar voltage.
                    current_value = 'HW SOLAR'
                elif value <= 1.999:# voltage range of print no solar input.
                    current_value = 'HW NO SOLAR'
                elif value >= 19.001 and  22.500:# voltage range of print no solar input.
                    current_value = 'HW SOLAR'                   
                else:
                    current_value = 'WARNING: SOLAR SYSTEM OVERVOLTAGE'# print warning
                solar_label.config(text = current_value)
#                solar2_label.config(text = current0_value)
                power1_label.config(text = current1_channel)
                
            window.after(1000, updateSolar)


def updateMain():
    for channel in CHANNELS:# in1 used to monitor main solar bank. 
        value = ads1015.get_compensated_voltage(channel=channel, reference_voltage=reference)
        if channel == 'in1/ref':
            current2_channel = 'Solar'
            if True:# using a conditional statement with a constant value ##################################
                if value >= 2.000 and value <= 17.500:# voltage range of print solar voltage.
                    main_value = 'MAINS:SOLAR'
                elif value <= 1.999:# voltage range of print no solar input.
                    main_value = 'MAINS:NO SOLAR'
                elif value >= 17.501 and 22.500:# voltage range of print no solar input.
                    main_value = 'MAINS SOLAR'    
                else:
                    main_value = 'WARNING: MAINS SOLAR OVERVOLTAGE'    
                main_label.config(text = main_value)
                power2_label.config(text = current2_channel)
            window.after(1000, updateSolar)

def updateBattery():# in2 displays battery status.
    for channel in CHANNELS:
        value = ads1015.get_compensated_voltage(channel=channel, reference_voltage=reference)
        if channel == 'in2/ref':
            current3_channel = 'Battery'
            spacer_needed = ' '
            
## note ## check relay function against the hash on or off ##
            if True:# using a conditional statement with a constant value  #############################
                if value <= 11.000:# range in battery capacity.
                    battery_value = 'SYSTEM DEAD RECHARGE OR BURY NOW'# code stuck here instead of line 169 elif value >= 13.501 and value <= 13.800: 
                    data_value = 'HOTWATER SYSTEM Off'
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 1, 0x00)# turns off ac.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 2, 0x00)# ensures hotwater system is off and hasnt latched on by other means.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 3, 0xFF)# turns off relay 3 audio alarm.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 4, 0xFF)# turns on relay 4 and 300A slave relay (using NC/COM contacts) ON DISCONNECTING BATTERY FROM CIRCUIT.

             
                elif value >= 11.001 and value <= 11.999:# range in battery capacity
                    battery_value = 'SYSTEM DYING RECHARGE NOW'
                    data_value = 'HOTWATERR SYSTEM Off'
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 1, 0x00)# turns off ac.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 2, 0x00)# ensures hotwater system is off and hasnt latched on by other means.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 3, 0x00)# turns off relay 3 audio alarm.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 4, 0x00)# turns on relay 4 and 300A slave relay (using NC/COM contacts) ON DISCONNECTING BATTERY FROM CIRCUIT.
                   
                elif value >= 12.000 and value <= 12.200:# range in battery capacity.
                    battery_value = 'SYSTEM LOW RECHARGE NOW'
                    data_value = 'HOTWATER SYSTEM  Off'
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 1, 0xFF)# turns On ac.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 2, 0x00)# ensures hotwater system is off and hasnt latched on by other means.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 3, 0x00)# turns off relay 3 audio alarm.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 4, 0x00)# turns on relay 4 and 300A slave relay (using NC/COM contacts) ON DISCONNECTING BATTERY FROM CIRCUIT.
       
                elif value >= 12.201 and value <= 13.000:# range in battery capacity.
                    battery_value =  'SYSTEM ON BATTERY'
                    data_value = 'HOTWATER SYSTEM  Off'
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 1, 0xFF)# turns On ac.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 2, 0x00)# ensures hotwater system is off and hasnt latched on by other means.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 3, 0x00)# turns off relay 3 audio alarm.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 4, 0x00)# turns on relay 4 and 300A slave relay (using NC/COM contacts) ON DISCONNECTING BATTERY FROM CIRCUIT.

                    
                elif value >= 13.001 and value <= 13.250:# range for bulk mode charging
                    battery_value =  'SYSTEM BULK'
                    data_value = 'HOTWATER SYSTEM  Off'
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 1, 0xFF)# turns On ac.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 2, 0x00)# ensures hotwater system is off and hasnt latched on by other means.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 3, 0x00)# turns off relay 3 audio alarm.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 4, 0x00)# turns on relay 4 and 300A slave relay (using NC/COM contacts) ON DISCONNECTING BATTERY FROM CIRCUIT.
                    
                elif value >= 13.251 and value <= 13.500:# range for bulk mode charging
                    battery_value =  'CHARGING SYSTEM BULK'
                    data_value = 'HOTWATER SYSTEM  On'
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 1, 0xFF)# turns On ac.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 2, 0x00)# ensures hotwater system is off and hasnt latched on by other means.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 3, 0x00)# turns off relay 3 audio alarm.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 4, 0x00)# turns on relay 4 and 300A slave relay (using NC/COM contacts) ON DISCONNECTING BATTERY FROM CIRCUIT.

                elif value >= 13.501 and value <= 13.800:# range of float mode
                    battery_value = 'CHARGING SYSTEM FLOAT'
                    data_value = 'HOTWATER SYSTEM  On'
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 1, 0xFF)# turns On ac.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 2, 0xFF)# ensures hotwater system is off and hasnt latched on by other means.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 3, 0x00)# turns off relay 3 audio alarm.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 4, 0x00)# turns on relay 4 and 300A slave relay (using NC/COM contacts) ON DISCONNECTING BATTERY FROM CIRCUIT.
  
                elif value >= 13.801 and value <= 14.500:# range of absorbsion mode
                    battery_value = 'CHARGING SYSTEM ABSORBSION'
                    data_value = 'HOTWATER SYSTEM  On'
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 1, 0xFF)# turns On ac.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 2, 0xFF)# ensures hotwater system is off and hasnt latched on by other means.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 3, 0x00)# turns off relay 3 audio alarm.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 4, 0x00)# turns on relay 4 and 300A slave relay (using NC/COM contacts) ON DISCONNECTING BATTERY FROM CIRCUIT.
 
                elif value >= 14.501 and value <= 15.500:# calcium mode thresholds 15.500v restores full battery capacity in heavily discharged batteries
#                   (not calcified or sulphated sla's which require aditional venting and full 16v charge)
                    battery_value = 'CHARGING SYSTEM CALCIUM MODE'
                    data_value = 'HOTWATER SYSTEM  Off'
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 1, 0xFF)# turns On ac.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 2, 0x00)# ensures hotwater system is off and hasnt latched on by other means.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 3, 0xFF)# turns On relay 3 audio alarm.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 4, 0x00)# turns on relay 4 and 300A slave relay (using NC/COM contacts) ON DISCONNECTING BATTERY FROM CIRCUIT.


                elif value >= 15.501 and value <= 16.000:# voltage range to trip following code.
                    battery_value = 'SYSTEMS WARNING: CALCIIUM MODE'
                    data_value = 'TRIP SYSTEM NOW'
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 1, 0xFF)# turns On ac.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 2, 0x00)# ensures hotwater system is off and hasnt latched on by other means.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 3, 0x00)# turns off relay 3 audio alarm.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 4, 0x00)# turns on relay 4 and 300A slave relay (using NC/COM contacts) ON DISCONNECTING BATTERY FROM CIRCUIT.
                 
                else: #value >= 16.001v trips following code.
                    battery_value = 'SYSTEMS WARNING:'
                    data_value = 'OVERVOLTAGE FAULT <16v'
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 1, 0x00)# turns Off ac.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 2, 0x00)# switches off relay 2 hotwater (system may be in fault or calcium mode).
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 3, 0xFF)# audio warning of fault or calcium mode
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 3, 0x00)# turns off relay 3 audio alarm.
#                    bus.write_byte_data(DEVICE_ADDR, 0x12, 4, 0xFF) # turns on relay 4 and isolates batteries from overvoltage faults <+16v, 
                   
                battery_label.config(text = battery_value)
                data_label.config(text = data_value)
                power3_label.config(text = current3_channel)
                spacer_label.config(text = spacer_needed)
            window.after(1000, updateBattery)



## control tabs ##
tabs_control = Notebook(window)
clock_tab = Frame(tabs_control)
alarm_tab = Frame(tabs_control)
systems_tab = Frame(tabs_control)
ac_tab = Frame(tabs_control)

tabs_control.add(clock_tab, text='Voltages.')
tabs_control.add(alarm_tab, text='Alarms.')
tabs_control.add(systems_tab, text='Systems.')
tabs_control.add(ac_tab, text='AirConditioner.')

tabs_control.pack(expand = 1, fill ="both")

date2_label = Label(clock_tab, font = 'calibri 5 bold', foreground = 'black')
date2_label.pack(anchor='n') #position (top)
date_label = Label(clock_tab, font = 'calibri 15 bold', foreground = 'black')
date_label.pack(anchor='n') #position (top)
time_label = Label(clock_tab, font = 'calibri 27 bold', foreground = 'black') # added module here
time_label.pack(anchor='center')

power1_label = Label(clock_tab, font = 'Times 13 bold', foreground='black')
power1_label.pack(anchor='s')
volts_label1 = Label(clock_tab, font = 'Times 22 bold', foreground='black')
volts_label1.pack(anchor='s')
power2_label = Label(clock_tab, font = 'Times 13 bold', foreground='black')
power2_label.pack(anchor='s')
volts_label2 = Label(clock_tab, font = 'Times 22 bold', foreground='black')
volts_label2.pack(anchor='s')
power3_label = Label(clock_tab, font = 'Times 13 bold', foreground='black')
power3_label.pack(anchor='s')
volts_label3 = Label(clock_tab, font = 'Times 22 bold', foreground='black')
volts_label3.pack(anchor='s')
labels = [volts_label1, volts_label2, volts_label3]

get_alarm_time_entry = Entry(alarm_tab, font = 'calibri 15 bold')
get_alarm_time_entry.pack(anchor='center')
alarm_instructions_label = Label(alarm_tab, font = 'calibri 12 bold', text = "Enter Alarm Time. Eg -> 01:30 PM, 01 -> Hour, 30 -> Minutes")
alarm_instructions_label.pack(anchor='s')
set_alarm_button = Button(alarm_tab, text = "Set Alarm", command=alarm)
set_alarm_button.pack(anchor='s')
alarm_status_label = Label(alarm_tab, font = 'calibri 15 bold')
alarm_status_label.pack(anchor='s')

spacer_label = Label(ac_tab, font = 'calibri 15 bold', foreground = 'black')
spacer_label.pack(anchor='n') #position
cpu_label = Label(ac_tab, font = 'calibri 15 bold', foreground = 'black')
cpu_label.pack(anchor='n') #position
cpu_label1 = Label(ac_tab, font = 'calibri 15 bold', foreground = 'black')
cpu_label1.pack(anchor='n') #position
#aircon_label = Label(ac_tab, font = 'calibri 15 bold', foreground = 'black')
#aircon_label.pack(anchor='n')

spacer_label = Label(systems_tab, font = 'calibri 15 bold', foreground = 'black')
spacer_label.pack(anchor='n') #position
solar_label = Label(systems_tab, font = 'calibri 15 bold', foreground = 'black')
solar_label.pack(anchor='n') #position
main_label = Label(systems_tab, font = 'calibri 15 bold', foreground = 'black')
main_label.pack(anchor='center') #position
spacer_label = Label(systems_tab, font = 'calibri 15 bold', foreground = 'black')
spacer_label.pack(anchor='n') #position
battery_label = Label(systems_tab, font = 'calibri 15 bold', foreground = 'black')
battery_label.pack(anchor='n') #position
spacer_label = Label(systems_tab, font = 'calibri 15 bold', foreground = 'black')
spacer_label.pack(anchor='n') #position
data_label = Label(systems_tab, font = 'calibri 15 bold', foreground = 'black')
data_label.pack(anchor='s') #position

##################  still to do  #######################
#temp_label = Label(battery_tab, font = 'calibri 31 bold', foreground = 'black') # added module here
#temp_label.pack(anchor='center')

#window.after_idle(update_sensor)

window.after_idle(update_cpu_temperature)
window.after_idle(updateBattery)
window.after_idle(updateVolts) #Call the updateVolts function after the gui has loaded
window.after_idle(updateSolar)
window.after_idle(updateMain)

clock()
window.mainloop()
and aircon side

Code: Select all

from tkinter import Tk
from tkinter.ttk import *

import smbus
DEVICE_BUS = 1
DEVICE_ADDR = 0x12
bus = smbus.SMBus(DEVICE_BUS)

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

from w1thermsensor import W1ThermSensor
#sensor ID and addresses
sensorID_Cab = "3c01d6070392"#  "28-3c01d6070392"
sensorID_Con = "3c01d60727c8"#  "28-3c01d60727c8"
sensorID_Evap = "3c01d6076a6a"#  "28-3c01d6076a6a"

window = Tk()
window.title("Systems Automatic Mode Rev 1.")
window.geometry('408x340') # ('408x310')
window.resizable(True, True)# (False, True) expands length ways
    
def get_Temp():    
    for mySensor in W1ThermSensor.get_available_sensors():# error redefining name 'mySensor' from outer scope (line 15).
        curSensorID = mySensor.id
        curTemp = mySensor.get_temperature()
        curTemp = round(curTemp,2)

        if curSensorID == sensorID_Cab:
            myTempCab = curTemp
            cab = ("  Cabin=  " + str(myTempCab) + "*C")
            if curTemp >= 24: #turns compressor on over 24*C
                bus.write_byte_data(DEVICE_ADDR, 3, 0xFF)# turns off compressor
            elif curTemp <= 24:#turns compressor off under 24*C
                bus.write_byte_data(DEVICE_ADDR, 3, 0x00)# turns on compressor
            cab_label.config(text = cab)
            
        elif curSensorID == sensorID_Con:
            myTempCon = curTemp
            con = ("  Condenser=  " + str(myTempCon) + "*C")
            if curTemp >= 65:#turns condenser fan on over 65*C
                bus.write_byte_data(DEVICE_ADDR, 1, 0xFF)# turns on condensor fan
            elif curTemp <= 65:#turns condenser fan off under 65*C
                bus.write_byte_data(DEVICE_ADDR, 1, 0x00)# turns off condensor fan  changed for test.
            con_label.config(text = con)
                    
        elif curSensorID == sensorID_Evap:
            myTempEvap = curTemp
            evap = ("  Evaporator=  " + str(myTempEvap) + "*C")
#            bus.write_byte_data(DEVICE_ADDR, 2, 0xFF)# turns on indoorfan
            evap_label.config(text = evap)
                
    window.after(1000, get_Temp)

tabs_control = Notebook(window)

ac_tab = Frame(tabs_control)
tabs_control.add(ac_tab, text='airconditioner.')
tabs_control.pack(expand = 1, fill ="both")


cab_label = Label(ac_tab, font = 'calibri 15 bold', foreground = 'black')
cab_label.pack(anchor='n') #position
con_label = Label(ac_tab, font = 'calibri 15 bold', foreground = 'black')
con_label.pack(anchor='n') #position
evap_label = Label(ac_tab, font = 'calibri 15 bold', foreground = 'black')
evap_label.pack(anchor='n') #position

window.after_idle(get_Temp)

window.mainloop()
to kill the aircon ive been using this

Code: Select all

#fan.py

import smbus
DEVICE_BUS = 1
DEVICE_ADDR = 0x12
bus = smbus.SMBus(DEVICE_BUS)

bus.write_byte_data(DEVICE_ADDR, 1, 0x00)# turns on indoorfan
bus.write_byte_data(DEVICE_ADDR, 2, 0x00)
bus.write_byte_data(DEVICE_ADDR, 3, 0x00)
  
exit
Without this site i wouldnt have gotten this far.
Thankyou.

Return to “Assistive technology and accessibility”