Skip to content

Instantly share code, notes, and snippets.

@kasparsd
Last active November 10, 2018 18:59
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 kasparsd/5458994a21a013ece6ebdf5e8cee5f59 to your computer and use it in GitHub Desktop.
Save kasparsd/5458994a21a013ece6ebdf5e8cee5f59 to your computer and use it in GitHub Desktop.
Wemos ESP8266 Home Assistant Binary Sensor Example

Use the following command to upload the main.py:

$ ampy --port /dev/tty.usbserial-1410 put main.py
import network
SSID = ''
PASSWORD = ''
def do_connect():
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print('connecting to network...')
sta_if.active(True)
sta_if.connect(SSID, PASSWORD)
while not sta_if.isconnected():
pass
print('network config:', sta_if.ifconfig())
do_connect()
import urequests, usocket
from machine import Pin, Timer
class Toggle:
def __init__(self, state = False):
self.state = state
def get(self):
return self.state
def toggle(self):
self.state = not self.state
return self.state
url = 'http://10.0.1.11:8123/api/states/binary_sensor.webut'
headers = { 'content-type': 'application/json' }
payload_template = '{ "state": "%s", "attributes": { "friendly_name": "WeBut" } }'
state = Toggle()
def to_state(value):
return 'on' if value else 'off'
def on_pressed(does):
print('pressed')
payload = payload_template % (to_state(state.toggle()))
resp = urequests.post(url, data=payload, headers=headers)
print(resp.json())
def debounce(pin):
timer.init(mode=Timer.ONE_SHOT, period=200, callback=on_pressed)
timer = Timer(0)
button = Pin(0, Pin.IN, Pin.PULL_UP)
button.irq(debounce, Pin.IRQ_RISING)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment