"""
Name: ecoMonitor
Title: 
Author: Cooper
Date: 31/12/2018

Desc:  This script looks out for the digital input and immediately turns down the max brightness

The onion is connected to a Digital Input which can be used to signal ECO mode state.
Dims the sign for a period & blanks it until the state changes again.

"""
import time
import logging
import platform

from hanip.onionip import onionIO

logger = logging.getLogger("ecoMonitor")

class ECOMonitor(object):
    def __init__(self):
        self.ignStatus = "1"   #This signal is inverted, if ignition is present then this goes to 0
        self.ignOffTime = 0

        self.setupIGNInput()

    def setupIGNInput(self):
        os_version = platform.release()
        logging.info("OS Version: %s" % os_version)

        if os_version == "":
            pinNum = 29
        elif os_version[0] == "4":
            # For OpenWRT1806
            pinNum = 29
        else:
            #For OpenWRT21
            pinNum = 509

        logging.info("Using pin %s" % pinNum)

        self.ignPin = onionIO.OnionIO(pinNum)

        try:
            status = self.ignPin.setDirection(0)
        except OSError:
            logging.exception("Pin already setup!")

        #It appears that the first "read" always returns high even though so perhaps there needs to be some time to
        #let it settle whilst poking it a few times.
        for ping in range(4):
            self.getIgnitionStatus()
            time.sleep(0.2)

    def getIgnitionStatus(self):
        newIgnStatus = self.ignPin.getIOValue().rstrip()

        if newIgnStatus != self.ignStatus:
            self.ignStatus = newIgnStatus
            logging.info("Ignition state changed: %s" % self.ignStatus)
            if self.ignStatus == "1":
                self.ignOffTime = time.time()
            else:
                self.ignOffTime = 0

        return self.ignStatus, self.ignOffTime

if __name__ == "__main__":
    ecomon = ECOMonitor()
    blankTimer = 1
    while 1:
        stat, timer = ecomon.getIgnitionStatus()

        if stat == "0":
            print("IGN On!")
        else:
            elapsedtime = int(time.time() - ecomon.ignOffTime)
            elapsedMins = elapsedtime / 60
            print("IGN Off: %i mins" % elapsedMins)

            if elapsedMins > blankTimer:
                print("*Signs Blanked*")
        time.sleep(1)