from machine import Pin, PWM
from utime import sleep_ms
from umqtt.simple import MQTTClient
import network

r = PWM(Pin(18),duty=0)
g = PWM(Pin(19),duty=0)
b = PWM(Pin(21),duty=0)

r.duty(1023) #ทำให้หลอดติดสีแดงในตอนแรก
g.duty(0)
b.duty(0)

wifi_ssid = "Wokwi-GUEST"
wifi_pwd = ""

MQTT_BROKER = "mqtt.netpie.io"  
MQTT_CLIENT = "55f2409e-0eb4-4b4c-b502-f8e3bcf82dd0" # Client ID
MQTT_USER = "6Xbvq3aburaroXx92p58HWLS9aegL5VY" # Token
MQTT_PWD = "XLV8EfXnf4XQ7naKnYoSXi4vJbA6PX7R" # Secret

def wifi_connect():
    	wlan = network.WLAN(network.STA_IF)
        wlan.active(False)
        wlan.active(True)
    	if not wlan.isconnected():
        		print('connecting to network...')
        		wlan.connect(wifi_ssid, wifi_pwd)
        		while not wlan.isconnected():
            			pass
    	print('network config:', wlan.ifconfig())

def sub_callback(topic, msg):
    	print((topic, msg))
            
    	if topic == b'@msg/color':
        		if msg == b'red':
            			r.duty(1023)
            			g.duty(0)
            			b.duty(0)
        		elif msg == b'green':
            			r.duty(0)
            			g.duty(1023)
            			b.duty(0)
        		elif msg == b'blue':
            			r.duty(0)
            			g.duty(0)
            			b.duty(1023)

def init_client():
    	global client
    	print("Trying to connect to MQTT Broker.")
    	try:
        		client = MQTTClient(MQTT_CLIENT, MQTT_BROKER, port=1883, 		user=MQTT_USER,password=MQTT_PWD)
        		client.connect()
        		print("Connected to ",MQTT_BROKER)
        		topic_sub = b'@msg/#'
        		client.set_callback(sub_callback)
        		client.subscribe(topic_sub)
    	except:
        		print("Trouble to init mqtt.") 

wifi_connect()  # connect to WiFi network
init_client()

while True:
    	client.check_msg()
    	sleep_ms(500)