PyUSB: reading from a USB device

pyusb read data
pyusb list all devices
pyusb documentation
pyusb windows
pyusb tutorial
pyusb macos
pyusb exceptions
pyusb dispose_resources

This is an updated and shortened question.

Communicating with a USB-device should be easy via PyUSB. So, I'm trying to read from a USB-device (oscilloscope) using PyUSB under Win10. Apparently, the USB-driver (libusb-win32 v1.2.6.0) is installed correctly since the device is found and I get some response from print(dev) (see below). From this I can see that the output endpoint address is 0x3 and the input endpoint address is 0x81

According to the Oscilloscope manual, I'm supposed to send :SDSLSCPI# to the device to set it into SCPI-mode and should get the reponse ':SCPION'. However, when sending :SDSLSCPI# the monitor of the oscilloscope reproduceably will freeze and it will restart.

If I send *IDN? I should get the response ,P1337,1842237,V2.4.0->. But only if the device is already in SCPI-mode. Apparently, it is not and I get a timeout error (see below).

So, what am I doing wrong here? What information am I missing in the PyUSB tutorial. Am I using the wrong PyUSB commands/parameters or is it about missing additional drivers or is it about the hardware, either Win10 or the device hardware? Thank you for hints on how to find out what's going wrong.

By the way, what is the second value in dev.read(0x81,7)? Number of bytes to read? Well, usually I don't know how many bytes the device will send. I was expecting a command to read until a linefeed or some other terminator character within the timeout time. Where can I find "fool-proof" documentation, tutorials and examples about PyUSB?

Code:

import usb.core
import usb.util

dev = usb.core.find(idVendor=0x5345, idProduct=0x1234)
if dev is None:
    raise ValueError('Device is not found')
# device is found :-)
print(dev)

dev.set_configuration()

msg = ':SDSLSCPI#'
print("Write:", msg, dev.write(3,msg))

print("Read:", dev.read(0x81,7))

Output from print(dev):

DEVICE ID 5345:1234 on Bus 000 Address 001 =================
 bLength                :   0x12 (18 bytes)
 bDescriptorType        :    0x1 Device
 bcdUSB                 :  0x200 USB 2.0
 bDeviceClass           :    0x0 Specified at interface
 bDeviceSubClass        :    0x0
 bDeviceProtocol        :    0x0
 bMaxPacketSize0        :   0x40 (64 bytes)
 idVendor               : 0x5345
 idProduct              : 0x1234
 bcdDevice              :  0x294 Device 2.94
 iManufacturer          :    0x1 System CPU
 iProduct               :    0x2 Oscilloscope
 iSerialNumber          :    0x3 SERIAL
 bNumConfigurations     :    0x1
  CONFIGURATION 1: 500 mA ==================================
   bLength              :    0x9 (9 bytes)
   bDescriptorType      :    0x2 Configuration
   wTotalLength         :   0x20 (32 bytes)
   bNumInterfaces       :    0x1
   bConfigurationValue  :    0x1
   iConfiguration       :    0x5 Bulk Data Configuration
   bmAttributes         :   0xc0 Self Powered
   bMaxPower            :   0xfa (500 mA)
    INTERFACE 0: Physical ==================================
     bLength            :    0x9 (9 bytes)
     bDescriptorType    :    0x4 Interface
     bInterfaceNumber   :    0x0
     bAlternateSetting  :    0x0
     bNumEndpoints      :    0x2
     bInterfaceClass    :    0x5 Physical
     bInterfaceSubClass :    0x6
     bInterfaceProtocol :   0x50
     iInterface         :    0x4 Bulk Data Interface
      ENDPOINT 0x81: Bulk IN ===============================
       bLength          :    0x7 (7 bytes)
       bDescriptorType  :    0x5 Endpoint
       bEndpointAddress :   0x81 IN
       bmAttributes     :    0x2 Bulk
       wMaxPacketSize   :  0x200 (512 bytes)
       bInterval        :    0x0
      ENDPOINT 0x3: Bulk OUT ===============================
       bLength          :    0x7 (7 bytes)
       bDescriptorType  :    0x5 Endpoint
       bEndpointAddress :    0x3 OUT
       bmAttributes     :    0x2 Bulk
       wMaxPacketSize   :  0x200 (512 bytes)
       bInterval        :    0x0

Error message:

Traceback (most recent call last):
  File "Osci.py", line 15, in <module>
    print("Read:", dev.read(0x81,7))
  File "C:\Users\Test\Programs\Python3.7.4\lib\site-packages\usb\core.py", line 988, in read
    self.__get_timeout(timeout))
  File "C:\Users\Test\Programs\Python3.7.4\lib\site-packages\usb\backend\libusb0.py", line 542, in bulk_read
    timeout)
  File "C:\Users\Test\Programs\Python3.7.4\lib\site-packages\usb\backend\libusb0.py", line 627, in __read
    timeout
  File "C:\Users\Test\Programs\Python3.7.4\lib\site-packages\usb\backend\libusb0.py", line 431, in _check
    raise USBError(errmsg, ret)
usb.core.USBError: [Errno None] b'libusb0-dll:err [_usb_reap_async] timeout error\n'

Update:

I got a reply from the vendor. And he confirms that the oscilloscope (or at least this specific series) crashes when sending the command :SDSLSCPI#. He will contact the developers which will back next week. OK, it seems so far no chance for me to get it to run with this specific device and the available documentation :-(.


msg = '*IDN?'

This is not a complete SCPI command: It is missing the newline \n character at the end.

That is also why the device was not able to send an answer via USB.

Read and Decode Data From Your Mouse Using This PyUSB Hack , How to read data from a mouse on Linux, or even Mac and Windows, using a claim the device usb.util.claim_interface(dev, interface) collected = 0 attempts� PyUSB aims to be an easy to use Python module to access USB devices. PyUSB relies on a native system library for USB access. Currently, it works out of the box with libusb 0.1, libusb 1.0, libusbx, libusb-win32 and OpenUSB, and works with any Python version starting at 2.4, including Python 3 releases. Documentation. The best way to start with PyUSB is through the PyUSB 1.0 tutorial, and API reference can be found in the doc strings. Support


SCPI is not enabled by default on OWON devices. According to the page#3 of the manual you need to send :SDSLSCPI# command to switch to the SCPI mode.

usb.read() always returns the same � Issue #239 � pyusb/pyusb , I looked into pylibftdi but with that library, I cannot even see this usb device. >>> import usb serial_number = '83836244' dev = None devices = list� On Wed, Oct 5, 2011 at 9:29 PM, Andhika Pratama wrote: > As you can see from my screen capture above that my device endpoint address > is 0x81, and I check couple of example also had the same address, that is > 0x81. and my device only have one endpoint. > Well, you are writing to endpoint 1, whereas the documentation you linked to says commands go to the control endpoint (=0).


Once you get the response from the device on *IDN? query you should be good to go. This is SCPI ;)

Try to send :CHAN1:SCAL 10v, and watch the display. It should change the vertical scale of channel 1 to 10V/div.

Watch this video, it will help you get a grip.

On your question about read() parameters. Quoting the PyUSB source:

def read(self, endpoint, size_or_buffer, timeout = None):
    r"""Read data from the endpoint.
    This method is used to receive data from the device. The endpoint
    parameter corresponds to the bEndpointAddress member whose endpoint
    you want to communicate with. The size_or_buffer parameter either
    tells how many bytes you want to read or supplies the buffer to
    receive the data (it *must* be an object of the type array).
    The timeout is specified in miliseconds.
    If the size_or_buffer parameter is the number of bytes to read, the
    method returns an array object with the data read. If the
    size_or_buffer parameter is an array object, it returns the number
    of bytes actually read.
    """

When the timeout is omitted, it is used the Device.default_timeout property as the operation timeout. Values are in milliseconds.

If you set the buffer size big enough, you will get only the bytes actually read. So your expectations are correct.

pyusb/pyusb: USB access for Python, Now PyUSB is an API rich, backend neutral Python USB module easy to use. As with most Python modules, PyUSB's documentation is based on Python doc� Re: [pyusb-users] Unable to read from an USB device Re: [pyusb-users] Unable to read from an USB device From: Wander Lairson Costa <wander.lairson@gm> - 2014-09-17 11:05:18


The Cisco PyUSB Developer Guide, USBIP, Cisco backend that connects PyUSB to USB devices connected over an IP For example, if your find returned the device object dev you can read the� [pyusb-users] Unable to read from an USB device [pyusb-users] Unable to read from an USB device. From: Gerry <gbrown@ge> - 2014-09-16 13:10:33


I guess there was no chance to answer this question unless somebody already went through the very same problems. I'm sorry for all of you (@Alex P., @Turbo J, @igrinis, @2xB) who took your time to make suggestions to help.

My findings: (I hope they will be useful to others):

  1. Everything seems to be OK with PyUSB.
  2. the vendor has provided outdated and wrong documentation. I hope very much that they will soon update the documentation on their homepage.
  3. Sending the command :SDSLSCPI# is not necessary to enter SCPI-mode (but actually leads to a crash/restart)
  4. For example: :CHAN1:SCAL 10v is wrong, it has to be :CH1:SCALe 10v (commands apparenty can't be abbreviated, although mentioned in the documentation that :CH1:SCAL 10v should also work.)
  5. the essential command to get data :DATA:WAVE:SCREen:CH1? was missing in the manual.

The way it is working for me (so far):

The following would have been the minimal code I expected from the vendor/manufacturer. But instead I wasted a lot of time debugging their documentation. However, still some strange things are going on, e.g. it seems you get data only if you ask for the header beforehand. But, well, this is not the topic of the original question.

Code:

### read data from a Peaktech 1337 Oscilloscope (OWON)
import usb.core
import usb.util

dev = usb.core.find(idVendor=0x5345, idProduct=0x1234)

if dev is None:
    raise ValueError('Device not found')
else:
    print(dev)
    dev.set_configuration()

def send(cmd):
    # address taken from results of print(dev):   ENDPOINT 0x3: Bulk OUT
    dev.write(3,cmd)
    # address taken from results of print(dev):   ENDPOINT 0x81: Bulk IN
    result = (dev.read(0x81,100000,1000))
    return result

def get_id():
    return send('*IDN?').tobytes().decode('utf-8')

def get_data(ch):
    # first 4 bytes indicate the number of data bytes following
    rawdata = send(':DATA:WAVE:SCREen:CH{}?'.format(ch))
    data = []
    for idx in range(4,len(rawdata),2):
        # take 2 bytes and convert them to signed integer using "little-endian"
        point = int().from_bytes([rawdata[idx], rawdata[idx+1]],'little',signed=True)
        data.append(point/4096)  # data as 12 bit
    return data

def get_header():
    # first 4 bytes indicate the number of data bytes following
    header = send(':DATA:WAVE:SCREen:HEAD?')
    header = header[4:].tobytes().decode('utf-8')
    return header

def save_data(ffname,data):
    f = open(ffname,'w')
    f.write('\n'.join(map(str, data)))
    f.close()

print(get_id())
header = get_header()
data = get_data(1)
save_data('Osci.dat',data)
### end of code

Result: (using gnuplot)

PyUSB / Re: [pyusb-users] [Help] Read and Write Data USB with , On Wed, Oct 5, 2011 at 9:29 PM, Andhika Pratama wrote: > As you can see from my screen capture above that my device endpoint address > is 0x81, and I� I have so far gotten to the stage of finding the device, now I am ready to talk to the USB using the devices protocol laid out in the specification on page 22. libusb is installed on my machine and so is PyUSB.


PyUSB read from devices : learnpython, I'm trying to listen for responses from a USB device using PyUSB and the USB has two endpoint addresses for input (0x81 and 0x82). I need to listen on 0x82� pyUSB sends and receives data in string format. The data which you are receiving is ASCII codes. You need to add the following line to read the data properly in the code. data = device.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize) RxData = ''.join([chr(x) for x in data]) print RxData


Reading USB in Python, Here's how you read from USB devices in Python. It's super useful if you want to make Duration: 8:12 Posted: Nov 9, 2019 [pyusb-users] pyusb dev.read() problem communicate with the device. Reverse Engineering by USB sniffing is the way to go if you do not have access to the device


USB Communication with Python and PyUSB, USB Communication with Python and PyUSB pip install --user pyusb The device is identified with a vendor:product pair included in lsusb output. this, but they say that if you need Isochronous Endpoints (read: audio or� to be honest i never in my life wrote a code that reads from serial, usb or parallel ports .. and i have no clue about how to do it.. i just need a headstart.. or a link to a useful tutorial.. notes.. * it has to be done by Python.. * the device is "GPS Receiver bu-353" * i have to read the "sentences" that the GPS receives from the satellite..