from machine import Pin, SoftI2C
from time import sleep
from bme680 import *
import ssd1306
import machine
import network
from umqtt.robust import MQTTClient
import sys


pwm = machine.PWM(machine.Pin(16), freq=50)

wifi = network.WLAN(network.STA_IF)

client = MQTTClient(client_id=b'esp32',
                    server=b'192.168.1.64',
                    port=1883,
                    user=b'patate',
                    password=b'patate',
                    keepalive=30,
                    ssl=False)

try:
    client.connect()
    print('Connection ok');
except Exception as e:
    print('Could not connect to MQTT server {}{}'.format(type(e).__name__, e))
    sys.exit()



# Fonction pour déplacer le servo moteur vers une position donnée
def set_position(position):
  # Convertion de la position en valeur de duty
  duty = int(position / 180 * 1023)
  # Envoi de la valeur de duty au servo moteur
  pwm.duty(duty)

i2c = SoftI2C(scl=Pin(22), sda=Pin(21))

bme = BME680_I2C(i2c=i2c)

# Définition de la tailler de l'écran oled
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)

if wifi.isconnected():
    print ("connecté au réseau wifi")
    print(wifi.ifconfig())

else:
    print ("NON connecté au réseau wifi")    

pin_led = Pin(2, mode=Pin.OUT) # Led sur l'ESP

ledR=Pin(14,Pin.OUT) # LED externe


def control(topic,msg):
    print(msg)
    if 'ledE' in topic:
        if 'true' in msg :
            pin_led.on()
        else :
            pin_led.off()
    elif 'ledR' in topic:
        if 'true' in msg :
            ledR.value(1)
        else :
            ledR.value(0)
    elif 'motor' in topic:
        
        if 'Droite' in msg :      
            set_position(10)
            time.sleep(0.4)
            set_position(0)
        else:
            set_position(20)
            time.sleep(0.4)
            set_position(0)


client.set_callback(control)
client.subscribe('esp32/ledE', 1)
client.subscribe('esp32/ledR', 1)
client.subscribe('esp32/motor', 1)

count=120

while True:
    try:
        client.check_msg()
        count+=1
        if (count>120) :
            # Données du BME680 :
            temperature = str(round(bme.temperature, 2))
            
            humidite = str(round(bme.humidity, 2))
            
            pression = str(round(bme.pressure, 2))
            
            gas = str(round(bme.gas/1000, 2))
            
            #print('temperature:', temperature,'|','humidite:', humidite,'|','pression:', pression, '|', 'Gas:', gas)
            
            oled.text(temperature + ' C', 0, 5) # Affichage de la temperatureerature
            oled.text(humidite + ' %', 0, 20) # Affichage de l'humiditeidité
            oled.text(pression + ' hPa', 0, 35) # Affichage de la pressionsion atmosphérique
            oled.text(gas + ' ppm', 0, 50) # Affichage du gaz
            oled.show() # Affiche les valeurs sur l'écran
            oled.fill(0) # Renitialise l'affichage
            
            bme680='{"temperature": '+ temperature + ',' + '"humidite": '+ humidite + ',' + '"pression": ' + pression + ',' + '"gas": ' + gas + '}'
            count=0
            client.publish('esp32/bme', bme680)
            print("Publish : " + str(bme680))
            
        time.sleep(0.1)
    except KeyboardInterrupt:
        print('Ctrl-C pressionsed...exiting')
        client.disconnect()
        sys.exit()






