# Learn more MicroPython with MQTT: https://RandomNerdTutorials.com/micropython-mqtt-publish-ds18b10-esp32-esp8266/ | |
import time | |
from umqttsimple import MQTTClient | |
import ubinascii | |
import machine | |
import micropython | |
import network | |
import esp | |
from machine import Pin | |
esp.osdebug(None) | |
import gc | |
gc.collect() | |
ssid = 'REPLACE_WITH_YOUR_SSID' | |
password = 'REPLACE_WITH_YOUR_PASSWORD' | |
ADAFRUIT_IO_URL = b'io.adafruit.com' | |
ADAFRUIT_USERNAME = b'' | |
ADAFRUIT_IO_KEY = b'' | |
ADAFRUIT_IO_FEEDNAME1 = b'temperature' | |
client_id = ubinascii.hexlify(machine.unique_id()) | |
mqtt_feedname1 = bytes('{:s}/feeds/{:s}'.format(ADAFRUIT_USERNAME, ADAFRUIT_IO_FEEDNAME1), 'utf-8') | |
last_message = 0 | |
message_interval = 30 | |
station = network.WLAN(network.STA_IF) | |
station.active(True) | |
station.connect(ssid, password) | |
while station.isconnected() == False: | |
pass | |
print('Connection successful') | |
def connect_mqtt(): | |
global client_id, ADAFRUIT_IO_URL | |
client = MQTTClient(client_id, ADAFRUIT_IO_URL, user=ADAFRUIT_USERNAME, password=ADAFRUIT_IO_KEY) | |
client.connect() | |
print('Connected to %s MQTT broker' % (ADAFRUIT_IO_URL)) | |
return client | |
def restart_and_reconnect(): | |
print('Failed to connect to MQTT broker. Reconnecting...') | |
time.sleep(10) | |
machine.reset() | |
def read_sensor(): | |
return b'1' | |
try: | |
client = connect_mqtt() | |
except OSError as e: | |
restart_and_reconnect() | |
while True: | |
try: | |
if (time.time() - last_message) > message_interval: | |
temp = read_sensor() | |
print(temp) | |
client.publish(mqtt_feedname1, temp) | |
last_message = time.time() | |
except OSError as e: | |
restart_and_reconnect() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment