如何通过写入“/dev/input/EventX”在一个文件流中发送和执行多个事件

How to send and execute multiple events in one file stream by writting to "/dev/input/EventX"

我正在写入 /dev/input/ 中的特定 eventX 文件,以触发“硬件”事件。问题是,只有在 文件关闭 之后,事件才会 执行 并触发新事件,需要重新打开文件。就好像所有的事件都放在一个队列中,然后当文件关闭时,它们就会被执行。例如

Task: Perform mouse press.

# Path is specific to my machine for the mouse
with open("/dev/input/event2") as controller: 
    send_mouse_click_event(controller) # This is put into a queue

print("File has closed") # here the press event triggers

send_mouse_click_event,依赖于函数send,定义如下

# First a `send` function is used to interact with file
# it is basically the inverse of 
def send(file_stream, type: int, code: int, value: int):
    timeval = str(time.time()).split(".") # Time that the event happend is requried, but seems to be redundant  
    if timeval[0][0] == '0': # the second part of `time.time()` must not start with a `0`
        utime = utime[1:len(utime)] 
    timeval = [int(item) for item in utime]
    # Convert to the following formats (long int, long int, ushort, ushort, uint)
    event: bytes = struct.pack('llHHI', *utime, type, code, value)
    file_stream.write(event)

# Now the specific events to trigger a mouse click
def send_mouse_click_event(filestream, value: int):
    # 0x90001 is always send before a click
    send(filestream, 4, 4, 0x90001)
    # 0x110 is indicating the LEFT CLICK
    # value is either 0 for mouse RELEASE and 1 for PRESS
    send(filestream, 1, 0x110, value)
    # (0, 0, 0) is indiciating the end of an event
    send(filestream, 0, 0, 0)

我的问题是,是否有任何事件可以 send() 指示我要执行队列中的所有项目。

关闭和打开文件是一项开销很大的操作,而且必须多次执行该操作会降低性能。必须有更好的方法来保持文件流打开。

除非在 open 调用中通过将 buffering 参数设置为 0 来禁用缓冲,否则文件流将完全缓冲或行缓冲。这取决于正在打开的文件类型和打开模式,但二进制文件流永远不会设置为行缓冲模式。

在缓冲模式下,write 方法将写入缓冲区,但缓冲区内容不会写入底层文件,直到缓冲区已满,或者在行缓冲模式下写入换行符.

flushclose方法将缓冲区内容写入底层文件。 close 方法之后也会关闭文件。

在 OP 的代码中,将 file_stream.flush() 添加到 send 函数的末尾将在每次调用 send 函数时将缓冲区内容写入底层文件。一种替代方法是在send_mouse_click_event函数的末尾添加filestream.flush(),以便将3次调用send写入的数据一次性刷新到底层文件。