#Lab4.1_GPIO_multiLED

import network
from machine import Pin
import time
import ujson
from umqtt.simple import MQTTClient

# MQTT Server Parameters
MQTT_CLIENT_ID = "demo1"
MQTT_BROKER    = "broker.hivemq.com" #"broker.mqttdashboard.com"
MQTT_USER      = ""
MQTT_PASSWORD  = ""
MQTT_TOPIC     = "cnc1"

led_red = Pin(23, Pin.OUT)
led_yellow = Pin(22, Pin.OUT) 
led_green = Pin(21, Pin.OUT) 
led_blue = Pin(4, Pin.OUT)

button_red = Pin(5, Pin.IN)
button_yellow = Pin(18, Pin.IN)
button_green = Pin(19, Pin.IN)


print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
  print(".", end="")
  time.sleep(0.1)
print(" Connected!")
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
led_blue.on()
print("Connected!")

countProd = 0

while True:   
                          
 status_red = button_red.value() 
 status_yellow = button_yellow.value()   
 status_green = button_green.value()       
 
 if status_green == 1: countProd = 0
 if status_yellow ==1: countProd = countProd + status_yellow

 msgs = ujson.dumps({ 
    "cnc-alarm" : status_red, #if status_red == 1 ? True else False,
    "cnc-out-product" : status_yellow,
    "cnc-actual-product" : countProd,
    "cnc-reset-product" : status_green #if status_green == 1: True else: False
  })
 

 if status_red ==1:

  led_red.on()
  led_yellow.off() 
  led_green.off()
  print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, msgs))
  client.publish(MQTT_TOPIC, msgs)
  time.sleep(0.5)
  print("status tombol merah: ", status_red)

 elif status_yellow ==1:

  led_red.off()
  led_yellow.on()
  led_green.off()
  print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, msgs))
  client.publish(MQTT_TOPIC, msgs)
  time.sleep(0.5)
  print("status tombol kuning: ", status_yellow)

 elif status_green ==1:

  led_red.off()
  led_yellow.off() 
  led_green.on()
  print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, msgs))
  client.publish(MQTT_TOPIC, msgs)
  time.sleep(0.5)
  print("status tombol hijau: ", status_green)

 else:
  led_red.off()
  led_yellow.off() 
  led_green.off()
  

esp:0
esp:2
esp:4
esp:5
esp:12
esp:13
esp:14
esp:15
esp:16
esp:17
esp:18
esp:19
esp:21
esp:22
esp:23
esp:25
esp:26
esp:27
esp:32
esp:33
esp:34
esp:35
esp:3V3
esp:EN
esp:VP
esp:VN
esp:GND.1
esp:D2
esp:D3
esp:CMD
esp:5V
esp:GND.2
esp:TX
esp:RX
esp:GND.3
esp:D1
esp:D0
esp:CLK
r1:1
r1:2
led1:A
led1:C
led2:A
led2:C
led3:A
led3:C
r2:1
r2:2
r3:1
r3:2
btn1:1.l
btn1:2.l
btn1:1.r
btn1:2.r
btn2:1.l
btn2:2.l
btn2:1.r
btn2:2.r
btn3:1.l
btn3:2.l
btn3:1.r
btn3:2.r
r4:1
r4:2
r5:1
r5:2
r6:1
r6:2
led4:A
led4:C
r7:1
r7:2