#!/usr/bin/python3

import network, machine, time
import urequests, ujson
import display, buttons, mch22

def reboot(pressed):
  if pressed:
    mch22.exit_python()

# Create the station (WiFi client) interface
sta_if = network.WLAN(network.STA_IF)

# Activate the station interface
sta_if.active(True)
sta_if.connect("MCH2022-open") # Open WiFi network

wait = 200 # 200x 100ms = 20 seconds
while not sta_if.isconnected() and wait > 0:
	wait -= 1
	time.sleep(0.1) # Wait 100ms

if sta_if.isconnected():
	print("Connected!")
	ip_addr, netmask, gateway, dns_server = sta_if.ifconfig()
	print("My IP address is '{}', with netmask '{}'.".format(ip_addr, netmask))
	print("The gateway is at '{}' and the DNS server is at '{}'.".format(gateway, dns_server))
else:
	print("Failed to connect to the WiFi network.")

diags_url = "https://vrmapi.victronenergy.com/v2/installations/171112/diagnostics?count=2000"

token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImUxMjY1YjZjNWNkOThlN2U2MWFhZWUxZGE1YzllZTI2In0.eyJ1aWQiOiIyMzE4MDYiLCJ0b2tlbl90eXBlIjoiZGVmYXVsdCIsImlzcyI6InZybWFwaS52aWN0cm9uZW5lcmd5LmNvbSIsImF1ZCI6Imh0dHBzOi8vdnJtYXBpLnZpY3Ryb25lbmVyZ3kuY29tLyIsImlhdCI6MTY1ODU5ODY1NywiZXhwIjoxNjU4Njg1MDU3LCJqdGkiOiJlMTI2NWI2YzVjZDk4ZTdlNjFhYWVlMWRhNWM5ZWUyNiJ9.BCS0XKUuRYDl-6UkiXitMEmmhRrziDO1Eh-0td5Y9uArcFp0AKcuM7vFmWCYB50QfT-3hoQppPV2K8rlB_T81ezgX68hz6Zg-RQ73BtTk-UwtU_dZbffuD2Jq97EjNT4M82-tPmPvg-HFa8wDHcphYKmpxSBcRM2T8dfaaSGXK5BW2fzDQazvJ5DD0Fl1WwY64YOrsuumEPHvw0vC8jVHQp7qHpOL3yI9eUMr1JTG5pJF6aXuNI3iE2mzY-h4soT4wiGeQCjvv0icMtilxfjvEE9gSobgd0iW4hJZfFLiRyyaazLn1X7u5op1RkmAGLtyRTMkPQyjPjxxYQ3VTJdEQ"
headers = {'X-Authorization': "Bearer " + token }

display.drawFill(display.WHITE)
display.drawText(40, 10, "2342 Village Power Grid", display.GREEN, "roboto_regular18")
display.drawText(120, 120, "loading...", display.BLUE, "roboto_regular12")
display.flush()

while True:
  response = urequests.get(url=diags_url, headers=headers)
  data = response.json()["records"]

  batterySoC=[element['rawValue'] for element in data if element['code']=="VSH"][0]
  generated=int(float([element['rawValue'] for element in data if element['code']=="Pdc"][0]))
  load=int([element['rawValue'] for element in data if element['code']=="o1"][0])

  print("Battery SoC is %s %%, PV generated %s Watts, Load %s Watts" % (batterySoC, generated, load))

  display.drawFill(display.WHITE)
  display.drawText(40, 10, "2342 Village Power Grid", display.GREEN, "roboto_regular18")

  display.drawText(10, 40, "Battery:", display.BLACK, "roboto_regular12")
  if batterySoC >= 40:
    display.drawText(100, 40, "%s%%" % batterySoC, display.GREEN, "roboto_regular12")
  else:
    display.drawText(100, 40, "%s%%" % batterySoC, display.RED, "roboto_regular12")

  display.drawText(10, 70, "PV generated:", display.BLACK, "roboto_regular12")
  if generated >= 10:
    display.drawText(100, 70, "%s Watts" % generated, display.GREEN, "roboto_regular12")
  else:
    display.drawText(100, 70, "%s Watts" % generated, display.BLACK, "roboto_regular12")

  display.drawText(10, 100, "Current Load:", display.BLACK, "roboto_regular12")
  display.drawText(100, 100, "%s Watts" % load, display.BLACK, "roboto_regular12")

  if generated >= load:
    display.drawText(50, 160, "Producing %s Watts" % (generated-load), display.GREEN, "roboto_regular18")
  else:
    display.drawText(50, 160, "Consuming %s Watts" % (load-generated), display.RED, "roboto_regular18")

  display.flush(display.FLAG_FORCE & display.FLAG_FULL)
  time.sleep(2)


