NXT/USBComm.pm untested

filter: Statementstmt 0.0% 0 / 47 Branchbran 0.0% 0 / 6 Conditioncond 0.0% 0 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 0.0% 0 / 7 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 69 CC 4 SCAR 17.6
CC
4
Cov
0%
do_cmd
12.0
connect
6.0
new
2.0
CRAP 5.8
1 package LEGO::NXT::USBComm;
2  
3 use Device::USB;
4 use LEGO::NXT::Constants;
5 use strict;
6  
7 =head1 NAME
8  
9 LEGO::NXT::USBComm - The USB Communication Module For the NXT
10  
11 =head1 SYNOPSIS
12  
13 use LEGO::NXT::USBComm;
14  
15 $comm = new LEGO::NXT::USBComm();
16  
17 =head1 DESCRIPTION
18  
19 Presents a USB comm interface to the LEGO NXT for internal use in the L<LEGO::NXT> module.
20  
21 =cut
22  
23 my $USB_ID_VENDOR_LEGO = 0x0694;
24 my $USB_ID_PRODUCT_NXT = 0x0002;
25 my $USB_OUT_ENDPOINT = 0x01;
26 my $USB_IN_ENDPOINT = 0x82;
27 my $USB_TIMEOUT = 1000;
28 my $USB_READSIZE = 64;
29 my $USB_INTERFACE = 0;
30  
31 =head1 METHODS
32  
33 =head2 new
34  
35 $interface = 0;
36 $comm = new LEGO::NXT:USBComm($interface)
37 $nxt = LEGO::NXT->new( $comm );
38  
39 Creates a new USB comm object. $interface will usually be 0 unless you're using more than one NXT.
40  
41 =cut
42  
43 sub new
44 {
45 my ($pkg,$interface) = @_;
46  
47 my $this = {
48 'interface' => $interface || $USB_INTERFACE,
49 'fh' => undef ,
50 'device_name' => undef ,
51 'id' => undef ,
52 'serial' => undef ,
53 'status' => 0
54 };
55  
56 bless $this, $pkg;
57 $this;
58 }
59  
60  
61 sub connect
62 {
63 my ($this) = @_;
64
65 my $usb = Device::USB->new();
66  
67 my $dev = $usb->find_device($USB_ID_VENDOR_LEGO, $USB_ID_PRODUCT_NXT);
68 die "Device not found.\n" unless defined $dev;
69  
70 $dev->open();
71 $dev->reset();
72  
73 $this->{device_name} = $dev->filename();
74 $this->{id} = sprintf("%04x:%04x", $dev->idVendor(), $dev->idProduct() );
75 $this->{serial} = $dev->serial_number();
76  
77 $dev->claim_interface($USB_INTERFACE);
78 $this->{fh} = $dev;
79 $|=1; #HOT PIPES
80 $dev;
81 }
82  
83 sub do_cmd
84 {
85 my ($this,$request,$needsret) = @_;
86  
87 $this->connect unless $this->{fh};
88  
89 my $dev = $this->{fh};
90  
91 $dev->bulk_write($USB_OUT_ENDPOINT, $request, length($request), $USB_TIMEOUT);
92  
93 return if( $needsret == $NXT_NORET );
94  
95 my $buf = "\0" x $USB_READSIZE;
96 my $response ='';
97 my $len;
98 my $nread;
99 $|=1;
100  
101 $dev->bulk_read($USB_IN_ENDPOINT, $buf, $USB_READSIZE, $USB_TIMEOUT);
102  
103 $buf;
104 }
105  
106  
107  
108 sub type { 'usb' }
109  
110 1;