comparison py/utils.py @ 439:31ac84425a2d

python raspberry pi rewrite
author Matt Johnston <matt@ucc.asn.au>
date Mon, 19 Nov 2012 22:46:34 +0800
parents
children 482d7852b511
comparison
equal deleted inserted replaced
438:2607e4f322cf 439:31ac84425a2d
1 import os
2 import sys
3 #import ctypes
4 import time
5 import select
6 import logging
7
8 L = logging.info
9 W = logging.warning
10 E = logging.error
11
12 DEFAULT_TRIES = 3
13 READLINE_SELECT_TIMEOUT = 1
14
15 clock_gettime = None
16 no_clock_gettime = True
17 def monotonic_time():
18 global clock_gettime
19 global no_clock_gettime
20 if no_clock_gettime:
21 return time.time()
22
23 class timespec(ctypes.Structure):
24 _fields_ = [
25 ('tv_sec', ctypes.c_long),
26 ('tv_nsec', ctypes.c_long)
27 ]
28 if not clock_gettime:
29 try:
30 librt = ctypes.CDLL('librt.so.0', use_errno=True)
31 clock_gettime = librt.clock_gettime
32 clock_gettime.argtypes = [ctypes.c_int, ctypes.POINTER(timespec)]
33 except:
34 W("No clock_gettime(), using fake fallback.")
35 no_clock_gettime = True
36 return time.time()
37
38 t = timespec()
39 CLOCK_MONOTONIC = 1 # see <linux/time.h>
40
41 if clock_gettime(CLOCK_MONOTONIC, ctypes.pointer(t)) != 0:
42 errno_ = ctypes.get_errno()
43 raise OSError(errno_, os.strerror(errno_))
44 return t.tv_sec + t.tv_nsec * 1e-9
45
46 # decorator, tries a number of times, returns None on failure, sleeps between
47 # Must be used as "@retry()" if arguments are defaulted
48 def retry(retries=DEFAULT_TRIES, try_time = 1):
49 def inner(func):
50 def new_f(*args, **kwargs):
51 for i in range(retries):
52 d = func(*args, **kwargs)
53 if d is not None:
54 return d
55 time.sleep(try_time)
56 return None
57
58 new_f.func_name = func.func_name
59 return new_f
60 return inner
61
62 def readline(sock):
63 timeout = READLINE_SELECT_TIMEOUT
64 buf = ''
65 while True:
66 (rlist, wlist, xlist) = select.select([sock], [], [], timeout)
67 if sock not in rlist:
68 # hit timeout
69 return None
70
71 c = sock.recv(1)
72 if c == '':
73 # lightblue timeout
74 return None
75 if c == '\r':
76 continue
77
78 buf += c
79 if c == '\n':
80 return buf
81
82 # from http://blog.stalkr.net/2011/04/pctf-2011-32-thats-no-bluetooth.html
83 def crc16(buff, crc = 0, poly = 0x8408):
84 l = len(buff)
85 i = 0
86 while i < l:
87 ch = ord(buff[i])
88 uc = 0
89 while uc < 8:
90 if (crc & 1) ^ (ch & 1):
91 crc = (crc >> 1) ^ poly
92 else:
93 crc >>= 1
94 ch >>= 1
95 uc += 1
96 i += 1
97 return crc
98
99 def cheap_daemon():
100 L("Daemonising.")
101 sys.stdout.flush()
102 sys.stderr.flush()
103 out = file('/dev/null', 'a+')
104 os.dup2(out.fileno(), sys.stdout.fileno())
105 os.dup2(out.fileno(), sys.stderr.fileno())
106
107 try:
108 pid = os.fork()
109 if pid > 0:
110 sys.exit(0)
111 except OSError, e:
112 E("Bad fork()")
113 sys.exit(1)
114
115 os.setsid()
116
117 try:
118 pid = os.fork()
119 if pid > 0:
120 sys.exit(0)
121 except OSError, e:
122 E("Bad fork()")
123 sys.exit(1)
124
125