MQTT Subscribe WORKING SCRIPT

All ESP8266 boards running MicroPython.
Official boards are the Adafruit Huzzah and Feather boards.
Target audience: MicroPython users with an ESP8266 board.
Post Reply
marine_hm
Posts: 16
Joined: Mon Oct 18, 2021 10:45 am
Location: USA: Eastern NC
Contact:

MQTT Subscribe WORKING SCRIPT

Post by marine_hm » Tue Dec 07, 2021 5:36 am

Code: Select all

# MQTT Subscribe
# By: Nick Sebring
# 11-20-2021


# *****IMPORT NECESSARY MODULES******** #
import machine
import network
import time
from umqtt.simple import MQTTClient


# *****CONNECT TO NETWORK************** #
wlan = network.WLAN(network.STA_IF)
wlan.connect('YOUR_SSID', 'YOUR_PASSWORD')
wlan.active(True)

time.sleep(2) # GIVES IT TIME TO CONNECT
# *****LOOP UNTIL CONNECTED*********** #
while not wlan.isconnected():
    print("Connecting to wifi ...")
    time.sleep(2) # GIVE IT TIME TO CONNECT
print("Connected to WiFi")
print('network config:', wlan.ifconfig()) # PRINTS OUT THE IPCONFIG DATA



# *****ASSIGN VARIABLES*****************#
led = machine.Pin(13, machine.Pin.OUT) # ASSIGN OBJECT NAME TO PIN#, OBJECT IS AN OUTPUT.
                                       # blue onboard LED on the ESP8266= Pin(2)
led(0)  # TURN OFF LED AT STARTUP
topic = "LED"  # MQTT TOPIC SUCH AS: upstairs/hallway/light.  HERE WE JUST NAMED IT "LED"
message = ""
# True when new message is received in callback
new = False


# DEFINE CALLBACK TO KEEP CHECKING FOR NEW MESSAGES
def MQTT_callback(topic, msg):
    global new
    global message
    print("received: ",topic,msg)
    message = msg
    new = True
    
    
# GIVE CLIENT A PROPER NAME, INTRODUCE CLIENT TO MQTT BROKER
SERVER = "192.168.1.13"
client = MQTTClient("ESP8266", SERVER) # EACH CLIENT MUST HAVE A UNIQUE "NAME/ID"
                                       # NAME CAN BE SOMETHING LIKE "ESP_SENSOR_2"

# CONNECT CLIENT TO MQTT BROKER
try:
    client.connect()
    print(client.connect())
    client.set_callback(MQTT_callback)
    client.subscribe(topic)
    print("Connected to MQTT Server and subscribed to: ", topic)
    mqtt = True
except:
    print("MQTT connect failed")
    mqtt = False
      

# LOOP IF WIFI AND MQTT CONNECTION WAS SUCCESSFUL 
while wlan.isconnected() and mqtt:
    try:
        client.check_msg()
        if new:
            print("New message: ",message)
            led(int(message))  # TELL OBJECT "led", (int EXPECT A NUMBER, (message: 0=OFF, 1=ON))
            new = False
    except:
        print("Client check failed ...")
    time.sleep(1)
print("Wifi disconnected or MQTT could not connect")

Post Reply