import lcddriver
import time
from datetime import datetime
import socket
import fcntl
import struct
import sys, os
import signal

lcd = lcddriver.lcd()

def get_ip_address(ifname):
    # result = "%s is not set" % ifname
    result = "not set"
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        result=socket.inet_ntoa(fcntl.ioctl(
            s.fileno(),
            0x8915,  # SIOCGIFADDR
            struct.pack('256s', bytes(ifname[:15],'utf-8'))
        )[20:24])
    except Exception:
        pass
    return result

def handler_stop_signals(signum, frame):
    #we are killed
    global lcd
    lcd.lcd_clear()        
    lcd.lcd_display_string("I am ",1)        
    lcd.lcd_display_string("   ...killed :-(",2) 
    exit(0)
    
def displayInfoToLCD():
    """
    Show information temp ip(s) time on 2 line lcd display
    """
    global lcd
    signal.signal(signal.SIGINT, handler_stop_signals)
    signal.signal(signal.SIGTERM, handler_stop_signals)
    while True:
        #get lcd driver and clear
        #see https://tutorials-raspberrypi.de/hd44780-lcd-display-per-i2c-mit-dem-raspberry-pi-ansteuern/        

       # while 1: 
       #    time.sleep(10)
        # read the values
        wl = get_ip_address('wlan0')
        eth = get_ip_address('eth0')
        temp = os.popen("vcgencmd measure_temp").readline()
        temp = (temp.replace("temp=","").replace("'C\n",""))
        times = datetime.now().strftime('%H:%M:%S')
        emptyField = -1
        sleeping=10
        if wl == "not set":
            wl = "wlan0 not set"
            emptyField = 0
        if eth == "not set":
            eth = "eth0 not set"
            if emptyField ==0:
                wl="no network"
                eth="no network"
                sleeping=2 #no network normally on start up
            emptyField = 1
            
            
        lcd.lcd_clear()
        if emptyField >= 0: #can show temperature directly 
            field = (emptyField+1)%2
            lcd.lcd_display_string("T:%s %s" %(temp ,times),emptyField+1)
            ip =  wl if (emptyField == 1) else eth  
            lcd.lcd_display_string(ip,field+1)
            time.sleep(sleeping)
        else:
            lcd.lcd_display_string("T: %s Celsius"%temp,1)
            lcd.lcd_display_string("Time: %s"%times,2)
            time.sleep(sleeping/2)
            lcd.lcd_clear()
            lcd.lcd_display_string(wl,1)
            lcd.lcd_display_string(eth,2)
            time.sleep(sleeping/2)
    

displayInfoToLCD() # should sleep some seconds
