Advertisement
hellbringer616

Thermostatv2.5

Oct 6th, 2020
1,318
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.65 KB | None
  1. import time
  2. import logging
  3. import datetime
  4. import board
  5. import adafruit_dht
  6. import gpiozero as gpio
  7. from importlib import reload
  8. from tkinter import *
  9.  
  10. # Function to make time stamps for logging.
  11. def timestamp():
  12.     return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S:')
  13.  
  14. # Set logging Level: logging.INFO, logging.WARNING, logging.ERROR, logging.DEBUG
  15. logging.basicConfig(filename='thermostat.log',level=logging.INFO)
  16.  
  17.  
  18. logging.info(timestamp() + "Initializing sensor and relays...")
  19.  
  20.  
  21. # Initialize the dht device, with data pin connected to:
  22. dhtDevice = adafruit_dht.DHT22(board.D17)
  23.  
  24. # Set GPIO pins for relays, set to OPEN state (0), use LED function to toggle on and off
  25. relay1 = gpio.LED(18, initial_value=0)
  26. relay2 = gpio.LED(23, initial_value=0)
  27. logging.info(timestamp() + "waiting 5 seconds to save relay wear...")
  28. time.sleep(5.0)
  29.  
  30. # Cause i don't know how else to trigger it... :)
  31. while True:
  32.     # Would love to make a function; except when i do it complains about "temperature_f is not defined" even when i set it as a global variable... the error comes from the guiTemp and guiTempText within the tkinter GUI code.
  33.     try:
  34.         # Get data from dht sensor
  35.         temperature = dhtDevice.temperature
  36.         temperature_f = round(temperature * (9 / 5) + 32)
  37.  
  38.     except RuntimeError as error:
  39.         # Errors happen fairly often, DHT's are hard to read, just log and keep going
  40.         logging.error(timestamp() + error.args[0])
  41.  
  42. # Set default values to avoid NPE errors.
  43.     currentMode = "NULL"
  44.     setTemp = 68
  45.  
  46. # Thermostat function
  47.     def thermostat():
  48.         global currentMode
  49.         global temperature
  50.         global temperature_f
  51.         guiTemp.config(text=temperature_f)
  52.         logging.info(timestamp() + currentMode)
  53.         logging.info(timestamp() + "Set temp set to: " + str(setTemp))
  54.  
  55. # Heating logic
  56.         if currentMode == "Heat":
  57.             if relay2.value == 1:
  58.                 relay2.off()
  59.                 logging.debug(timestamp() + "Relay2 (cool) enabled; disabling")
  60.             if temperature_f < setTemp:
  61.                 logging.debug(timestamp() + "Temp: {:.1f}".format(temperature_f))
  62.                 logging.info(timestamp() + "Temperature less than desired temp: Heating")
  63.                 if relay1.value == 0:
  64.                     relay1.on()
  65.  
  66.             else:
  67.                 logging.debug(timestamp() + "Temp: {:.1f}".format(temperature_f))
  68.                 logging.info(timestamp() + "Not running")
  69.                 if relay1.value == 1:
  70.                     relay1.off()
  71.                     logging.debug(timestamp() + "disabling relay1 (heat)")
  72.  
  73. # Cooling logic
  74.         if currentMode == "Cool":
  75.             if relay1.value == 1:
  76.                 relay1.off()
  77.                 logging.debug(timestamp() + "Relay1 (heat) enabled; disabling")
  78.             if temperature_f > setTemp:
  79.                 logging.debug(timestamp() + "Temp: {:.1f}".format(temperature_f))
  80.                 loggin.info(timestamp() + "Temperature greater than desired temp: Cooling")
  81.                 if relay2.value == 0:
  82.                     relay2.on()
  83.             else:
  84.                 logging.debug(timestamp() + "Temp: {:.1f}".format(temperature_f))
  85.                 logging.info(timestamp() + "Not running")
  86.                 if relay2.value == 1:
  87.                     relay2.off()
  88.                     logging.debug(timestamp() + "disabling relay2 (cool)")
  89.  
  90. # Repeat of above try function to get GUI to update; cause i'm lazy.
  91.         try:
  92.             # Print the values to the serial port
  93.             temperature = dhtDevice.temperature
  94.             temperature_f = round(temperature * (9 / 5) + 32)
  95.  
  96.         except RuntimeError as error:
  97.             # Errors happen fairly often, DHT's are hard to read, just keep going
  98.             logging.error(timestamp() + error.args[0])
  99.         main.after(3000,thermostat) # Runs the loop every 3 seconds within the function.
  100.  
  101.     main = Tk() # Main tkinter function.
  102.     main.title("Thermostat")
  103.     main.geometry("800x600") # Sets window resolution
  104.     main.configure(bg="black", cursor="none") # Sets background color of the window to black and disables the Mouse Cursor.
  105.     main.overrideredirect(True) # Makes fullscreen
  106.  
  107.     guiTempText = Label(main, text="Current Temperature: ", font=(None, 25), fg="white", bg="black")
  108.     guiTemp = Label(main, text=temperature_f, font=(None, 30), fg="white", bg="black")
  109.     guiTemp.config(text=temperature_f)
  110.     guiTempText.place(relx = 0.5, rely= 0.10, anchor = CENTER)
  111.     guiTemp.place(relx = 0.5, rely= 0.20, anchor = CENTER)
  112.     setTempLabel = Label(main, font=(None, 20), text=setTemp, fg="white", bg="black")
  113.     setTempLabel.place(relx = 0.5, rely= 0.40, anchor = CENTER)
  114.  
  115. # Create setTemp adjustment buttons and place them in the GUI
  116.     def tempPlusButtonClick():
  117.         global setTemp
  118.         setTemp = setTemp + 1
  119.         setTempLabel.config(text=setTemp)
  120.         print(setTemp)
  121.         return
  122.  
  123.     def tempMinusButtonClick():
  124.         global setTemp
  125.         setTemp = setTemp - 1
  126.         setTempLabel.config(text=setTemp)
  127.         logging.debug(timestamp() + setTemp)
  128.         return
  129.  
  130.     plusButton = Button(main, text="+", fg="white", bg="black", padx=20, pady=20, command=tempPlusButtonClick)
  131.     plusButton.place(relx = 0.4, rely= 0.40, anchor = CENTER)
  132.     minusButton = Button(main, text="-", fg="white", bg="black", padx=20, pady=20, command=tempMinusButtonClick)
  133.     minusButton.place(relx = 0.6, rely= 0.40, anchor = CENTER)
  134.  
  135. # Create currentMode set buttons and places them in the GUI
  136.     def heatButtonClick():
  137.         global currentMode
  138.         currentMode = "Heat"
  139.         currentModeLabel.config(text="Current Mode: " + currentMode)
  140.         logging.info(timestamp() + "Mode set to Heat")
  141.         return
  142.  
  143.     def coolButtonClick():
  144.         global currentMode
  145.         currentMode = "Cool"
  146.         currentModeLabel.config(text="Current Mode: " + currentMode)
  147.         logging.info(timestamp() + "Mode set to Cool")
  148.         return
  149.  
  150.     currentModeLabel = Label(main, text="Current Mode: " + currentMode, font=(None, 20), fg="white", bg="black")
  151.     currentModeLabel.place(relx = 0.5, rely= 0.55, anchor = CENTER)
  152.  
  153.     heatButton = Button(main, text="Heat", padx=30, pady=30, bg="red", command=heatButtonClick)
  154.     heatButton.place(relx = 0.4, rely= 0.70, anchor = CENTER)
  155.     coolButton = Button(main, text="Cool", padx=30, pady=30, bg="blue", command=coolButtonClick)
  156.     coolButton.place(relx = 0.6, rely= 0.70, anchor = CENTER)
  157.  
  158. # Run a loop every 3 seconds after the thermostat function to update the GUI
  159.     main.after(3000,thermostat)
  160. # Has to be here otherwise the program doesn't run.
  161.     main.mainloop()
  162.  
Advertisement
RAW Paste Data Copied
Advertisement