#!/usr/bin/python

# Display stuff on LCD
# Willem A Schreuder
# 11/26/2015

# Import modules
import time
import Adafruit_CharLCD as LCD

def Temp():
   "Get temperature from 1wire sensor"
   #  Snarf list of slaves
   fd = open("/sys/bus/w1/devices/w1_bus_master1/w1_master_slaves")
   text = fd.read()
   fd.close()
   slaves = text.split("\n")
   slaves.sort()

   #  Snarf text
   temps = []
   for slave in slaves:
      if slave=="": continue
      fd = open("/sys/bus/w1/devices/"+slave+"/w1_slave")
      text = fd.read()
      fd.close()

      #  Split lines
      lines = text.split("\n")
      words = lines[1].split(" ")

      #  Get temperature
      C = float(words[9][2:])/1000
      F = 9*C/5+32
      temps.append("%.1fF" % F)
   return temps

# Initialize the LCD using the pins 
lcd = LCD.Adafruit_CharLCDPlate()
lcd.clear()

#  Screen colors
kol = 0
colors = ([1,1,1],[1,0,0],[1,1,0],[0,1,0],[0,1,1],[0,0,1],[1,0,1],[0,0,0])

def DateTime():
   "Return date and time strings"
   lt = time.localtime()
   d = "%4d%.2d%.2d" % lt[0:3]
   t = "%.2d:%.2d:%.2d" % lt[3:6]
   return (d,t);

def Show(row,old,new):
   "Update string but only copy differences"
   for i in range (0,len(new)):
      if i>=len(old) or old[i] != new[i]:
         lcd.set_cursor(i,row)
         lcd.message(new[i])
   return new

def Color(kol):
   "Update backlit color"
   kol = kol%len(colors)
   (r,g,b) = colors[kol]
   lcd.set_color(r,g,b)
   return kol

d0 = ''
t0 = ''
while True:
   #  Display color
   if lcd.is_pressed(LCD.SELECT):
      kol = Color(0)
   elif lcd.is_pressed(LCD.RIGHT):
      kol = Color(kol+1);
   elif lcd.is_pressed(LCD.LEFT):
      kol = Color(kol-1);
   #  Display date and time
   (d,t) = DateTime();
   temps = Temp()
   d += "   "+temps[0]
   t += "   "+temps[1]
   if d0!=d: d0=Show(0,d0,d)
   if t0!=t: t0=Show(1,t0,t)
   #  Pause
   time.sleep(0.1)
