from Tkinter import *
from RPIO import PWM
import smbus
import wiringpi2

root = Tk()
root.geometry("200x200")
root.title("LED PWM tester")

global pwm_set
pwm_set = 400

global lux
lux = 0

global first_cycle
first_cycle = 1

global changed
changed = 1

DEVICE     = 0x23 # Default device I2C address

POWER_DOWN = 0x00 # No active state
POWER_ON   = 0x01 # Power on
RESET      = 0x07 # Reset data register value

# Start measurement at 4lx resolution. Time typically 16ms.
CONTINUOUS_LOW_RES_MODE = 0x13
# Start measurement at 1lx resolution. Time typically 120ms
CONTINUOUS_HIGH_RES_MODE_1 = 0x10
# Start measurement at 0.5lx resolution. Time typically 120ms
CONTINUOUS_HIGH_RES_MODE_2 = 0x11
# Start measurement at 1lx resolution. Time typically 120ms
# Device is automatically set to Power Down after measurement.
ONE_TIME_HIGH_RES_MODE_1 = 0x20
# Start measurement at 0.5lx resolution. Time typically 120ms
# Device is automatically set to Power Down after measurement.
ONE_TIME_HIGH_RES_MODE_2 = 0x21
# Start measurement at 1lx resolution. Time typically 120ms
# Device is automatically set to Power Down after measurement.
ONE_TIME_LOW_RES_MODE = 0x23

if wiringpi2.piBoardRev() == 1:
   bus = smbus.SMBus(0) # Rev 1 Pi uses 0
else:
   bus = smbus.SMBus(1)  # Rev 2 Pi uses 1

def convertToNumber(data):
  # Simple function to convert 2 bytes of data
  # into a decimal number
  return ((data[1] + (256 * data[0])) / 1.2)

def readLight(addr=DEVICE):
  data = bus.read_i2c_block_data(addr,ONE_TIME_HIGH_RES_MODE_1)
  return convertToNumber(data)

def pClick():
   global pwm_set
   global changed
   if pwm_set < 1000:
      pwm_set +=1
      changed = 1
      mLabel1.config(text = "PWM: " + str(pwm_set/10.0) + "%")

def nClick():
   global pwm_set
   global changed
   if pwm_set > 0:
      pwm_set -=1
      changed = 1
      mLabel1.config(text = "PWM: " + str(pwm_set/10.0) + "%")

def Refreshener():
   global lux
   lux = readLight()

   mLabel2.config(text="Light level: " + str(round(lux,1)) + " lx")

   global first_cycle
   if first_cycle > 0:
      first_cycle = 0
      wiringpi2.wiringPiSetupGpio()
      wiringpi2.pinMode(18,2)
      wiringpi2.pwmSetMode(0)
      wiringpi2.pwmSetClock(2)
      wiringpi2.pwmSetRange(1000)
      wiringpi2.pwmWrite(18,0)


   global changed
   if changed > 0:
      changed = 0
      wiringpi2.pwmWrite(18,pwm_set)

   root.after(200,Refreshener)

mButton1 = Button(text = "PWM +", command = pClick, fg = "darkgreen", bg = "white")
mButton1.pack()
mButton2 = Button(text = "PWM -", command = nClick, fg = "darkgreen", bg = "white")
mButton2.pack()
mLabel1 = Label(text = "PWM: " + str(pwm_set/10.0) + "%")
mLabel1.pack()
mLabel2 = Label(text = "Light level: " + str(lux) + " lx")
mLabel2.pack()

Refreshener()

root.mainloop()