Here's my code so far:
Code: Select all
# *****ASSIGN VARIABLES*****************#
# RELAY 1
rel1 = machine.Pin(05, machine.Pin.OUT) # ASSIGN OBJECT NAME TO GPIO PIN 05(D1), OBJECT IS AN OUTPUT.
rel1(0) # TURN OFF RELAY AT STARTUP
topic = "Relay1" # MQTT TOPIC SUCH AS: upstairs/hallway/light1.
# RELAY 2
rel2 = machine.Pin(04, machine.Pin.OUT) # ASSIGN OBJECT NAME TO GPIO PIN 04(D2), OBJECT IS AN OUTPUT.
rel2(0) # TURN OFF RELAY AT STARTUP
topic = "Relay2" # MQTT TOPIC SUCH AS: upstairs/hallway/light2.
message = ""
# True when new message is received in callback
new = False
# ******** CAN I SKIP THE TWO "TOPICS" ABOVE? ********
# 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_Relay", 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()) # This just results in printing a 0 DO I NEED IT?
client.set_callback(MQTT_callback)
client.subscribe("Relay1"), ("Relay2") # This subscribes to just "Relay2"
# TRYING TO SUBSCRIBE TO MULTIPLE TOPICS#
# client.subscribe(topic) # ******** This works with single topic *******
# client.subscribe("Relay1") + ("Relay2") # This does NOT work
# client.subscribe("Relay1") & ("Relay2") # This does NOT work
# client.subscribe[(("Relay1"), ("Relay2"))] # This does NOT work
# client.subscribe[(("Relay1") + ("Relay2"))] # This does NOT work
print("Connected to MQTT Server and subscribed to: ", topic)
mqtt = True
except:
print("MQTT connect failed")
mqtt = False
###### NEED TO FIGURE OUT HOW TO CHECK FOR 2 TOPICS ###########
# LOOP IF WIFI AND MQTT CONNECTION WAS SUCCESSFUL
while wlan.isconnected() and mqtt:
try:
client.check_msg()
if new:
print("New message: ",message)
rel1(int(message)) # TELL OBJECT "relay1", (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")
# ******** I'm thinking on the lines of: ********
# if:
# topic=="Relay1"
# rel1(int(message)) # TELL OBJECT "relay1", (int EXPECT A NUMBER, (message: 0=OFF, 1=ON))
# elif:
# topic=="Relay2"
# rel2(int(message)) # TELL OBJECT "relay2", (int EXPECT A NUMBER, (message: 0=OFF, 1=ON))