from machine import Pin, PWM, Timer
from umqtt.simple import MQTTClient
import ujson
import os
import sys
CHANNEL_TOKEN = 'token_h8pD5j9nQGbIzmeh'
CHANNEL_NAME = 'lightTrafficControl'
RESOURCE_NAME1 = 'green'
RESOURCE_NAME2 = 'red'
RESOURCE_NAME3 = 'yellow'
MQTT_SERVER = 'mqtt.beebotte.com'
MQTT_USER = 'token:' + CHANNEL_TOKEN
MQTT_TOPIC1 = CHANNEL_NAME + '/' + RESOURCE_NAME1
MQTT_TOPIC2 = CHANNEL_NAME + '/' + RESOURCE_NAME2
MQTT_TOPIC3 = CHANNEL_NAME + '/' + RESOURCE_NAME3
greenLed_pin = Pin(14, Pin.OUT)
redLed_pin = Pin(13, Pin.OUT)
yellowLed_pin = Pin(12, Pin.OUT);
greenst=False
redst=False
yellowst=False
greenLed_pin(greenst)
redLed_pin(redst)
yellowLed_pin(yellowst)
PING_PERIOD = 120
pingTimer = Timer(0)
def handlePingTimerInt(timer):
try:
client.ping()
print('Ping')
except Exception as e:
print('Ping error: ',e)
def mqtt_callback(topic, msg):
msgback= b'{"data":false,"ispublic":true}'
global greenst
global redst
global yellowst
try:
topic = topic.decode('utf-8')
json_data = ujson.loads(msg)
dt = json_data.get("data")
print(f"{topic}: {msg}",dt)
if dt is None:
print("No Data")
return
if not isinstance(dt, bool):
print("Bool error")
return
if topic == MQTT_TOPIC1 and dt!=greenst:
greenLed_pin.value(dt)
redLed_pin.value(0)
yellowLed_pin.value(0)
client.publish(MQTT_TOPIC2,msgback, qos=0)
client.publish(MQTT_TOPIC3,msgback, qos=0)
greenst=dt
redst=False
yellowst=False
elif topic == MQTT_TOPIC2 and dt!=redst :
greenLed_pin.value(0)
redLed_pin.value(dt)
yellowLed_pin.value(0)
client.publish(MQTT_TOPIC1,msgback, qos=0)
client.publish(MQTT_TOPIC3,msgback, qos=0)
greenst=False
redst=dt
yellowst=False
elif topic == MQTT_TOPIC3 and dt!=yellowst:
greenLed_pin.value(0)
redLed_pin.value(0)
yellowLed_pin.value(dt)
client.publish(MQTT_TOPIC1,msgback, qos=0)
client.publish(MQTT_TOPIC2,msgback, qos=0)
greenst=False
redst=False
yellowst=dt
except Exception as e:
print(f"Error: {e}")
random_num = int.from_bytes(os.urandom(3), 'little')
mqtt_client_id = bytes('client_' + str(random_num), 'utf-8')
client = MQTTClient(mqtt_client_id,MQTT_SERVER,user=MQTT_USER,password='',keepalive=PING_PERIOD*2)
try:
client.connect()
pingTimer.init(period=PING_PERIOD*1000, mode=Timer.PERIODIC, callback=handlePingTimerInt)
except Exception as e:
print('could not connect to MQTT server {}{}'.format(type(e).__name__, e))
sys.exit()
client.set_callback(mqtt_callback)
client.subscribe(MQTT_TOPIC1)
client.subscribe(MQTT_TOPIC2)
client.subscribe(MQTT_TOPIC3)
while True:
try:
client.wait_msg()
except KeyboardInterrupt:
print('Ctrl-C pressed...exiting')
client.disconnect()
pwm.deinit()
sys.exit()