Mercurial > templog
diff server/ts.py @ 328:46070aaf29ea
A bit of work on the server python
author | Matt Johnston <matt@ucc.asn.au> |
---|---|
date | Sat, 26 May 2012 10:17:27 +0800 |
parents | 5639c74f2cbb |
children | b5925cb4f264 |
line wrap: on
line diff
--- a/server/ts.py Tue May 22 23:45:16 2012 +0800 +++ b/server/ts.py Sat May 26 10:17:27 2012 +0800 @@ -1,7 +1,14 @@ #!/usr/bin/env python2.7 +BTADDR = "00:12:03:27:70:88" +SLEEP_TIME = 180 + import sys import httplib +import time +import traceback + +from utils import monotonic_time, retry lightblue = None try: @@ -9,8 +16,6 @@ except ImportError: import bluetooth -BTADDR = "00:12:03:27:70:88" - def get_socket(addr): if lightblue: s = lightblue.socket() @@ -19,40 +24,32 @@ s = bluetooth.BluetoothSocket( bluetooth.RFCOMM ) s.connect((addr, 1)) + s.setnonblocking(True) + return s # from http://blog.stalkr.net/2011/04/pctf-2011-32-thats-no-bluetooth.html def crc16(buff, crc = 0, poly = 0x8408): - l = len(buff) - i = 0 - while i < l: - ch = ord(buff[i]) - uc = 0 - while uc < 8: - if (crc & 1) ^ (ch & 1): - crc = (crc >> 1) ^ poly - else: - crc >>= 1 - ch >>= 1 - uc += 1 - i += 1 - return crc + l = len(buff) + i = 0 + while i < l: + ch = ord(buff[i]) + uc = 0 + while uc < 8: + if (crc & 1) ^ (ch & 1): + crc = (crc >> 1) ^ poly + else: + crc >>= 1 + ch >>= 1 + uc += 1 + i += 1 + return crc +@retry() def fetch(sock): sock.send("fetch\n") - def readline(self): - buf = '' - while true: - c = self.recv(1) - if c == '\r': - continue - - buf.append(c) - if c == '\n': - return buf - crc = 0 lines = [] @@ -93,3 +90,70 @@ return None return ''.join(lines) + +@retry() +def turn_off(sock): + sock.send("btoff\n"); + # read newline + l = readline(sock) + if not l: + print>>sys.stderr, "Bad response to btoff\n" + return None + + off, next_wake = l.rstrip().split(':') + if off != 'Off': + print>>sys.stderr, "Bad response to btoff '%s'\n" % l + + return int(next_wake) + + +def do_comms(sock): + d = None + # serial could be unreliable, try a few times + for i in range(FETCH_TRIES): + d = fetch(sock) + if d: + break + time.sleep(1) + if not d: + return + + res = send_results() + if not res: + return + + clear_meas(sock) + + next_wake = turn_off(sock) + sock.close() + return next_wake + +testcount = 0 + +def sleep_for(secs): + until = monotonic_time + secs + while True: + length = until < monotonic_time() + if length <= 0: + return + time.sleep(length) + +def main(): + + while True: + sock = get_socket() + sleep_time = SLEEP_TIME + if sock: + next_wake = None + try: + next_wake = do_comms(sock) + except Exception, e: + print>>sys.stderr, "Error in do_comms:" + traceback.print_last(file=sys.stderr) + if next_wake: + sleep_time = min(next_wake, sleep_time) + + sleep_for(sleep_time) + +if __name__ == '__main__': + main()