# Import LCD library
from RPLCD import i2c
import psutil
import datetime
import os
from uptime import uptime
# Import sleep library
from time import sleep

# constants to initialise the LCD
lcdmode = 'i2c'
cols = 20
rows = 4
charmap = 'A00'
i2c_expander = 'PCF8574'

# Generally 27 is the address;Find yours using: i2cdetect -y 1 
address = 0x27 
port = 0 # 0 on an older Raspberry Pi

# Initialise the LCD
lcd = i2c.CharLCD(i2c_expander, address, port=port, charmap=charmap,
                  cols=cols, rows=rows)


while True:
    myCmd = ""
    # Write a string on first line and move to next line
    mem_data = psutil.virtual_memory()
    net_sum = psutil.net_if_addrs()["eth0"]
    eth0_ip = (net_sum[0][1])
    cpu_load = round(psutil.getloadavg()[0],2)
    uptime_s = int(uptime())
    uptime_f = str(datetime.timedelta(seconds=uptime_s))
    line1 = f'{"Mem: " + str(mem_data.percent): <20}'
    line2 = f'{"IP : " + str(eth0_ip): <20}'
    line4 = f'{"CPU: " + str(cpu_load): <20}'
    print(cpu_load)
    lcd.backlight_enabled =  True
    lcd.cursor_pos = (0, 0)
    lcd.write_string(line1)
    lcd.crlf()
    lcd.write_string(line2)
    lcd.crlf()
    lcd.write_string('Up : ' + str(uptime_f))
    lcd.crlf()
    lcd.write_string(line4)
    sleep(5)
    #lcd.clear()
    # Switch off backlight
    #lcd.backlight_enabled =  False
    #sleep(3)
    # Clear the LCD screen
    #lcd.close(clear=True)