-
-
Save JayPalm/8bfd836b696c28ec5dc1f6b5b4dd18ea to your computer and use it in GitHub Desktop.
microPython - mqtt_as example with HiveMQ Broker (TLS)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import network | |
import uasyncio as asyncio | |
from machine import Pin | |
from mqtt_as.original import MQTTClient, config | |
config["ssid"] = "<SSID>" | |
config["wifi_pw"] = "<WIFI_PW" | |
config["client_id"] = "uPy-client-3943" | |
config["port"] = 8883 | |
config["server"] = "48c156647b6a4157b8f16210196bb4bf.s2.eu.hivemq.cloud" | |
config["user"] = "uPy-test-client" | |
config["password"] = "TestClientCredentialsForExample" | |
config["keepalive"] = 60 | |
config["ssl"] = True | |
config["ssl_params"] = { | |
"server_hostname": "48c156647b6a4157b8f16210196bb4bf.s2.eu.hivemq.cloud" | |
} | |
loop = asyncio.get_event_loop() | |
# Subscription callback | |
async def flash(): | |
print("LED ON") | |
await asyncio.sleep_ms(500) | |
print("LED OFF") | |
# sub_led = Pin(12, Pin.OUT) # Blue | |
def sub_cb(topic, msg, retained): | |
print(f"MSG Recieved: {topic} - {msg}") | |
c, r = [int(x) for x in msg.decode().split(" ")] | |
print( | |
"Topic = {} Count = {} Retransmissions = {} Retained = {}".format( | |
topic.decode(), c, r, retained | |
) | |
) | |
loop.create_task(flash()) | |
# Demonstrate scheduler is operational and TLS is nonblocking. | |
async def heartbeat(): | |
# led = LED(2) # Green | |
while True: | |
await asyncio.sleep_ms(2000) | |
print("LED TOGGLED") | |
# wifi_led = LED(1) # LED on for WiFi fail/not ready yet | |
async def wifi_han(state): | |
if state: | |
print("wifi_led off") | |
else: | |
print("wifi_led on") | |
print("Wifi is ", "up" if state else "down") | |
await asyncio.sleep(1) | |
# If you connect with clean_session True, must re-subscribe (MQTT spec 3.1.2.4) | |
async def conn_han(client): | |
await client.subscribe("result", 1) | |
async def main(client): | |
await client.connect() | |
n = 0 | |
await asyncio.sleep(2) # Give broker time | |
while True: | |
print("publish", n) | |
# If WiFi is down the following will pause for the duration. | |
await client.publish("result", "{} {}".format(n, client.REPUB_COUNT), qos=1) | |
n += 1 | |
await asyncio.sleep(20) # Broker is slow | |
# Define configuration | |
config["subs_cb"] = sub_cb | |
config["connect_coro"] = conn_han | |
config["wifi_coro"] = wifi_han | |
# Set up client | |
MQTTClient.DEBUG = True # Optional | |
client = MQTTClient(config) | |
loop.create_task(heartbeat()) | |
try: | |
loop.run_until_complete(main(client)) | |
finally: | |
client.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment