#!/usr/bin/env python
from __future__ import print_function
import tsl2561
import json
import sys
import statistics
import time

REPEATS = 5

def main():
   try:
      sensor = tsl2561.Tsl2561(tsl2561.I2C_SMBUS, tsl2561.I2C_ADDRESS, debug=0)
   except tsl2561.DeviceNotFound:
      print("ERROR: Grove light sensor not found", file=sys.stderr)
      sys.exit(1)

   saturated = False

   ambients = []
   irs = []
   luxs = []

   for i in range(REPEATS):
      time.sleep(1)

      ambient, ir, _ambient, _ir, _lux = sensor.readLux(0) # auto gain
      saturated |= ambient >= 0xffff or ir >= 0xffff

      #print(ambient, ir, _ambient, _ir, _lux)

      ambients.append(ambient)
      irs.append(ir)
      luxs.append(_lux)

   if saturated:
      print("sensor saturated", file=sys.stderr)

   ##print(ambients, irs, luxs, saturated, file=sys.stderr)

   data = {
      'saturated': saturated,
      'ambient': statistics.mean(ambients),
      'ir': statistics.mean(irs),
      'lux': statistics.mean(luxs)
      }

   print(json.dumps(data))

if __name__ == '__main__':
   main()
