Пример #1
0
class Keyboard():
    def __init__(self):
        self.keyboard = adafruit_hid.keyboard.Keyboard(usb_hid.devices)
        self.keyboard_layout = KeyboardLayoutUS(self.keyboard)

    def press(self, key):
        self.keyboard.press(key)

    def release_all(self):
        self.keyboard.release_all()

    def write(self, text):
        self.keyboard_layout.write(text)
Пример #2
0
btn = digitalio.DigitalInOut(board.SW1)
btn.direction = digitalio.Direction.INPUT
btn.pull = digitalio.Pull.UP

led_r = digitalio.DigitalInOut(board.LED2_R)
led_r.direction = digitalio.Direction.OUTPUT
led_g = digitalio.DigitalInOut(board.LED2_G)
led_g.direction = digitalio.Direction.OUTPUT
led_b = digitalio.DigitalInOut(board.LED2_B)
led_b.direction = digitalio.Direction.OUTPUT

led_r.value, led_g.value, led_b.value = True, True, True
# Set up a keyboard device.
kbd = Keyboard()
layout = KeyboardLayoutUS(kbd)

while True:
    if not btn.value:
        kbd.send(Keycode.GUI, Keycode.R)
        led_g.value = False
        time.sleep(0.5)
        layout.write('notepad\n')
        led_g.value = True
        led_b.value = False
        time.sleep(0.5)
        led_b.value = True
        layout.write('secret message')
        led_r.value = False
        time.sleep(3)
        led_r.value = True
Пример #3
0
# Use default HID descriptor
hid = HIDService()
device_info = DeviceInfoService(
    software_revision=adafruit_ble.__version__, manufacturer="Adafruit Industries"
)
advertisement = ProvideServicesAdvertisement(hid)
advertisement.appearance = 961
scan_response = Advertisement()

ble = adafruit_ble.BLERadio()
if ble.connected:
    for c in ble.connections:
        c.disconnect()

print("advertising")
ble.start_advertising(advertisement, scan_response)

k = Keyboard(hid.devices)
kl = KeyboardLayoutUS(k)
while True:
    while not ble.connected:
        pass
    print("Start typing:")
    while ble.connected:
        c = sys.stdin.read(1)
        sys.stdout.write(c)
        kl.write(c)
        # print("sleeping")
        time.sleep(0.1)
    ble.start_advertising(advertisement)
Пример #4
0
        b = result[0] | result[1] << 8
        for i in range(x, y):
            if not (1 << i) & b:
                pressed[i] = 1
            else:
                pressed[i] = 0
    return pressed
held = [0] * 16
while True:
    pressed = read_button_states(0, 16)

    if pressed[0]:
        pixels[0] = colourwheel(0 * 16)  # Map pixel index to 0-255 range

        if not held[0]:
            layout.write("volu")
            kbd.send(Keycode.ENTER)
            #held[0] = 1

    elif pressed[1]:
        pixels[1] = colourwheel(1 * 16)  # Map pixel index to 0-255 range

        if not held[1]:
            layout.write("mpc next")
            kbd.send(Keycode.ENTER)
            held[1] = 1

    elif pressed[2]:
        pixels[2] = colourwheel(2 * 16)  # Map pixel index to 0-255 range

        if not held[2]:
Пример #5
0
)

#Get instructions from remote flask server.
instruction_URL = f"http://{secrets['server_ip']}:8000/download/{secrets['duckyname']}"

#Create request, and get text of response
instructions = requests.get(instruction_URL).text.split('\n')
print(instructions)

keyboard = Keyboard(usb_hid.devices)
keyboard_layout = KeyboardLayoutUS(keyboard)

#Parsing instructions.
for line in instructions:
    if line[:6] == "STRING":
        keyboard_layout.write(line[6:])
    elif line[:3] == "WIN" or line[:5] == "SUPER":
        keyboard.press(Keycode.GUI)
        keyboard.release_all()
    elif line[:5] == "ENTER":
        keyboard.press(Keycode.ENTER)
        keyboard.release_all()
    elif line[:4] == "CTRL":
        other_key = line[5:]
        keyboard.press(Keycode.CONTROL)
        keyboard_layout.write(other_key)
        keyboard_layout.release_all()
    elif line[:4] == "WAIT":
        time.sleep(float(line[4:]))

#set up RGB led to be Blue, now that all instructions have been carried out
Пример #6
0
class HidScript:
    def __init__(self, debug=False):
        self.debug = debug
        #self.mouse = Mouse(usb_hid.devices)
        self.keyboard = Keyboard(usb_hid.devices)
        self.keyboard_layout = KeyboardLayoutUS(
            self.keyboard)  # Change for non-US
        self.default_delay = 0
        self.string_delay = 0
        self.last_cmd = ""
        self.last_arg = ""

        # Keycode only has US mappings, not sure if AdaFruit has others
        #
        # TODO - consider a data structure which consumes less RAM for
        # constrained platforms.
        #
        # Keep a separate structure for multi-key combos to lower memory
        # usage.
        #
        self.tuple_keymap = {
            "CTRL-ALT": (Keycode.CONTROL, Keycode.ALT),
            "CTRL-SHIFT": (Keycode.CONTROL, Keycode.SHIFT),
            "ALT-SHIFT": (Keycode.ALT, Keycode.SHIFT)
        }

        self.keymap = {
            "ALT": Keycode.ALT,
            "APP": Keycode.APPLICATION,
            "BREAK": Keycode.PAUSE,
            "CAPSLOCK": Keycode.CAPS_LOCK,
            "CONTROL": Keycode.CONTROL,
            "CTRL": Keycode.CONTROL,
            "DELETE": Keycode.DELETE,
            "DOWNARROW": Keycode.DOWN_ARROW,
            "DOWN": Keycode.DOWN_ARROW,
            "END": Keycode.END,
            "ENTER": Keycode.ENTER,
            "ESC": Keycode.ESCAPE,
            "ESCAPE": Keycode.ESCAPE,
            "GUI": Keycode.GUI,
            "HOME": Keycode.HOME,
            "INSERT": Keycode.INSERT,
            "LEFTARROW": Keycode.LEFT_ARROW,
            "LEFT": Keycode.LEFT_ARROW,
            "MENU": Keycode.APPLICATION,
            "NUMLOCK": Keycode.KEYPAD_NUMLOCK,
            "PAGEUP": Keycode.PAGE_UP,
            "PAGEDOWN": Keycode.PAGE_DOWN,
            "PAUSE": Keycode.PAUSE,
            "PRINTSCREEN": Keycode.PRINT_SCREEN,
            "RIGHTARROW": Keycode.RIGHT_ARROW,
            "RIGHT": Keycode.RIGHT_ARROW,
            "SCROLLLOCK": Keycode.SCROLL_LOCK,
            "SHIFT": Keycode.SHIFT,
            "SPACE": Keycode.SPACE,
            "TAB": Keycode.TAB,
            "UPARROW": Keycode.UP_ARROW,
            "UP": Keycode.UP_ARROW,
            "WINDOWS": Keycode.WINDOWS,
            "a": Keycode.A,
            "A": Keycode.A,
            "b": Keycode.B,
            "B": Keycode.B,
            "c": Keycode.C,
            "C": Keycode.C,
            "d": Keycode.D,
            "D": Keycode.D,
            "e": Keycode.E,
            "E": Keycode.E,
            "f": Keycode.F,
            "F": Keycode.F,
            "g": Keycode.G,
            "G": Keycode.G,
            "h": Keycode.H,
            "H": Keycode.H,
            "i": Keycode.I,
            "I": Keycode.I,
            "j": Keycode.J,
            "J": Keycode.J,
            "k": Keycode.K,
            "K": Keycode.K,
            "l": Keycode.L,
            "L": Keycode.L,
            "m": Keycode.M,
            "M": Keycode.M,
            "n": Keycode.N,
            "N": Keycode.N,
            "o": Keycode.O,
            "O": Keycode.O,
            "p": Keycode.P,
            "P": Keycode.P,
            "q": Keycode.Q,
            "Q": Keycode.Q,
            "r": Keycode.R,
            "R": Keycode.R,
            "s": Keycode.S,
            "S": Keycode.S,
            "t": Keycode.T,
            "T": Keycode.T,
            "u": Keycode.U,
            "U": Keycode.U,
            "v": Keycode.V,
            "V": Keycode.V,
            "w": Keycode.W,
            "W": Keycode.W,
            "x": Keycode.X,
            "X": Keycode.X,
            "y": Keycode.Y,
            "Y": Keycode.Y,
            "z": Keycode.Z,
            "Z": Keycode.Z,
            #
            # The DuckyScript encoder didn't appear to have the following codes and
            # probably used the STRING command to deal with some of them. Adding them shouldn't
            # hurt but does consume RAM. Some are Mac specific.
            #
            "F1": Keycode.F1,
            "F2": Keycode.F2,
            "F3": Keycode.F3,
            "F4": Keycode.F4,
            "F5": Keycode.F5,
            "F6": Keycode.F6,
            "F7": Keycode.F7,
            "F8": Keycode.F8,
            "F9": Keycode.F9,
            "F10": Keycode.F10,
            "F11": Keycode.F11,
            "F12": Keycode.F12,
            "F13": Keycode.F13,
            "F14": Keycode.F14,
            "F15": Keycode.F15,
            "F16": Keycode.F16,
            "F17": Keycode.F17,
            "F18": Keycode.F18,
            "F19": Keycode.F19,
            "BACKSLASH": Keycode.BACKSLASH,
            "COMMA": Keycode.COMMA,
            "COMMAND": Keycode.COMMAND,
            "FORWARD_SLASH": Keycode.FORWARD_SLASH,
            "GRAVE_ACCENT": Keycode.GRAVE_ACCENT,
            "LEFT_BRACKET": Keycode.LEFT_BRACKET,
            "OPTION": Keycode.ALT,
            "PERIOD": Keycode.PERIOD,
            "POUND": Keycode.POUND,
            "QUOTE": Keycode.QUOTE
        }

    # Dropped the following to save memory (for now):
    #       "0": Keycode.ZERO,  "1": Keycode.ONE,
    #       "2": Keycode.TWO,   "3": Keycode.THREE,
    #       "4": Keycode.FOUR,  "5": Keycode.FIVE,
    #       "6": Keycode.SIX,   "7": Keycode.SEVEN,
    #       "8": Keycode.EIGHT, "9": Keycode.NINE,
    #       "RIGHT_ALT": Keycode.RIGHT_ALT,
    #       "RIGHT_BRACKET": Keycode.RIGHT_BRACKET,
    #       "RIGHT_CONTROL": Keycode.RIGHT_CONTROL,
    #       "RIGHT_GUI": Keycode.RIGHT_GUI,
    #       "RIGHT_SHIFT": Keycode.RIGHT_SHIFT,
    #       "SEMICOLON": Keycode.SEMICOLON,

    # Execute a single command in a HidScript file
    # REPEAT handled in process
    #
    def _exec_cmd(self, cmd, arg):
        if cmd == "REM":
            pass
        elif cmd == "STRING":
            if self.string_delay:
                for c in arg:
                    self.keyboard_layout.write(c)
                    time.sleep(self.string_delay)
            else:
                self.keyboard_layout.write(arg)
        elif cmd in self.keymap:
            if arg and arg in self.keymap:
                self.keyboard.send(self.keymap[cmd], self.keymap[arg])
            else:
                self.keyboard.send(self.keymap[cmd])
        elif cmd in self.tuple_keymap:
            for keycode in self.tuple_keymap[cmd]:
                self.keyboard.press(keycode)
            if arg and arg in self.keymap:
                self.keyboard.send(self.keymap[arg])
            else:
                self.keyboard.release_all()

        if cmd == "DELAY":
            time.sleep(int(arg) / 100.0)
        elif (cmd == "DEFAULTDELAY") or (cmd == "DEFAULT_DELAY"):
            self.default_delay = int(arg) / 100.0
        elif (cmd == "STRINGDELAY") or (cmd == "STRING_DELAY"):
            self.string_delay = int(arg) / 1000.0
        else:
            time.sleep(self.default_delay)

    # Process a HidScript file
    #
    def process(self, scriptname):
        try:
            with open(scriptname) as f:
                for line in f:
                    # Eliminate leading or trailing whitespace
                    # TODO - does this break any STRING commands?
                    #
                    line = line.strip()
                    values = line.split(" ", 1)
                    if self.debug: print("Script line: ", line)
                    cmd = values[0]
                    if len(values) == 2:
                        arg = values[1]
                    else:
                        arg = ""

                    # Handle REPEAT command at this level, but all other commands
                    # are handled by _exec_cmd()
                    #
                    if cmd == "REPEAT":
                        arg = int(arg)
                        for i in range(arg):
                            self._exec_cmd(self.last_cmd, self.last_arg)
                    else:
                        self.last_cmd = cmd
                        self.last_arg = arg
                        self._exec_cmd(cmd, arg)

        except OSError:
            if self.debug: print("Could not read file: ", scriptname)
Пример #7
0
# Set up keyboard and mouse.
kbd = Keyboard(usb_hid.devices)
layout = KeyboardLayoutUS(kbd)
mouse = Mouse(usb_hid.devices)
direction = True

while True:
    # Test buttons on Maker Pi Pico
    if not btn1.value:
        # Debounce
        time.sleep(0.3)
        while not btn1.value:
            pass
        # Type 'abc' followed by newline.
        layout.write('abc\n')
        # Type numbers followed by newline.
        layout.write('789\n')
        # Type symbols followed by tab.
        layout.write('!?_*\t')
        # Type lowercase 'x'.
        kbd.send(Keycode.X)
        # Type capital 'Y'.
        kbd.send(Keycode.SHIFT, Keycode.Y)

    if not btn2.value:
        # Debounce
        time.sleep(0.3)
        while not btn2.value:
            pass
        # Toggle mouse wheel up/down by one unit
 progress_bar.value = now % 30
 event = keys.events.get()
 # wakeup if knob turned or button pressed
 if knob.position != knob_pos or event:
     if not awake:
         last_update = 0 # force an update
     awake = True
     knob_pos = knob.position
     wake_up_time = now
 # handle key presses
 if event:
     if event.pressed:
         key_pressed = event.key_number
         # knob
         if key_pressed == 12:
             keyboard_layout.write(totp_codes[current_key])
             keyboard.send(Keycode.ENTER)
         # keeb
         elif key_pressed != current_key:
             # is it a configured key?
             if totp_keys[key_pressed]:
                 current_key = key_pressed
                 pixels.fill(0)
                 last_update = 0 # force an update
 # update codes
 if progress_bar.value < 0.5 and now - last_compute > 2:
     totp_codes = compute_codes(timebase(now))
     last_compute = now
 # update display
 if now - last_update > DISPLAY_RATE and awake:
     pixels[current_key] = totp_keys[current_key][2]
Пример #9
0
buttonpins = [board.BUTTON_A, board.BUTTON_B]
buttons = []
buttonkeys = [Keycode.LEFT_ARROW, Keycode.RIGHT_ARROW]
controlkey = Keycode.SHIFT
time.sleep(1)
kbd = Keyboard()
layout = KeyboardLayoutUS(kbd)
for pin in buttonpins:
    button = DigitalInOut(pin)
    button.direction = Direction.INPUT
    button.pull = Pull.DOWN
    buttons.append(button)
led = DigitalInOut(board.D13)
led.direction = Direction.OUTPUT
print('Waiting for button presses')
while True:
    for button in buttons:
        if button.value:
            print('Button #%d Pressed' % i)
            i = buttons.index(button)
            led.value = True
            k = buttonkeys[i]
            layout.write(k) if type(k) is str else kbd.press(controlkey, k)
            led.value = False
            _hy_anon_var_1 = None
        else:
            i = buttons.index(button)
            k = buttonkeys[i]
            _hy_anon_var_1 = kbd.release(controlkey, k)

Пример #10
0
class Impl:
    def __init__(self):
        # incoming keypad
        self.keypad = MatrixKeypad(row_pins, col_pins, layers)

        # outgoing keypresses
        self.keyboard = None
        self.keyboard_layout = None

        g = displayio.Group(max_size=7)

        self.labels = labels = []
        labels.append(Label(terminalio.FONT, max_glyphs=32, scale=2, color=0))
        labels.append(Label(terminalio.FONT, max_glyphs=32, scale=3, color=0))
        labels.append(Label(terminalio.FONT, max_glyphs=32, scale=3, color=0))
        labels.append(Label(terminalio.FONT, max_glyphs=32, scale=3, color=0))
        labels.append(Label(terminalio.FONT, max_glyphs=32, scale=3, color=0))
        labels.append(Label(terminalio.FONT, max_glyphs=32, scale=3, color=0))

        for li in labels:
            g.append(li)

        bitmap = displayio.Bitmap((display.width + 126) // 127,
                                  (display.height + 126) // 127, 1)
        palette = displayio.Palette(1)
        palette[0] = 0xffffff

        tile_grid = displayio.TileGrid(bitmap, pixel_shader=palette)
        bg = displayio.Group(scale=127)
        bg.append(tile_grid)

        g.insert(0, bg)

        display.show(g)

    def getch(self):
        while True:
            time.sleep(.02)
            c = self.keypad.getch()
            if c is not None:
                return c

    def setline(self, i, text):
        li = self.labels[i]
        text = text[:31] or " "
        if text == li.text:
            return
        li.text = text
        li.anchor_point = (0, 0)
        li.anchored_position = (1, max(1, 41 * i - 7) + 6)

    def refresh(self):
        pass

    def paste(self, text):
        if self.keyboard is None:
            if usb_hid:
                self.keyboard = Keyboard(usb_hid.devices)
                self.keyboard_layout = KeyboardLayoutUS(self.keyboard)
            else:
                return

        if self.keyboard_layout is None:
            raise ValueError("USB HID not available")
        text = str(text)
        self.keyboard_layout.write(text)
        raise RuntimeError("Pasted")

    def start_redraw(self):
        display.auto_refresh = False

    def end_redraw(self):
        display.auto_refresh = True

    def end(self):
        pass
Пример #11
0
    'KEYPAD_BACKSLASH': Keycode.KEYPAD_BACKSLASH,
    'APPLICATION': Keycode.APPLICATION,
    'POWER': Keycode.POWER
}
setter = 0
timer = 0
cpx.pixels.brightness = 0.01
cpx.pixels.fill((255, 0, 0))
#print(lines)
while True:
    if cpx.button_a:
        for line in lines:
            line = line.split()
            print(line)
            if line[0] == "STRING":
                layout.write(' '.join(line[1:]))
                setter = 1

            if line[0] == "DELAY":
                sleep(int(line[1]))
                timer = 1

            if not setter and not timer:
                for l in line:
                    kbd.press(command_dispatcher[l])
                print("Done")
                for l in line:
                    kbd.release(command_dispatcher[l])
                print("------")

            setter = 0
Пример #12
0
from adafruit_circuitplayground.express import cpx
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS

kbd = Keyboard()
layout = KeyboardLayoutUS(kbd)

while True:
    if cpx.button_a:
        # Type 'abc' followed by Enter (a newline).
        layout.write('\noof\n')
        while cpx.button_a:
            pass



)
tg.flip_y = True
g1.append(tg)
g = displayio.Group()
g.append(g1)
g.append(label)
display.show(g)
display.auto_refresh = False

i = 0
spin = ".oOo"
old_payload = None
while True:
    cam.capture(bitmap)

    for row in qrdecoder.decode(bitmap, qrio.PixelPolicy.EVEN_BYTES):
        payload = row.payload
        try:
            payload = payload.decode("utf-8")
        except UnicodeError:
            payload = str(payload)
        if payload != old_payload:
            label.text = payload
            keyboard_layout.write(payload)
            old_payload = payload

    # Clear out the odd bytes, so that the bitmap displays as greyscale
    view[1::2] = 0
    bitmap.dirty()
    display.refresh(minimum_frames_per_second=0)
Пример #14
0
                keys[k].set_led(*colours[current_layer])
                
    # Loop through all of the keys in the layer and if they're pressed, get the
    # key code from the layer's key map
    for k in layers[current_layer].keys():
        if keys[k].pressed:
            key_press = layers[current_layer][k]

            # If the key hasn't just fired (prevents refiring)
            if not fired:
                fired = True

                # Send the right sort of key press and set debounce for each
                # layer accordingly (layer 2 needs a long debounce)
                if (
                        (current_layer == 1) |
                        (current_layer == 4)
                ):
                    debounce = short_debounce
                    keyboard.send(key_press)
                elif current_layer == 2:
                    debounce = long_debounce
                    layout.write(key_press)
                elif current_layer == 3:
                    debounce = short_debounce
                    consumer_control.send(key_press)

    # If enough time has passed, reset the fired variable
    if fired and time.monotonic() - keybow.time_of_last_press > debounce:
        fired = False
hid = HIDService(HID_DESCRIPTOR)
device_info = DeviceInfoService(software_revision=adafruit_ble.__version__,
                                manufacturer="Adafruit Industries")
print(device_info.manufacturer)
advertisement = ProvideServicesAdvertisement(hid)
advertisement.appearance = 961

ble = adafruit_ble.BLERadio()
print(to_hex(bytes(advertisement)))
if not ble.connected:
    print("advertising")
    ble.start_advertising(advertisement)
else:
    print("already connected")
    print(ble.connections)

k = Keyboard(hid.devices)
kl = KeyboardLayoutUS(k)
while True:
    while not ble.connected:
        pass
    #print("Start typing:")
    while ble.connected:
        # c = sys.stdin.read(1)
        # sys.stdout.write(c)
        #kl.write(c)
        kl.write("h")
        # print("sleeping")
        time.sleep(0.1)
    ble.start_advertising(advertisement)
Пример #16
0
                                    # tuple means it's a single action
                                    if isinstance(_cur_actions, tuple):
                                        # put it in a list by itself
                                        _cur_actions = [_cur_actions]

                                    # loop over the actions
                                    for _action in _cur_actions:
                                        # HID keyboard keys
                                        if _action[0] == KEY:
                                            kbd.press(*_action[1])
                                            kbd.release(*_action[1])

                                        # String to write from layout
                                        elif _action[0] == STRING:
                                            kbd_layout.write(_action[1])

                                        # Consumer control code
                                        elif _action[0] == MEDIA:
                                            cc.send(_action[1])

                                        # Key press
                                        elif _action[0] == KEY_PRESS:
                                            kbd.press(*_action[1])

                                        # Key release
                                        elif _action[0] == KEY_RELEASE:
                                            kbd.release(*_action[1])

                                        # if there are multiple actions
                                        if len(_cur_actions) > 1:
touch0 = touchio.TouchIn(board.A0)
touch1 = touchio.TouchIn(board.A1)
touch2 = touchio.TouchIn(board.A2)

# the keyboard object
# sleep for a bit to avoid a race condition on some systems
time.sleep(1)
kbd = Keyboard()
layout = KeyboardLayoutUS(kbd)

while True:
    if touch0.value:
        led.value = True
        print("A0 touched!")
        layout.write("?F3ErPs5.C.m.0.d.S.")  # enter your own password here
        time.sleep(1)

    if touch1.value:
        led.value = True
        print("A1 touched!")
        layout.write("6@LKNs(WV[vq6N")  # enter your own password here
        time.sleep(1)

    if touch2.value:
        led.value = True
        print("A2 touched!")
        layout.write("3Ff0rT@9j2y&")  # enter your own password here
        time.sleep(1)

    time.sleep(0.01)
Пример #18
0
            elif OS == MAC:
                kbd.send(Keycode.ALT, Keycode.M)
            elif OS == LINUX:
                kbd.press(Keycode.CONTROL, Keycode.SHIFT)
                kbd.press(Keycode.U)
                kbd.release_all()
                kbd.send(Keycode.ZERO)
                kbd.send(Keycode.THREE)
                kbd.send(Keycode.B)
                kbd.send(Keycode.C)
                kbd.send(Keycode.ENTER)
    if caps[2]:
        if ENABLE_KEYBOARD:
            if OS == WINDOWS:
                type_alt_code(227)
            elif OS == MAC:
                kbd.send(Keycode.ALT, Keycode.P)
            elif OS == LINUX:
                kbd.press(Keycode.CONTROL, Keycode.SHIFT)
                kbd.press(Keycode.U)
                kbd.release_all()
                kbd.send(Keycode.ZERO)
                kbd.send(Keycode.THREE)
                kbd.send(Keycode.C)
                kbd.send(Keycode.ZERO)
                kbd.send(Keycode.ENTER)
    if caps[3]:
        if ENABLE_KEYBOARD:
            layout.write('https://www.digikey.com/python\n')
    time.sleep(0.1)
Пример #19
0
##    elif isinstance(color, int):
##        # pull apart rgb values in int, adjust, then re-assemble
##        r = (color >> 16) & 0xff
##        g = (color >> 8) & 0xFF
##        b = color & 0xfF
##        rgblist = adjust_color([r, g, b])
##        return (rgblist[0] << 16) + (rgblist[1] << 8) + rgblist[2]
##    else:
##        raise ValueError("Unexpected color type: " + type(color))

# Loop forever
while True:
    # If left button pressed and die has been rolled at least once
    # then type the total score and press enter and zero total
    if cpx.button_a and roll_total > 0:
        layout.write(str(roll_total) + '\n')
        roll_total = 0
    
    # If right button pressed the decrease brightness
    # wrap around at 0 to original maximum value
    if cpx.button_b:
        if dice_brightness == 0:
            dice_brightness = DICE_MAXBRIGHTNESS
        else:
            dice_brightness -= 1
        cpx.pixels.brightness = 1 / (2**(DICE_MAXBRIGHTNESS - dice_brightness))
        ##dice_color = adjust_color(dice_color,
        ##                          1 / (2**(DICE_MAXBRIGHTNESS - dice_brightness)))
        ##show_die(cpx.pixels, roll_number, dice_color)
        # wait for use to take finger off button
        while cpx.button_b:
Пример #20
0
if mac:
    leftCtrl = Keycode.LEFT_GUI
else:
    leftCtrl =  Keycode.LEFT_CONTROL

sleep(1)
keyboard = Keyboard()
layout = KeyboardLayoutUS(keyboard)
sleep(0.500)
if windows:
    keyboard.press(Keycode.LEFT_GUI, Keycode.R)
    sleep(0.01)
    keyboard.release_all()
    sleep(0.200)
    layout.write("cmd\n")
    sleep(0.100)
elif mac:
    keyboard.press(Keycode.LEFT_GUI)
    layout.write(" ")
    sleep(0.1)
    keyboard.release_all()
    layout.write("terminal")
    sleep(0.5)
    keyboard.press(Keycode.RETURN)
    sleep(0.1)
    keyboard.release_all()
    sleep(0.5)
else:
    keyboard.press(leftCtrl)
    layout.write("t")
Пример #21
0
# SPDX-FileCopyrightText: 2018 Anne Barela for Adafruit Industries
#
# SPDX-License-Identifier: MIT

import usb_hid
from adafruit_circuitplayground.express import cpx
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS

kbd = Keyboard(usb_hid.devices)
layout = KeyboardLayoutUS(kbd)

while True:
    if cpx.button_a:
        # Type 'Jane Doe' followed by Enter (a newline).
        layout.write('Jane Doe\n')
        while cpx.button_a:
            pass
Пример #22
0
				pw_subdir = unlock_code + '/'
				selected_keynum = 0
				default_pixels = num_to_neo[selected_keynum % 16]
				if unlock_code:
					unlock_failures = 0
		else:
			default_color = color_unlock_mode
			default_pixels = [0,3]
			unlock_code = ""
		set_neo(pixels, default_pixels, default_color, True)
		unlock_entry_mode = unlock_entry_mode ^ True			
	elif t1:
		if unlock_entry_mode:
			unlock_code = unlock_code + '1'
		else:
			if selected_keynum == 9999:
				selected_keynum = 0
			elif obj_exists(data_dir + pw_subdir + (zero_pads + str(selected_keynum + 1))[-4:] + '.txt'):
				selected_keynum += 1
			else:
				selected_keynum = 0
			default_pixels = num_to_neo[selected_keynum % 16]
			set_neo(pixels, default_pixels, color_keynum, True)
	elif t2:
		if unlock_entry_mode:
			unlock_code = unlock_code + '2'
		else:
			target_string = load_raw_keyfile(data_dir + pw_subdir, (zero_pads + str(selected_keynum))[-4:] + '.txt')
			if target_string:
				keyboard_layout.write(target_string)
print("Waiting for button presses")

while True:
    # check each button
    # when pressed, the LED will light up,
    # when released, the keycode or string will be sent
    # this prevents rapid-fire repeats!
    for button in buttons:
        if button.value:  # pressed?
            i = buttons.index(button)
            print("Button #%d Pressed" % i)

            # turn on the LED
            led.value = True

            while button.value:
                pass  # wait for it to be released!
            # type the keycode or string
            k = buttonkeys[i]  # get the corresp. keycode/str
            if type(k) is str:
                layout.write(k)
            else:
                kbd.press(controlkey, k)  # press...
                kbd.release_all()  # release!

            # turn off the LED
            led.value = False

    time.sleep(0.01)
Пример #24
0
    while ble.connected or not ble_enabled.value:
        if not central.value:
            led.value = True
            print("Running")
            while True:
                i = random.randint(0, upper)
                if not buttons[i].value:
                    break

            audio.play(wave)
            if i == 0:
                print("Button 1")
                pixels.fill((0, 0, 255))
                if ble_enabled.value:
                    kl.write("Button 1")
            elif i == 1:
                print("Button 2")
                pixels.fill((0, 255, 0))
                if ble_enabled.value:
                    kl.write("Button 2")
            elif i == 2:
                print("Button 3")
                pixels.fill((255, 255, 255))
                if ble_enabled.value:
                    kl.write("Button 3")

            if not ble_enabled.value:
                print(
                    "BLE HID has been disabled, slide the slide switch to the left to re-enable"
                )
# For QT Py M0:
# led = digitalio.DigitalInOut(board.SCK)
led.direction = digitalio.Direction.OUTPUT

print("Waiting for key pin...")

while True:
    # Check each pin
    for key_pin in key_pin_array:
        if not key_pin.value:  # Is it grounded?
            i = key_pin_array.index(key_pin)
            print("Pin #%d is grounded." % i)

            # Turn on the red LED
            led.value = True

            while not key_pin.value:
                pass  # Wait for it to be ungrounded!
            # "Type" the Keycode or string
            key = keys_pressed[i]  # Get the corresponding Keycode or string
            if isinstance(key, str):  # If it's a string...
                keyboard_layout.write(key)  # ...Print the string
            else:  # If it's not a string...
                keyboard.press(control_key, key)  # "Press"...
                keyboard.release_all()  # ..."Release"!

            # Turn off the red LED
            led.value = False

    time.sleep(0.01)
Пример #26
0
k = Keyboard(hid.devices)
kl = KeyboardLayoutUS(k)
while True:
    while not ble.connected:
        pass
    print("Start typing:")

    while ble.connected:
        if not button_1.value:  # pull up logic means button low when pressed
            #print("back")  # for debug in REPL
            k.send(Keycode.BACKSPACE)
            time.sleep(0.1)

        if not button_2.value:
            kl.write("Bluefruit")  # use keyboard_layout for words
            time.sleep(0.4)

        if not button_3.value:
            k.send(Keycode.SHIFT, Keycode.L)  # add shift modifier
            time.sleep(0.4)

        if not button_4.value:
            kl.write("e")
            time.sleep(0.4)

        if not button_5.value:
            k.send(Keycode.ENTER)
            time.sleep(0.4)

    ble.start_advertising(advertisement)
Пример #27
0
    if len(pulse1) != len(pulse2):
        return False
    for i in range(len(pulse1)):
        threshold = int(pulse1[i] * fuzzyness)
        if abs(pulse1[i] - pulse2[i]) > threshold:
            return False
    return True


# Create pulse input and IR decoder.
pulsein.clear()
pulsein.resume()

# Loop waiting to receive pulses.
while True:
    led[0] = (0, 0, 0)  # LED off
    # Wait for a pulse to be detected.
    pulses = decoder.read_pulses(pulsein)
    led[0] = (0, 0, 100)  # flash blue

    print("\tHeard", len(pulses), "Pulses:", pulses)
    # Got a pulse set, now compare.
    if fuzzy_pulse_compare(key1_pulses, pulses):
        print("****** KEY 1 DETECTED! ******")
    keyboard.press(Keycode.SPACE)
    keyboard.release_all()

    if fuzzy_pulse_compare(key2_pulses, pulses):
        print("****** KEY 2 DETECTED! ******")
    keyboard_layout.write("hello!")
while scroll_lock:
    update_lock()
    time.sleep(0.1)

print("Meeting starting")

start = time.monotonic()  # Press reset on your board to reset the time
previous_scroll_lock = False
while True:
    update_lock()
    pixel.fill((0xFF if num_lock else 0x0, 0xFF if caps_lock else 0x0,
                0xFF if scroll_lock else 0x0))  # Create a color

    if scroll_lock != previous_scroll_lock:
        now = time.monotonic()
        current = now - start
        hours = int((current / 3600))
        minutes = int((current / 60) % 60)
        seconds = int(current % 60)
        if hours == 0:
            string = "{minutes:02d}:{seconds:02d} ".format(minutes=minutes,
                                                           seconds=seconds)
        else:
            string = "{hours}:{minutes:02d}:{seconds:02d} ".format(
                hours=hours, minutes=minutes, seconds=seconds)
        print("Sending : ", string)
        layout.write(string)
        previous_scroll_lock = scroll_lock

    time.sleep(0.1)
Пример #29
0
class Calculator:
    def __init__(self):
        self._number1 = N("0")
        self._number2 = None
        self.trail = ["Ready."]
        self.entry = ""
        self.op = None
        self.keyboard = None
        self.keyboard_layout = None

    def paste(self, text):
        if self.keyboard is None:
            if usb_hid:
                self.keyboard = Keyboard(usb_hid.devices)
                self.keyboard_layout = KeyboardLayoutUS(self.keyboard)
            else:
                return

        if self.keyboard_layout is None:
            self.add_trail("No USB")
        else:
            text = str(text)
            self.keyboard_layout.write(text)

            self.add_trail(f"Pasted {text}")

    def add_trail(self, msg):
        self.trail = self.trail[-3:] + [str(msg).upper()]

    @property
    def number1(self):
        return self._number1

    @number1.setter
    def number1(self, number):
        self._number1 = number
        self.add_trail(number)

    @property
    def number2(self):
        if self.entry == "":
            if self._number2 is not None:
                return self._number2
            return None
        return N(self.entry)

    @number2.setter
    def number2(self, number):
        self._number2 = number
        self.entry = ''

    def clear(self):
        self.number1 = N("0")

    def clear_entry(self):
        self.number2 = None

    def key_pressed(self, k):  # pylint: disable=too-many-branches
        if k == K_CL:
            if self.entry:
                self.entry = self.entry[:-1]
            elif self.op:
                print("clear op")
                self.op = None
            elif self.number2 is None:
                self.clear()
            else:
                print("clear entry - op = ", self.op)
                self.clear_entry()

        if len(k) == 1 and k in "0123456789":
            self.entry = self.entry + k

        if k == "." and not "." in self.entry:
            if self.entry == "":
                self.entry = "0"
            self.entry = self.entry + k

        if k == K_PA:
            if self.number2 is not None:
                self.paste(self.number2)
            else:
                self.paste(self.number1)

        if k == "=":
            self.do_binary_op(0)

        if k == "%":
            self.do_binary_op(1)

        op = unary.get(k)
        if op:
            self.do_unary_op(op)

        if k in binary:
            if self.number2 is not None:
                if self.op:
                    self.do_binary_op(0)
                else:
                    self.number1 = self.number2
                    self.clear_entry()
            self.op = k

    def do_unary_op(self, op):
        if self.number2 is not None:
            self.number2 = op(self.number2)
        else:
            self.number1 = op(self.number1)

    def do_binary_op(self, i):
        if self.op and self.number2 is not None:
            op = binary[self.op][i]
            self.op = None
            self.number1 = op(self.number1, self.number2)
            self.clear_entry()

    def show(self):
        rows = [""] * 4
        trail = self.trail
        if len(trail) > 0:
            rows[2] = trail[-1]
        if len(trail) > 1:
            rows[1] = trail[-2]
        if len(trail) > 2:
            rows[0] = trail[-3]

        entry_or_number = self.entry or self.number2
        cursor = ' :' if (self.number2 is None or self.entry != "") else ""
        op = self.op or ''
        op = 'd' if op == '/' else op
        rows[-1] = f"{op}{entry_or_number or ''}{cursor}"
        for r in rows:
            print(r)
        text_area.text = "\n".join(rows)
Пример #30
0
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS

# I/O
pin_ready = digitalio.DigitalInOut(board.D3)
pin_ready.direction = digitalio.Direction.INPUT
pin_ready.pull = digitalio.Pull.UP

meter = mitutoyo.Digimatic(req=board.D0, clock=board.D1, data=board.D2)

# USB HID keyboard emulation.
time.sleep(1)
kbd = Keyboard(usb_hid.devices)
layout = KeyboardLayoutUS(kbd)

print("Ready.")

while True:
    # wait until ready goes low
    while pin_ready.value:
        time.sleep(0.1)

    reading = meter.read()
    if reading:
        print("Typing %s." % reading)
        layout.write(str(reading) + "\n")

    # wait until ready goes up again to just get a single reading per press
    while not pin_ready.value:
        time.sleep(0.1)