#
# http://www.toolz.com - software@toolz.com
# 
# $Id: LUX.pm,v 1.1 2023/10/04 21:44:53 todd Exp $
#
# This module is made to work with the TSL2561 Lux sensor.
# Datasheet at https://cdn-shop.adafruit.com/datasheets/TSL2561.pdf
# Hardware configuration: https://cdn-shop.adafruit.com/datasheets/TSL2561.pdf
#
# readVal returns an array, element 0 is IR + visible, element 1 is visible
# light.
# See the documentation for RPi::I2C for info on how to determine how your
# I2C bus is defined and required prerequisites.  The Raspberry Pi defaults are assumed.
#
# There are no license restrictions on this code.
#
use warnings;
package RPi::I2C::LUX;
our $VERSION = '1.1';
require Exporter;
our @ISA = qw(Exporter);
@EXPORT = qw(readVal);
use Time::HiRes;

# TSL2561 Address
$DEVADDR = 0x39;	# default address on i2c bus

sub new
{
	my ($class,%args) = @_;
	my $key;

	# defaults
	my %params = (
		devaddr		=>	$DEVADDR,
		busno			=>	1,	# 0, 1
		version		=> "$VERSION",
	);

	# default overrides
	foreach $key (keys %args)
	{
		$params{$key} = $args{$key};
	}
	$params{bus} = 		RPi::I2C->new ($params{devaddr});
	foreach $key (keys %params) { $self->{$key} = $params{$key}; }
	bless $self, $class;

	# Select control register, 0x00(00) with command register, 0x80(128)
	# 		0x03(03)	Power ON mode
	$self->{bus}->write_byte(0x03,0x00|0x80);
	# Select timing register, 0x01(01) with command register, 0x80(128)
	# 		0x02(02)	Nominal integration time = 402ms
	$self->{bus}->write_byte(0x02,0x01|0x80);		# integration time
	sleep(0.5);

	return $self;
}

sub readVal
{
	my ($self,$byte) = @_;
	my @data = (0,0);
	my @data1 = (0,0);

	@data = $self->{bus}->read_block(2,0x0C | 0x80);
	@data1 = $self->{bus}->read_block(2,0x0E | 0x80);
	my $ch0 = ($data[1] * 256) + $data[0];
	my $ch1 = ($data1[1] * 256) + $data1[0];

	return ($ch0,$ch0-$ch1);	# IR+visible, visible
}

1;

