Device is D1 Mini V3.0.0.
It works better when serial cable is not plugged into PC.
WiFi coverage is really good at test spot.
I'm pretty sure that there is something with MQTT connection, but don't know how to test and repair.
Serial monitor (within Thonny) thus not print out anything, except while fresh restart of ESP and Thonny.
Code: Select all
from umqtt.simple import MQTTClient
import machine
import utime
import ubinascii
from config import SERVER, COMMAND_TOPIC, STATE_TOPIC, AVAILABILITY_TOPIC
#sensor setup and read function
import sensor_DS18X20
import gc
gc.collect()
#onboard LED is on pin 2
LED = machine.Pin(2, machine.Pin.OUT, value=1)
#disply module
import OLED
OLED.redraw("--", "starting", ".")
#unique ID
CLIENT = None
CLIENT_ID = ubinascii.hexlify(machine.unique_id())
#MQTT messages handling background function
def new_msg(topic, msg):
print("Received {}".format(msg))
if msg == b"on":
LED.value(0)
CLIENT.publish(STATE_TOPIC, "on")
elif msg == b"off":
LED.value(1)
CLIENT.publish(STATE_TOPIC, "off")
gc.collect()
#main loop
#def main():
#global CLIENT
CLIENT = MQTTClient(CLIENT_ID, SERVER)
CLIENT.set_callback(new_msg)
CLIENT.connect()
CLIENT.subscribe(COMMAND_TOPIC)
# Publish as available once connected
CLIENT.publish(AVAILABILITY_TOPIC, "online")
print("Connected to {}, subscribed to {} topic".format(SERVER, COMMAND_TOPIC))
temp_current = 99
temp_min = 18
temp_max = 23
temp_offset = 1
rstate = "idle"
last_temp_time = utime.time()
gc.collect()
try:
while 1:
CLIENT.check_msg()
dt = utime.time() - last_temp_time
OLED.redraw(str(temp_current), rstate, str(dt))
if dt > 5:
# read sensor
temp_current = round(sensor_DS18X20.temperature,1)
# after read, some time is needed for conversion (750 ms from used example)
# therefore UI and states update is set in later time (next 'if')
if dt > 6:
# save time of this update
last_temp_time = utime.time()
# evalueate temperature and set state
print(temp_current)
if temp_current < temp_min:
print("set to heating")
rstate = "heating"
if temp_current > temp_max:
print("set to cooling")
rstate = 'cooling'
if (temp_current > (temp_min + temp_offset)) and (temp_current < (temp_max - temp_offset)):
print("set to idle")
rstate = 'idle'
# refresh displays
#OLED.redraw(str(temp_current), rstate, str(dt))
except OSError as exc:
print("EXCEPTION")
print(exc.errno)