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