aboutsummaryrefslogtreecommitdiff
path: root/AT91SAM7S256/armdebug/nxt-python-fantom/nxt/bluesock.py
blob: 99917f2e7cfb9181b53d393c36f40b1390dbac1c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# nxt.bluesock module -- Bluetooth socket communication with LEGO Minstorms NXT
# Copyright (C) 2006, 2007  Douglas P Lau
# Copyright (C) 2009  Marcus Wanner
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

try:
    import fantomglue as bluetooth
except ImportError:
    try:
        import bluetooth
    except ImportError:
        import lightblueglue as bluetooth
        
import os
from .brick import Brick

class BlueSock(object):

    bsize = 118  # Bluetooth socket block size
    PORT = 1     # Standard NXT rfcomm port

    def __init__(self, host):
        self.host = host
        self.sock = None
        self.debug = False

    def __str__(self):
        return 'Bluetooth (%s)' % self.host

    def connect(self):
        if self.debug:
            print 'Connecting via Bluetooth...'
        sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
        sock.connect((self.host, BlueSock.PORT))
        self.sock = sock
        if self.debug:
            print 'Connected.'
        return Brick(self)

    def close(self):
        if self.debug:
            print 'Closing Bluetooth connection...'
        self.sock.close()
        if self.debug:
            print 'Bluetooth connection closed.'

    def send(self, data):
        if self.debug:
            print 'Send:',
            print ':'.join('%02x' % ord(c) for c in data)
        l0 = len(data) & 0xFF
        l1 = (len(data) >> 8) & 0xFF
        d = chr(l0) + chr(l1) + data
        self.sock.send(d)

    def recv(self):
        data = self.sock.recv(2)
        l0 = ord(data[0])
        l1 = ord(data[1])
        plen = l0 + (l1 << 8)
        data = self.sock.recv(plen)
        if self.debug:
            print 'Recv:',
            print ':'.join('%02x' % ord(c) for c in data)
        return data

def _check_brick(arg, value):
    return arg is None or arg == value

def find_bricks(host=None, name=None):
    for h, n in bluetooth.discover_devices(lookup_names=True):
        if _check_brick(host, h) and _check_brick(name, n):
            yield BlueSock(h)