Skip to content

Instantly share code, notes, and snippets.

@akrv
Last active January 29, 2017 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akrv/967951657ec731c0204d27bd18279aa5 to your computer and use it in GitHub Desktop.
Save akrv/967951657ec731c0204d27bd18279aa5 to your computer and use it in GitHub Desktop.
This is a program for toggling the WiFi Switch from internet using MQTT
from umqtt.simple import MQTTClient
from machine import Pin
import ubinascii
import machine
import micropython
global switch_state
switch_state = True
CLIENT_ID = ubinascii.hexlify(machine.unique_id())
SERVER = 'localhost'
TOPIC = b"home/tv"
#-- Pin which the relay is connected to
relayPin = 12
p6 = Pin(relayPin, Pin.OUT) # create output pin on GPIO6
#-- Connected to switch with internal pullup enabled
# buttonPin = 0
# buttonDebounce = 0
# p3 = Pin(buttonPin, Pin.OUT) # create output pin on GPIO3
#-- MQTT led
mqttLed=13
p13 = Pin(mqttLed, Pin.OUT) # create output pin on GPIO7
p13.low()
def sub_cb(topic,msg):
global switch_state
print((topic, msg))
if msg == b"on":
p13.value(0)
p6.value(1)
switch_state = 1
elif msg == b"off":
p13.value(1)
p6.value(0)
switch_state = 0
def main(server=SERVER):
c = MQTTClient(CLIENT_ID, server)
# Subscribed messages will be delivered to this callback
c.set_callback(sub_cb)
c.connect()
c.subscribe(TOPIC)
print("Connected to %s, subscribed to %s topic" % (server, TOPIC))
try:
while 1:
# micropython.mem_info()
c.wait_msg()
finally:
c.disconnect()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment