Skip to content

Instantly share code, notes, and snippets.

@neosarchizo
Created November 1, 2022 04:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neosarchizo/94a9168dbe2efd4cabb241e8eeb08104 to your computer and use it in GitHub Desktop.
Save neosarchizo/94a9168dbe2efd4cabb241e8eeb08104 to your computer and use it in GitHub Desktop.
MicroPython - ESP32 WiFi MQTT 통신 : subscribe
from network import WLAN, STA_IF
from time import time, sleep
from usocket import socket
from mqttclient import MQTTClient
SERVER = 'broker.mqttdashboard.com'
PORT = 1883
CLIENT_ID = 'esp32'
TOPIC = 'devicemart'
wlan = WLAN(STA_IF)
wlan.active(True)
start_time = time()
if not wlan.isconnected():
print('Connecting to network...')
wlan.connect('devicemart', 'devicemart1')
while not wlan.isconnected():
if time() - start_time > 15:
print('Connecting WiFi Timeout!')
quit()
config = wlan.ifconfig()
print(config)
print('IP : ' + config[0])
print('SUBNET : ' + config[1])
print('GATEWAY : ' + config[2])
print('DNS : ' + config[3])
def on_subscribe(topic, msg):
print('topic: {}'.format(topic))
print('msg: {}'.format(msg))
client = MQTTClient(CLIENT_ID, SERVER, PORT)
client.set_callback(on_subscribe)
client.connect()
client.subscribe(TOPIC)
while True:
client.check_msg()
sleep(0.3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment