Exemple #1
0
    def __init__(self, port=DEFAULT_PORTS["LightSensor"], address=0x29):
        Sensor.__init__(self, "LightSensor", port)
        if address not in i2c.scan():
            raise OSError(
                "Please check if the light sensor is connected to Port 6 or an I2C hub"
            )

        TSL2561.__init__(self, i2c, address=address)
Exemple #2
0
def init_capteur():
    logger.debug("Initialisation du bus I2C")
    try:
        bus = SMBus(1)
    except FileNotFoundError as e:
        logger.fatal("Erreur dans la recherche du bus I2C : %s", e)
        sys.exit(ERR_I2C)
    logger.debug("Initialisation du capteur TSL")
    try:
        tsl = TSL2561(bus)
    except IOError as e:
        logger.fatal("Erreur dans la recherche du capteur : %s", e)
        sys.exit(ERR_TSL)
    try:
        gain = int(config["Capteur"]["gain"])
        tsl.gain(gain)
    except (KeyError, ValueError) as e:
        logger.error(
            "Erreur dans le fichier de configuration."
            "lecture du gain du capteur : %s", e)
    logger.info("Gain du capteur : %s", tsl.gain())
    try:
        integration = int(config["Capteur"]["integration"])
        tsl.integration_time(integration)
    except (KeyError, ValueError) as e:
        logger.error(
            "Erreur dans le fichier de configuration."
            "lecture du temps d'intégration du capteur : %s", e)
    logger.info("Temps d'intégration du capteur : %s ms.",
                tsl.integration_time())
    return tsl
Exemple #3
0
 def setup(self):
     try:
         self.tsl = TSL2561(debug=1)
         self.tsl.set_auto_range(16)
         self.sensor_running = True
     except Exception as err:
         logger.warning("Error starting %s: %s" % (self.name, err))
Exemple #4
0
def check_brightness(queue, notify_queue):
    tsl = TSL2561(debug=1)
    brightness = 0
    lux = 0

    while (True):
        try:
            lux = tsl.lux()
        except:
            print "Error polling Lux Sensor"
        #print lux

        if brightness == 0:
            if (lux > 10):
                brightness = eval_brightness(queue, notify_queue, brightness,
                                             lux)
        elif brightness == 4:
            if (lux > 35 or lux < 5):
                brightness = eval_brightness(queue, notify_queue, brightness,
                                             lux)
        elif brightness == 7:
            if (lux > 110 or lux < 25):
                brightness = eval_brightness(queue, notify_queue, brightness,
                                             lux)
        elif brightness == 15:
            if (lux < 90):
                brightness = eval_brightness(queue, notify_queue, brightness,
                                             lux)

        time.sleep(1)
Exemple #5
0
def initialisation():
    print("Vérification du capteur...")
    try:
        bus = SMBus(1)
    except FileNotFoundError as e:
        print("Erreur dans la recherche du bus I2C : {}".format(e),
              file=sys.stderr)
        sys.exit(ERR_I2C)
    try:
        tsl = TSL2561(bus)
    except IOError as e:
        print("Erreur dans la recherche du capteur : {}".format(e),
              file=sys.stderr)
        sys.exit(ERR_TSL)
    print("Démarrage du serveur.")
    config = configparser.ConfigParser()
    config.read(FICH_CONFIG)
    try:
        addr = config["Serveur"]["address"]
        port = int(config["Serveur"]["port"])
    except (KeyError, ValueError) as e:
        print("Erreur dans la lecture du fichier de configuration :  "
              "{}".format(e),
              file=sys.stderr)
        sys.exit(ERR_CONFIG)
    return tsl, addr, port
Exemple #6
0
def initialize_sensors():
    tsl = TSL2561()
    print "[*] Light sensor is initialized"
    pin = 1
    pir = OnionGpio(pin)
    pir_status = pir.setInputDirection()
    print "[*] PIR sensor is initialized: ", pir_status
    return tsl, pir
Exemple #7
0
 def show_data(self, screen, line):
     if not isinstance(screen, Display):
         raise TypeError(
             "The 'screen' parameter must be an instance of Display!")
     reading = TSL2561.read(self)
     msg = ">{0}: {1} lux".format(self.port, reading)
     screen.show_line(line, msg)
     return reading
Exemple #8
0
    def __init__(self, address, bus, testing=False):
        super(TSL2561Sensor, self).__init__()
        self._lux = None
        self.i2c_address = address
        self.i2c_bus = bus

        if not testing:
            from tsl2561 import TSL2561
            self.tsl = TSL2561(address=self.i2c_address, busnum=self.i2c_bus)
Exemple #9
0
def main():
    try:
        tsl = TSL2561(debug=1)
        while True:
            #tsl = TSL2561()
            print('lummiance = %d lux' % tsl.lux())
            time.sleep(1)
    except Exception, err:
        print Exception, err
Exemple #10
0
    def __init__(self, input_dev, testing=False):
        super(InputModule, self).__init__(input_dev,
                                          testing=testing,
                                          name=__name__)

        if not testing:
            from tsl2561 import TSL2561

            self.i2c_address = int(str(input_dev.i2c_location), 16)
            self.i2c_bus = input_dev.i2c_bus
            self.tsl = TSL2561(address=self.i2c_address, busnum=self.i2c_bus)
def process_req(message):
    tsl=TSL2561(busnum=1)

    # Get the values 
    lux_value = tsl.lux() 
 
    # format the message
    message = "SENSOR_REP,DEV=ADA_TSL2561,SUB_DEV=LUX,LUX=%d,SENSOR_REP_STOP" % (lux_value)

    # Return the message
    return message
Exemple #12
0
    def __init__(self, input_dev, testing=False, run_main=True):
        super(InputModule, self).__init__()
        self.logger = logging.getLogger("mycodo.inputs.tsl2561")
        self.run_main = run_main

        if not testing:
            from tsl2561 import TSL2561
            self.logger = logging.getLogger("mycodo.tsl2561_{id}".format(
                id=input_dev.unique_id.split('-')[0]))
            self.i2c_address = int(str(input_dev.i2c_location), 16)
            self.i2c_bus = input_dev.i2c_bus
            self.tsl = TSL2561(address=self.i2c_address, busnum=self.i2c_bus)
def read_function(tsl = TSL2561(debug=True), temp_sensor = W1ThermSensor(), dht_sense = Adafruit_DHT.AM2302, gpio_ht  = 11):
    date_time = datetime.datetime.now(pytz.timezone("US/Eastern")).strftime("%Y-%m-%d %H:%M:%S")
    h2o_temp = temp_sensor.get_temperature() #DS18B20 
    humidity, temperature = Adafruit_DHT.read_retry(dht_sense, gpio_ht) #AM2302
    light = tsl.lux() #TSL2561
    
    #Because this will be saved both to mLab remotely and locally in csv file
    #It was necessary to order the dictionary to ensure each appended observation is properly ordered
    #To align with the CSV file.
    
    sensor_observation = OrderedDict([('date_time',[date_time]),('water_temp',[round(h2o_temp, 2)]), ('air_temp',[round(temperature,2)]), ('humidity',[round(humidity,2)]), ('light_level',[light])])
    return sensor_observation
def main():
    bme = bme680.BME680(i2c_addr=0x77)

    # Initialize BME sensor
    bme.set_humidity_oversample(bme680.OS_2X)
    bme.set_pressure_oversample(bme680.OS_4X)
    bme.set_temperature_oversample(bme680.OS_8X)
    bme.set_filter(bme680.FILTER_SIZE_3)
    bme.set_gas_status(bme680.ENABLE_GAS_MEAS)

    # Initialize USB mic
    pyaud = pyaudio.PyAudio()
    stream = pyaud.open(format=pyaudio.paInt16,
                        channels=1,
                        rate=32000,
                        input_device_index=2,
                        input=True)

    # Main loop
    while (1):
        bme.get_sensor_data()
        tempCelcius = float("{0:.2f}".format(bme.data.temperature))
        # Convert the above variable to fahrenheit
        temperature = float(tempCelcius * (9 / 5) + 32)
        pressure = float("{0:.2f}".format(bme.data.pressure))
        humidity = float("{0:.2f}".format(bme.data.humidity))
        gas = float("{0:.2f}".format(bme.data.gas_resistance))

        # Read from lux sensor
        tsl = TSL2561(debug=True)
        luxVal = tsl.lux()

        # Read from USB mic
        rawsamps = stream.read(2048, exception_on_overflow=False)
        samps = numpy.fromstring(rawsamps, dtype=numpy.int16)
        dB = analyse.loudness(samps) + 60

        print('\n')
        currentDT = datetime.datetime.now()
        print(str(currentDT))
        print("      -- BME680 --")
        print("Temperature: {}".format(temperature))
        print("Pressure: {}".format(pressure))
        print("Humidity: {}".format(humidity))
        print("Gas: {}".format(gas))
        print("      -- TSL2561 --")
        print("Lux: {}".format(luxVal))
        print("      -- USB Mic --")
        print("Sound in dB: {}".format(dB))
        print('\n')
        print("---------------------------")

        time.sleep(WAIT_PERIOD)
Exemple #15
0
    def __init__(self, input_dev, testing=False):
        super(TSL2561Sensor, self).__init__()
        self.logger = logging.getLogger("mycodo.inputs.tsl2561")
        self._lux = None

        if not testing:
            from tsl2561 import TSL2561
            self.logger = logging.getLogger(
                "mycodo.inputs.tsl2561_{id}".format(id=input_dev.id))
            self.i2c_address = int(str(input_dev.location), 16)
            self.i2c_bus = input_dev.i2c_bus
            self.tsl = TSL2561(address=self.i2c_address, busnum=self.i2c_bus)
Exemple #16
0
    def __init__(self, input_dev, testing=False, run_main=True):
        super(InputModule, self).__init__()
        self.setup_logger(testing=testing, name=__name__, input_dev=input_dev)
        self.run_main = run_main

        if not testing:
            from tsl2561 import TSL2561

            self.i2c_address = int(str(input_dev.i2c_location), 16)
            self.i2c_bus = input_dev.i2c_bus
            self.tsl = TSL2561(
                address=self.i2c_address,
                busnum=self.i2c_bus)
Exemple #17
0
def measure_lux(address):
    tsl = TSL2561(debug=True, address=address)
    tsl.set_auto_range(True)
    if address == 0x39 or 0x49:
        # jsonData = {"lux({})".format(address):tsl.lux()}
        return tsl.lux()

        ##Uncomment if you want to load infrared broadband information
        # broadband,ir=tsl._get_data()
        # print(broadband)
        # print(ir)
    else:
        print("doesnt exist that sensor")
Exemple #18
0
    def __init__(self, pin_dht11=4, demo=False):
        self.demo = demo
        if self.demo:
            return

        try:
            GPIO.setwarnings(False)
            GPIO.setmode(GPIO.BCM)
            GPIO.cleanup()
        except NameError:
            raise Exception('Please add option "--demo".')

        self.tsl2561 = TSL2561(debug=True)
        self.dht11 = dht11.DHT11(pin=pin_dht11)
    def setup_lightsensor(self):

        from tsl2561 import TSL2561
        from tsl2561.constants import *  # pylint: disable=unused-wildcard-import
        try:
            self._has_light_sensor = False
            self._logger.info("Initializing TSL2561 Light Sensor")
            # See https://github.com/sim0nx/tsl2561/blob/master/tsl2561/tsl2561.py
            # address=None, busnum=None, integration_time=TSL2561_INTEGRATIONTIME_402MS, gain=TSL2561_GAIN_1X, autogain=False, debug=False
            # TODO: Allow config of gain and integration time and maybe address?
            self._tsl2561 = TSL2561(address=TSL2561_ADDR_LOW)
            self._logger.info("TSL2561 Light Sensor configured")
            self._has_light_sensor = True
        except Exception as e:
            self._logger.warn(
                "Initialzing TSL2561 FAILED. Error: {0}".format(e))
def adjust_display_brightness(sensor: TSL2561):
    from display import instance as display
    global last_light_sensor_sample_ts
    global current_display_brightness
    now = time.ticks_ms()
    if now - last_light_sensor_sample_ts > LIGHT_SENSOR_SAMPLE_INTERVAL:
        lux = sensor.read()
        if lux >= 12:
            b = 255
        else:
            b = 0
        if abs(current_display_brightness - b) > 10:
            current_display_brightness = b
            display.set_brightness(b)
            print("[LIGHT] {} lux, set display brightness to {}".format(
                lux, b))
        last_light_sensor_sample_ts = now
Exemple #21
0
    def __init__(self, Settings, mqtt):
        threading.Thread.__init__(self)
        #self.controlObjects = []
        self.stopping = False

        self.sensor = TSL2561(debug=False, autogain=True)
        #self.sensor.set_integration_time)1)
        #self.sensor.set_gain(1)
        #~ self.sensor.set_gain(1)

        self.settings = Settings  #.Settings()

        self.manualTimeout = 0
        self.BrightnessTweak = self.settings.getIntOrSet('brightness_tweak', 0)
        if (self.BrightnessTweak < 0) or (self.BrightnessTweak > 120):
            self.BrightnessTweak = 50
            self.settings.getIntOrSet('brightness_tweak', self.BrightnessTweak)

        self.currentLevel = 100  #+ self.BrightnessTweak
        self.currentluxLevel = 0

        #self.readings = [15]*10 # average over the last 10 readings
        self.LuxReadings = [15] * 10  # average over the last 10 Lux readings

        # Turn on brightness PWM
        self.pwmtftbrightness = pigpio.pi()
        self.pwmtftbrightness.set_PWM_range(18, 300)  #400
        self.pwmtftbrightness.set_PWM_frequency(18, 2000)  #400
        self.pwmtftbrightness.set_PWM_dutycycle(18, 8)
        self.pwmscale = 4.2
        self.lastreading = -1
        self.mqtt = mqtt
        self.forceUpdate = False
        self.autoLux = self.settings.getIntOrSet("display_autolux", 1)
        self.minLux = self.settings.getIntOrSet("display_minLux", 2000)
        self.maxLux = self.settings.getIntOrSet("display_maxLux", 100)
        self.maxWPM = 300
        self.loglux = False
Exemple #22
0
#!/usr/bin/python3

from tsl2561 import TSL2561
from bme680 import BME680
from ds18b20_therm import DS18B20
import bme680
import MySQLdb

tsl = TSL2561()
bme = BME680(i2c_addr=bme680.I2C_ADDR_SECONDARY)
ds = DS18B20()

bme.set_humidity_oversample(bme680.OS_2X)
bme.set_pressure_oversample(bme680.OS_4X)
bme.set_temperature_oversample(bme680.OS_8X)
bme.set_filter(bme680.FILTER_SIZE_3)
bme.set_gas_status(bme680.ENABLE_GAS_MEAS)

bme.set_gas_heater_temperature(320)
bme.set_gas_heater_duration(150)
bme.select_gas_heater_profile(0)

bme.get_sensor_data()

sample = {
    "air_temp": 0,
    "ground_temp": 0,
    "pressure": 0,
    "humidity": 0,
    "air_conductivity": 0,
    "light": 0
Exemple #23
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals

from tsl2561 import TSL2561
'''Driver for the TSL2561 digital luminosity (light) sensors.

Pick one up at http://www.adafruit.com/products/439

Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!

Code ported from Adafruit Arduino library,
commit ced9f731da5095988cd66158562c2fde659e0510:
https://github.com/adafruit/Adafruit_TSL2561
'''

if __name__ == "__main__":
    tsl = TSL2561(debug=True)

    print(tsl.lux())
Exemple #24
0
import time
import mysql.connector
from tsl2561 import TSL2561

LightSensor = TSL2561()

config = {
    'user': '******',
    'password': '******',
    'host': 'localhost',
    'database': 'agrowsoftdb',
    'raise_on_warnings': False,
}

while True:
    time.sleep(5)
    try:
        light = LightSensor.lux()
        print(light)
    except:
        pass

    try:
        cnx = mysql.connector.connect(**config)
        cursor = cnx.cursor()
        query = ("UPDATE settings SET var=%s where ID=%s")
        args = light, '150'
        cursor.execute(query, args)

        cursor.execute(query)
        cursor.close()
#!/usr/bin/env python
import rospy
# mensajes tipo Int
#from openaggdl.msg import IntR
from std_msgs.msg import Float64
# ------- Sensores
"""[requiered]sudo pip install tsl2561"""
"""[requiered]sudo pip install adafruit_gpio"""  
from tsl2561 import TSL2561
    
if __name__ == '__main__':
    rospy.init_node("sensor_tsl2561")
    rate = rospy.get_param("~rate_hz", 1)
    base_parms = "/var_types/environment_variables/{}"
    r = rospy.Rate(rate)

    sensor = TSL2561()

    tsl2561_pub = rospy.Publisher("light_intensity/raw", Float64, queue_size=10)
    
    while not rospy.is_shutdown():

        data = sensor.lux()
        rospy.loginfo("light_intensity/raw : [{}]".format(data))
        
        if data is not None:
            tsl2561_pub.publish(data)
            rospy.set_param(base_parms.format("light_intensity/last_value"), data)
        
        r.sleep()
Exemple #26
0
    def initialize(self):
        from tsl2561 import TSL2561

        self.sensor = TSL2561(
            address=int(str(self.input_dev.i2c_location), 16),
            busnum=self.input_dev.i2c_bus)
Exemple #27
0
 def do_work(self, current_values={}):
     tsl = TSL2561(address=self.__address, busnum=self.__bus)
     value = tsl.lux()
     return None if not isinstance(value, int) else value
Exemple #28
0
def main():
    try:
        mac_addr = open('/sys/class/net/wlan0/address').readline()

        # Connect to remote mySQL db
        con = MySQLdb.Connection(host=HOST,
                                 port=PORT,
                                 user=USER,
                                 passwd=PASSWORD,
                                 db=DB)
        c = con.cursor()
        c.execute(
            '''CREATE TABLE IF NOT EXISTS data(mac CHAR(17), temp FLOAT, pres FLOAT, hum FLOAT, gas FLOAT, lux INTEGER, db FLOAT, dt DATETIME)'''
        )

        # Initialize Corlysis db
        parser = argparse.ArgumentParser()
        parser.add_argument("db", help="dataDB")
        parser.add_argument("token", help="35d4aa441b94cdbae7404050edd3fad6")
        args = parser.parse_args()
        corlysis_params = {
            "db": args.db,
            "u": "token",
            "p": args.token,
            "precision": "ms"
        }

        # Initialize sensor
        bme = bme680.BME680(i2c_addr=0x77)
        bme.set_humidity_oversample(bme680.OS_2X)
        bme.set_pressure_oversample(bme680.OS_4X)
        bme.set_temperature_oversample(bme680.OS_8X)
        bme.set_filter(bme680.FILTER_SIZE_3)
        bme.set_gas_status(bme680.ENABLE_GAS_MEAS)

        # Initialize USB mic
        pyaud = pyaudio.PyAudio()
        stream = pyaud.open(format=pyaudio.paInt16,
                            channels=1,
                            rate=32000,
                            input_device_index=2,
                            input=True)

        payload = ""
        counter = 1
        problem_counter = 0

        now = time.strftime('%Y-%m-%d %H:%M:%S')
        print("Readings began " + now)
        print("Press ctrl+c to end readings and close connection.")

        animation = "|/-\\"
        aniCount = 0

    except Exception as e:
        print(e)
        f = open("/home/pi/smarterCampus/errors.txt", "w")
        f.write(str(e) + '\n')
        f.close()
        exit(1)

    # Main loop
    while (True):
        # Only have to write to log if an error occured
        ERROR = False
        try:
            # Get time for corlysis and db
            unix_time_ms = int(time.time() * 1000)
            now = time.strftime('%Y-%m-%d %H:%M:%S')

            # Read from BME
            bme.get_sensor_data()
            tempCelcius = float("{0:.2f}".format(bme.data.temperature))
            # Convert the above variable to fahrenheit
            temperature = float(tempCelcius * (9 / 5) + 32)
            pressure = float("{0:.2f}".format(bme.data.pressure))
            humidity = float("{0:.2f}".format(bme.data.humidity))
            # Convert ohms to kohms
            gas = float("{0:.2f}".format((bme.data.gas_resistance / 1000)))

            # Read from lux sensor
            tsl = TSL2561(debug=True)
            luxVal = tsl.lux()

            # Read from USB mic
            rawsamps = stream.read(2048, exception_on_overflow=False)
            samps = numpy.fromstring(rawsamps, dtype=numpy.int16)
            deciVal = analyse.loudness(samps) + 65

            line = "sensors_data temperature={},pressure={},humidity={},gas={},luxVal={},decib={} {}\n".format(
                temperature, pressure, humidity, gas, luxVal, deciVal,
                unix_time_ms)
            payload += line

            if counter % SENDING_PERIOD == 0:
                try:
                    # try to send data to cloud
                    r = requests.post(URL,
                                      params=corlysis_params,
                                      data=payload)
                    if r.status_code != 204:
                        raise Exception("data not written")
                    payload = ""
                except:
                    problem_counter += 1
                    print('cannot write to InfluxDB')
                    if problem_counter == MAX_LINES_HISTORY:
                        problem_counter = 0
                        payload = ""

            counter += 1

            # Print animation
            sys.stdout.write("\rCollecting data... " + animation[aniCount])
            sys.stdout.flush()
            aniCount += 1
            if (aniCount == 4):
                aniCount = 0

            time_diff_ms = int(time.time() * 1000) - unix_time_ms
            # print(time_diff_ms)
            if time_diff_ms < READING_DATA_PERIOD_MS:
                time.sleep((READING_DATA_PERIOD_MS - time_diff_ms) / 1000.0)

            values = (mac_addr, temperature, pressure, humidity, gas, luxVal,
                      deciVal, now)
            add_val = ("INSERT INTO data "
                       "(mac, temp, pres, hum, gas, lux, db, dt)"
                       "VALUES (%s, %s, %s, %s, %s, %s, %s, %s)")
            c.execute(add_val, values)
            con.commit()

        except KeyboardInterrupt:
            con.close()
            if ERROR == True:
                f.write("End of log since " + now + "\n\n")
                f.close()
            exit(0)

        except Exception as e:
            pass
            f = open("/home/pi/smarterCampus/Databases/Errors.txt", "w")
            print(e)
            f.write(str(e) + '\n')
            ERROR = True
Exemple #29
0
#!/usr/bin/env python3
# https://www.raspberrypi-spy.co.uk/2015/06/basic-temperature-logging-to-the-internet-with-raspberry-pi/
import time, os, sys
import urllib.request, urllib.parse, urllib.error, urllib.request, urllib.error, urllib.parse

import bme280
from tsl2561 import TSL2561, TSL2561_GAIN_16X

tsl = TSL2561(gain=TSL2561_GAIN_16X, autogain=True)

import paho.mqtt.client as mqtt

client = mqtt.Client()
client.connect("localhost")
client.loop_start()
import json

import secrets


class Config:
    interval = 10
    url = 'https://api.thingspeak.com/update'
    key = secrets.thingspeak


def postThingspeak(temp, pres, humi, lux, bb, ir):
    values = {
        'api_key': Config.key,
        'field1': temp,
        'field2': pres,
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from tsl2561 import TSL2561
import RPi.GPIO as GPIO
import sys
import os
import time
count = 0x0
tsl2561_int = 23  # the Raspberry Pi port where the interrupt is connected to.

tsl = TSL2561(debug=False, autogain=False, gain=0, integration_time=0)
tsl.enable()
tsl.disableInterrupt()
tsl.setInterruptThresholdLow(0x0, 0x0)
tsl.setInterruptThresholdHigh(0xE0, 0x0)
tsl.enableLevelInterrupt(2)

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(tsl2561_int, GPIO.IN, pull_up_down=GPIO.PUD_UP)


def rising_edge_callback(channel):
    print "edge detected"
    global count
    ir = tsl.readWord(0x8E)
    if ir is not 0:
        count += 1
    os.system("clear")
    print "Interrupt count: %i" % count