Java/Android stuff (me coding dirty \o/)
[saartuer.git] / libtuer.py
1 import logging, logging.handlers, syslog, os
2
3 # logging function
4 class Logger:
5         def __init__ (self):
6                 import __main__ as main
7                 self.name = os.path.basename(main.__file__)
8                 self.logger = logging.getLogger(self.name)
9                 self.logger.setLevel(logging.INFO)
10                 self.handler = logging.handlers.SysLogHandler(address = '/dev/log', facility = logging.handlers.SysLogHandler.LOG_LOCAL0)
11                 self.logger.addHandler(self.handler)
12         def log (self, what):
13                 thestr = "%s[%d]: %s" % (self.name,os.getpid(),what)
14                 print (thestr)
15                 self.logger.info(thestr)
16
17 logger = Logger()
18
19 def log (what):
20         logger.log(what)
21  
22
23 # Threaded callback class
24 class ThreadFunction():
25         _CALL = 0
26         _TERM = 1
27         
28         def __init__(self, f):
29                 self._f = f
30                 self._q = queue.Queue()
31                 self._t = threading.Thread(target=self._thread_func)
32                 self._t.start()
33         
34         def _thread_func(self):
35                 while True:
36                         (cmd, data) = self._q.get()
37                         # run command
38                         if cmd == _CALL:
39                                 self._f(*data)
40                         elif cmd == _TERM:
41                                 assert data is None
42                                 break
43                         else:
44                                 raise NotImplementedError("Command %d does not exist" % cmd)
45         
46         def __call__(self, *arg):
47                 self._q.put((self._CALL, arg))
48         
49         def stop(self):
50                 self._q.put((_TERM, None))
51                 self._t.join()