 # -*- coding:UTF-8 -*-
 #! /usr/bin/python3
import RPi.GPIO as GPIO
import Adafruit_DHT
import time
import subprocess

from board import SCL, SDA
import busio
from PIL import Image, ImageDraw, ImageFont
import adafruit_ssd1306

DHT_SENSOR = Adafruit_DHT.DHT22
DHT_PIN = 24

HUMIDIFICATEUR_PIN = 21
HUMIDITE_MIN = 70
HUMIDITE_MAX = 85

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# huimidifcateur
GPIO.setup(HUMIDIFICATEUR_PIN,GPIO.OUT)
# Create the I2C interface.
i2c = busio.I2C(SCL, SDA)

# Create the SSD1306 OLED class.
# The first two parameters are the pixel width and pixel height.  Change these
# to the right size for your display!
disp = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c)

# Clear display.
disp.fill(0)
disp.show()

# Create blank image for drawing.
# Make sure to create image with mode '1' for 1-bit color.
width = disp.width
height = disp.height
image = Image.new("1", (width, height))

# Get drawing object to draw on image.
draw = ImageDraw.Draw(image)

# Draw a black filled box to clear the image.
draw.rectangle((0, 0, width, height), outline=0, fill=0)

# Draw some shapes.
# First define some constants to allow easy resizing of shapes.
padding = -2
top = padding
bottom = height - padding
# Move left to right keeping track of the current x position for drawing shapes.
x = 0

# Load default font.
font = ImageFont.load_default()


while True:
    draw.rectangle((0, 0, width, height), outline=0, fill=0)
    
    humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
    if humidity is not None and temperature is not None:
        humidity_inf = "Humidity="+str(humidity)+"%".format(humidity)
        draw.text((x+45, top + 0), "Sechage", font=font, fill=255)
        draw.text((x+10, top + 10), "Temperature = {0:0.1f} C".format(temperature), font=font, fill=255)
        draw.text((x+15, top + 20), "Humidite = {0:0.1f} %".format(humidity), font=font, fill=255)
        # Display image.
        disp.image(image)
        disp.show()
        time.sleep(0.1)
        if humidity < HUMIDITE_MIN:
            GPIO.output(HUMIDIFICATEUR_PIN,GPIO.HIGH)
        if humidity > HUMIDITE_MAX:
            GPIO.output(HUMIDIFICATEUR_PIN,GPIO.LOW)
    else:
        print("Failed to retrieve data from humidity sensor")
    