import ujson as json
import machine
import ubinascii
import utime
from light_sensor.umqtt.simple import MQTTClient


class LightSensor:
    """A class for interacting with a photoresistor on a ESP8266. Suggested using 1K Ohm Resistor and 3.3V power
     source"""

    def __init__(self, pin=0, threshold=200):
        self.adc = machine.ADC(pin)
        self.threshold = threshold

    def read_light(self):
        if self.adc.read() > self.threshold:
            return True
        else:
            False


CONFIG = {
    "broker": "10.0.1.146",
    "sensor_pin": 0,
    "client_id": b"esp8266_" + ubinascii.hexlify(machine.unique_id()),
    "topic": b"light",
}

client = None
sensor_pin = None


def setup_pins():
    global sensor_pin
    sensor_pin = machine.ADC(CONFIG.get("sensor_pin"))


def load_config():
    try:
        with open("/config.json") as f:
            config = json.loads(f.read())
    except (OSError, ValueError):
        print("Couldn't load /config.json")
        save_config()
    else:
        CONFIG.update(config)
        print("Loaded config from /config.json")


def save_config():
    try:
        with open("/config.json", "w") as f:
            f.write(json.dumps(CONFIG))
    except OSError:
        print("Couldn't save /config.json")


def main():
    client = MQTTClient(CONFIG['client_id'], CONFIG['broker'])
    client.connect()
    print("Connected to {} using id {}".format(CONFIG['broker'], CONFIG['client_id']))
    while True:
        data = sensor_pin.read()
        payload = json.dumps({"payload": data}).encode('utf-8')
        client.publish('{}/{}'.format(CONFIG['topic'],
                                      CONFIG['client_id']),
                       payload)
        print('Sensor state: {}'.format(data))
        utime.sleep(5)


if __name__ == '__main__':
    load_config()
    setup_pins()
    main()
