25939a61ee3d3dbbda368a0d3b942a7549fd023e
[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         CMD_GREEN_ON  = 3
10         CMD_GREEN_OFF = 4
11         CMD_RED_ON    = 5
12         CMD_RED_OFF   = 6
13         
14         class CMD():
15                 def __init__(self, name, pin, tid, todo):
16                         self.name = name
17                         self.pin = pin
18                         self.tid = tid
19                         self.todo = todo
20                         # don't do the GPIO setup here, the main init did not yet run
21                 
22                 def execute(self):
23                         logger.info("Actor: Running command %s" % self.name)
24                         for (value, delay) in self.todo:
25                                 if value is not None:
26                                         logger.debug("Actor: Setting pin %d to %d" % (self.pin, value))
27                                         GPIO.output(self.pin, value)
28                                 if delay > 0:
29                                         time.sleep(delay)
30         
31         CMDs = {
32                 CMD_UNLOCK:  CMD("unlock",         pin=12, tid=0, todo=[(True, 0.3), (False, 0.1)]),
33                 CMD_LOCK:  CMD("lock",             pin=16, tid=0, todo=[(True, 0.3), (False, 0.1)]),
34                 CMD_BUZZ: CMD("buzz",              pin=22, tid=1, todo=[(True, 2.5), (False, 0.1)]),
35                 CMD_GREEN_ON: CMD("green on",      pin=23, tid=2, todo=[(True, 0)]),
36                 CMD_GREEN_OFF: CMD("green off",    pin=23, tid=2, todo=[(False, 0)]),
37                 CMD_RED_ON: CMD("red on",          pin=26, tid=2, todo=[(True, 0)]),
38                 CMD_RED_OFF: CMD("red on",          pin=26, tid=2, todo=[(False, 0)]),
39         }
40         
41         def __init__(self):
42                 # launch threads, all running the "_execute" method
43                 self.threads = {}
44                 for cmd in Actor.CMDs.values():
45                         GPIO.setup(cmd.pin, GPIO.OUT)
46                         GPIO.output(cmd.pin, False)
47                         if not cmd.tid in self.threads:
48                                 self.threads[cmd.tid] = ThreadFunction(self._execute, "Actor TID %d" % cmd.tid)
49         
50         def _execute(self, cmd):
51                 Actor.CMDs[cmd].execute()
52         
53         def act(self, cmd):
54                 # dispatch command to correct thread
55                 self.threads[Actor.CMDs[cmd].tid](cmd)
56         
57         def stop(self):
58                 for thread in self.threads.values():
59                         thread.stop()