from utime import sleep
# from sargs import *
# ----- BEGIN sargs.py ------
# Simulator seems to have trouble with instantiating the objects below in other files (syntax error at the end of the file)
# Exact same code works on the real micropython board, so I'll just assume it's simulator weirdness
from machine import Pin, I2C, PWM, UART, unique_id, Timer
import mhz19
import logging
logger = logging.getLogger("sargs")
import ssd1306

import network
from umqtt.simple import MQTTClient

# WiFi piekļuves punkta uzstādījumi
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""

# MQTT brokera uzstādījumi
MQTT_CLIENT_ID="PDw2Fg0JDCcLJiEyHwkDFzc"
MQTT_USERNAME=MQTT_CLIENT_ID
MQTT_PASSWORD="sH+dJJeEMasUs9cMRPLR+VnV"
MQTT_CHANNEL="1620901"
MQTT_WRITE_API_KEY="S4WBV7H1QM768WBF"
mqtt = None
class LEDPin(Pin):
  def turn_on(self):
    self.value(1)
  def turn_off(self):
    self.value(0)

  def ieslegt(self):
    self.value(1)
  def izslegt(self):
    self.value(0)

def pagaidit(v):
  sleep(v)

# 
LED_RED = LEDPin(33, Pin.OUT)
LED_YELLOW = LEDPin(25, Pin.OUT)
LED_GREEN = LEDPin(26, Pin.OUT)
PIN_LDR = Pin(34, Pin.IN)
PIN_ARM = Pin(35, Pin.IN, Pin.PULL_UP)
PIN_LCD_DATA = Pin(21, pull=Pin.PULL_UP)
PIN_LCD_CLOCK = Pin(22, pull=Pin.PULL_UP)
LED_LEFT_EYE = LEDPin(23, Pin.OUT)
LED_RIGHT_EYE = LEDPin(19, Pin.OUT)

sensor_uart = 2

if unique_id() == b"\xd8\xa0\x1d\x65\x27\x60":
  logger.info("ESP32-D4 detected, using UART 1")
  sensor_uart = 1

CO2_SENSOR = mhz19.MHZ19Sim(UART(sensor_uart, 9600, timeout=1000))

PWM_BUZZER = PWM(Pin(32, Pin.OUT), 1000)


def wifi_check():
  sta_if = network.WLAN(network.STA_IF)
  sta_if.active(True)
  sta_if.connect(WIFI_SSID, WIFI_PASSWORD)
  logger.info("attempting connection to WiFI")
  sleep(5)
  if sta_if.isconnected():
    logger.info("WiFi connection OK, IP address: %s" % sta_if.ifconfig()[0])
    global mqtt
    mqtt = MQTTClient(MQTT_CLIENT_ID, "mqtt3.thingspeak.com", user=MQTT_USERNAME, password=MQTT_PASSWORD)
    mqtt.connect()

  else:
    logger.info("WiFi connection failed")

SCREEN = None

# initializing screen can fail if it doesn't respond to I2C commands, blink red LED and reboot
try:
    SCREEN = ssd1306.SSD1306_I2C(128, 64, I2C(0, sda=PIN_LCD_DATA, scl=PIN_LCD_CLOCK))
except OSError:
    logger.error("Ekrans neatbild")
    for _ in range(10):
        LED_RED.value(1)
        sleep(0.5)
        LED_RED.value(0)
        sleep(0.5)
    sys.exit()

co2_measurement = None

def handle_co2_measurement(m):
  co2_measurement = co2_measurement

timer_ticks = 0
def background_task():
  """ Background task is executed periodically (~10Hz), from a timer callback.
  It should handle re-drawing screen, handling WiFi status polling, 
  calibration statemachine (and probably something else I haven't thought about yet)
  """

  SCREEN.fill(0)

  if co2_measurement is None:
    SCREEN.text("Sensors uzsilst", 0, 0, 1)
  else:
    SCREEN.text("CO2: %d ppm" % reading, 0, 0, 1)
  

  # since user can change the threshold in main.py, use the state of output LEDs
  if LED_GREEN.value():
    SCREEN.text("LABS GAISS!", 0, 20, 2)
  elif LED_YELLOW.value():
    SCREEN.text("ATVER LOGU!", 0, 20, 2)
  elif LED_RED.value():
    SCREEN.text("AARGH!", 0, 20, 2)

  SCREEN.show()


timer = Timer(3)
timer.init(mode=Timer.PERIODIC)
timer_channel = timer.channel(Timer.A, freq=10)
timer_channel.irq(handler=background_task, trigger=Timer.TIMEOUT)



# ----- END sargs.py ------


# Pārbaude pēc ieslēgšanās: ieslēdzam visas gaismas diodes pēc kārtas un pēc tam izslēdzam tās
pins = [LED_GREEN, LED_YELLOW, LED_RED, LED_LEFT_EYE, LED_RIGHT_EYE]
for p in pins:
  p.turn_on()
  sleep(0.5)
sleep(1)
for p in reversed(pins):
  p.turn_off()
  sleep(0.5)

# Ekrāna pārbaude
SCREEN.text('Sveika, pasaule!', 0, 0, 1)
SCREEN.show()


wifi_check()


CO2_SENSOR.set_sim_co2(420)

while True:
  measurement = CO2_SENSOR.get_co2_measurement()

  handle_co2_measurement(measurement)

  for pin in [LED_RED, LED_YELLOW, LED_RED]:
    pin.turn_off()

  if reading < 500:
    LED_GREEN.turn_on()
  elif reading < 1000:
    LED_YELLOW.turn_on()  
  elif reading > 1000:
    LED_RED.turn_on()
      
    
  sleep(60)