import badge
import ugfx
import wifi
import time
import urequests
import deepsleep

SESSION_URL = "https://find.z-wave.me/zboxweb"
SESSION_PARAMS = "act=auth&login=86128%2Fadmin&pass=admin1" # Box 86128 in Z-Wave Village, admin:admin1
COMMAND_URL = "https://find.z-wave.me/ZAutomation/api/v1/devices/%s/command/" # light bulb
AUTH_HEADER = "YWRtaW46YWRtaW4x" # admin:admin1
DEVICE_ID = "ZWayVDev_zway_36-0-37"

def on(pressed):
	if pressed: send("on")

def off(pressed):
	if pressed: send("off")

def quit(pressed):
	global quit
	if pressed: quit = True

zbw_token = None
def getToken():
	global zbw_token
	if zbw_token is None:
		h = {"Content-Type": "application/x-www-form-urlencoded"}
		l = urequests.request("POST", SESSION_URL, SESSION_PARAMS, headers = h)
		zbw_token = l.content.decode("utf8")
		l.close()
	return zbw_token

def send(cmd):
	h = {"Cookie": "ZBW_SESSID=" + getToken(), "Authorization": "Basic " + AUTH_HEADER}
	l = urequests.request("GET", (COMMAND_URL % DEVICE_ID) + cmd, headers = h)
	l.close()

def display_connecting():
	ugfx.clear(ugfx.WHITE)
	ugfx.demo("Connecting")
	ugfx.flush()

def welcome():
	ugfx.demo("Using Z-Wave")
	ugfx.string(20, 113, "Go to Z-Wave Village and use Up/Down to control", "Roboto_Regular12", ugfx.BLACK)
	ugfx.flush()

# init hardware
badge.init()
badge.eink_init()
ugfx.init()
ugfx.input_init()

ugfx.set_lut(ugfx.LUT_FULL)
ugfx.clear(ugfx.WHITE)
ugfx.flush()

wifi.init()
while not wifi.sta_if.isconnected():
	display_connecting()
	time.sleep(0.1)
	pass

# attach button handlers
ugfx.input_attach(ugfx.JOY_UP, on)
ugfx.input_attach(ugfx.JOY_DOWN, off)
ugfx.input_attach(ugfx.BTN_B, quit)

welcome()

quit = False
while not quit:
	pass

deepsleep.reboot()

