Skip to content

problem with close #61

Closed
Closed

Description

@shawnhsy

It seems that once a 'data' listener is added, device can not be closed properly.

I encountered the problem with code like this. ran it in node console

>var HID = require('node-hid');
undefined
>var p = h.devices()[1].path;         // had a bar code scanner connected
undefined
>var dev = new HID.HID(p);
undefined
>dev.on('data', function(d){console.log(d)});
......
>dev.removeAllListeners('data');
......
>dev.close();                               //close the device
undefined
>dev = new HID.HID(p);               //reopen the device, failed, seems like the device is not released
cannot open device with path \\?\hid#vi...blahblahblah

reopen is good when i skip the dev.on('data',...) and dev.removeAllListeners('data') statement.

Is it a bug?

Activity

  1. shawnhsy commented on Apr 24, 2014

    @shawnhsy
    Author

    looked into the code. i think it's caused by a hidapi issue.
    signal11/hidapi#48
    to all that suffered from this issue, a walkaround is suggested in the above link.

  2. amullins83 commented on Jan 8, 2015

    @amullins83

    In my opinion, this could be fixed in node-hid by calling hid_read_timeout instead of hid_read in the read loop. Before emitting the data event, we'll check for either no data (return 0) or an error (return -1). The error usually means the device handle is closed. Repeat until the return value is something other than 0. I'm trying it out now on my Windows 7 x64 box.

  3. amullins83 commented on Jan 8, 2015

    @amullins83

    To follow up: preliminary results are negative. I'm getting exactly the same behavior as before. I'll post my edits to a fork in case anyone wants to look at it. There's a very good chance I'm just missing something here.

  4. amullins83 commented on Jan 9, 2015

    @amullins83

    I posted PR signal11/hidapi#208 to address this issue. This will only improve the experience on Vista and above. On Windows XP, if you have a way to force the device to send data by writing to it, performing a write AFTER removing event listeners but BEFORE calling close() seems to work. Here's an example for my device:

    var hid = require("node-hid");
    var dev = new hid.HID(myVendorId, myProductId);
    dev.on("data", myListener);
    // ... Communication happening ...
    dev.removeAllListeners("data");
    dev.write([EndPoint, 1, EndOfCommandToken]); // Makes device respond with an error message
    dev.close();

    The problem has to do with the read thread waiting for data that never arrives. As long as the read thread is alive, the system can't release the device handle. Getting the device to send data will let the read thread exit, which lets the device close properly.

  5. peitschie commented on Jun 19, 2019

    @peitschie

    I had this issue also, and found that I could workaround it by calling setNonBlocking(true) on the HID device prior to subscribing to any data.

    There's an open issue from 2017 about this undocumented function: #216

  6. todbot commented on Jun 19, 2019

    @todbot
    Contributor

    This is expected behavior. Any open device with an installed event listener will block process exit until close.

  7. peitschie commented on Jun 19, 2019

    @peitschie

    Any open device with an installed event listener will block process exit until close.

    Unfortunately, even calling dev.removeAllListeners("data") and dev.close() is not sufficient to avoid the hang here (this was on a ubuntu xenial x32 armv7 raspberry pi based device).

    Basically, without setting non-blocking, the nodejs process would always hang during shutdown until I terminated it (i.e., SIGTERM) 😞

  8. todbot commented on Jun 19, 2019

    @todbot
    Contributor

    Hi @peitschie,
    Do you have a small self-contained script that demonstrates this?
    What hardware are you talking to?
    The Ubuntu you're running on your Pi isn't Raspbian, but something else? (I'm a bit confused by the "x32 amv7" designation)
    I'd like to try to replicate what you're seeing. I have plenty of Pis and hopefully can get the HID hardware you're talking to.

  9. peitschie commented on Jun 19, 2019

    @peitschie

    Hi @todbot

    For me, something as simple as this is sufficient to cause the hang:

    var HID = require('node-hid');
    var util = require('util');
    
    var devices = HID.devices();
    console.log(util.inspect(devices));
    
    var button = new HID.HID(`/dev/hidraw1`);
    button.on("data", data => console.log(`Received`, data));
    
    setTimeout(() => {
      console.log("exiting");
      button.removeAllListeners("data");
      button.close();
      process.exit(0);
    }, 3000);
    

    The output from that is:

    root@ubuntu:/home/user/node-hid-usb-repro# node index.js
    [ { vendorId: 53769,
        productId: 4608,
        path: '/dev/hidraw0',
        serialNumber: '1',
        manufacturer: 'USBButton',
        product: 'USBButton',
        release: 1,
        interface: 0,
        usagePage: 68,
        usage: 12336 },
      { vendorId: 53769,
        productId: 4608,
        path: '/dev/hidraw1',
        serialNumber: '1',
        manufacturer: 'USBButton',
        product: 'USBButton',
        release: 1,
        interface: 1 } ]
    exiting
    ^C
    

    (The ^C is where I interrupted, as the process wasn't closing)
    Checking the open file handles, the /dev/hidraw1 device has been closed at this stage, but still the process won't exit:

    total 0
    lrwx------. 1 root root 64 Jun 19 22:49 0 -> /dev/pts/4
    lrwx------. 1 root root 64 Jun 19 22:49 1 -> /dev/pts/4
    lr-x------. 1 root root 64 Jun 19 22:49 10 -> /dev/null
    lrwx------. 1 root root 64 Jun 19 22:49 11 -> /dev/pts/4
    lrwx------. 1 root root 64 Jun 19 22:49 2 -> /dev/pts/4
    lr-x------. 1 root root 64 Jun 19 22:49 3 -> pipe:[3895843]
    l-wx------. 1 root root 64 Jun 19 22:49 4 -> pipe:[3895843]
    lrwx------. 1 root root 64 Jun 19 22:49 5 -> anon_inode:[eventpoll]
    lr-x------. 1 root root 64 Jun 19 22:49 6 -> pipe:[3895844]
    l-wx------. 1 root root 64 Jun 19 22:49 7 -> pipe:[3895844]
    lrwx------. 1 root root 64 Jun 19 22:49 8 -> anon_inode:[eventfd]
    lrwx------. 1 root root 64 Jun 19 22:49 9 -> /dev/pts/4
    

    I realise this morning there are a bunch of quirks which might be contributing to what I'm seeing though. I'll let you be the judge 😃 .

    1. This is an LXC container with the USB forwarded on from the host
    2. Due to the above, I am manually performing mknod /dev/hidraw1 c 247 1 to create the device

    The container details are (sorry for the slab of data... I am not sure which is relevant to you):

    root@ubuntu:~# uname -a
    Linux ubuntu 3.10.33 #260 SMP PREEMPT !Mon Apr 29 19:32:43 CST 2019 armv7l armv7l armv7l GNU/Linux
    
    root@ubuntu:~# dpkg-architecture --list
    DEB_BUILD_ARCH=armhf
    DEB_BUILD_ARCH_BITS=32
    DEB_BUILD_ARCH_CPU=arm
    DEB_BUILD_ARCH_ENDIAN=little
    DEB_BUILD_ARCH_OS=linux
    DEB_BUILD_GNU_CPU=arm
    DEB_BUILD_GNU_SYSTEM=linux-gnueabihf
    DEB_BUILD_GNU_TYPE=arm-linux-gnueabihf
    DEB_BUILD_MULTIARCH=arm-linux-gnueabihf
    DEB_HOST_ARCH=armhf
    DEB_HOST_ARCH_BITS=32
    DEB_HOST_ARCH_CPU=arm
    DEB_HOST_ARCH_ENDIAN=little
    DEB_HOST_ARCH_OS=linux
    DEB_HOST_GNU_CPU=arm
    DEB_HOST_GNU_SYSTEM=linux-gnueabihf
    DEB_HOST_GNU_TYPE=arm-linux-gnueabihf
    DEB_HOST_MULTIARCH=arm-linux-gnueabihf
    DEB_TARGET_ARCH=armhf
    DEB_TARGET_ARCH_BITS=32
    DEB_TARGET_ARCH_CPU=arm
    DEB_TARGET_ARCH_ENDIAN=little
    DEB_TARGET_ARCH_OS=linux
    DEB_TARGET_GNU_CPU=arm
    DEB_TARGET_GNU_SYSTEM=linux-gnueabihf
    DEB_TARGET_GNU_TYPE=arm-linux-gnueabihf
    DEB_TARGET_MULTIARCH=arm-linux-gnueabihf
    
    root@ubuntu:~# cat /proc/cpuinfo
    Processor       : ARMv7 Processor rev 1 (v7l)
    processor       : 0
    BogoMIPS        : 1.93
    
    processor       : 1
    BogoMIPS        : 1.93
    
    processor       : 2
    BogoMIPS        : 1.93
    
    processor       : 3
    BogoMIPS        : 1.93
    
    Features        : swp half thumb fastmult vfp edsp neon vfpv3 tls vfpv4
    CPU implementer : 0x41
    CPU architecture: 7
    CPU variant     : 0x0
    CPU part        : 0xc05
    CPU revision    : 1
    
    Hardware        : Amlogic Meson8B
    Revision        : 000a
    Serial          : 1b00000000000000
    
    root@ubuntu:~# lscpu
    Architecture:          armv7l
    Byte Order:            Little Endian
    CPU(s):                4
    On-line CPU(s) list:   0-3
    Thread(s) per core:    1
    Core(s) per socket:    4
    Socket(s):             1
    CPU max MHz:           1536.0000
    CPU min MHz:           24.0000
    Hypervisor vendor:     (null)
    Virtualization type:   full
    
    root@ubuntu:~# lshw
    ubuntu
        description: Computer
        product: AMLOGIC
        width: 32 bits
      *-core
           description: Motherboard
           physical id: 0
           capabilities: amlogic_8726_m8b
         *-cpu:0
              description: CPU
              product: cpu
              physical id: 0
              bus info: cpu@0
              size: 768MHz
              capacity: 1536MHz
              capabilities: cpufreq
         *-cpu:1
              description: CPU
              product: cpu
              physical id: 1
              bus info: cpu@1
              size: 768MHz
              capacity: 1536MHz
              capabilities: cpufreq
         *-cpu:2
              description: CPU
              product: cpu
              physical id: 2
              bus info: cpu@2
              size: 768MHz
              capacity: 1536MHz
              capabilities: cpufreq
         *-cpu:3
              description: CPU
              product: cpu
              physical id: 3
              bus info: cpu@3
              size: 768MHz
              capacity: 1536MHz
              capabilities: swp half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 cpufreq
         *-memory
              description: System memory
              physical id: 4
              size: 220MiB
      *-usbhost:0
           product: DWC OTG Controller
           vendor: Linux 3.10.33 dwc_otg_hcd
           physical id: 1
           bus info: usb@2
           logical name: usb2
           version: 3.10
           capabilities: usb-2.00
           configuration: driver=hub slots=1 speed=480Mbit/s
         *-usb
              description: Human interface device
              product: USBButton
              vendor: USBButton
              physical id: 1
              bus info: usb@2:1
              version: 0.01
              serial: 1
              capabilities: usb-2.00
              configuration: driver=usbhid maxpower=100mA speed=2Mbit/s
      *-usbhost:1
           product: DWC OTG Controller
           vendor: Linux 3.10.33 dwc_otg_hcd
           physical id: 2
           bus info: usb@1
           logical name: usb1
           version: 3.10
           capabilities: usb-2.00
           configuration: driver=hub slots=1 speed=480Mbit/s
      *-network:0 DISABLED
           description: Ethernet interface
           physical id: 3
           logical name: gretap0
           capabilities: ethernet physical
           configuration: broadcast=yes multicast=yes
      *-network:1
           description: Ethernet interface
           physical id: 4
           logical name: eth0
           serial: 00:16:3e:28:51:9d
           size: 10Gbit/s
           capabilities: ethernet physical
           configuration: autonegotiation=off broadcast=yes driver=veth driverversion=1.0 duplex=full ip=10.10.10.253 link=yes multicast=yes port=twisted pair speed=10Gbit/s
    
  10. todbot commented on Jun 19, 2019

    @todbot
    Contributor

    Awesome, thanks for the detailed response.

    What is the HID device you are communicating with? Is there a way I can obtain or recreate it?

    Also, what does lsusb -v report?

    Is there a quick "getting started with lxc" that I can follow to create a container similar to what you're using?

  11. todbot commented on Jun 19, 2019

    @todbot
    Contributor

    Oh another question. If you change the top of your script to set the driverType to be 'libusb':

    var HID = require('node-hid');
    HID.setDriverType('libusb');
    

    is the effect any different?

  12. peitschie commented on Jun 20, 2019

    @peitschie

    Thanks for looking at this 😺

    Changing the driver to libusb had no effect.

    The output from lsusb -v is:

    root@ubuntu:~# lsusb -v
    
    Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
    Couldn't open device, some information will be missing
    Device Descriptor:
      bLength                18
      bDescriptorType         1
      bcdUSB               2.00
      bDeviceClass            9 Hub
      bDeviceSubClass         0 Unused
      bDeviceProtocol         1 Single TT
      bMaxPacketSize0        64
      idVendor           0x1d6b Linux Foundation
      idProduct          0x0002 2.0 root hub
      bcdDevice            3.10
      iManufacturer           3
      iProduct                2
      iSerial                 1
      bNumConfigurations      1
      Configuration Descriptor:
        bLength                 9
        bDescriptorType         2
        wTotalLength           25
        bNumInterfaces          1
        bConfigurationValue     1
        iConfiguration          0
        bmAttributes         0xe0
          Self Powered
          Remote Wakeup
        MaxPower                0mA
        Interface Descriptor:
          bLength                 9
          bDescriptorType         4
          bInterfaceNumber        0
          bAlternateSetting       0
          bNumEndpoints           1
          bInterfaceClass         9 Hub
          bInterfaceSubClass      0 Unused
          bInterfaceProtocol      0 Full speed (or root) hub
          iInterface              0
          Endpoint Descriptor:
            bLength                 7
            bDescriptorType         5
            bEndpointAddress     0x81  EP 1 IN
            bmAttributes            3
              Transfer Type            Interrupt
              Synch Type               None
              Usage Type               Data
            wMaxPacketSize     0x0004  1x 4 bytes
            bInterval              12
    
    Bus 002 Device 005: ID d209:1200 Ultimarc
    Couldn't open device, some information will be missing
    Device Descriptor:
      bLength                18
      bDescriptorType         1
      bcdUSB               2.00
      bDeviceClass            0 (Defined at Interface level)
      bDeviceSubClass         0
      bDeviceProtocol         0
      bMaxPacketSize0         8
      idVendor           0xd209 Ultimarc
      idProduct          0x1200
      bcdDevice            0.01
      iManufacturer           2
      iProduct                2
      iSerial                 1
      bNumConfigurations      1
      Configuration Descriptor:
        bLength                 9
        bDescriptorType         2
        wTotalLength           59
        bNumInterfaces          2
        bConfigurationValue     1
        iConfiguration          2
        bmAttributes         0xa0
          (Bus Powered)
          Remote Wakeup
        MaxPower              100mA
        Interface Descriptor:
          bLength                 9
          bDescriptorType         4
          bInterfaceNumber        0
          bAlternateSetting       0
          bNumEndpoints           1
          bInterfaceClass         3 Human Interface Device
          bInterfaceSubClass      0 No Subclass
          bInterfaceProtocol      0 None
          iInterface              2
            HID Device Descriptor:
              bLength                 9
              bDescriptorType        33
              bcdHID               1.11
              bCountryCode            0 Not supported
              bNumDescriptors         1
              bDescriptorType        34 Report
              wDescriptorLength      33
             Report Descriptors:
               ** UNAVAILABLE **
          Endpoint Descriptor:
            bLength                 7
            bDescriptorType         5
            bEndpointAddress     0x81  EP 1 IN
            bmAttributes            3
              Transfer Type            Interrupt
              Synch Type               None
              Usage Type               Data
            wMaxPacketSize     0x0008  1x 8 bytes
            bInterval              10
        Interface Descriptor:
          bLength                 9
          bDescriptorType         4
          bInterfaceNumber        1
          bAlternateSetting       0
          bNumEndpoints           1
          bInterfaceClass         3 Human Interface Device
          bInterfaceSubClass      1 Boot Interface Subclass
          bInterfaceProtocol      1 Keyboard
          iInterface              2
            HID Device Descriptor:
              bLength                 9
              bDescriptorType        33
              bcdHID               1.11
              bCountryCode            0 Not supported
              bNumDescriptors         1
              bDescriptorType        34 Report
              wDescriptorLength     168
             Report Descriptors:
               ** UNAVAILABLE **
          Endpoint Descriptor:
            bLength                 7
            bDescriptorType         5
            bEndpointAddress     0x82  EP 2 IN
            bmAttributes            3
              Transfer Type            Interrupt
              Synch Type               None
              Usage Type               Data
            wMaxPacketSize     0x0008  1x 8 bytes
            bInterval              10
    
    Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
    Couldn't open device, some information will be missing
    Device Descriptor:
      bLength                18
      bDescriptorType         1
      bcdUSB               2.00
      bDeviceClass            9 Hub
      bDeviceSubClass         0 Unused
      bDeviceProtocol         1 Single TT
      bMaxPacketSize0        64
      idVendor           0x1d6b Linux Foundation
      idProduct          0x0002 2.0 root hub
      bcdDevice            3.10
      iManufacturer           3
      iProduct                2
      iSerial                 1
      bNumConfigurations      1
      Configuration Descriptor:
        bLength                 9
        bDescriptorType         2
        wTotalLength           25
        bNumInterfaces          1
        bConfigurationValue     1
        iConfiguration          0
        bmAttributes         0xe0
          Self Powered
          Remote Wakeup
        MaxPower                0mA
        Interface Descriptor:
          bLength                 9
          bDescriptorType         4
          bInterfaceNumber        0
          bAlternateSetting       0
          bNumEndpoints           1
          bInterfaceClass         9 Hub
          bInterfaceSubClass      0 Unused
          bInterfaceProtocol      0 Full speed (or root) hub
          iInterface              0
          Endpoint Descriptor:
            bLength                 7
            bDescriptorType         5
            bEndpointAddress     0x81  EP 1 IN
            bmAttributes            3
              Transfer Type            Interrupt
              Synch Type               None
              Usage Type               Data
            wMaxPacketSize     0x0004  1x 4 bytes
            bInterval              12
    

    Regarding the exact hardware, it is a relatively cheap button purchased from http://usbbutton.com/, running on a proprietary hardware system (though I have no way to discover the exact hardware, sorry).

    Regarding LXC usage, I did a quick google and browse, and seems like something such as https://linuxcontainers.org/lxd/getting-started-cli/#creating-and-using-your-first-container is decently straightfoward if you have a linux system somewhere.

    I followed https://medium.com/@konpat/usb-passthrough-to-an-lxc-proxmox-15482674f11d to figure out how to allow the USB device through to the container. For the USB button, the exact lines I added to the container's config were:

    lxc.cgroup.devices.allow = c 188:* rwm
    lxc.cgroup.devices.allow = c 247:* rwm
    

    I suspect there's a way to do that for a running, but I don't know exactly how to do it, unfortunately 😿 . It looks like something akin to https://discuss.linuxcontainers.org/t/providing-access-to-loop-and-other-devices-in-containers/1352... but I have no way of discovering the exact commands, sorry, as I only get access from within the container on the proprietary system.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions