Package nxt :: Module usbsock

Source Code for Module nxt.usbsock

 1  # nxt.usbsock module -- USB socket communication with LEGO Minstorms NXT 
 2  # Copyright (C) 2006-2007  Douglas P Lau 
 3  # Copyright (C) 2009  Marcus Wanner 
 4  # 
 5  # This program is free software: you can redistribute it and/or modify 
 6  # it under the terms of the GNU General Public License as published by 
 7  # the Free Software Foundation, either version 3 of the License, or 
 8  # (at your option) any later version. 
 9  # 
10  # This program is distributed in the hope that it will be useful, 
11  # but WITHOUT ANY WARRANTY; without even the implied warranty of 
12  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
13  # GNU General Public License for more details. 
14   
15  import usb 
16  from nxt.brick import Brick 
17   
18  ID_VENDOR_LEGO = 0x0694 
19  ID_PRODUCT_NXT = 0x0002 
20   
21 -class USBSock(object):
22 'Object for USB connection to NXT' 23 24 bsize = 60 # USB socket block size 25
26 - def __init__(self, device):
27 self.device = device 28 self.handle = None 29 self.debug = False
30
31 - def __str__(self):
32 return 'USB (%s)' % (self.device.filename)
33
34 - def connect(self):
35 'Use to connect to NXT.' 36 if self.debug: 37 print 'Connecting via USB...' 38 config = self.device.configurations[0] 39 iface = config.interfaces[0][0] 40 self.blk_out, self.blk_in = iface.endpoints 41 self.handle = self.device.open() 42 self.handle.setConfiguration(1) 43 self.handle.claimInterface(0) 44 self.handle.reset() 45 if self.debug: 46 print 'Connected.' 47 return Brick(self)
48
49 - def close(self):
50 'Use to close the connection.' 51 if self.debug: 52 print 'Closing USB connection...' 53 self.device = None 54 self.handle = None 55 self.blk_out = None 56 self.blk_in = None 57 if self.debug: 58 print 'USB connection closed.'
59
60 - def send(self, data):
61 'Use to send raw data over USB connection ***ADVANCED USERS ONLY***' 62 if self.debug: 63 print 'Send:', 64 print ':'.join('%02x' % ord(c) for c in data) 65 self.handle.bulkWrite(self.blk_out.address, data)
66
67 - def recv(self):
68 'Use to recieve raw data over USB connection ***ADVANCED USERS ONLY***' 69 data = self.handle.bulkRead(self.blk_in.address, 64) 70 if self.debug: 71 print 'Recv:', 72 print ':'.join('%02x' % (c & 0xFF) for c in data) 73 # NOTE: bulkRead returns a tuple of ints ... make it sane 74 return ''.join(chr(d & 0xFF) for d in data)
75
76 -def find_bricks(host=None, name=None):
77 'Use to look for NXTs connected by USB only. ***ADVANCED USERS ONLY***' 78 # FIXME: probably should check host and name 79 for bus in usb.busses(): 80 for device in bus.devices: 81 if device.idVendor == ID_VENDOR_LEGO and \ 82 device.idProduct == ID_PRODUCT_NXT: 83 yield USBSock(device)
84