import time
import atexit
import configparser
import RPi.GPIO as GPIO

from sensors import Sensors
from display import Display
from network import Network

config = configparser.RawConfigParser()
config.read(r'./config.ini')

display = Display(config)
sensor = Sensors(config)
network = Network(config)


# Init program
def init():
    # Button
    BUTTON = int(config.get('button', 'BUTTON'))

    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)

    GPIO.setup(BUTTON, GPIO.IN, pull_up_down=GPIO.PUD_UP)

    # Add button event
    GPIO.add_event_detect(BUTTON, GPIO.FALLING, callback=handlePushButton, bouncetime=250)

    pass

# Function called on push button (change sensor)
def handlePushButton(button):
    channel = sensor.getChannel() + 1
    if (channel > 8):
        channel = 0

    sensor.setChannel(channel)
    display.print("  :"+str(channel)+"-")

# On exit
def handleExit():
    print("GoodBye!")
    display.print("--:--")
    time.sleep(2)
    display.clear()

# Main programm
def main():
    init()
    print("Let's go!")

    while True:
        network.check()
        display.print(sensor.getValue())

        # Wait before next loop
        time.sleep(2)

atexit.register(handleExit)

if __name__ =='__main__':
    try:
        main()
    except KeyboardInterrupt:
        pass
