#!/usr/bin/python
#by SQ6QV
#prerequisites
#sudo apt-get install python-dev python-pip libfreetype6-dev libjpeg-dev
#sudo -H pip install --upgrade pip
#sudo apt-get purge python-pip
#sudo -H pip install --upgrade luma.oled



from luma.core.interface.serial import i2c, spi
from luma.core.render import canvas
from luma.core import lib

from luma.oled.device import sh1106

import RPi.GPIO as GPIO

import time
import subprocess

from PIL import Image
from PIL import ImageFont



font = ImageFont.truetype('pm.ttf', 10)

width = 128
height = 64
image = Image.new('1', (width, height))

padding = -2
top = padding
bottom = height-padding
x = 1

USER_I2C = 0

if  USER_I2C == 1:
	RST = 25
	GPIO.setmode(GPIO.BCM)
	GPIO.setup(RST,GPIO.OUT)
	GPIO.output(RST,GPIO.HIGH)
	
	serial = i2c(port=1, address=0x3c)
else:
	serial = spi(device=0, port=0, bus_speed_hz = 8000000, transfer_size = 4096, gpio_DC = 24, gpio_RST = 25)

disp = sh1106(serial, rotate=2)

while True:
    with canvas(disp) as draw:
      try:
        draw.rectangle((0,0,width,height), outline=0, fill=0)
        IP = subprocess.check_output("hostname -I", shell = True )
        IP = IP.split(" ")[0]
        draw.text((x, top),"IP: " + str(IP),  font=font, fill=255)

        LINES = subprocess.check_output("php /var/www/html/spdxl/display.php", shell = True )
        lines = LINES.splitlines()

        draw.text((x, top+11),lines[1],  font=font, fill=255)
        draw.text((x, top+22),lines[2],  font=font, fill=255)
        draw.text((x, top+33),lines[3],  font=font, fill=255)
        draw.text((x, top+44),lines[4],  font=font, fill=255)
        draw.text((x, top+55),lines[5],  font=font, fill=255)
        time.sleep(1)
      except:
        draw.text((110, top),"E",  font=font, fill=255)


