デバイスエニュメレーション

このセクションでは、デバイスの列挙、接続されているデバイス情報の取得、およびその接続トポロジについて説明します。

シンプルなデバイス列挙

利用可能なビデオキャプチャデバイスの情報を取得する最も簡単な方法は、DeviceEnum.devices() を呼び出すことです。このクラスメソッドは、DeviceInfo オブジェクトのフラットなリストを返します。

以下のコードスニペットは、デバイス一覧を取得し、デバイス情報をコンソールへ出力する方法を示しています。

def print_device_list():
    print("Enumerating all attached video capture devices...")

    device_list = ic4.DeviceEnum.devices()

    if len(device_list) == 0:
        print("No devices found")
        return

    print(f"Found {len(device_list)} devices:")

    for device_info in device_list:
        print(format_device_info(device_info))

デバイス情報は、シンプルなヘルパー関数を使用して出力されます。

def format_device_info(device_info: ic4.DeviceInfo) -> str:
    return f"Model: {device_info.model_name} Serial: {device_info.serial}"

インターフェース/デバイストポロジの取得

デバイスの列挙は、インターフェース単位でも実行できます。インターフェースとは、カメラが接続される物理的なハードウェア(例:USB コントローラ、ネットワークアダプタ)を指します。

システム内で利用可能なインターフェース一覧を取得するには、DeviceEnum.interfaces() を呼び出します。 各インターフェースに対しては、Interface.devices を使って、現在接続されているビデオキャプチャデバイスを取得できます。

以下のコードスニペットは、インターフェース一覧の取得方法を示し、その後、インターフェース情報とデバイス情報をコンソールへ出力します。

def print_interface_device_tree():
    print("Enumerating video capture devices by interface...")

    interface_list = ic4.DeviceEnum.interfaces()

    if len(interface_list) == 0:
        print("No interfaces found")
        return

    for itf in interface_list:
        print(f"Interface: {itf.display_name}")
        print(f"\tProvided by {itf.transport_layer_name} [TLType: {str(itf.transport_layer_type)}]")

        device_list = itf.devices

        if len(device_list) == 0:
            print("\tNo devices found")
            continue

        print(f"\tFound {len(device_list)} devices:")

        for device_info in device_list:
            print(f"\t\t{format_device_info(device_info)}")

デバイスの接続/切断通知を受け取る

DeviceEnum オブジェクトでは、利用可能なデバイス一覧に変化があった際にプログラムへ通知するイベントハンドラを登録できます。 接続デバイスの変更通知を受け取るには、DeviceEnum.event_add_device_list_changed() を使用してコールバック関数を登録します。

以下のコードスニペットは、デバイス一覧変更イベントハンドラの登録方法と、最後にハンドラを解除する方法を示しています。

def example_device_list_changed():
    enumerator = ic4.DeviceEnum()

    token = enumerator.event_add_device_list_changed(handle_device_list_changed)

    print("Waiting for DeviceListChanged event")
    print("Press Enter to exit")
    input()

    # Technically, this is not necessary, because the enumerator object is deleted when the function is exited
    # But for demonstration purposes, the event handler is removed:
    enumerator.event_remove_device_list_changed(token)

デバイスリスト変更ハンドラの例は以下のようになります。

def handle_device_list_changed(device_enum: ic4.DeviceEnum):
    print("Device list changed!")

    print(f"Found {len(ic4.DeviceEnum.devices())} devices")

    print(ic4.DeviceEnum.devices())