comparison server/ts.py @ 21:2029633912c2

untested simple server proxy code
author Matt Johnston <matt@ucc.asn.au>
date Tue, 22 May 2012 23:45:16 +0800
parents
children 885532437100
comparison
equal deleted inserted replaced
20:878be5e353a0 21:2029633912c2
1 #!/usr/bin/env python2.7
2
3 import sys
4 import httplib
5
6 lightblue = None
7 try:
8 import lightblue
9 except ImportError:
10 import bluetooth
11
12 BTADDR = "00:12:03:27:70:88"
13
14 def get_socket(addr):
15 if lightblue:
16 s = lightblue.socket()
17 s.connect(addr, 1)
18 else:
19 s = bluetooth.BluetoothSocket( bluetooth.RFCOMM )
20 s.connect((addr, 1))
21
22 return s
23
24 # from http://blog.stalkr.net/2011/04/pctf-2011-32-thats-no-bluetooth.html
25 def crc16(buff, crc = 0, poly = 0x8408):
26     l = len(buff)
27     i = 0
28     while i < l:
29         ch = ord(buff[i])
30         uc = 0
31         while uc < 8:
32             if (crc & 1) ^ (ch & 1):
33                 crc = (crc >> 1) ^ poly
34             else:
35                 crc >>= 1
36             ch >>= 1
37             uc += 1
38         i += 1
39     return crc
40
41
42 def fetch(sock):
43 sock.send("fetch\n")
44
45 def readline(self):
46 buf = ''
47 while true:
48 c = self.recv(1)
49 if c == '\r':
50 continue
51
52 buf.append(c)
53 if c == '\n':
54 return buf
55
56 crc = 0
57
58 lines = []
59 l = readline(sock)
60 if l != 'START\n':
61 print>>sys.stderr, "Bad expected START line '%s'\n" % l.rstrip('\n')
62 return None
63 crc = crc16(l, crc)
64 lines.append(l)
65
66 while true:
67 l = readline(sock)
68
69 crc = crc16(l, crc)
70
71 if l == 'END\n':
72 break
73
74 lines.append(l)
75
76 l = readline(sock)
77 recv_crc = None
78 try:
79 k, v = l.rstrip('\n').split('=')
80 if k == 'CRC':
81 recv_crc = int(v)
82 if recv_crc < 0 or recv_crc > 0xffff:
83 recv_crc = None
84 except ValueError:
85 pass
86
87 if recv_crc is None:
88 print>>sys.stderr, "Bad expected CRC line '%s'\n" % l.rstrip('\n')
89 return None
90
91 if recv_crc != crc:
92 print>>sys.stderr, "Bad CRC: calculated 0x%x vs received 0x%x\n" % (crc, recv_crc)
93 return None
94
95 return ''.join(lines)