#!/usr/bin/python # Poll the TSL2591 Light Sensor import tsl2591 import time import datetime import paho.mqtt.publish as publish import paho.mqtt.client as mqtt # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) #The callback for when this client publishes to the server. def on_publish(client, userdata, mid): timestamp = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S ') if rc[0] != 0: print (str(timestamp) +" Publish produced return code "+str(rc[0])) print(str(timestamp) +" message published") def on_disconnect_handler(client, userdata, rc): if rc != 0: print("Unexpected disconnection.") def on_log(client, userdata, level, buf): print("log: ",buf) #Setup parameters interval = 59 #number of seconds to wait between each poll # Open the log file fo = open("/home/pi/Light_Sensor/sensor.log", "a+") print "Light sensor reading every",interval,"seconds" print "Lux Full IR" tsl = tsl2591.Tsl2591() # initialize an instance mqttc = mqtt.Client(client_id="TSL2591@PiZero") mqttc.on_connect = on_connect mqttc.on_publish = on_publish mqttc.on_disconnect = on_disconnect_handler #mqttc.on_log=on_log #enable this to display mqtt logging mqttc.username_pw_set("emonpi", "emonpimqtt2016") mqttc.connect("192.168.0.8", 1883, 60) mqttc.loop_start() #Start a loop that reads the buffers and invokes call backs while True: full, ir = tsl.get_full_luminosity() # read raw values (full spectrum and ir spectrum) lux = tsl.calculate_lux(full, ir) # convert raw values to lux timestamp = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S ') print timestamp, lux, full, ir lux = str(lux) fo.write (str(timestamp+lux+'\n')) #send value via MQTT rc=mqttc.publish("TSL2591/light",lux,qos=1) time.sleep(interval) # Close opened file fo.close()