Created
January 18, 2018 16:12
-
-
Save scttnlsn/d2b8d1300e888107eb4227b74e25ae41 to your computer and use it in GitHub Desktop.
ESP8266 + MQTT relay
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import machine | |
import network | |
import ubinascii | |
from umqtt.simple import MQTTClient | |
SSID = '' | |
PASSWORD = '' | |
BROKER = '' | |
TOPIC = '' | |
CLIENT_ID = b'esp8266_' + ubinascii.hexlify(machine.unique_id()) | |
client = None | |
relay = machine.Pin(5, machine.Pin.OUT) | |
def connect(): | |
sta_if = network.WLAN(network.STA_IF) | |
ap_if = network.WLAN(network.AP_IF) | |
if ap_if.active(): | |
ap_if.active(False) | |
if not sta_if.isconnected(): | |
sta_if.active(True) | |
sta_if.connect(SSID, PASSWORD) | |
while not sta_if.isconnected(): | |
pass | |
def callback(topic, message): | |
if message == b'on': | |
relay.value(1) | |
elif message == b'off': | |
relay.value(0) | |
elif message == b'toggle': | |
relay.value(1 - relay.value()) | |
def main(): | |
connect() | |
client = MQTTClient(CLIENT_ID, BROKER) | |
client.set_callback(callback) | |
client.connect() | |
client.subscribe(TOPIC) | |
try: | |
while True: | |
client.wait_msg() | |
finally: | |
client.disconnect() | |
if __name__ == '__main__': | |
relay.value(0) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment