double click in for loop

78 Views Asked by At

I have a simple python program that reads the input of a hid device from a for-loop. I wan't to implement different actions (long, single, double, tripple press) for a single button.

The problem with my solution is that, compared to all other solutions I've seen, my loop only gets triggered if a button is pressed. That means that I can't simply call a function with a time constrain, because I would never trigger the single click.

I think I need a thread for this. But I'm not sure and don't know how I could do that. Any help appreciated!

This is what I tried:

clicked = False
def set_clicked():
    global clicked
    clicked = True


click_registered = False
click_time = time.time()
def click_handler():
    global click_registered, clicked, click_time

    if click_registered and time.time() - click_time > 0.35:
        click_registered = False
        print("single")

    if clicked:
        if click_registered:
            if time.time() - click_time < 0.35:
                click_registered = False
                print("double")
        else:
            click_registered = True
        clicked = False
        click_time = time.time()


for event in device.read_loop(): # loops forever
    if event.code == 1:  # button pressed
        set_clicked()

    click_handler()

If there is other action after a single click, the loop is not triggered and neither will the single click.

I came up with the following as a possible solution for detecting a double click. But that still feels not quite right. Anybody having an elegant solution for that?

import threading
import time

press_count = 0
def thread_function(name):
    global press_count
    start_time = time.time()
    
    while time.time() - start_time < 0.35:
        if press_count == 2:
            press_count = 0
            print("double")
            return
    print("single")
    press_count = 0
    return

for n in range(3):
    if len(threading.enumerate()) >= 1:
        press_count+=1

    if len(threading.enumerate()) == 1:
        t = threading.Thread(target=thread_function, args=(1,))
        t.start()

    if n == 0:
        time.sleep(0.5)
    if n == 1:
        time.sleep(0.1)
0

There are 0 best solutions below