Skip to content

Instantly share code, notes, and snippets.

@m0nochr0me
Created August 10, 2021 01:31
Show Gist options
  • Save m0nochr0me/c616e73db0d1e8a6cdbeff8a77c8ef86 to your computer and use it in GitHub Desktop.
Save m0nochr0me/c616e73db0d1e8a6cdbeff8a77c8ef86 to your computer and use it in GitHub Desktop.
ESP8266 MQTT Lamp
from umqtt.simple import MQTTClient
import machine
import utime
import ntptime
import ubinascii
import sys
ESSID = "myWiFiSSID"
PWD = "myWiFiPassword"
MQTTSRV = "192.168.1.1"
MQTTPORT = 1883
MQTTUSER = "myuser"
MQTTPWD = "MyPa55w0rD"
command_topics = ("lamp0", "lamp1")
INTERVAL = 1
lamp0 = machine.Pin(4, machine.Pin.OUT, value=0)
lamp1 = machine.Pin(5, machine.Pin.OUT, value=0)
last = 0
err = 0
resync = 0
client = None
def cb_msg(topic, msg):
#print("RCV: {} - {}".format(topic, msg))
channel = topic.decode().split("/")[-1]
if channel == "lamp0":
lamp0.on() if msg == b'1' else lamp0.off()
elif channel == "lamp1":
lamp1.on() if msg == b'1' else lamp1.off()
def initmclient():
mclient_id = ubinascii.hexlify("AutoLamp")
mclient = MQTTClient(mclient_id, MQTTSRV, MQTTPORT, MQTTUSER, MQTTPWD)
mclient.set_callback(cb_msg)
mclient.connect()
for topic in command_topics:
mclient.subscribe(topic)
return mclient
def initwlan():
network.phy_mode(2) #802.11g
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
sta_if.active(True)
sta_if.connect(ESSID, PWD)
while not sta_if.isconnected():
pass
#print("WLAN CFG:", sta_if.ifconfig())
return sta_if
initwlan()
rtc = machine.RTC()
def synctime():
try:
ntptime.settime()
#print("NTP SYNC OK")
except:
#print('NTP ERROR')
utime.sleep(10)
machine.reset()
sys.exit(0)
synctime()
def initmqtt():
global client
if client:
try:
client.disconnect()
except:
#print("MQTT DISCONNECT ERROR")
pass
try:
client = initmclient()
#print('MQTT INIT OK')
except:
#print('MQTT INIT ERROR')
utime.sleep(10)
machine.reset()
sys.exit(0)
initmqtt()
while True:
utime.sleep(INTERVAL)
resync += 1
if resync > 300:
synctime()
initmqtt()
resync = 0
try:
client.check_msg()
except:
err += 1
#print('MQTT CHECK ERROR')
if err > 10:
#print('MQTT CHECK FATAL')
utime.sleep(10)
machine.reset()
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment