简体   繁体   English

如何(可靠地)读取嵌入式(无头)Linux中的USB条形码扫描器?

[英]How to (reliably) read USB barcode scanner in embedded (headless) Linux?

I need to interface generic USB scanners ( not a single, defined, model) with an embedded Linux device (mips32/MT7620 running Linux 3.18, if it matters). 我需要将通用USB扫描仪( 不是单一的,定义的,模型)与嵌入式Linux设备(运行Linux 3.18的mips32 / MT7620,如果重要)连接起来。

All scanners operate in "keyboard emulation mode" and, sure enough, if plugged into a desktop Linux send their data directly as keyboard input to console. 所有扫描仪都以“键盘仿真模式”运行,当然,如果插入桌面,Linux会将其数据作为键盘输入直接发送到控制台。

This does not happen on device (ie: I do not see any char unto the serial debug console, which makes sense as it misses all X input subsystem). 不会对设备发生(即我没有看到对串口调试控制台,这是有道理的,因为它错过所有的X输入子系统任何字符)。

All scanners present themselves as Input device on /dev/input/event0 . 所有扫描仪都在/dev/input/event0上显示为输入设备。

My current attempt is using python evdev ; 我目前的尝试是使用python evdev ; code is quite straightforward: 代码非常简单:

import asyncio
import evdev

edev = evdev.InputDevice('/dev/input/event0')
async for event in edev.async_read_loop():
    if event.type == evdev.ecodes.EV_KEY and event.value == 1:
        handle_event(event)

Note: this is just an extracted snippet; 注意:这只是一个摘录片段; I can post a runnable example, if needed. 如果需要,我可以发布一个可运行的示例。

This is essentially this answer (I'm using asyncio , can that be a problem?) and it seems to work, but actually loses events. 这基本上是这个答案 (我使用asyncio ,这可能是一个问题?)它似乎工作,但实际上失去了事件。

If barcode scanner sends events back-to back I seem to start losing events quite early (after about 16 events <= 8 chars!). 如果条形码扫描器背靠背发送事件,我似乎很早就开始丢失事件(大约16个事件之后<= 8个字符!)。

If I can insert between-char delay (~1ms is enough) then everything works as expected, but that's not an option on many scanners. 如果我可以插入-chac延迟(〜1ms就足够了),那么一切都按预期工作,但这不是许多扫描仪的选项。

What am I missing? 我错过了什么?

For whoever is in the same predicament: I was unable to find a Pure Python working solution. 对于处于同样困境的人:我无法找到纯Python 工作解决方案。

I resorted to a very simple "C" program (most of it are tables): 我使用了一个非常简单的“C”程序(大部分都是表格):

#include <stdio.h>
#include <fcntl.h>
#include <linux/input.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>

void INThandler() {
    exit(0);
}

char ttab[] = {
     0,  27, '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', '\b',  /* Backspace */
  '\t', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']','\n',        /* Enter key */
     0, 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';','\'', '`',   0,        /* Left shift */
  '\\', 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/',   0,                  /* Right shift */
  '*',
    0,  /* Alt */
  ' ',  /* Space bar */
    0,  /* Caps lock */
    0,  /* 59 - F1 key ... > */
    0,   0,   0,   0,   0,   0,   0,   0,
    0,  /* < ... F10 */
    0,  /* 69 - Num lock*/
    0,  /* Scroll Lock */
    0,  /* Home key */
    0,  /* Up Arrow */
    0,  /* Page Up */
  '-',
    0,  /* Left Arrow */
    0,
    0,  /* Right Arrow */
  '+',
    0,  /* 79 - End key*/
    0,  /* Down Arrow */
    0,  /* Page Down */
    0,  /* Insert Key */
    0,  /* Delete Key */
    0,   0,   0,
    0,  /* F11 Key */
    0,  /* F12 Key */
    0,  /* All other keys are undefined */
};


char ntab[] = {
    0,  27, '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', '\b',   /* Backspace */
 '\t', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']','\n',         /* Enter key */
    0, 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';','\'', '`',   0,         /* Left shift */
 '\\', 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/',   0,                   /* Right shift */
  '*',
    0,  /* Alt */
  ' ',  /* Space bar */
    0,  /* Caps lock */
    0,  /* 59 - F1 key ... > */
    0,   0,   0,   0,   0,   0,   0,   0,
    0,  /* < ... F10 */
    0,  /* 69 - Num lock*/
    0,  /* Scroll Lock */
    0,  /* Home key */
    0,  /* Up Arrow */
    0,  /* Page Up */
  '-',
    0,  /* Left Arrow */
    0,
    0,  /* Right Arrow */
  '+',
    0,  /* 79 - End key*/
    0,  /* Down Arrow */
    0,  /* Page Down */
    0,  /* Insert Key */
    0,  /* Delete Key */
    0,   0,   0,
    0,  /* F11 Key */
    0,  /* F12 Key */
    0,  /* All other keys are undefined */
};

char stab[] = {
    0,  27, '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', 0,      /* Backspace */
    0, 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '{', '}',   0,         /* Enter key */
    0, 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ':', '"',   0,'\n',         /* Left shift */
    0, 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '<', '>', '?',   0,                   /* Right shift */
  '*',
    0,  /* Alt */
  ' ',  /* Space bar */
    0,  /* Caps lock */
    0,  /* 59 - F1 key ... > */
    0,   0,   0,   0,   0,   0,   0,   0,
    0,  /* < ... F10 */
    0,  /* 69 - Num lock*/
    0,  /* Scroll Lock */
    0,  /* Home key */
    0,  /* Up Arrow */
    0,  /* Page Up */
  '-',
    0,  /* Left Arrow */
    0,
    0,  /* Right Arrow */
  '+',
    0,  /* 79 - End key*/
    0,  /* Down Arrow */
    0,  /* Page Down */
    0,  /* Insert Key */
    0,  /* Delete Key */
    0,   0,   0,
    0,  /* F11 Key */
    0,  /* F12 Key */
    0,  /* All other keys are undefined */
};

int main() {
    char devname[] = "/dev/input/event0";
    int device = open(devname, O_RDONLY);
    struct input_event ev;
    int shift = 0;
    char line[4096], *p = line;

    signal(SIGINT, INThandler);
    fputs("starting\n", stdout);
    //fputs("starting\n", stderr);
    while (1) {
        read(device, &ev, sizeof(ev));
        if (ev.type == 1) {
            if (ev.code == 42)
                shift = ev.value;
            else if (ev.value) {
                //printf("Key: %i State: %i\n", ev.code, ev.value);
                char *t = shift? stab: ntab;
                char ch = t[ev.code];
                //printf("Key: %02d State: %d [%c]\n", ev.code, ev.value, ch);
                if (ch == '\n') {
                    *p = '\0';
                    fputs(line, stdout); fputc('\n', stdout); fflush(stdout);
                    //fputs(line, stderr); fputc('\n', stderr); fflush(stderr);
                    p = line;
                } else
                    *p++ = ch;
            }
        }
    }
}

... driven from Python: ......来自Python:

async def handle_events(self):
    log.debug("handle_events(%s): st start", self.dev)
    while True:
        if self.hid is None:
            log.debug("handle_events(%s): checking...", self.dev)
            self.hid = await asyncio.create_subprocess_exec(
                '/usr/local/bin/readEvents',
                stdout=asyncio.subprocess.PIPE
            )
            try:
                out = await asyncio.wait_for(self.hid.stdout.readline(), 10)
            except asyncio.TimeoutError:
                log.debug("handle_events(%s): timeout on startup message", self.dev)
                self.hid.terminate()
                self.hid = None
            else:
                out = out.strip()
                if out != b'starting':
                    log.debug("handle_events(%s): bad startup message: %s", self.dev, out)
                    self.hid.terminate()
                    self.hid = None
                else:
                    log.debug("handle_events(%s): startup msg received", self.dev)
        else:
            if self.hid.stdout.at_eof():
                log.info("handle_events(%s): killing subprocess", self.dev)
                rc = await self.hid.wait()
                log.info("handle_events(%s): subprocess exited with status %s", self.dev, rc)
                self.hid = None
                await asyncio.sleep(10)
        if self.hid is not None:
            line = await self.hid.stdout.readline()
            if not line:
                log.error('handle_events: readline() ERROR:')
                self.hid.terminate()
                self.hid = None
            else:
                line = line.strip()
                log.info('handle_events: received line: "%s"', line)
                await self.process_line(line)

I'm sure Python driver can be simplified. 我确信Python驱动程序可以简化。 This is verbatim from my (working) application. 这是我(工作)应用程序的逐字记录。

HiH! HIH!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM