Пример #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)
    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")
Пример #3
0
    def __init__(self, config):
        """
        Init and binds the H/W
        """
        # Pimoroni's RGB Keypad - Default wiring
        self.KEYPAD = RgbKeypad()
        self.KEYS = self.KEYPAD.keys
        # DS3231 module, i2c1, SCL=GP11 and SDA=GP10
        i2c = busio.I2C(board.GP11, board.GP10)
        self.DS = DS3231(i2c)
        print(self.DS.datetime)  # Just to check time at boot when dev

        self.CONFIG = config

        # USB HID
        keyboard = Keyboard(usb_hid.devices)
        if self.CONFIG.get("layout", "us") == "fr":
            # More to come
            from adafruit_hid.keyboard_layout_fr import KeyboardLayoutFR
            self.LAYOUT = KeyboardLayoutFR(keyboard)
        else:
            # Default US layout
            from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS
            self.LAYOUT = KeyboardLayoutUS(keyboard)

        # Pico display
        self.DISPLAY = pico_dio.get_display()
        self.SCREENS = dict()
        self.SCREENS["splash"] = pico_dio.get_splash()

        self.DISPLAY.show(self.SCREENS["splash"])

        self.UPDATE_INDEX = 0
        self.LOCKED = False
        self.LAST_CODE = ""
        self.OTP = None
        self.MODE = 0
        self.PAGE = 0
        self.INDEX = None
        self.LAST_COUNTER = 0  # time // 30, OTP counter

        self.SCREENS["OTP"] = pico_dio.get_otp_group()
        self.SCREENS["PAGE"] = pico_dio.get_page_group()

        self.display_page(self.PAGE)

        for key in self.KEYS:
            @self.KEYPAD.on_press(key)
            def press_handler(a_key):
                self.handle_numpad(button_to_numpad(a_key.number))
Пример #4
0
    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}")
Пример #5
0
    def __init__(self,
                 name="Generic Keyboard",
                 gpio_row=None,
                 gpio_col=None,
                 layout=None,
                 layers=None,
                 macro_layer=None):
        self.name = name
        self.kbd = Keyboard(usb_hid.devices)  # Setup keyboard HID device
        self.kbd_layout = KeyboardLayoutUS(self.kbd)
        self.keymap = KeyboardHwLayout(layout)  # map layout to hw layout

        self.key_row = []  # write
        self.key_col = []  # read

        self.last_scan_matrix = {
        }  # used to determine diff between scans (if a release needs to be signalled)

        # Layers 0, 1, 2, 3 where 0 is the default layer 1 & 2 is the extended layers and 3 is the macro layer
        self.current_layer = 0

        # Setup write pins
        for pin in gpio_row:
            key_pin = digitalio.DigitalInOut(pin)
            key_pin.direction = digitalio.Direction.OUTPUT
            self.key_row.append(key_pin)

        # Setup read pins
        for pin in gpio_col:
            key_pin = digitalio.DigitalInOut(pin)
            key_pin.direction = digitalio.Direction.INPUT
            key_pin.pull = digitalio.Pull.UP
            self.key_col.append(key_pin)
    def __init__(self,
                 joy_x_pin=board.A4,
                 joy_y_pin=board.A3,
                 joy_z_pin=board.D2,
                 joy_gnd_pin=board.A5,
                 dpad_l_pin=board.D3,
                 dpad_r_pin=board.D4,
                 dpad_u_pin=board.D1,
                 dpad_d_pin=board.D0,
                 mc_top_pin=board.SCK,
                 mc_middle_pin=board.MOSI,
                 mc_bottom_pin=board.MISO,
                 outputScale=20.0,
                 deadbandCutoff=0.1,
                 weight=0.2):
        self.x_axis = PiperJoystickAxis(joy_x_pin,
                                        outputScale=outputScale,
                                        deadbandCutoff=deadbandCutoff,
                                        weight=weight)
        self.y_axis = PiperJoystickAxis(joy_y_pin,
                                        outputScale=outputScale,
                                        deadbandCutoff=deadbandCutoff,
                                        weight=weight)
        self.joy_z = PiperJoystickZ(joy_z_pin)
        self.dpad = PiperDpad(dpad_l_pin, dpad_r_pin, dpad_u_pin, dpad_d_pin)
        self.minecraftbuttons = PiperMineCraftButtons(mc_top_pin,
                                                      mc_middle_pin,
                                                      mc_bottom_pin)

        # Drive pin low if requested for easier joystick wiring
        if joy_gnd_pin is not None:
            # Provide a ground for the joystick - this is to facilitate
            # easier wiring
            self.joystick_gnd = DigitalInOut(joy_gnd_pin)
            self.joystick_gnd.direction = Direction.OUTPUT
            self.joystick_gnd.value = 0

        self.keyboard = Keyboard(usb_hid.devices)
        self.keyboard_layout = KeyboardLayoutUS(
            self.keyboard)  # Change for non-US
        self.mouse = Mouse(usb_hid.devices)

        # State
        #
        self.state = _UNWIRED
        self.timer = time.monotonic()
        self.last_mouse_wheel = time.monotonic()
        self.last_mouse = time.monotonic()
        self.dotstar_led = adafruit_dotstar.DotStar(board.APA102_SCK,
                                                    board.APA102_MOSI, 1)
        self.dotstar_led.brightness = 0.2
        self.up_pressed = False
        self.down_pressed = False
        self.left_pressed = False
        self.right_pressed = False
        self.mc_mode = _MC_DEFAULT
        self.mc_flyingdown_req = False
        self.mc_sprinting_req = False
        self.mc_crouching_req = False
        self.mc_utility_req = False
# A simple neat keyboard demo in circuitpython

# The button pins we'll use, each will have an internal pulldown
buttonpins = [board.BUTTON_A, board.BUTTON_B]
# our array of button objects
buttons = []
# The keycode sent for each button, will be paired with a control key
buttonkeys = [Keycode.A, "Hello World!\n"]
controlkey = Keycode.SHIFT

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

# make all pin objects, make them inputs w/pulldowns
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:
    # check each button
Пример #8
0
    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
        }
Пример #9
0
    k.release_all()
    dot[0] = (0, 0, 0)
    led.value = 0


""" Set up the board's input and output """

# Set up the "Dotstar" RGB LED on the Trinket M0 board
# They're designed to work in a sequence with a string of other LEDs,
# but since you only have one you'll just set the value for dot[0]
dot = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=lB)
dot[0] = (0, 0, 0)

# Set up the Keyboard object
k = Keyboard()
kL = KeyboardLayoutUS(k)

# The "Right" physical button, or "bR", is wired up so that pressing down will
# make an electrical connection from pin D2 on the board to the ground power connection.
# For this to work, set the pin D2 to be an Input, with an internal resistor pulling
# the pin "up" away from the ground.
bR = DigitalInOut(board.D2)
bR.direction = Direction.INPUT
bR.pull = Pull.UP
#   Note! If you have a "v1" board from RoboThon, you will need to pull the pin DOWN instead.
#   There was a small electrical change that was made to the board after this first version.

# Same for the "Left" physical button, "bL", but this time on pin D0.
bL = DigitalInOut(board.D0)
bL.direction = Direction.INPUT
bL.pull = Pull.UP
Пример #10
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)
Пример #11
0
from adafruit_hid.keyboard import Keyboard
gc.collect()
from adafruit_hid.keycode import Keycode
gc.collect()
from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS
gc.collect()
import board
import pulseio
import adafruit_dotstar
import adafruit_irremote
import time

# The keyboard object!
time.sleep(1)  # Sleep for a bit to avoid a race condition on some systems
keyboard = Keyboard()
keyboard_layout = KeyboardLayoutUS(keyboard)  # We're in the US :)

led = adafruit_dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1)
decoder = adafruit_irremote.GenericDecode()
pulsein = pulseio.PulseIn(board.REMOTEIN, maxlen=100, idle_state=True)

# Expected pulse, pasted in from previous recording REPL session:
key1_pulses = [0]

key2_pulses = [1]

print('IR listener')


# Fuzzy pulse comparison function:
def fuzzy_pulse_compare(pulse1, pulse2, fuzzyness=0.2):
from adafruit_hid.keycode import Keycode

# A simple neat keyboard demo in CircuitPython

# The pins we'll use, each will have an internal pullup
keypress_pins = [board.A1, board.A2]
# Our array of key objects
key_pin_array = []
# The Keycode sent for each button, will be paired with a control key
keys_pressed = [Keycode.A, "Hello World!\n"]
control_key = Keycode.SHIFT

# The keyboard object!
time.sleep(1)  # Sleep for a bit to avoid a race condition on some systems
keyboard = Keyboard(usb_hid.devices)
keyboard_layout = KeyboardLayoutUS(keyboard)  # We're in the US :)

# Make all pin objects inputs with pullups
for pin in keypress_pins:
    key_pin = digitalio.DigitalInOut(pin)
    key_pin.direction = digitalio.Direction.INPUT
    key_pin.pull = digitalio.Pull.UP
    key_pin_array.append(key_pin)

# For most CircuitPython boards:
led = digitalio.DigitalInOut(board.D13)
# For QT Py M0:
# led = digitalio.DigitalInOut(board.SCK)
led.direction = digitalio.Direction.OUTPUT

print("Waiting for key pin...")
Пример #13
0
                      5: Keycode.SPACE,
                      6: Keycode.SHIFT}

https://learn.adafruit.com/vote-keyboard/software
import board
from digitalio import DigitalInOut, Direction, Pull
import adafruit_dotstar as dotstar
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keycode import Keycode
from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS

dot = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
dot[0] = (0, 0, 0)

kbd = Keyboard()
kbdLayout = KeyboardLayoutUS(kbd)
state = []
pins = {}
buttonMap = [
    dict(row="D4", col="D0", id=1),
    dict(row="D4", col="D1", id=2),
    dict(row="D4", col="D2", id=3),
    dict(row="D3", col="D2", id=4),
    dict(row="D3", col="D0", id=5),
    dict(row="D3", col="D1", id=6)]

# Set up row pins
for pin in ["D4", "D3"]:
    p = DigitalInOut(getattr(board, pin))
    p.direction = Direction.OUTPUT
    pins[pin] = p
Пример #14
0
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import time
import random
from adafruit_circuitplayground.express import cpx

from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS
 
keyboard = Keyboard()
layout = KeyboardLayoutUS(keyboard)

ROLL_THRESHOLD  = 30        # Total acceleration 
DICE_COLOR      = (0xEA, 0x62, 0x92)  # Dice digits color
DICE_MAXBRIGHTNESS = 6

# dictionary storing the NeoPixels to set for each face
dice_pixels = {
 1 : (2,),
 2 : (4, 9),
 3 : (0, 4, 7),
 4 : (1, 3, 6, 8),
 5 : (0, 2, 4, 5, 9),
 6 : (0, 2, 4, 5, 7, 9)
}
    print("Secrets are kept in secrets.py, please add them there!")
    raise
except KeyError:
    print("TOTP info not found in secrets.py.")
    raise

# set board to use PCF8523 as its RTC
pcf = adafruit_pcf8523.PCF8523(board.I2C())
rtc.set_time_source(pcf)

#-------------------------------------------------------------------------
#                       H I D    S E T U P
#-------------------------------------------------------------------------
time.sleep(1)  # Sleep for a bit to avoid a race condition on some systems
keyboard = Keyboard(usb_hid.devices)
keyboard_layout = KeyboardLayoutUS(keyboard)  # We're in the US :)

#-------------------------------------------------------------------------
#                    D I S P L A Y    S E T U P
#-------------------------------------------------------------------------
display = board.DISPLAY

# Secret Code font by Matthew Welch
# http://www.squaregear.net/fonts/
font = bitmap_font.load_font("/secrcode_28.bdf")

name = label.Label(terminalio.FONT, text="?"*18, color=0xFFFFFF)
name.anchor_point = (0.0, 0.0)
name.anchored_position = (0, 0)

code = label.Label(font, text="123456", color=0xFFFFFF)
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS
from digitalio import DigitalInOut, Direction

led = DigitalInOut(board.D13)
led.direction = Direction.OUTPUT

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:
Пример #17
0
from adafruit_displayio_layout.widgets.icon_widget import IconWidget
from adafruit_featherwing import tft_featherwing_35

# seems to help the touchscreen not get stuck with chip not found
time.sleep(3)

# display and touchscreen initialization
displayio.release_displays()
tft_featherwing = tft_featherwing_35.TFTFeatherWing35()
display = tft_featherwing.display
touchscreen = tft_featherwing.touchscreen

# HID setup
kbd = Keyboard(usb_hid.devices)
cc = ConsumerControl(usb_hid.devices)
kbd_layout = KeyboardLayoutUS(kbd)

# variables to envorce timout between icon presses
COOLDOWN_TIME = 0.5
LAST_PRESS_TIME = -1

# 'mock' icon indexes for the layer buttons
# used for debouncing
PREV_LAYER_INDEX = -1
NEXT_LAYER_INDEX = -2
HOME_LAYER_INDEX = -3

# start on first layer
current_layer = 0

# Make the main_group to hold everything
# neopixel.mpy

import board
import time
import usb_hid
import neopixel

from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keycode import Keycode
from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS

pixel = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2)

time.sleep(1)  # sleep for a bit to avoid a race condition on some systems
kbd = Keyboard(usb_hid.devices)  # the keyboard object!
layout = KeyboardLayoutUS(kbd)  # you're americans :)

num_lock = False  # NUM LOCK
caps_lock = False  # CAPS LOCK
scroll_lock = False  # SCROLL LOCK


def update_lock():
    global num_lock, caps_lock, scroll_lock
    report = int.from_bytes(usb_hid.devices[0].last_received_report, "big")
    num_lock = (report & 0x01) == 0x01  # NUM LOCK
    caps_lock = (report & 0x02) == 0x02  # CAPS LOCK
    scroll_lock = (report & 0x04) == 0x04  # SCROLL LOCK


update_lock()
Пример #19
0
"""programme 6-8-2 : saisie dans un tableur"""
# importation des modules natifs utiles
from time import *
from board import *
from digitalio import *
# importation de modules supplémentaires
from adafruit_lsm6ds import *
import usb_hid
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keycode import Keycode
from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS

# Instanciation du clavier
clavier = Keyboard(usb_hid.devices)
layout = KeyboardLayoutUS(clavier)

# Instanciation du bus de communication I2C sur le module Feather
bus_i2c = I2C()
# Instanciation de l'accéléromètre LSM6DS33
accelerometre = LSM6DS33(bus_i2c)

# Instanciation de la LED interne et du bouton interne
led = DigitalInOut(D13)
led.direction = Direction.OUTPUT
led.value = False
bouton = DigitalInOut(SWITCH)
bouton.pull = Pull.UP

# Attente d'appui sur le bouton permettant à l'utilisateur de se placer
# sur la feuille de son tableur
while bouton.value:
Пример #20
0
esp.set_analog_write(27, 1)

#Print SSID of network and assigned address
print(
    f"Connected to {secrets['SSID']}. IP Addr is {esp.pretty_ip(esp.ip_address)}"
)

#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)
Пример #21
0
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keycode import Keycode
from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS
import adafruit_thermistor

# Switch to quickly enable/disable

# light level

# temperature

# Set the keyboard object!
# Sleep for a bit to avoid a race condition on some systems
time.sleep(1)
kbd = Keyboard()
layout = KeyboardLayoutUS(kbd)  # US is only current option...

print("Time\tLight\tTemperature\tX\tY\tZ")  # Print column headers


def slow_write(string):  # Typing should not be too fast for
    for c in string:  # the computer to be able to accept
        layout.write(c)
        time.sleep(0.2)  # use 1/5 second pause between characters


while True:
    if cpx.switch:  # If the slide switch is on, don't log
        continue

    # Turn on the LED to show we're logging
Пример #22
0
def keyboard_config(key_to_be_pressed):
    kbd = Keyboard(usb_hid.devices)
    layout = KeyboardLayoutUS(kbd)
    kbd.send(key_to_be_pressed)
Пример #23
0
from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS
from adafruit_hid.keycode import Keycode

from adafruit_hid.consumer_control import ConsumerControl
from adafruit_hid.consumer_control_code import ConsumerControlCode

from digitalio import DigitalInOut, Direction, Pull
cs = DigitalInOut(board.GP17)
cs.direction = Direction.OUTPUT
cs.value = 0
num_pixels = 16
pixels = adafruit_dotstar.DotStar(board.GP18, board.GP19, num_pixels, brightness=0.1, auto_write=True)
i2c = busio.I2C(board.GP5, board.GP4)
device = I2CDevice(i2c, 0x20)
kbd = Keyboard(usb_hid.devices)
layout = KeyboardLayoutUS(kbd)
def colourwheel(pos):
    if pos < 0 or pos > 255:
        return (0, 0, 0)
    if pos < 85:
        return (255 - pos * 3, pos * 3, 0)
    if pos < 170:
        pos -= 85
        return (0, 255 - pos * 3, pos * 3)
    pos -= 170
    return (pos * 3, 0, 255 - pos * 3)
def read_button_states(x, y):
    pressed = [0] * 16
    with device:
        device.write(bytes([0x0]))
        result = bytearray(2)
Пример #24
0
led.value = False

# Configure buttons on Maker Pi Pico
btn1 = digitalio.DigitalInOut(board.GP20)
btn2 = digitalio.DigitalInOut(board.GP21)
btn3 = digitalio.DigitalInOut(board.GP22)
btn1.direction = digitalio.Direction.INPUT
btn2.direction = digitalio.Direction.INPUT
btn3.direction = digitalio.Direction.INPUT
btn1.pull = digitalio.Pull.UP
btn2.pull = digitalio.Pull.UP
btn3.pull = digitalio.Pull.UP

# 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.
Пример #25
0
from digitalio import DigitalInOut, Direction, Pull

from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS
from adafruit_hid.keycode import Keycode

switch = DigitalInOut(board.GP20)
switch.direction = Direction.INPUT
switch.pull = Pull.UP

switch2 = DigitalInOut(board.GP21)
switch2.direction = Direction.INPUT
switch2.pull = Pull.UP

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

while True:
    if not switch.value:
        print('y')
        keyboard.press(Keycode.LEFT_ALT, Keycode.F1)
        keyboard.release_all()

    if not switch2.value:
        print('y')
        keyboard.press(Keycode.LEFT_ALT, Keycode.F2)
        keyboard.release_all()

    print('---')
    time.sleep(0.2)
Пример #26
0
from adafruit_hid.keycode import Keycode
from digitalio import DigitalInOut, Direction, Pull

# A simple neat keyboard demo in circuitpython

# The button pins we'll use, each will have an internal pulldown
buttonpins = [board.BUTTON_A, board.BUTTON_B]
# our array of button objects
buttons = []

# the keyboard object!
# sleep for a bit to avoid a race condition on some systems
time.sleep(1)
kbd = Keyboard()
# we're americans :)
layout = KeyboardLayoutUS(kbd)
sending = False
led = DigitalInOut(board.D13)
led.direction = Direction.OUTPUT


def init():
    # make all pin objects, make them inputs w/pulldowns
    for pin in buttonpins:
        button = DigitalInOut(pin)
        button.direction = Direction.INPUT
        button.pull = Pull.DOWN
        buttons.append(button)
    print("Press A to start send key")
    print("Press B to stop sending key")    
    
Пример #27
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)
Пример #28
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)
Пример #29
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
Пример #30
0
                                manufacturer="Adafruit Industries")
advertisement = ProvideServicesAdvertisement(hid)
advertisement.appearance = 961
scan_response = Advertisement()
scan_response.complete_name = "CircuitPython HID"

ble = adafruit_ble.BLERadio()
if not ble.connected:
    print("advertising")
    ble.start_advertising(advertisement, scan_response)
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:
        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)