from mqtt_as import MQTTClient, config
import uasyncio as asyncio
# Local configuration
config['ssid'] = 'Wokwi-GUEST' # Optional on ESP8266
config['wifi_pw'] = ''
config['server'] = 'broker.emqx.io' # Change to suit e.g. 'iot.eclipse.org'
config['client_id'] = 'cxyProject1Light111111111'
async def messages(client): # Respond to incoming messages
# If MQTT V5is used this would read
# async for topic, msg, retained, properties in client.queue:
async for topic, msg, retained in client.queue:
print(topic.decode(), msg.decode(), retained)
async def up(client): # Respond to connectivity being (re)established
print('TP3: Up!')
while True:
await client.up.wait() # Wait on an Event
client.up.clear()
await client.subscribe('v1/china/ujs/cs/is/cxy/devices/light1/rpc/request', 1) # renew subscriptions
async def main(client):
print('TP2: In main')
await client.connect()
for coroutine in (up, messages):
asyncio.create_task(coroutine(client))
n = 0
while True:
print('Waiting 5 seconds before sending data ...')
await asyncio.sleep(5)
print('publish', n)
# If WiFi is down the following will pause for the duration.
await client.publish('v1/china/ujs/cs/is/cxy/devices/light1/rpc/response', '{}'.format(n), qos = 1)
n += 1
config["queue_len"] = 1 # Use event interface with default queue size
MQTTClient.DEBUG = True # Optional: print diagnostic messages
print('TP0')
client = MQTTClient(config)
print('TP1')
try:
asyncio.run(main(client))
finally:
client.close() # Prevent LmacRxBlk:1 errors