Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/nxt_plugin/nxt/ipsock.py
blob: 66c1a511cb60a6364e617c28a22e0fef47889936 (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
# nxt.ipsock module -- Server socket communication with LEGO Minstorms NXT
# Copyright (C) 2011  zonedaobne, 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.

import socket
from nxt.brick import Brick

class IpSock(object):
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.sock = None
        self.debug = False

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

    def connect(self):
        if self.debug:
            print 'Connecting via Server...'
        sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((self.host, self.port))
        #TODO: sasl authentication here?
        self.sock = sock
        if self.debug:
            print 'Connected.'
        self.send('\x98')
        self.type = 'ip'+self.recv()
        return Brick(self)

    def close(self):
        if self.debug:
            print 'Closing Server connection...'
        self.sock.send('\x99')
        self.sock.close()
        if self.debug:
            print 'Server connection closed.'

    def send(self, data):
        if self.debug:
            print 'Send:',
            print ':'.join('%02x' % ord(c) for c in data)
        self.sock.send(data)

    def recv(self):
        data = self.sock.recv(1024)
        if self.debug:
            print 'Recv:',
            print ':'.join('%02x' % ord(c) for c in data)
        return data

#TODO: add a find_bricks method and a corresponding broadcast system to nxt_server?