import ugfx, gc, wifi, badge, deepsleep
from time import *
import urequests as requests
#from led_test3 import base64
#
#def draw_bitmap(x, y, w, data):
#	x0 = x
#	dx = 0
#	ugfx.pixel(x, y, ugfx.BLACK)
#
#	for i in range(len(data)):
#		c = data[i]
#		for j in range(8):
#			p = (c & 1 << j) != 0
#			if not p:
#				ugfx.pixel(x, y, ugfx.BLACK)
#			x += 1
#			dx += 1
#			if dx >= w:
#				x = x0
#				dx = 0
#				y += 1
#
#a = base64.b64decode("asdf")

ugfx.init()

error = 0;

while True:
	try:
		# Make sure WiFi is connected
		wifi.init()

		ugfx.clear(ugfx.WHITE);
		ugfx.string(10,10,"Waiting for wifi...","Roboto_Regular12", 0)
		ugfx.flush()

		# Wait for WiFi connection
		while not wifi.sta_if.isconnected():
			 sleep(0.1)

		# loading screen
		ugfx.clear(ugfx.WHITE);
		ugfx.string(10,10,"Getting pixeldata ...","Roboto_Regular12", 0)
		ugfx.flush()

		count = 0;

		while True:
			# fetching data
			url = "http://wrtlprnft.net/.well-known/acme-challenge/badge.php"
			r = requests.get(url)
			gc.collect()
			data = r.json()
			r.close()

			# print data
			ugfx.clear(ugfx.WHITE);
			ugfx.string(10,10,"0: (" + str(data["0"]["r"]) + ", " + str(data["0"]["g"]) + ", " + str(data["0"]["b"]) + ", " + str(data["0"]["w"]) + ")","Roboto_Regular12", 0)
			ugfx.string(10,22,"1: (" + str(data["1"]["r"]) + ", " + str(data["1"]["g"]) + ", " + str(data["1"]["b"]) + ", " + str(data["1"]["w"]) + ")","Roboto_Regular12", 0)
			ugfx.string(10,34,"2: (" + str(data["2"]["r"]) + ", " + str(data["2"]["g"]) + ", " + str(data["2"]["b"]) + ", " + str(data["2"]["w"]) + ")","Roboto_Regular12", 0)
			ugfx.string(10,46,"3: (" + str(data["3"]["r"]) + ", " + str(data["3"]["g"]) + ", " + str(data["3"]["b"]) + ", " + str(data["3"]["w"]) + ")","Roboto_Regular12", 0)
			ugfx.string(10,58,"4: (" + str(data["4"]["r"]) + ", " + str(data["4"]["g"]) + ", " + str(data["4"]["b"]) + ", " + str(data["4"]["w"]) + ")","Roboto_Regular12", 0)
			ugfx.string(10,70,"5: (" + str(data["5"]["r"]) + ", " + str(data["5"]["g"]) + ", " + str(data["5"]["b"]) + ", " + str(data["5"]["w"]) + ")","Roboto_Regular12", 0)
			ugfx.string(10,82,"count: " + str(count) + ", error: " + str(error),"Roboto_Regular12", 0)
			ugfx.flush()

			count += 1

			led_data = []
			for led in ["0", "1", "2", "3", "4", "5"]:
				for value in ["g", "r", "b", "w"]:
					led_data.append(data[led][value])
			badge.leds_send_data(bytes(led_data),24)

			sleep(data["sleep"]);
	except:
		error += 1
		ugfx.clear(ugfx.WHITE);
		ugfx.string(10,82,"count: " + str(count) + ", error: " + str(error),"Roboto_Regular12", 0)
		ugfx.flush()
