make the actor more multi-threaded and do more logging
[saartuer.git] / actor.py
1 from libtuer import ThreadFunction, logger
2 import RPi.GPIO as GPIO
3 import time
4         
5 class Actor:
6         CMD_BUZZ = 0
7         CMD_UNLOCK = 1
8         CMD_LOCK = 2
9         
10         class CMD():
11                 def __init__(self, name, pin, tid, todo):
12                         self.name = name
13                         self.pin = pin
14                         self.tid = tid
15                         self.todo = todo
16                         # don't do the GPIO setup here, the main init did not yet run
17                 
18                 def execute(self):
19                         logger.info("Actor: Running command %s" % self.name)
20                         for (value, delay) in self.todo:
21                                 if value is not None:
22                                         logger.debug("Actor: Setting pin %d to %d" % (self.pin, value))
23                                         GPIO.output(self.pin, value)
24                                 time.sleep(delay)
25         
26         CMDs = {
27                 CMD_UNLOCK:  CMD("unlock", pin=12, tid=0, todo=[(True, 0.3), (False, 0.1)]),
28                 CMD_LOCK:  CMD("lock", pin=16, tid=0, todo=[(True, 0.3), (False, 0.1)]),
29                 CMD_BUZZ: CMD("buzz", pin=22, tid=1, todo=[(True, 2.0), (False, 0.1)]),
30         }
31         
32         def __init__(self):
33                 # launch threads, all running the "_execute" method
34                 self.threads = {}
35                 for cmd in Actor.CMDs.values():
36                         GPIO.setup(cmd.pin, GPIO.OUT)
37                         if not cmd.tid in self.threads:
38                                 self.threads[cmd.tid] = ThreadFunction(self._execute, "Actor TID %d" % cmd.tid)
39         
40         def _execute(self, cmd):
41                 Actor.CMDs[cmd].execute()
42         
43         def act(self, cmd):
44                 # dispatch command to correct thread
45                 self.threads[Actor.CMDs[cmd].tid](cmd)
46         
47         def stop(self):
48                 for thread in self.threads.values():
49                         thread.stop()