Package nxt :: Module bluesock

Source Code for Module nxt.bluesock

 1  # nxt.bluesock module -- Bluetooth 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 bluetooth 
16  import os 
17  from nxt.brick import Brick 
18   
19 -class BlueSock(object):
20 21 bsize = 118 # Bluetooth socket block size 22 PORT = 1 # Standard NXT rfcomm port 23
24 - def __init__(self, host):
25 self.host = host 26 self.sock = None 27 self.debug = False
28
29 - def __str__(self):
30 return 'Bluetooth (%s)' % self.host
31
32 - def connect(self):
33 if self.debug: 34 print 'Connecting via Bluetooth...' 35 sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) 36 sock.connect((self.host, BlueSock.PORT)) 37 self.sock = sock 38 if self.debug: 39 print 'Connected.' 40 return Brick(self)
41
42 - def close(self):
43 if self.debug: 44 print 'Closing Bluetooth connection...' 45 self.sock.close() 46 if self.debug: 47 print 'Bluetooth connection closed.'
48
49 - def send(self, data):
50 if self.debug: 51 print 'Send:', 52 print ':'.join('%02x' % ord(c) for c in data) 53 l0 = len(data) & 0xFF 54 l1 = (len(data) >> 8) & 0xFF 55 d = chr(l0) + chr(l1) + data 56 self.sock.send(d)
57
58 - def recv(self):
59 data = self.sock.recv(2) 60 l0 = ord(data[0]) 61 l1 = ord(data[1]) 62 plen = l0 + (l1 << 8) 63 data = self.sock.recv(plen) 64 if self.debug: 65 print 'Recv:', 66 print ':'.join('%02x' % ord(c) for c in data) 67 return data
68
69 -def _check_brick(arg, value):
70 return arg is None or arg == value
71
72 -def find_bricks(host=None, name=None):
73 for h, n in bluetooth.discover_devices(lookup_names=True): 74 if _check_brick(host, h) and _check_brick(name, n): 75 yield BlueSock(h)
76