summaryrefslogtreecommitdiff
path: root/src/actions.py
blob: 1e40bbd8be3423f46e6994d7536f7aafdb6bc8aa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
from supervisor import ticks_ms
import ticks
import time
from random import randrange

class Action(object):
    def __new__(cls):
        if not hasattr(cls, 'instance'):
          cls.instance = super(Action, cls).__new__(cls)
          cls.instance.events = []
        return cls.instance


    def __init__(self):
        """ Do nothing and do not get any constructor.
            This is intended because it allow to call the class directly like :
            Action().key( … )
        """
        pass

    def set_macropad(self, macropad):
        self.macropad = macropad

    def key(self, pressed, sequence):
        """ Send a key to the host
        """

        if pressed:
            action = self.macropad.keyboard.press
            s = sequence
        else:
            action = self.macropad.keyboard.release
            s = reversed(sequence)
        for item in s:
            action(item)

    def sequence(self, keys):
        """ Send a sequence of keys to the host
        """
        for key in keys:
            self.key(True, key)
            time.sleep( randrange(25, 74)/400. )
            self.key(False, key)

    def delay(self, duration, callback):
        "Register a delayed task"
        time = ticks_ms()
        next_tick = ticks.add(
                ticks_ms(),
                duration
                )
        self.events.append((next_tick, callback))

    def flash(self, key, release_color):
        "Flash the key with a high light for 10ms"
        def restore():
            if self.macropad.pixels[key] == (127, 127, 127):
                self.macropad.pixels[key] = release_color
                self.macropad.pixels.show()
        self.delay(10, restore)
        self.macropad.pixels[key] = (127, 127, 127)

    def collect_tasks(self):
        "Execute all the delayed tasks"
        remain = []
        time = ticks_ms()
        for event in self.events:
            if not ticks.less(event[0]):
                event[1]()
            else:
                remain.append(event)
        self.events = remain