import network
import ujson
import ubinascii
from machine import Pin, ADC, unique_id
from time import sleep
from random import randrange
from umqtt.simple import MQTTClient

def blink(secs=1):
  led.on()
  sleep(secs)
  led.off()
  sleep(secs)

print("Hello, ESP32!")
SSID = 'Wokwi-GUEST'
KEY = ''
MQTT_BROKER = '202.67.15.108'
MQTT_USER = 'sugiana'
MQTT_PASSWORD = 'K3adilan'
MQTT_TOPIC = 'agar-aki-awet'

led = Pin(2, Pin.OUT)

wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
  print('Connecting to network ... ', end='')
  wlan.connect(SSID, KEY)
  while not wlan.isconnected():
    blink(0.5)
  net_conf = wlan.ifconfig()
  print('connected', net_conf)
  ip = net_conf[0]

led.on()
print('Connecting to MQTT server ... ', end='')
client_id = ubinascii.hexlify(unique_id())
client = MQTTClient(client_id, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print('connected.')
led.off()

# Normally Open = PLN tidak terhubung ke charger
relay_pln = Pin(12, Pin.OUT)
# Normally Open = inverter tidak terhubung ke beban
relay_beban = Pin(14, Pin.OUT)

sensor = ADC(Pin(36))
sensor.atten(ADC.ATTN_11DB)  # Full range: 3.3v

PENGALI = 15 * 28205 / 27000 / 4096
val = 3372  # Simulasi
data = dict(client_id=client_id, ip=ip)
while True:
  relay_pln.value(1)  # PLN off agar pengukuran voltase aki benar
  # val = sensor.read()
  val += randrange(-1, 1) * randrange(1, 10)  # Simulasi
  relay_pln.value(0)  # PLN on agar charger aktif
  if val < 12.15:  # Kurang dari 60% ?
    relay_beban.value(1)  # Beban off
  elif val > 12.75:  # Lebih dari 90% ?
    relay_beban.value(0)  # Beban on
  data['volt'] = val * PENGALI
  print(data)
  msg = ujson.dumps(data)
  client.publish(MQTT_TOPIC, msg)
  blink()
  sleep(60)