Method: LIBUSB::Context#on_hotplug_event

Defined in:
lib/libusb/context.rb

#on_hotplug_event(events: HOTPLUG_EVENT_DEVICE_ARRIVED | HOTPLUG_EVENT_DEVICE_LEFT, flags: 0, vendor_id: HOTPLUG_MATCH_ANY, product_id: HOTPLUG_MATCH_ANY, dev_class: HOTPLUG_MATCH_ANY) {|device, event| ... } ⇒ HotplugCallback

Register a hotplug event notification.

Register a callback with the LIBUSB::Context. The callback will fire when a matching event occurs on a matching device. The callback is armed until either it is deregistered with LIBUSB::Context::HotplugCallback#deregister or the supplied block returns :finish to indicate it is finished processing events.

If the flag HOTPLUG_ENUMERATE is passed the callback will be called with a :HOTPLUG_EVENT_DEVICE_ARRIVED for all devices already plugged into the machine. Note that libusb modifies its internal device list from a separate thread, while calling hotplug callbacks from #handle_events, so it is possible for a device to already be present on, or removed from, its internal device list, while the hotplug callbacks still need to be dispatched. This means that when using HOTPLUG_ENUMERATE, your callback may be called twice for the arrival of the same device, once from #on_hotplug_event and once from #handle_events; and/or your callback may be called for the removal of a device for which an arrived call was never made.

Since libusb version 1.0.16.

Parameters:

Yield Parameters:

Yield Returns:

  • (Symbol)

    :finish to deregister the callback, :repeat to receive additional events

Returns:

  • The handle to the registered callback.

Raises:

  • in case of failure



540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
# File 'lib/libusb/context.rb', line 540

def on_hotplug_event(events: HOTPLUG_EVENT_DEVICE_ARRIVED | HOTPLUG_EVENT_DEVICE_LEFT,
                     flags: 0,
                     vendor_id: HOTPLUG_MATCH_ANY,
                     product_id: HOTPLUG_MATCH_ANY,
                     dev_class: HOTPLUG_MATCH_ANY,
                     &block)

  handle = HotplugCallback.new self, @ctx, @hotplug_callbacks

  block2 = proc do |ctx, pDevice, event, _user_data|
    raise "internal error: unexpected context" unless @ctx==ctx
    dev = Device.new self, pDevice

    blres = block.call(dev, event)

    case blres
    when :finish
      1
    when :repeat
      0
    else
      raise ArgumentError, "hotplug event handler must return :finish or :repeat"
    end
  end

  res = Call.libusb_hotplug_register_callback(@ctx,
              events, flags,
              vendor_id, product_id, dev_class,
              block2, nil, handle)

  LIBUSB.raise_error res, "in libusb_hotplug_register_callback" if res<0

  # Avoid GC'ing of the block:
  @hotplug_callbacks[handle[:handle]] = block2

  return handle
end