pyusbモジュールについて。

PythonによるUSBデバイスの使い方。

tags:python, module, hardware, tips
created:2007-02-05T20:24:24

PythonによるUSBデバイスの使い方 PythonからUSBを使うためのモジュールPyUSBの使い方。

インストーラ

Windows用インストーラが公開されていないので作ってみました。

pyusb 2.1(オリジナル): http://pyusb.berlios.de/

ソースパッケージ: ソースアーカイブ

セットアップ

あらかじめ必要なモジュール

フィルタドライバーインストーラのダウンロードとインストールを行っておいてください。

libusb-win32 : http://libusb-win32.sourceforge.net/

最新版はlibusb-win32-filter-bin-0.1.10.1.exeというファイルです。

付属のサンプル実行画面:

../../_images/testlibusb.png

このツールでコントロールしたいデバイスのidVender、idProductをあらかじめメモして置くと良いでしょう。

使い方

import usb
import exceptions

class UsbDevice:
  def __init__(self, vendor_id, product_id):
    busses = usb.busses()
    self.handle = None
    for bus in busses:
      devices = bus.devices
      for dev in devices:
        if dev.idVendor==vendor_id and dev.idProduct==product_id:
          self.dev = dev
          self.conf = self.dev.configurations[0]
          self.intf = self.conf.interfaces[0][0]
          self.endpoints = []
          for endpoint in self.intf.endpoints:
            self.endpoints.append(endpoint.address)
          return
    raise exceptions.IndentationError('Not found device!')

  def open(self):
    if self.handle:
      self.handle = None
    self.handle = self.dev.open()
    self.handle.setConfiguration(self.conf)
    self.handle.claimInterface(self.intf)
    self.handle.setAltInterface(self.intf)

dev=UsbDevice(0x05DB, 0x0009)
dev.open()
dev.handle.bulkRead(dev.endpoints[0].address,1)

endpointは入出力ポートであり、属性にaddressやdirection、typeなどがあります。

リードライトにはこのaddressが必要です。

dev.handleにはいくつかのコマンドがあります。

  • bulkRead
  • bulkWrite
  • claimInterface
  • clearHalt
  • controlMsg
  • interruptRead
  • interruptWrite
  • releaseInterface
  • reset
  • resetEndpoint
  • setAltInterface
  • setConfiguration

以下の5種類だけ使えば大抵の事はできるでしょう。

  • controlMsg
  • bulkRead
  • bulkWrite
  • interruptRead
  • interruptWrite