Advertisement
Guest User

Sonoff MQTT Sample

a guest
Dec 8th, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.62 KB | None | 0 0
  1. from machine import Pin, idle, reset
  2. from network import WLAN, STA_IF
  3. from time import time, sleep_ms
  4.  
  5. # https://raw.githubusercontent.com/micropython/micropython-lib/mqtt/umqtt.simple/umqtt/simple.py
  6. from mqtt import MQTTClient
  7.  
  8. # Enter the name of your Wi-Fi and its password here.
  9. # If you have an open Wi-Fi, simply remove the second item.
  10. WIFI_SSID_PASSWORD = '__SSID__', '__PWD__'
  11. WIFI_CONNECTION_TIMEOUT = 10  # seconds
  12.  
  13. MQTT_BROKER_INFO = dict(client_id='ESP8266-%d' % time(),
  14.                         server='m10.cloudmqtt.com',
  15.                         port=13633,
  16.                         user='***REMOVED***',
  17.                         password='***REMOVED***')
  18. MQTT_TOPIC = b'esp'
  19. MQTT_PING_INTERVAL = 30  # seconds
  20.  
  21. # --------------------------------------------------------------------------- #
  22.  
  23. led = Pin(13, Pin.OUT)
  24. relay = Pin(12, Pin.OUT)
  25. button = Pin(0, Pin.IN)
  26. button_state_prev = button.value()
  27. button_state_now = button_state_prev
  28. btn_value = False
  29.  
  30. def on_message(topic, msg):
  31.     print('%s -> %s' % (str(topic), msg))
  32.     if topic == MQTT_TOPIC:
  33.         if msg == b'led on':
  34.             print('Turning LED ON')
  35.             led.off()
  36.         elif msg == b'led off':
  37.             print('Turning LED OFF')
  38.             led.on()
  39.         if msg == b'rel on':
  40.             print('Turning Realy ON')
  41.             relay.on()
  42.         elif msg == b'rel off':
  43.             print('Turning Realy OFF')
  44.             relay.off()
  45.         elif msg == b'controller online':
  46.             print('Controller online')
  47.             for i in range(4):
  48.                 led.off()  # actually on
  49.                 sleep_ms(100)
  50.                 led.on()  # actually off
  51.                 sleep_ms(100)
  52.  
  53. STA = WLAN(STA_IF)
  54. STA.active(True)
  55.  
  56. while not STA.isconnected():
  57.     print("Connecting to Wi-Fi...")
  58.     wifi_reconnect_time = time() + WIFI_CONNECTION_TIMEOUT
  59.     STA.connect(*WIFI_SSID_PASSWORD)
  60.     while not STA.isconnected() and time() < wifi_reconnect_time:
  61.         sleep_ms(500)
  62.     if not STA.isconnected():
  63.         print("Connection FAILED!")
  64.         continue
  65.  
  66.     print("Connected!")
  67.  
  68.     mq = MQTTClient(**MQTT_BROKER_INFO)
  69.     mq.set_callback(on_message)
  70.  
  71.     def mqtt_connect():
  72.         try:
  73.             mq.connect()
  74.             mq.subscribe(MQTT_TOPIC, qos=1)
  75.             return True
  76.         except Exception as e:
  77.             print("[Exception] %s: %s" % (type(e).__name__, e))
  78.             return False
  79.  
  80.     mqtt_connected = False
  81.  
  82.     while not mqtt_connected:
  83.         if not STA.isconnected():
  84.             print("Wi-Fi Connection failed!")
  85.             break
  86.         print("Connecting to MQTT...")
  87.  
  88.         mqtt_connected = mqtt_connect()
  89.  
  90.         if not mqtt_connected:
  91.             continue
  92.         print("Connected!")
  93.  
  94.         mq.publish(MQTT_TOPIC, 'device online', qos=1)
  95.  
  96.         print("Waiting for messages...")
  97.  
  98.         next_ping = time() + MQTT_PING_INTERVAL
  99.  
  100.         while True:
  101.             try:
  102.                 mq.check_msg()
  103.                
  104.                 button_state_prev = button_state_now
  105.                 button_state_now = button.value()
  106.  
  107.                 # Falling edge detection
  108.                 if button_state_prev == 1 and button_state_now == 0:
  109.                     btn_value = not btn_value
  110.                     mq.publish(MQTT_TOPIC, 'btn pressed', qos=1)
  111.  
  112.                 if time() >= next_ping:
  113.                     mq.ping()
  114.                     next_ping = time() + MQTT_PING_INTERVAL
  115.                 sleep_ms(100)
  116.  
  117.             except Exception as e:
  118.                 print("%s: %s" % (type(e).__name__, e))
  119.                 device = None
  120.                 break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement