def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) serv_light = self.add_preload_service('LightSensor') self.char_lux = serv_light.configure_char('CurrentAmbientLightLevel') self.tsl = tsl2591.Tsl2591()
def AlertPerameters(): data = array('f', [0] * 10) datum = 0 for f in data: tsl = tsl2591.Tsl2591() # initialize light sensor full, ir = tsl.get_full_luminosity( ) # read raw values (full spectrum an$ lux = tsl.calculate_lux(full, ir) # convert raw values to lux data[datum] = lux datum += 1 #time.sleep(1) minLight = min(data) maxLight = max(data) #print(maxLight) #print(minLight) #print("\n") #for f in data: #print(f) #print("\n") #print('Tne minimum is: {}' .format(minLight)) #print('The maximum is: {}' .format(maxLight)) return (minLight, maxLight)
def initialize_input(self): import tsl2591 self.sensor = tsl2591.Tsl2591(i2c_bus=self.input_dev.i2c_bus, sensor_address=int( str(self.input_dev.i2c_location), 16))
def __init__(self, sensor_id): logging.info(MODULE_NAME + ": constructor start") # intialize the sensor self.sensor = tsl2591.Tsl2591() # initialize self.sensor_id = sensor_id logging.info(MODULE_NAME + ": constructor exit")
def boucleMesure(): sensorTsl = tsl2591.Tsl2591() # initialize sensorBMP = BMP280.BMP280() wp10 = warp10Client.Warp10Client(WARP10_SERVER, WARP10_READ_TOKEN, WARP10_WRITE_TOKEN, WARP10_APPLI_ID) while True: #get Lux full, ir = sensorTsl.get_full_luminosity( ) # read raw values (full spectrum and ir spectrum) lux = sensorTsl.calculate_lux(full, ir) # convert raw values to lux wp10.addValueForWrite("lux", [("sensor", "1")], lux) logger.debug( "capteur luminuosité : lux:{0} ,total:{1} , infraRouge:{2}".format( lux, full, ir)) #get Temp end presure temp = sensorBMP.read_temperature() pres = sensorBMP.read_sealevel_pressure( altitude_m=QNH_ALTI) / 100 # div 100 = converion en hecto pascal logger.debug( "capteur BMP280 : température:{0}, pression niveau de la mer:{1}". format(temp, pres)) wp10.addValueForWrite("temp", [("sensor", "1")], temp) wp10.addValueForWrite("pressure", [("sensor", "1")], pres) wp10.pushValues() time.sleep(WAIT_SECONDE)
def BuildConfig(): data = array('f',[0]*10) datum = 0 for f in data: tsl = tsl2591.Tsl2591() # initialize light sensor full, ir = tsl.get_full_luminosity() # read raw values (full spectrum and IR) lux = tsl.calculate_lux(full, ir) # convert raw values to lux data[datum] = lux datum += 1 #time.sleep(1) #the maximum and minimum values of light in lux recorded by sensor minLight = min(data) maxLight = max(data) #The buffer variable adds a buffer to max and min values to prevent unwarranted alerts; change this value to your preference. buffer = 10 #the maximum and minimum values of light in lux with buffer applied minimum = minLight - buffer maximum = maxLight + buffer #creates a configuration file using these values is configurable in config.txt file. config = open('config.txt', 'w') config.write('minimum_light_threshold={}\n' .format(minimum)) config.write('maximum_light_threshold={}\n' .format (maximum)) config.write('output_path=<REPLACE>\n') config.write('which_dht=22\n') config.write('which_data_pin=<REPLACE>\n') config.write('email_sender=<REPLACE>\n') config.write('email_receiver=<REPLACE>\n') config.write('rclone_profile=<REPLACE>\n') config.write('rclone_path=<REPLACE>\n') config.write('upload_once_per_day=True\n') config.close()
def __init__(self, *args, **kwargs): super(TSL2591, self).__init__(*args, **kwargs) self.lux_char = self.get_service("LightSensor") \ .get_characteristic("CurrentAmbientLightLevel") self.tsl = tsl2591.Tsl2591()
def get_measurement(self): """ Gets the TSL2591's lux """ tsl = tsl2591.Tsl2591(self.i2c_address, "/dev/i2c-" + str(self.i2c_bus)) 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 return lux
def __init__(self): ''' initialize the hostIP and leds GPIO pins''' # 18, 19, 20, 21, 22, 23, 24, 25 are the connected GPIO pins self.leds = LEDBoard(18, 19, 20, 21, 22, 23, 24, 25, pwm=False) self.sensor = tsl2591.Tsl2591() self.lux_dictionary = self.calibrate_light()
def getLight(): init = tsl2591.Tsl2591() full, ir = init.get_full_luminosity( ) # read raw values (full spectrum and ir spectrum) lux = init.calculate_lux(full, ir) # convert raw values to lux if lux is not None and full is not None and ir is not None: return lux, full, ir else: print 'Failed to get light reading.' sys.exit(1)
def __init__(self, input_dev, testing=False): super(InputModule, self).__init__() self.setup_logger(testing=testing, name=__name__, input_dev=input_dev) if not testing: import tsl2591 self.i2c_address = int(str(input_dev.i2c_location), 16) self.i2c_bus = input_dev.i2c_bus self.tsl = tsl2591.Tsl2591(i2c_bus=self.i2c_bus, sensor_address=self.i2c_address)
def call_tsl2591(): # # Driver for the Luminosity sensor. This sensor gets visual and near-IR # Luminosity. # import tsl2591 tsl = tsl2591.Tsl2591() # initialize 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 return (lux, full, ir)
def BuildConfig(which_dht, which_data_pin): light = array('f', [0] * 10) temp = array('f', [0] * 10) humid = array('f', [0] * 10) for i in range(10): tsl = tsl2591.Tsl2591() # initialize light sensor full, ir = tsl.get_full_luminosity( ) # read raw values (full spectrum and IR) lux = tsl.calculate_lux(full, ir) # convert raw values to lux humidity, temperature = Adafruit_DHT.read_retry( int(which_dht), int(which_data_pin)) light[i] = lux temp[i] = temperature humid[i] = humidity #time.sleep(1) #the maximum and minimum values of light in lux recorded by sensor minLight = min(light) maxLight = max(light) minTemp = min(temp) maxTemp = max(temp) minHumid = min(humid) maxHumid = max(humid) # The buffer variable adds a buffer to max and min values to prevent unwarranted alerts # Please feel free to adjust these values. light_buffer = 10 temp_buffer = 3 humidity_buffer = 5 #creates a configuration file using these values is configurable in config.txt file. config = open('config.txt', 'w') config.write('minimum_light_threshold={}\n'.format(minLight - light_buffer)) config.write('maximum_light_threshold={}\n'.format(maxLight + light_buffer)) config.write('minimum_temp_threshold={}\n'.format(minTemp - temp_buffer)) config.write('maximum_temp_threshold={}\n'.format(maxTemp + temp_buffer)) config.write('minimum_humidity_threshold={}\n'.format(minHumid - humidity_buffer)) config.write('maximum_humidity_threshold={}\n'.format(maxHumid + humidity_buffer)) config.write('output_path=<REPLACE>\n') config.write('which_dht={}\n'.format(which_dht)) config.write('which_data_pin={}\n'.format(which_data_pin)) config.write('slack_webhook=<REPLACE>\n') config.write('rclone_profile=<REPLACE>\n') config.write('rclone_path=<REPLACE>\n') config.write('hr_lights_on=<REPLACE>\n') config.write('hr_lights_off=<REPLACE>\n') config.write('upload_once_per_day=True\n') config.close()
def __init__(self, address, bus, testing=False): super(TSL2591Sensor, self).__init__() self.logger = logging.getLogger("mycodo.inputs.tsl2591_sensor") self._lux = None self.i2c_address = address self.i2c_bus = bus if not testing: import tsl2591 self.logger = logging.getLogger( "mycodo.inputs.tsl2591_{bus}_{add}".format(bus=bus, add=address)) self.tsl = tsl2591.Tsl2591(i2c_bus=self.i2c_bus, sensor_address=self.i2c_address)
def __init__(self, input_dev, testing=False): super(TSL2591Sensor, self).__init__() self.logger = logging.getLogger("mycodo.inputs.tsl2591_sensor") self._lux = None if not testing: import tsl2591 self.logger = logging.getLogger( "mycodo.inputs.tsl2591_sensor_{id}".format(id=input_dev.id)) self.i2c_address = int(str(input_dev.location), 16) self.i2c_bus = input_dev.i2c_bus self.tsl = tsl2591.Tsl2591(i2c_bus=self.i2c_bus, sensor_address=self.i2c_address)
def __init__(self, input_dev, testing=False): super(InputModule, self).__init__() self.logger = logging.getLogger("mycodo.inputs.tsl2591_sensor") if not testing: import tsl2591 self.logger = logging.getLogger("mycodo.tsl2591_{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 = tsl2591.Tsl2591(i2c_bus=self.i2c_bus, sensor_address=self.i2c_address)
def Sense(filepath, whichDHT, whichDataPin): # keeps track of the time # hour = datetime.datetime.now().strftime("%H") #hour of day # minute = datetime.datetime.now().strftime("%M") #minute of hour tsl = tsl2591.Tsl2591() # initialize light sensor timeStamp = datetime.datetime.today().strftime("%H:%M:%S") #I'm concidering reducing the precision here, because it can be a bit confusing to look at; no need for microseconds. date = datetime.datetime.today().strftime("%Y-%m-%d") date2 = datetime.datetime.today() - datetime.timedelta(days=1) config = ReadConfig() if not os.path.exists('{}sensorOutput_{}.txt'.format(filepath, date)): OpenFile(filepath) if config["upload_once_per_day"] == 'True': pass UploadFile2(filepath, config["rclone_profile"], config["rclone_path"], date2.strftime("%Y-%m-%d")) else: pass f = open('{}sensorOutput_{}.txt'.format(filepath, date) ,'a') #initialize the temp/humidity sensor. The Adafruit_DHT function takes(which DHT sensor you are using, which GPIO data pin you are using) humidity, temperature = Adafruit_DHT.read_retry(whichDHT, whichDataPin) 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 #below prints outputs in shell, and writes them to output{date}.txt # This prints everything to the outut file in one line. print(date, timeStamp, temperature, humidity, full, ir, lux, sep=",", file=f) # This prints everything else to stdout. print("Temp: {0:0.1f} C\nHumidity: {1:0.1f} %\n".format(temperature, humidity)) #f.write("Temp: {0:0.1f} C\nHumidity: {1:0.1f}%\n".format(temperature, humidity)) print("Current date and time: \n", timeStamp) #f.write("Current date and time: {}\n".format(timeStamp)) print("Full Spectrum Light: {}\n".format(full)) #f.write("Full Spectrum Light: {}\n".format(full)) print("Infrared Light: {}\n".format(ir)) #f.write("Infrared Light: {}\n".format(ir)) print("Calculated Lux: {}\n".format(lux)) #f.write("Calculated Lux: {}\n".format(lux)) print("\n") #f.write("\n") return lux
def main(): ser = serial.Serial(SERIAL_PORT, SERIAL_BAUD) vehicle = connect(USB_PORT, baud=USB_BAUD, wait_ready=True) tsl = tsl2591.Tsl2591() #tsl.set_gain(tsl2591.GAIN_HIGH) GPIOPIN = 4 while True: try: # enter what appears to be a non-blocking loop. A blocking mode seems available. #msg = pixhawk.recv_match(blocking=False) #if msg: #handle_message(msg) t = {} t['hdg'] = round(vehicle.heading, DECIMAL_PLACES) t['spd'] = round(vehicle.groundspeed, DECIMAL_PLACES) t['alt'] = round(vehicle.location.global_frame.alt, DECIMAL_PLACES) t['dt'] = datetime.datetime.utcnow().isoformat() t['vol'] = vehicle.battery.voltage # millivolts t['cur'] = vehicle.battery.current # 10 * milliamperes humidity, temperature = read_am2302(GPIOPIN) t['tmp'] = round(temperature, DECIMAL_PLACES) #t['hum'] = round(humidity, DECIMAL_PLACES) lux = read_tsl2591(tsl) t['lux'] = int(lux) t['e'] = 0 telemetry = json.dumps(t, separators=(',', ':')) tpacket = telemetry.ljust(TELEMETRY_PACKET_SIZE).encode('latin-1') written = ser.write(tpacket) print('Wrote packet size %s' % written) #print(telemetry) if (ser.in_waiting >= CONTROL_PACKET_SIZE): raw_data = ser.read(size=CONTROL_PACKET_SIZE) on_control(raw_data, vehicle) except KeyboardInterrupt: print('KeyboardInterrupt - closing') break except IOError: print('IOError - packet not sent') print('\nClosing serial connections...') vehicle.close() ser.close()
def main(): data_set = [] while True: tsl = tsl2591.Tsl2591() full, ir = tsl.get_full_luminosity() lux = tsl.calculate_lux(full, ir) data = {'data1': lux} data_set.append(data) #print "Luminosity = {} lux".format(lux) if len(data_set) >= AVERAGE_READ: average_data = average(data_set) timestamp, avg_lux, max_lux, min_lux = average_data csvwrite([timestamp, min_lux, avg_lux, max_lux]) del data_set[:] sleep(1)
def Sense(filepath, whichDHT, whichDataPin): #keeps track of the time hour = datetime.datetime.now().strftime("%H") #hour of day minute = datetime.datetime.now().strftime("%M") #minute of hour #prevents the rest of the script from running from 11:59 to 12:01 to prevent scheduling conflicts with other programs. if hour != 11 or minute != 59: if hour != 0 or minute != 0: tsl = tsl2591.Tsl2591() # initialize light sensor timeStamp = datetime.datetime.now( ) #I'm concidering reducing the precision here, because it can be a bit confusing to look at; no need for microseconds. date = datetime.datetime.now().strftime("%m-%d-%y") f = open('{}sensorOutput_{}.txt'.format(filepath, date), 'a') #initialize the temp/humidity sensor. The Adafruit_DHT function takes(which DHT sensor you are using, which GPIO data pin you are using) humidity, temperature = Adafruit_DHT.read_retry( whichDHT, whichDataPin) 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 #below prints outputs in shell, and writes them to output{date}.txt print("Temp: {0:0.1f} C\nHumidity: {1:0.1f} %\n".format( temperature, humidity)) f.write("Temp: {0:0.1f} C\nHumidity: {1:0.1f}%\n".format( temperature, humidity)) print("Current date and time: \n", timeStamp) f.write("Current date and time: {}\n".format(timeStamp)) print("Full Spectrum Light: {}\n".format(full)) f.write("Full Spectrum Light: {}\n".format(full)) print("Infrared Light: {}\n".format(ir)) f.write("Infrared Light: {}\n".format(ir)) print("Calculated Lux: {}\n".format(lux)) f.write("Calculated Lux: {}\n".format(lux)) print("\n") f.write("\n") return lux
def getSensors(): tsl = tsl2591.Tsl2591() data_temp_pres = getBMP280() time.sleep(0.2) full, ir = tsl.get_full_luminosity() tsl.bus.close() data = { "temperature": "%.2f" % (data_temp_pres[0]), "temperature_unit": "Celcius", "pressure": "%.2f" % (data_temp_pres[1]), "pressure_unit": "Millibar", "luminosity_full": "%.2f" % (tsl.calculate_lux(full, ir)), "luminosity_full_unit": "Lux", "luminosity_visible": "%.2f" % (full), "luminosity_visisble_unit": "Raw", "luminosity_ir": "%.2f" % (ir), "luninosity_ir_unit": "Raw" } #return { json.dumps(data) } return (data)
def measure(): """Read the soil moisture level and return it as a dictionary""" now = datetime.now(pytz.timezone('UTC')).astimezone( pytz.timezone("US/Pacific")).strftime("%Y-%m-%d %H:%M:%S") try: tsl = tsl2591.Tsl2591() # initialize 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 return { 'task': 'sun_reading', 'status': 'success', 'value_numeric': lux, 'value_enum': None, 'timestamp': now } except BaseException as err: return { 'task': 'sun_reading', 'status': 'failure', 'value_numeric': None, 'value_enum': None, 'timestamp': now }
sensor_error = 1000 if args.error == True: sensor_error = args.error #read csv file csvData = pd.read_csv(args.csv) dataMatrix = csvData.as_matrix() luxval, luxdur = np.split(dataMatrix, 2, axis = 1) #sum durations to get start time for each value luxtimes = np.cumsum(luxdur)-luxdur exp_start = args.start exp_dur = args.duration sensor = tsl2591.Tsl2591() while time.time() < exp_start: time.sleep(1) arr_ind = 0 cur_time = time.time() - exp_start while cur_time < exp_dur while cur_time < luxtimes[arr_ind]: arr_ind+=1 if cur_time % sensor_delay == 0: full, ir = self.sensor.get_full_luminosity() lux = self.sensor.calculate_lux(full, ir) if abs(luxval[arr_ind]-lux) > sensor_error: #TODO:Make error message/export to file
#| pins provided below only for reference): #| - SCL (for I2C) => Pin 9; Configured in included tsl2591.py file, not here #| - SDA (for I2C) => Pin 10; Configured in included tsl2591.py file, not here #| #| Sparkfun Sound Detector: #| - Envelope => Pin 13 ("audioEnvelope"); used as ADC Input w/ 11DB Attenuation for nearly linear 0-3.3V range #| #| *For battery voltage monitoring: Hookup voltage input to Pin 15 ("battery_voltage") #| *To enable Opto-JFET to allow 5V power to sensors, Pin 19 is used ("sensor_power") #----------------------------------------------------------------------------------------- trigger_1 = Pin('P21', mode=Pin.OUT) echo_1 = Pin('P22', mode=Pin.IN) trigger_2 = Pin('P23', mode=Pin.OUT) echo_2 = Pin('P18', mode=Pin.IN) tsl = tsl2591.Tsl2591( 0) #Pins 9 and 10 are dedicated to the Ambient Light Sensor audioEnvelope = adc.channel(pin='P13', attn=ADC.ATTN_11DB) battery_voltage = adc.channel(pin='P15', attn=ADC.ATTN_11DB) sensor_power = Pin('P19', mode=Pin.OUT) #----------------------------------------------------------------------------------------- #| Initialize Misc. Variables used during operation: #----------------------------------------------------------------------------------------- count = 0 sleep_time = 10000 latest_readings = [] distance_to_use = 0 flow_rate_integer = -1 presence_of_debris = False
pre_time = 0 elapsed_time = 100 sensor = Adafruit_DHT.AM2302 # 2302 pin = 4 # Parse command line parameters. sensor_args = { '11': Adafruit_DHT.DHT11, '22': Adafruit_DHT.DHT22, '2302': Adafruit_DHT.AM2302 } print "Sensor Module Testing (CTRL+C to exit)" GPIO.setmode(GPIO.BCM) GPIO.setup(PIR_PIN, GPIO.IN) time.sleep(2) tsl = tsl2591.Tsl2591() # initialize def temp_hum_light_loop(): global temperature, humidity, lux 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 #print lux, full, ir humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) temperature = temperature * 1.8 + 32 if humidity is None and temperature is None: print('Failed to get reading. Try again!') sys.exit(1)
import machine import ubinascii import tsl2591 #Setup and Configuration #Initialize Sensor Pinout adc = ADC(0) adc.vref(1108) adc.init(bits=12) trigger_1 = Pin('P21', mode=Pin.OUT) echo_1 = Pin('P22', mode=Pin.IN) trigger_2 = Pin('P23', mode=Pin.OUT) echo_2 = Pin('P18', mode=Pin.IN) audioEnvelope = adc.channel(pin='P13', attn=ADC.ATTN_11DB) #Pins 9 and 10 are dedicated to the Ambient Light Sensor tsl = tsl2591.Tsl2591(0) #Initialize ADC count = 0 sleep_time = 10000 latest_readings = [] distance_to_use = 0 presence_of_debris = False pycom.heartbeat(False) #Sensor Threshold values Sound_Level_low = 270 Sound_Level_medium = 400 Sound_Level_high = 600 Water_Level_normal = 11
def __setstate__(self, state): self.__dict__.update(state) self.tsl = tsl2591.Tsl2591()
def get_lux(self): tsl = tsl2591.Tsl2591() full, ir = tsl.get_full_luminosity() lux = tsl.calculate_lux(full, ir) print("Lux Reading:", lux) return lux
def get_full(self): tsl = tsl2591.Tsl2591() full, ir = tsl.get_full_luminosity() print("Full Reading:", full) return full
def get_ir(self): tsl = tsl2591.Tsl2591() full, ir = tsl.get_full_luminosity() print("Infra-Red Reading", ir) return ir