import network
import time
import ujson
from machine import Pin
from umqtt.simple import MQTTClient
# =====================================================
# MQTT Parameters
# =====================================================
MQTT_CLIENT_ID = "vent-stepper-subscriber"
MQTT_BROKER = "broker.hivemq.com"
MQTT_TOPIC = "smart/vent/system"
# =====================================================
# Stepper Pins
# =====================================================
STEP_PIN = Pin(14, Pin.OUT)
DIR_PIN = Pin(12, Pin.OUT)
# =====================================================
# WiFi Connection
# =====================================================
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect("Wokwi-GUEST", "")
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
# =====================================================
# MQTT Connection
# =====================================================
print("Connecting to MQTT...", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
# target position
position = 0
target = 0
STEP_DELAY = 800
# =====================================================
# Step Function
# =====================================================
def step(dir):
DIR_PIN.value(dir)
STEP_PIN.value(1)
time.sleep_us(STEP_DELAY)
STEP_PIN.value(0)
time.sleep_us(STEP_DELAY)
# 2
# =====================================================
# MQTT Callback
# =====================================================
def on_msg(topic, msg):
global target
data= ujson.loads(msg)
state = data["state"]
print("msg: ", state)
if state == "OPEN":
target = 200
elif state == "HALF":
target = 100
elif state == "CLOSE":
target = 0
# 1
# =====================================================
# MQTT Setup
# =====================================================
client.set_callback(on_msg)
client.connect()
client.subscribe(MQTT_TOPIC)
print("Connected and subscribed")
# 3
# =====================================================
# Main Loop
# =====================================================
while True:
client.check_msg()
if position < target:
step(1)
position +=1
elif position > target:
step(0)
position -=1
time.sleep_ms(1)