#!/usr/bin/python
#by SQ6QV

import time

import Adafruit_GPIO.SPI as SPI
import Adafruit_SSD1306

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

import subprocess

# Raspberry Pi pin configuration:
RST = None

# 128x32 display with hardware I2C:
disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST)

disp.begin()
disp.clear()
disp.display()

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

draw = ImageDraw.Draw(image)

draw.rectangle((0,0,width,height), outline=0, fill=0)

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


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

counter=0
while True:
    try:
        draw.rectangle((0,0,width,height), outline=0, fill=0)
        
        page=(counter/5) %2
        counter+=1
	if page==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()


        if page==1:
	    draw.text((x, top),lines[1],  font=font, fill=255)
        draw.text((x, top+11),lines[2],  font=font, fill=255)
        draw.text((x, top+22),lines[3],  font=font, fill=255)
        disp.image(image)
	disp.display()
        time.sleep(1)
    except:
        draw.text((110, top),"E",  font=font, fill=255)
        disp.image(image)
	disp.display()


