-
-
Save JayPalm/fb5fd662b00d8147844987537315f760 to your computer and use it in GitHub Desktop.
micropython mqtt.simple example with HiveMQ broker
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 | |
from umqtt.simple import MQTTClient | |
network_config = {"ssid": "<ssid>", "wifi_pw": "<wifi_pw>"} | |
sta_if = network.WLAN(network.STA_IF) | |
sta_if.active(True) | |
sta_if.connect(network_config["ssid"], network_config["wifi_pw"]) | |
time.sleep(5) | |
sta_if.ifconfig() | |
def sub_cb(topic, msg): | |
print((topic, msg)) | |
config = {} | |
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" | |
} | |
def main(config=config): | |
client = MQTTClient(**config) | |
client.set_callback(sub_cb) | |
client.connect() | |
client.subscribe("foo") | |
val = 0 | |
while True: | |
try: | |
client.publish("result", f"Result: {val}") | |
print(f"Published: result - {val}") | |
client.check_msg() | |
val += 1 | |
time.sleep(5) | |
except KeyboardInterrupt: | |
print("Ended by user") | |
client.disconnect() | |
break | |
except Exception as err: | |
print("Error encountered:") | |
print(err) | |
break | |
if __name__=="__main__": | |
main(config) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment