| 1 | package LEGO::NXT::BlueComm; | ||
| 2 | |||
| 3 | 0 | ▶ | use Net::Bluetooth; |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 4 | use LEGO::NXT::Constants; | ||
| 5 | use strict; | ||
| 6 | |||
| 7 | =head1 NAME | ||
| 8 | |||
| 9 | LEGO::NXT::BlueComm - The Bluetooth Communication Module For the NXT | ||
| 10 | |||
| 11 | =head1 SYNOPSIS | ||
| 12 | |||
| 13 | use LEGO::NXT::BlueComm; | ||
| 14 | |||
| 15 | $comm = new LEGO::NXT::BlueComm('xx:xx:xx:xx',0); | ||
| 16 | |||
| 17 | =head1 DESCRIPTION | ||
| 18 | |||
| 19 | Presents a Bluetooth comm interface to the LEGO NXT for internal use in the L<LEGO::NXT> module. | ||
| 20 | |||
| 21 | =head1 METHODS | ||
| 22 | |||
| 23 | =head2 new | ||
| 24 | |||
| 25 | $btaddr = 'xx:xx:xx:xx'; | ||
| 26 | $port = 0; | ||
| 27 | $comm = new LEGO::NXT:BlueComm($btaddr,$port); | ||
| 28 | $nxt = LEGO::NXT->new( $comm ); | ||
| 29 | |||
| 30 | Creates a new Bluetooth comm object. $btaddr is the bluetooth address of your NXT - can be obtained by "hcitool scan" on Linux platforms. $port should be 0 or 1. | ||
| 31 | |||
| 32 | =cut | ||
| 33 | |||
| 34 | sub new | ||
| 35 | { | ||
| 36 | my ($pkg,$btaddr,$channel) = @_; | ||
| 37 | |||
| 38 | my $this = { | ||
| 39 | 'btaddr' => $btaddr , | ||
| 40 | 'channel' => $channel || 0, | ||
| 41 | 'fh' => undef , | ||
| 42 | 'status' => 0 | ||
| 43 | }; | ||
| 44 | |||
| 45 | bless $this, $pkg; | ||
| 46 | $this; | ||
| 47 | } | ||
| 48 | |||
| 49 | |||
| 50 | sub connect | ||
| 51 | { | ||
| 52 | my ($this) = @_; | ||
| 53 | |||
| 54 | my $bt = Net::Bluetooth->newsocket("RFCOMM"); | ||
| 55 | die "Socket could not be created!" unless(defined($bt)); | ||
| 56 | |||
| 57 | if($bt->connect($this->{btaddr}, $this->{channel} ) != 0) { | ||
| 58 | die "connect error: $!"; | ||
| 59 | } | ||
| 60 | |||
| 61 | $this->{fh} = $bt->perlfh(); | ||
| 62 | $| = 1; #just in case our pipes are not already hot. | ||
| 63 | |||
| 64 | $bt; | ||
| 65 | } | ||
| 66 | |||
| 67 | sub do_cmd | ||
| 68 | { | ||
| 69 | my ($this,$msg,$needsret) = @_; | ||
| 70 | |||
| 71 | $this->connect() unless defined $this->{fh}; | ||
| 72 | |||
| 73 | my $fh = $this->{fh}; | ||
| 74 | |||
| 75 | syswrite( $fh, $msg, length $msg ); | ||
| 76 | return if( $needsret == $NXT_NORET ); | ||
| 77 | |||
| 78 | #Begin reading response, if requested. | ||
| 79 | |||
| 80 | my ($rin, $rout) = ('',''); | ||
| 81 | my $rbuff; | ||
| 82 | my $total; | ||
| 83 | |||
| 84 | vec ($rin, fileno($fh), 1) = 1; | ||
| 85 | |||
| 86 | while( select($rout=$rin, undef, undef, 1) ) | ||
| 87 | { | ||
| 88 | my $char = ''; | ||
| 89 | my $nread=0; | ||
| 90 | |||
| 91 | eval | ||
| 92 | { | ||
| 93 | local $SIG{ALRM} = sub { die "alarm\n" }; | ||
| 94 | alarm 1; | ||
| 95 | $nread = sysread $fh, $char, 1; | ||
| 96 | alarm 0; | ||
| 97 | }; | ||
| 98 | $rbuff .= $char; | ||
| 99 | } | ||
| 100 | return $rbuff; | ||
| 101 | } | ||
| 102 | |||
| 103 | sub type { 'blue' } | ||
| 104 | |||
| 105 | 1; | ||