AmbientOrb-Serial

 view release on metacpan or  search on metacpan

lib/AmbientOrb/Serial.pm  view on Meta::CPAN


    my $message = $self->color_to_ascii( $color, $anim );

    my $result = $self->send( $message );
    if ( not $result =~ "A+" )
    {
	return 0;
    }
    return 1;
       
}

=head2 pulse
The pulse method instructs the orb to change its color and pulse.

It takes a two arguments -- the color to turn to, and the pulse frequency.

=cut

sub pulse
{
    my ( $self, $color, $anim ) = @_;
    return $self->color( $color, $anim );
}

#private methods

sub create_serial_port
{
    my ( $port_name ) = @_;
    my $serial_port;

    if ( $OS_win )
    {
	$serial_port = Win32::SerialPort->new( $port_name );
    }
    else
    {
	$serial_port = Device::SerialPort->new( $port_name );
    }
    
    croak "unable to connect to serial port $port_name: $^E"
	unless $serial_port;

    #as per the specification
    $serial_port->baudrate(19200);
    $serial_port->databits(8);
    $serial_port->stopbits(1);
    $serial_port->parity("none");
    $serial_port->handshake("none");
    return $serial_port;
}
	
	

sub send {
    my ( $self, $message ) = @_;
    $self->serial_port->write( $message );
    my $result;

    #the docs say that you have to poll a lot to get the 
    #correct result back.  there is no doubt a better way 
    #to do this, but 1000 seems to be a nice magic number 
    for ( 1 .. 1000 )
    {
	$result = $self->serial_port->input;
	if ( $result =~ /\w+/ )
	{
	    last;
	}
    }
    return $result;
}
	
sub color_to_ascii
{
    my ( $self, $color, $anim ) = @_;

    my $colorval = $color_map{$color};

    croak "unknown color $colorval!" unless defined $colorval;

    $anim = $animation_map{$anim} if defined $anim;
    $anim ||= 0;

    my $firstByte   = ( ($colorval + ( 37 * $anim)) / 94 ) + 32;
    my $secondByte  = ( ($colorval + ( 37 * $anim)) % 94 ) + 32 ;
		      
    $secondByte = sprintf("%c", $secondByte);
    $firstByte  = sprintf("%c", $firstByte );
    my $packme  = "~A" . $firstByte . $secondByte;
    my $message = pack("a4", $packme);
    
    return $message;
}

sub DESTROY
{
    my ( $self ) = @_;
    if ( defined $self->serial_port )
    {
	$self->serial_port->close() || warn "unable to close serial port!\n";
	undef $self->serial_port;
    }
}

1; # End of AmbientOrb::Serial



( run in 1.429 second using v1.01-cache-2.11-cpan-a1f116cd669 )