Mercurial > ~darius > hgwebdir.cgi > ZigBee
annotate zbmux.py @ 16:ce3712110055
Remove superfluous debugging.
author | darius@Inchoate |
---|---|
date | Sat, 17 Jan 2009 21:44:17 +1030 |
parents | a472d6eab97e |
children |
rev | line source |
---|---|
12 | 1 # |
2 # Mux the ZB module to TCP ports | |
3 # | |
4 # Copyright (c) 2009 | |
5 # Daniel O'Connor <darius@dons.net.au>. All rights reserved. | |
6 # | |
7 # Redistribution and use in source and binary forms, with or without | |
8 # modification, are permitted provided that the following conditions | |
9 # are met: | |
10 # 1. Redistributions of source code must retain the above copyright | |
11 # notice, this list of conditions and the following disclaimer. | |
12 # 2. Redistributions in binary form must reproduce the above copyright | |
13 # notice, this list of conditions and the following disclaimer in the | |
14 # documentation and/or other materials provided with the distribution. | |
15 # | |
16 # THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND | |
17 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | |
18 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE | |
19 # ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE | |
20 # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | |
21 # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS | |
22 # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) | |
23 # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT | |
24 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY | |
25 # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF | |
26 # SUCH DAMAGE. | |
27 # | |
28 | |
29 from twisted.internet.serialport import SerialPort | |
30 from twisted.internet.protocol import Protocol | |
14 | 31 from twisted.conch.telnet import TelnetTransport, TelnetBootstrapProtocol |
32 from twisted.conch.insults import insults | |
12 | 33 from twisted.protocols import basic |
34 from twisted.internet import protocol, reactor | |
35 from twisted.python import log | |
14 | 36 import sys, zb, logging, logging.handlers, string |
12 | 37 |
38 portname = '/dev/cuaU0' | |
39 baudrate = 38400 | |
40 lognamebase = '/tmp/zbmux-%d.log' | |
41 baseport = 1080 | |
42 zbids = [1, 2] | |
43 | |
14 | 44 class ZBClient(insults.TerminalProtocol): |
12 | 45 """Client for the TCP connection""" |
14 | 46 #: Time to wait before sending pending data (seconds) |
47 QUEUE_TIME = 0.1 | |
48 | |
12 | 49 def connectionMade(self): |
50 log.msg("Got new client") | |
14 | 51 self.terminal.eraseDisplay() |
52 self.terminal.resetPrivateModes([]) | |
53 | |
54 # Send the last whole line we've seen out | |
15
a472d6eab97e
Play back the last 5 lines to newly connected clients rather than 1.
darius@Inchoate
parents:
14
diff
changeset
|
55 for l in self.factory.lastlines: |
a472d6eab97e
Play back the last 5 lines to newly connected clients rather than 1.
darius@Inchoate
parents:
14
diff
changeset
|
56 self.message(l + '\n') |
14 | 57 |
58 self.pending = "" | |
59 self.pendtimer = None | |
60 self.factory.clients.append(self) | |
12 | 61 |
62 def connectionLost(self, reason): | |
63 log.msg("Lost a client") | |
64 self.factory.clients.remove(self) | |
14 | 65 |
66 def keystrokeReceived(self, keyID, modifier): | |
67 """Got some data, add it to the pending output queue""" | |
68 if modifier != None: | |
69 print "Received unhandled modifier: %s" % (str(modifier)) | |
70 return | |
71 #if keyID not in string.printable: | |
72 # print "Received unhandled keyID: %r" % (keyID,) | |
73 # return | |
74 #log.msg("Got key ->%s<-" % (keyID)) | |
75 self.pending = self.pending + keyID | |
76 if self.pendtimer == None: | |
77 self.pendtimer = reactor.callLater(self.QUEUE_TIME, self.sendData) | |
78 | |
79 def sendData(self): | |
80 """Send pending data to module""" | |
81 #log.msg("sending " + self.pending) | |
82 self.factory.zbproto.sendData(self.factory.zbid, self.pending) | |
83 self.pending = "" | |
84 self.pendtimer = None | |
85 | |
12 | 86 def message(self, message): |
87 """Called to write a mesage to our client""" | |
14 | 88 self.terminal.write(message) |
12 | 89 |
90 class ZBFactory(protocol.ServerFactory): | |
91 """Factory for a ZB module | |
92 | |
93 Represents a remote ZB module and has zero or more clients and a log file. | |
94 """ | |
95 protocol = ZBClient | |
96 | |
14 | 97 def __init__(self, zbid, lognamebase): |
12 | 98 self.zbid = zbid |
99 self.clients = [] | |
100 self.tmpline = "" | |
15
a472d6eab97e
Play back the last 5 lines to newly connected clients rather than 1.
darius@Inchoate
parents:
14
diff
changeset
|
101 self.lastlines = [] |
12 | 102 |
103 # Open logger | |
104 self.logger = logging.getLogger('Zigbee-%d' % (zbid)) | |
105 self.logger.setLevel(logging.DEBUG) | |
106 | |
107 # Add the log message handler to the logger | |
108 handler = logging.handlers.RotatingFileHandler( | |
109 lognamebase % (zbid), maxBytes = 20 * 1024, backupCount = 5) | |
110 | |
111 self.logger.addHandler(handler) | |
112 | |
113 def message(self, zbid, message): | |
114 """Called when we get a message, check it's for us - if it is log it and write to our clients""" | |
115 if zbid != self.zbid: | |
116 return | |
117 | |
118 for c in self.clients: | |
119 c.message(message) | |
120 | |
121 # Logger is line oriented, convert from packet oriented here | |
122 self.tmpline = self.tmpline + message | |
123 tmp = self.tmpline.split('\n') | |
124 for l in tmp[0:-1]: | |
15
a472d6eab97e
Play back the last 5 lines to newly connected clients rather than 1.
darius@Inchoate
parents:
14
diff
changeset
|
125 self.lastlines.append(l) |
a472d6eab97e
Play back the last 5 lines to newly connected clients rather than 1.
darius@Inchoate
parents:
14
diff
changeset
|
126 self.lastlines = self.lastlines[-5:] |
12 | 127 self.logger.debug(l.replace('\n', '')) |
128 self.tmpline = tmp[-1] | |
129 | |
130 class ZBProto(Protocol): | |
131 """Protocol to handle packets from the ZB module on the serial port""" | |
132 def __init__(self): | |
133 self.pkts = zb.Packets() | |
134 self.factories = [] | |
135 | |
136 def dataReceived(self, data): | |
137 """Parses data from ZB module into packets, calls each factory if a RX packet is received""" | |
138 #log.msg("Read data " + data) | |
139 if self.pkts.processstr(data) > 0: | |
140 while len(self.pkts.pktq) > 0: | |
141 a = self.pkts.pktq.pop(0) | |
142 #log.msg("type is " + str(type(a))) | |
143 if type(a) == type(zb.RX_16_Bit()): | |
144 #log.msg("Rx'd from %d => %s" % (a.sender, a.payloadstr)) | |
145 for f in self.factories: | |
146 f.message(a.sender, a.payloadstr) | |
14 | 147 if type(a) == type(zb.TX_Status()): |
148 #log.msg("Tx status for frame %d is %s" % (a.frameid, a.statusMsg)) | |
149 pass | |
150 | |
12 | 151 def sendData(self, zbid, data): |
152 """Sends a chunk of data to our ZB module""" | |
153 #log.msg("%d <= %s" % (zbid, data)) | |
14 | 154 |
12 | 155 # Chop up data into pieces the module can handle |
14 | 156 maxsz = zb.TX_16_Bit.PKT_MAX_PAYLOAD |
12 | 157 for i, j in zip(range(0, len(data), maxsz), range(maxsz, len(data) + maxsz, maxsz)): |
158 p = zb.TX_16_Bit(zbid, data[i:j]) | |
159 self.transport.write(p.Pack()) | |
160 #log.msg("sent " + str(p)) | |
14 | 161 |
12 | 162 if __name__ == '__main__': |
163 logFile = sys.stdout | |
164 log.startLogging(logFile) | |
165 | |
166 # ZigBee serial protocol handler | |
167 zbproto = ZBProto() | |
168 SerialPort(zbproto, portname, reactor, baudrate = 38400) | |
169 | |
170 # Per-module TCP listener | |
171 for id in zbids: | |
14 | 172 f = ZBFactory(id, lognamebase) |
173 f.zbproto = zbproto | |
174 f.protocol = lambda: TelnetTransport(TelnetBootstrapProtocol, | |
175 insults.ServerProtocol, | |
176 ZBClient) | |
177 zbproto.factories.append(f) | |
178 reactor.listenTCP(baseport + id, f) | |
12 | 179 |
180 reactor.run() |