# Some display code yoinked from Adafruit libraries, licence below.
#
# Copyright (c) 2017 Adafruit Industries
# Author: Tony DiCola & James DeVito
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# nametab's temperature display script, specifically for the el cheapo yellow/blue
# 128x64px OLEDs displays.
#


import time

import RPi.GPIO as GPIO
import time
import os

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     # on the PiOLED this pin isnt used
# Note the following are only used with SPI:
DC = 23
SPI_PORT = 0
SPI_DEVICE = 0

# 128x64 display with hardware I2C:
disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)

# Initialize library.
disp.begin()

# Clear display.
disp.clear()
disp.display()

# Create blank image for drawing.
# Make sure to create image with mode '1' for 1-bit color.
width = disp.width
height = disp.height
image = Image.new('1', (width, height))

# get drawing object to draw on image.
draw = ImageDraw.Draw(image)

# clear
draw.rectangle((0,0,width,height), outline=0, fill=0)

# bounds
padding = -2
top = padding
bottom = height-padding
# move left to right keeping track of the current x position for drawing stuff.
x = 0

# cd to here
os.chdir(os.path.dirname(os.path.abspath(__file__)))
print("set filedir")

# paths for my temperature probe. yours will be different.
sensor_file_path = "/sys/bus/w1/devices/28-3c01d60716ee/w1_slave"
sensor_dir = "/sys/bus/w1/devices/28-3c01d60716ee"

def display_good_temp(command_out):
    print("display_good_temp called")

    # remove the "-t"
    shorttemp = str(command_out[2:7])

    # set small font. make sure the .ttf is in the same directory as this script.
    font = ImageFont.truetype('pixel font-7.ttf', 22)

    # draw 'coolant:'
    draw.text((x+2, top),"Coolant:",  font=font, fill=255)

    # embiggen font
    font = ImageFont.truetype('pixel font-7.ttf', 40)

    # draw temperature, removing the mystery b + backtick and adding symbols
    draw.text((x+2, top + 28),shorttemp[2:4] + "." + shorttemp[4:5] + "\u00B0C",  font=font, fill=255)


# loop, checking the sensor and updating the display
while True:

    # clear
    draw.rectangle((0,0,width,height), outline=0, fill=0)

    # compose cat command to read temperature sensor and grep for the actual temperature digits
    cmd = "cat " + sensor_file_path + " |grep -o -P  '.{0,0}t=.{0,5}'"

    # get output of command, handle disconnected sensor fuckups gracefully
    try:
        command_out = subprocess.check_output(cmd, shell = True )

        # if fuckup, draw "error"
        if("No such file or directory" in str(command_out)):

            # set small font
            font = ImageFont.truetype('pixel font-7.ttf', 22)

            # draw 'error:'
            draw.text((x+2, top),"Error:",  font=font, fill=255)

            # embiggen font
            font = ImageFont.truetype('pixel font-7.ttf', 40)

            # draw 'FUCK?'
            draw.text((x+2, top + 28),"FUCK?",  font=font, fill=255)

        else:
            display_good_temp(command_out)
            print("display_good_temp called successfully with " + str(command_out) + " at unix time " + str(time.time()))

    except: # this is all duplicate code from above and you should feel bad.

        print("exception handled, displaying error message." + " At unix time " + str(time.time()))

        # set small font
        font = ImageFont.truetype('pixel font-7.ttf', 22)

        # draw 'error:'
        draw.text((x+2, top),"Error:",  font=font, fill=255)

        # embiggen font
        font = ImageFont.truetype('pixel font-7.ttf', 40)

        # draw 'FUCK?'
        draw.text((x+2, top + 28),"FUCK?",  font=font, fill=255)


    # display image.
    disp.image(image)
    disp.display()
    time.sleep(0.1)
