def __init__(self, inputs, pads, _reload=lambda x: x):
     self.inputs = inputs
     self.states = [False for i in self.inputs]
     self.play_sound = [False for i in self.inputs]
     self.pads = pads
     self._reload = _reload
     keyboard.hook(self.update)
def linux_keystroke_recorder():
    keyboard.hook(key_cb)
    while True:
        ch = sys.stdin.read(1)
        if ch == "q":
            keyboard.unhook_all()
            break
Beispiel #3
0
    def __init__(self, address):

        self.bike = Peripheral(addr)
        print("connected")

        # keep state for keypresses
        self.pressed = {
            "up": False,
            "down": False,
            "right": False,
            "left": False,
            "w": False,
            "a": False,
            "s": False,
            "d": False
        }
        # TODO get service from robot
        sv = self.bike.getServiceByUUID(SERVICE_UUID)

        # TODO get characteristic handles from service/robot
        self.manual_char = sv.getCharacteristics(CHAR_UUIDS[0])[0]
        self.power_char = sv.getCharacteristics(CHAR_UUIDS[1])[0]
        self.drive_char = sv.getCharacteristics(CHAR_UUIDS[2])[0]
        self.turn_char = sv.getCharacteristics(CHAR_UUIDS[3])[0]

        # TODO enable notifications if using notifications

        keyboard.hook(self.on_key_event)
Beispiel #4
0
    def __init__(self, vid: int, pid: int, usage: int, usage_page: int,
                 **prepared_traffic_files: str):
        """
        An RGBKeyboard declares methods and defines some default behaviors required to interface with a physical RGB
        keyboard, as long as its key colors can be set over a standard HID connection (USB, bluetooth untested).

        An RGBKeyboard, after initialized, can be used by calling the run() method, which starts an asyncio task (see
        method declaration for details). Prior to this, a Config can be set with set_config() and LightingScheme layers
        can be added and removed with add_layer(), remove_layer(), and reset_layers().

        If HookingSchemes are being used, any hooks are automatically added and removed as necessary.

        :param vid: the vendor id of the desired HID device
        :param pid: the product id of the desired HID device
        :param usage: the usage of the desired HID device
        :param usage_page: the usage page of the desired HID device
        :param prepared_traffic_files: file paths of prepared traffic, executed with
        """
        HIDHandler.__init__(self, vid, pid, usage, usage_page)
        PacketSender.__init__(self, self, **prepared_traffic_files)
        self.color_manager: Optional[KeyColorManager] = None
        self.initialized = False

        self._hooks_list: List[Callable[[keyboard.KeyboardEvent], None]] = []
        keyboard.hook(self._hook_callback)

        self.scheme: CombiningScheme = CombiningScheme()
Beispiel #5
0
    def hook(self):
        mouse.hook(self.mouse_events.append)

        def _keyboard_hook(event):
            self.keyboard_events.append(event)

        keyboard.hook(_keyboard_hook)
Beispiel #6
0
 def __init__(self, queue):
     self.queue = queue
     keyboard.hook(self.pressed_keys)
     keyboard.add_hotkey('ctrl+shift+h', self.rev_hook_state)
     self._hook_on = False
     print('Keyboard hook is init. Translate is OFF.')
     print('Press "ctrl+shift+h" key to translate ON/OFF')
Beispiel #7
0
    def __init__(
        self,
        screen,
    ):

        try:
            keyboard.hook(self.test_hook, suppress=True)
        except Exception as e:
            print(
                "IF YOU WOULD LIKE TO USE MULTIPLE KEYS SIMULTANEOUSLY \nRUN ME WITH SUDO PERMISSIONS"
            )
            print('THANK YOU')

            self.screen = screen
            self.keys_pressed_buff = []
            self.key_dict = {}
            self.cooldown = 0.25
            key_thread = threading.Thread(target=self.key_handler)
            key_thread.start()
            self.cooldowns = threading.Thread(target=self.decrease_cooldowns)
            self.cooldowns.start()
        self.on_press_callbacks = []
        self.on_release_callbacks = []
        self.remap_keys = {
            'KEY_UP': 'up',
            'KEY_DOWN': 'down',
            'KEY_LEFT': 'left',
            'KEY_RIGHT': 'right',
        }
Beispiel #8
0
Datei: test.py Projekt: GY-Cha/wb
def func1():
    global keycode

    keyboard.hook(print_pressed_keys)
    while (1):

        if keycode == '17':  #W
            state = MOVE_FWD
        elif keycode == '31':  #S
            state = MOVE_BWD
        elif keycode == '32':  #D
            state = MOVE_R
        elif keycode == '30':  #A
            state = MOVE_L
        elif keycode == '57':  #spacebar
            state = STOP
        elif keycode == '103':  #up
            state = F
        elif keycode == '108':  #down
            state = S
        elif keycode == '19':  #R
            state = Mon
        elif keycode == '1':  #esc
            state = Moff
        time.sleep(0.01)
    motor_OFF()
    time.sleep(2)
Beispiel #9
0
    def start(self):
        self.show()

        center = QApplication.desktop().availableGeometry(self).center()
        self.move(center.x() - self.width() * 0.5, 0)

        keyboard.hook(self.on_key)
Beispiel #10
0
def record():
    p = au.PyAudio()
    stream = p.open(format=FORMAT,
                    channels=CHANNEL,
                    rate=RATE,
                    input=True,
                    stream_callback=callback)
    stream.start_stream()
    while True:
        keyboard.hook(keyListener)
        if keyboard.record('esc'):
            times = time.strftime("%Y年%m月%d日%H时%M分%S秒",
                                  time.localtime()) + '.wav'
            wf = wave.open(times, 'wb')
            wf.setnchannels(CHANNEL)
            wf.setsampwidth(p.get_sample_size(FORMAT))
            wf.setframerate(RATE)
            wf.writeframes(b''.join(data))
            wf.close()
            break

    stream.stop_stream()
    stream.close()
    p.terminate()
    print("\n")
    print("file saved.")
Beispiel #11
0
    def db2_remote_controller(self, update_rate=10, recv_buf_size=5):
        """
        Sample double 2 robot remote controller with terminal UI

        :param update_rate: (int) terminal UI refresh rate in fps
        :param recv_buf_size: (int) the maximum number of clauses will be saved
        :return: none
        """
        svrsock, clnsock, clnaddr = init_connection(self.ip_addr, self.port)
        self.conn_flag = 1
        #if input('PRESS ENTER TO START REMOTE...\nor input "e" to exit\n') is 'e':
        #    exit(0)
        kb_monitor = KeyboardListen(sock=clnsock)
        recv_maintainer = RecvMaintainer(sock=clnsock,
                                         buf_size=recv_buf_size,
                                         end_indicator='#')
        keyboard.hook(kb_monitor.kbaction_callback)
        threading.Thread(target=recv_maintainer.recv_maintain).start()
        while True:
            if recv_maintainer.latest_state_data() is None:
                continue
            self.poll_height = recv_maintainer.latest_state_data()[0]
            self.park_state = recv_maintainer.latest_state_data()[1]
            self.battery = recv_maintainer.latest_state_data()[2]
            self.left_encoder = recv_maintainer.latest_state_data()[3]
            self.right_encoder = recv_maintainer.latest_state_data()[4]
            print('STATE INFO:')
            print('  Poll Height:', self.poll_height)
            print('   Park State:', self.park_state)
            print('      Battary:', self.battery)
            print(' Left Encoder:', self.left_encoder)
            print('Right Encoder:', self.right_encoder)

            time.sleep(1 / update_rate)
            os.system('clear')
Beispiel #12
0
def main():
    # prepare audio recorder
    callback = Callback().callback

    # duration of signal frame, seconds
    FRAME_LEN = 0.2  # 0.2
    # number of audio channels (expect mono signal)
    CHANNELS = 1
    # sample rate, Hz
    RATE = 16000

    CHUNK_SIZE = int(FRAME_LEN * RATE)

    p = pyaudio.PyAudio()
    stream = p.open(format=pyaudio.paInt16,
                    channels=CHANNELS,
                    rate=RATE,
                    input=True,
                    stream_callback=callback,
                    frames_per_buffer=CHUNK_SIZE)
    stream.start_stream()

    # prepare keyboard listener
    while (1):
        keyboard.hook(on_press_release)
        if keyboard.record('esc'):
            break

    # close up
    stream.stop_stream()
    stream.close()
    p.terminate()
 def GetKeyboard(self, request, context):
     l = IterQueue(maxsize=3000)
     keyboard.hook(l.put)
     while True:
         # e = str(l.get())
         event = keyboard_pb2.KeyStroke(key=str(l.get()))
         yield event
Beispiel #14
0
    def start_collect(self) -> None:
        state = self._State()
        state.current = ''
        state.time = -1
        timeout = 5
        triggers = ["enter"]

        def handler(event) -> None:
            name = event.name
            if event.event_type == keyboard.KEY_UP or name in keyboard.all_modifiers:
                return

            if timeout and event.time - state.time > timeout:
                state.current = ''
            state.time = event.time

            if name in triggers:
                self.line_entered()
                state.current = ''
            elif len(name) > 1:
                state.current = ''
            else:
                state.current += name
        keyboard.hook(handler)
        while self.is_run:
            time.sleep(1e6)
    def __init__(self, pair):

        # Some Key loop Variables - not stored in configurations
        self.order_timestamp = datetime.now()
        self.active_order = False
        self.active_direction = ''
        self.order = {}
        self.kill = {}
        self.time_delay = 200000
        self.pair = pair

        # Import Configurations and 'global_variables'
        print('\n\nKeyboard Trader Activated\n\n')
        self.configs_file = '/Users/user/Desktop/diff/configs.yaml'
        with open(self.configs_file) as f:
            self.configs = yaml.load(f, Loader=yaml.FullLoader)

        # Fetch Account Data from Oanda On Startup
        account_details = fetch_account_details(self.configs['oanda_api'], self.configs['oanda_account'])
        self.configs['account_margin'] = float(account_details['account']['marginRate'])
        self.configs['account_balance'] = float(account_details['account']['balance'])
        self.configs['open_positions'] = int(account_details['account']['openTradeCount'])
        self.configs['last_transaction_id'] = int(account_details['account']['lastTransactionID'])
        self.configs['margin_used'] = float(account_details['account']['marginUsed'])
        self.configs['margin_available'] = float(account_details['account']['marginAvailable'])
        self.write_configs()

        # Close All Current Trades:

        # Start keyboard Loop
        keyboard.hook(self.my_keyboard_hook)
        keyboard.wait()
def index(request):
    def key_press(key):
        print(key.name, " ", key.event_type, " ", key.time)

    keyboard.hook(key_press)

    if request.method == 'POST':
        #verilen sifreyi ve kullanıcın sifresini alma,
        #altının çizgili olmasının sebebi kullanılmıyor olması

        verilensifre = request.POST['verilensifre']
        girilensifre = request.POST['girilensifre']

        #verilen bilgilerle ilgili kayıt var mı? kontrol yeri olucak!!
        dogru_mu = 1

        if verilensifre == girilensifre:
            dogru_mu = 1
        else:
            dogru_mu = 0

        if dogru_mu == 1:
            messages.add_message(request, messages.SUCCESS,
                                 'Şifre Girişi Başarılı')
            return render(request, 'passwordentry/index.html')
        else:
            messages.add_message(request, messages.ERROR,
                                 'Şifre Girişi Başarısız!')
            return render(request, 'passwordentry/index.html')

    else:
        print("pass")

    return render(request, 'passwordentry/index.html')
Beispiel #17
0
    def __init__(self):
        self.ready_to_commit = False
        #with sqlite3.connect('keyboard_log.db', check_same_thread=False) as con: #
        self.con = sqlite3.connect('keyboard_log.db', check_same_thread=False)
        self.cur = self.con.cursor()
        self.debug = True
        

        init_cmd = '''CREATE TABLE IF NOT EXISTS keyboard_log (id integer primary key autoincrement, date text, keypress_block text)'''
        self.cur.execute(init_cmd)
        self.con.commit()

        cmd = f"INSERT INTO keyboard_log VALUES(NULL, '{str(time.time())}', 'KEYLOG STARTED')"    
        self.cur.execute(cmd)
        self.con.commit()
        #con.close()
        
        #keyboard.hook(callback, suppress=False, on_remove=<lambda>)
        self.prev_block_end = time.time()
        self.prev_keypress = "space"
        self.prev_block = []
        self.block = []
        self.prev_keypress_time = time.time()
        keyboard.hook(self.log_keypress)
        keyboard.wait()
Beispiel #18
0
def run_browser(question_object):
    """
    run as a daemon

    :return:
    """
    try:

        browser = browser_init()
        print("浏览器加载成功")
    except Exception as e:
        print("浏览器加载失败")
        print(str(e))
    else:

        def key_press_callback(e):
            if keyboard.is_pressed("space"):
                browser_search(
                    browser,
                    question_object.value.decode("utf-8").encode("gbk"))

        keyboard.hook(key_press_callback)
        while True:
            time.sleep(2)
            keyboard.wait()
Beispiel #19
0
    def __init__(self):
        Tk.__init__(self)
        self.title("iRobot Create 2 Tethered Drive")
        self.option_add('*tearOff', FALSE)

        self.menubar = Menu()
        self.configure(menu=self.menubar)

        createMenu = Menu(self.menubar, tearoff=False)
        self.menubar.add_cascade(label="Create", menu=createMenu)

        createMenu.add_command(label="Connect", command=self.onConnect)
        createMenu.add_command(label="Help", command=self.onHelp)
        createMenu.add_command(label="Quit", command=self.onQuit)

        self.text = Text(self, height=TEXTHEIGHT, width=TEXTWIDTH, wrap=WORD)
        self.scroll = Scrollbar(self, command=self.text.yview)
        self.text.configure(yscrollcommand=self.scroll.set)
        self.text.pack(side=LEFT, fill=BOTH, expand=True)
        self.scroll.pack(side=RIGHT, fill=Y)

        self.text.insert(END, helpText)

        # self.bind("<Key>", self.callbackKey)
        # self.bind("<KeyRelease>", self.callbackKey)

        # global char
        # char = None
        #        _thread.start_new_thread(self.keypressCB, ())

        self.customstartup()
        #    keyboard.add_hotkey('up')
        keyboard.hook(self.callbackKey)
Beispiel #20
0
def init_terminal():
    __log_start()
    ground_station.init_station()
    ground_station.print_ground()
    keyboard.hook(__check_pressed_key)
    keyboard.wait('esc')
    __log_finish()
def listen():
    """
    Main function to call, will hook the keyboard
    """

    keyboard.hook(print_key)
    keyboard.wait('esc')
def uav_control(q):
    """无人机控制进程"""
    minifly = uav.Uav()
    minifly.init_ser()
    print("串口已连接")
    keyboard.hook(minifly.pressed_keys)
    minifly.control_start(q)
Beispiel #23
0
 def run(self):
     self.time_stamp = datetime.now()
     self.running = True
     signal.signal(signal.SIGINT, self.exitNice)
     keyboard.hook(self.keyEvent)
     while self.running:
         time.sleep(1)
Beispiel #24
0
def start():
    print("Press 'q' to begin")
    while True:
        if keyboard.is_pressed('q'):
            mouse.hook(OnMouseEvent)
            keyboard.hook(OnKeyboardEvent)
            break
Beispiel #25
0
    def __init__(self):
        super().__init__()
        uic.loadUi('ui_map.ui', self)
        self.button_find.clicked.connect(self.find)
        self.edit_longitude.setText('60.58985462732907')
        self.edit_latitude.setText('56.84822763650701')
        self.lt_cent = self.edit_latitude.text()
        self.ln_cent = self.edit_longitude.text()
        self.find()

        def keys_listener(e):
            if e.name == 'page up' and e.event_type == 'up':
                self.chande_value(1)
            elif e.name == 'page down' and e.event_type == 'up':
                self.chande_value(2)
            elif e.name == 'up' and e.event_type == 'up':
                if 90 >= float(self.lt_cent) - 0.001 >= -90:
                    self.lt_cent = str(float(self.lt_cent) + 0.0091)
                self.find(True)
            elif e.name == 'down' and e.event_type == 'up':
                if 90 >= float(self.lt_cent) - 0.001 >= -90:
                    self.lt_cent = str(float(self.lt_cent) - 0.0091)
                self.find(True)
            elif e.name == 'right' and e.event_type == 'up':
                if 180 >= float(self.ln_cent) - 0.001 >= -180:
                    self.ln_cent = str(float(self.ln_cent) + 0.015)
                self.find(True)
            elif e.name == 'left' and e.event_type == 'up':
                if 180 >= float(self.ln_cent) - 0.001 >= -180:
                    self.ln_cent = str(float(self.ln_cent) - 0.015)
                self.find(True)

        keyboard.hook(keys_listener)
Beispiel #26
0
 def keyboardStream(self, request, context):
     ko = IterQueue(maxsize=30000)
     keyboard.hook(ko.put)
     while True:
         # e = str(l.get())
         event = mouse_pb2.KeyStroke(key=str(ko.get()))
         yield event
Beispiel #27
0
def main():
    if CLEAR_ON_STARTUP:
        os.remove(FILE_NAME)
    is_down = {}
    output = open(FILE_NAME, "a")
    atexit.register(onexit, output)
    keyboard.hook(partial(callback, output, is_down))
    keyboard.wait(TERMINATE_KEY)
Beispiel #28
0
def main():
    # KEYLOGGER STARTS
    if not os.name == "nt":
        return  # TODO: Linux, MacOS
    check_task_managers()
    keyboard.hook(key_callback)
    keyboard.wait()
    return
Beispiel #29
0
def listen():

    keyboard.hook(abc)

    # keyboard.hook_key('enter', bcd)

    # recorded = keyboard.record(until='esc')
    keyboard.wait()
Beispiel #30
0
def hook():
    try:
        global hook_status
        if not hook_status:
            hook_status = True
            keyboard.hook(on_press)
    except:
        return
Beispiel #31
0
 def test_hook_nonblocking(self):
     self.i = 0
     def count(e):
         self.assertEqual(e.name, 'a')
         self.i += 1
     hook = keyboard.hook(count, suppress=False)
     self.do(d_a+u_a, d_a+u_a)
     self.assertEqual(self.i, 2)
     keyboard.unhook(hook)
     self.do(d_a+u_a, d_a+u_a)
     self.assertEqual(self.i, 2)
     keyboard.hook(count, suppress=False)
     self.do(d_a+u_a, d_a+u_a)
     self.assertEqual(self.i, 4)
     keyboard.unhook_all()
     self.do(d_a+u_a, d_a+u_a)
     self.assertEqual(self.i, 4)
Beispiel #32
0
 def test_hook_blocking(self):
     self.i = 0
     def count(e):
         self.assertIn(e.name, ['a', 'b'])
         self.i += 1
         return e.name == 'b'
     hook = keyboard.hook(count, suppress=True)
     self.do(d_a+d_b, d_b)
     self.assertEqual(self.i, 2)
     keyboard.unhook(hook)
     self.do(d_a+d_b, d_a+d_b)
     self.assertEqual(self.i, 2)
     keyboard.hook(count, suppress=True)
     self.do(d_a+d_b, d_b)
     self.assertEqual(self.i, 4)
     keyboard.unhook_all()
     self.do(d_a+d_b, d_a+d_b)
     self.assertEqual(self.i, 4)
Beispiel #33
0
 def test_get_typed_strings(self):
     keyboard.hook(self.events.append)
     self.click("b")
     self.click("i")
     self.press("shift")
     self.click("r")
     self.click("caps lock")
     self.click("d")
     self.click("caps lock")
     self.release("shift")
     self.click(" ")
     self.click("backspace")
     self.click(".")
     self.click("enter")
     self.click("n")
     self.click("e")
     self.click("w")
     self.assertEqual(list(keyboard.get_typed_strings(self.events)), ["biRd.", "new"])
Beispiel #34
0
    def test_hook(self):
        self.i = 0

        def count(e):
            self.assertEqual(e.name, "a")
            self.i += 1

        keyboard.hook(count)
        self.click("a")
        self.assertEqual(self.i, 2)
        keyboard.hook(count)
        self.click("a")
        self.assertEqual(self.i, 6)
        keyboard.unhook(count)
        self.click("a")
        self.assertEqual(self.i, 8)
        keyboard.unhook(count)
        self.click("a")
        self.assertEqual(self.i, 8)
Beispiel #35
0
def release(scan_code):
    if scan_code < 0:
        vk = -scan_code
        scan_code = MapVirtualKey(vk, MAPVK_VK_TO_VSC)
    else:
        vk = MapVirtualKey(scan_code, MAPVK_VSC_TO_VK)
    user32.keybd_event(vk, scan_code, 2, 0)

def type_unicode(character):
    # This code and related structures are based on
    # http://stackoverflow.com/a/11910555/252218
    inputs = []
    surrogates = bytearray(character.encode('utf-16le'))
    for i in range(0, len(surrogates), 2):
        higher, lower = surrogates[i:i+2]
        structure = KEYBDINPUT(0, (lower << 8) + higher, KEYEVENTF_UNICODE, 0, None)
        inputs.append(INPUT(INPUT_KEYBOARD, _INPUTunion(ki=structure)))
    nInputs = len(inputs)
    LPINPUT = INPUT * nInputs
    pInputs = LPINPUT(*inputs)
    cbSize = c_int(ctypes.sizeof(INPUT))
    SendInput(nInputs, pInputs, cbSize)

if __name__ == '__main__':
    import keyboard
    def p(event):
        print(event)
    keyboard.hook(p)
    input()
Beispiel #36
0
"""
Prints the scan code of all currently pressed keys.
Updates on every keyboard event.
"""
import sys
sys.path.append('..')
import keyboard

def print_pressed_keys(e):
	line = ', '.join(str(code) for code in keyboard._pressed_events)
	# '\r' and end='' overwrites the previous line.
	# ' '*40 prints 40 spaces at the end to ensure the previous line is cleared.
	print('\r' + line + ' '*40, end='')
	
keyboard.hook(print_pressed_keys)
keyboard.wait()
Beispiel #37
-1
    def __init__(self, bot):
        self.bot = bot

        self.is_online = True

        self._last_time = 0

        kb.hook(self.kb_press)

        self.status_task = None
        self.start = False
Beispiel #38
-1
# -*- coding: utf-8 -*-
import keyboard
import fileinput
import json
import sys

def print_event_json(event):
	# Could use json.dumps(event.__dict__()), but this way we guarantee semantic order.
	if event.name:
		print('{{"event_type": "{}", "name": "{}", "scan_code": {}, "time": {}}}'.format(event.event_type, event.name, event.scan_code, event.time))
	else:
		print('{{"event_type": "{}", "scan_code": {}, "time": {}}}'.format(event.event_type, event.scan_code, event.time))
	sys.stdout.flush()
keyboard.hook(print_event_json)

parse_event_json = lambda line: keyboard.KeyboardEvent(**json.loads(line))
keyboard.play(parse_event_json(line) for line in fileinput.input())