Python如何读取GPIO事件的匿名linux文件

时间:2021-09-07 10:22:40

Working on a python 3 implementation of the new linux gpio implementation. The initial setup works great:

使用python 3实现新的linux gpio实现。最初的设置效果很好:

class gpioevent_request(ctypes.Structure):
    _pack_ = 1
    _fields_ = [
                ('lineoffset', ctypes.c_ulong),
                ('handleflags', ctypes.c_ulong),
                ('eventflags', ctypes.c_ulong),
                ('consumer_label', ctypes.c_char * 32),
                ('fd', ctypes.c_int),
                ]

class gpioevent_data(ctypes.Structure):
    _pack_ = 1
    _fields_ = [
                ('timestamp', ctypes.c_ulonglong),
                ('id', ctypes.c_ulong),
                ]

self.event = gpioevent_request()
self.eventData = gpioevent_data()
...
# Open /dev/gpiochipx with os.open and set up the event structure
...
fcntl.ioctl(self._fd, GPIO_GET_LINEEVENT_IOCTL, self.event)

My challenge comes when I try to read the event information that is stored in the anonymous linux file created by the GPIO_GET_LINEEVENT_IOCTL call.

当我尝试读取由GPIO_GET_LINEEVENT_IOCTL调用创建的匿名linux文件中存储的事件信息时,我的挑战就来了。

If I try os.read I get an invalid argument response:

如果我试着操作系统。读取我得到一个无效的参数响应:

os.read(self.event.fd, bytesToRead)

If I try libc read then it will read the file but I get all zeros for my data (timestamp and id):

如果我尝试libc读取,它会读取文件,但是我的数据(时间戳和id)都是0:

import ctypes.util
libc = ctypes.CDLL(ctypes.util.find_library('c'))
self.f_read = libc.read
self.f_read(self.event.fd, ctypes.byref(self.eventData), ctypes.sizeof(self.eventData))

using epoll does seem to trigger the file on the rising or falling edge on my input pin but it works intermittently:

使用epoll似乎可以触发我的输入pin的上升或下降边缘上的文件,但它间歇性地工作:

p = select.epoll()
p.register(self.event.fd, select.EPOLLIN | select.EPOLLET | select.EPOLLPRI)

Any insight is appreciated greatly.

任何见解都将受到极大的赞赏。

1 个解决方案

#1


2  

My suspicion is that you don't want to _pack_ your ctypes.Structures at all. The docs say

我的怀疑是你不想打包你的ctype。结构。医生说

By default, Structure and Union fields are aligned in the same way the C compiler does it. It is possible to override this behavior be specifying a pack class attribute in the subclass definition.

默认情况下,结构和联合字段的对齐方式与C编译器相同。可以重写在子类定义中指定pack类属性的行为。

Since these are structures you're sharing with libc calls, you'll want them in the same default layout that it's used to seeing them.

由于这些是与libc调用共享的结构,所以您将希望它们处于与它们相同的默认布局中。

#1


2  

My suspicion is that you don't want to _pack_ your ctypes.Structures at all. The docs say

我的怀疑是你不想打包你的ctype。结构。医生说

By default, Structure and Union fields are aligned in the same way the C compiler does it. It is possible to override this behavior be specifying a pack class attribute in the subclass definition.

默认情况下,结构和联合字段的对齐方式与C编译器相同。可以重写在子类定义中指定pack类属性的行为。

Since these are structures you're sharing with libc calls, you'll want them in the same default layout that it's used to seeing them.

由于这些是与libc调用共享的结构,所以您将希望它们处于与它们相同的默认布局中。