Coder Social home page Coder Social logo

python-usbtmc's Introduction

Python USBTMC Readme

For more information and updates: http://alexforencich.com/wiki/en/python-usbtmc/start

GitHub repository: https://github.com/python-ivi/python-usbtmc

Google group: https://groups.google.com/d/forum/python-ivi

Introduction

Python USBTMC provides a pure Python USBTMC driver for controlling instruments over USB.

Requirements

  • Python 2 or Python 3
  • PyUSB

Installation

Extract and run

# python setup.py install

Configuring udev

If you cannot access your device without running your script as root, then you may need to create a udev rule to properly set the permissions of the device. First, connect your device and run lsusb. Find the vendor and product IDs. Then, create a file /etc/udev/rules.d/usbtmc.rules with the following content:

# USBTMC instruments

# Agilent MSO7104
SUBSYSTEMS=="usb", ACTION=="add", ATTRS{idVendor}=="0957", ATTRS{idProduct}=="1755", GROUP="usbtmc", MODE="0660"

substituting the correct idVendor and idProduct from lsusb. You will also need to create the usbtmc group and add yourself to it or substitute another group of your choosing. It seems that udev does not allow 0666 rules, usually overriding the mode to 0664, so you will need to be a member of the associated group to use the device.

If you want to put the kernel usbtmc device in the same group, add the following content to the usbtmc.rules file as well. This is optional as Python USBTMC bypasses and disconnects the kernel usbtmc driver and the device will actually disappear from /dev when Python USBTMC connects.

# Devices
KERNEL=="usbtmc/*",       MODE="0660", GROUP="usbtmc"
KERNEL=="usbtmc[0-9]*",   MODE="0660", GROUP="usbtmc"

Windows setup

To use Python USBTMC in Windows, PyUSB and libusb are required. They can be downloaded from:

An INF file will also need to be created in order to use devices with libusb. Without a properly set up INF file, Python USBTMC will not be able to locate the device. There are instructions on the libusb page for how to generate the INF file.

Usage examples

Connecting to Agilent MSO7104A via USBTMC:

import usbtmc
instr =  usbtmc.Instrument(2391, 5973)
print(instr.ask("*IDN?"))
# returns 'AGILENT TECHNOLOGIES,MSO7104A,MY********,06.16.0001'

When multiple instruments are connected they can be identified by serial number:

import usbtmc
instr =  usbtmc.Instrument(2391, 5973, 'MY********')
print(instr.ask("*IDN?"))
# returns 'AGILENT TECHNOLOGIES,MSO7104A,MY********,06.16.0001'

It is also possible to connect with VISA resource strings like so:

import usbtmc
instr =  usbtmc.Instrument("USB::0x0957::0x1755::INSTR")
print(instr.ask("*IDN?"))
# returns 'AGILENT TECHNOLOGIES,MSO7104A,MY********,06.16.0001'

and:

import usbtmc
instr =  usbtmc.Instrument("USB::0x0957::0x1755::MY********::INSTR")
print(instr.ask("*IDN?"))
# returns 'AGILENT TECHNOLOGIES,MSO7104A,MY********,06.16.0001'

python-usbtmc's People

Contributors

alexforencich avatar jeremyherbert avatar karlp avatar philpem avatar wallacbe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-usbtmc's Issues

Agilent U2702A USB scope support

Dear developer,

I have an usb oscilloscope Agilent U2702A, which should be a USBTMC 488.2 Class device (and probably does not use the SCPI commands). The scope data-sheet says: "Compatible with Microsoft Windows operating systems only. Requires a direct USB connection to the PC so the appropriate driver can be installed in the USB modular instrument."
I followed the instructions of using the python-usbtmc package and I tried to operate the device. I was unsuccessful, the device even was not listed as usbtmc device (using the method "list_devices()").

I tried to enable the device in the code (analogously as U2722A/U2723A devices has been added recently). After that the device was detected, but the method "ask" crashed on acquiring the device serial number (the line with "serial = self.device.serial_number"), which ended with "usb.core.USBError: [Errno 32] Pipe error", similarly as in

http://www.eevblog.com/forum/testgear/python-based-instrument-control/50/

My question is: is there any chance that usb oscilloscope Agilent U2702A can work with python-usbtmc package? What should I do for it?

Thank you in advance for you time and an effort to answer!

Best regards, Susnicek

Fails with pyusb-1.0.0b2 on Windows

Just a warning about the current version of the pyusb dependency:
It crashes on script end without Exception message ("Python has stopped working") after the destructors are run

The good news: it works with pyusb-1.0.0b1

Rigol Connection Problem Linux

Hi,

I have a problem connecting to a Rigol Ds1054z the first time after the scope has been reset. Subsequent connects are fine.

E.g.

  • Turn on rigol, connect using USBTMC library FAIL
  • Turn on rigol, send some random command with OS driver (echo '*idn?' >> /dev/usbtmc0), connect to rigol using python-usbtmc (hangs), kill python, connect to rigol again using python-usbtmc, WORKS
  • Unplug and replug usb cable and connect again using just python usbtmc WORKS

Turn scope off and on, I have to repeat the weird combination of sending command through kernel driver, running usbtmc python connection script twice.

Also, if I turn scope on and off, and run python usbtmc connection, it just hangs indefinitely and detaches the scope from the kernel, so then I have to go replug it.

Once I do this weird random fix of sending command through kernel driver, I can use the scope for weeks if I don't turn it off. Also, the scope takes a while to read data, 24million points takes 5min.

Any ideas why this could be happening?

It's happened on two computers, an Ubuntu and Arch Linux machine.

How can I destroy the connection?

There's a way to destroy the object and close the communication ? I need to communicate with others devices that use another protocol with serial/usb and this protocol is in conflict with another.

ask for raw data causes utf8 codec error

When doing this:

rawdata = instr.ask(“:WAV:DATA? CHAN1″)[10:]

an exception is raised which ends in:

File “/usr/lib/python2.7/encodings/utf_8.py”, line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: ‘utf8′ codec can’t decode byte 0×99 in position 10: invalid start byte

Both on Raspbian and Ubuntu x86_64, latest everything.

Stopped working overnight? Appears rules aren't being applied.

Hello,

I got python-usbtmc working yesterday, and was having a good time connecting to my Keysight Ocilloscope, running IDN queries, etc. All from my Raspberry Pi 3B+. I followed everything in the readme file, except the optional Kernel bit. But this morning, it's not working!

The output from lsusb:

pi@raspberrypi:~ $ lsusb
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 005: ID 04d9:0007 Holtek Semiconductor, Inc. 
Bus 001 Device 004: ID 093a:2510 Pixart Imaging, Inc. Optical Mouse
Bus 001 Device 023: ID 0957:0588 Agilent Technologies, Inc. 
Bus 001 Device 002: ID 2109:3431 VIA Labs, Inc. Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

My usbtmc.rules file:

# USBTMC instruments

# Agilent DSO1052B
SUBSYSTEM=="usb", ACTION=="add", ATTRS{idVendor}=="0x0957", ATTRS{idProduct}=="0x0588", GROUP="usbtmc", MODE="0660"

My Python3 code:

>>> import usbtmc
>>> inst = usbtmc.Instrument(0x0957, 0x0588)
>>> print(inst.ask("*IDN") 

However, this morning the exact same code is returning:

usb.core.USBError: [Errno 13] Access denied (insufficient permissions)

The Pi was left on overnight, too - so nothing should have restarted, etc. The USB device was disconnected and reconnected in the morning. I didn't change anything, other than I probably re-started Python.

I've gone back through the readme (again, not the optional part) and I'm just not getting anywhere. When plugged in, the device is added to /dev/usbtmc0. Using ls -all, I get:

pi@raspberrypi:/dev $ ls -all | grep usbtmc*
crw-------   1 root root    180, 176 Jun 11 14:13 usbtmc0

Which doesn't look right to me. I've done some udevadm debugging to try and highlight an issue, and I'm seeing this line, which looks wrong, as I'd expect the mode to be picked up from my usbtmc.rules file:

usbtmc0: Handling device node '/dev/usbtmc0', devnum=c180:176, mode=0600, uid=0, gid=0

Does anyone have any thoughts?

usbtmc Error -410: "Query Interrupted"

I am trying to communicate with a Keysight network analyzer and a Raspberry Pi 3 (through Python 3 and usbtmc). My current code looks like this:

import usbtmc
import time

instr = usbtmc.Instrument(0x2a8d, 0x5c18)
print(instr.ask("*IDN?"))

instr.timeout = 2000
instr.write("CALC:PAR2:DEF S21")
instr.write("CALC:PAR1:SEL")
instr.write("CALC:FORM MLOGarithmic")
instr.write("FREQ:STAR MIN")
instr.write("FREQ:STOP 21E9")
instr.write("AVER:COUN 500")
#instr.ask("CALC:DATA:FDATa?") #this line does not work

#reset device after each run to avoid having the 'operation timed out' error
instr.clear(25)

These commands are just setting up a lot of formatting on the device. Unfortunately I keep getting an error on my device itself that says "Error -410: Query INTERRUPTED", which I take to mean that something else started before the previous command finished. I think this may be solved with the timeout but am not sure. Any ideas?

usb timeouts on OS X 10.11.6

hello,

i'm getting the following traceback from python when trying to send data to a Rigol mso1104z:

>>> import usbtmc
>>> usbtmc.list_devices()
[<DEVICE ID 1ab1:04ce on Bus 020 Address 013>]
>>> ins = usbtmc.Instrument(0x1ab1, 0x04ce)
>>> print(ins.ask("*IDN?"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "usbtmc/usbtmc.py", line 608, in ask
    return self.read(num, encoding)
  File "usbtmc/usbtmc.py", line 591, in read
    return self.read_raw(num).decode(encoding).rstrip('\r\n')
  File "usbtmc/usbtmc.py", line 514, in read_raw
    self.bulk_out_ep.write(req)
  File "build/bdist.macosx-10.11-x86_64/egg/usb/core.py", line 387, in write
  File "build/bdist.macosx-10.11-x86_64/egg/usb/core.py", line 948, in write
  File "build/bdist.macosx-10.11-x86_64/egg/usb/backend/libusb1.py", line 824, in bulk_write
  File "build/bdist.macosx-10.11-x86_64/egg/usb/backend/libusb1.py", line 920, in __write
  File "build/bdist.macosx-10.11-x86_64/egg/usb/backend/libusb1.py", line 595, in _check
usb.core.USBError: [Errno 60] Operation timed out

happy to collect more data if it will help.

Can you update PyPI repository?

Nice work!
Saved me from manually performing 1000+ measurements for my Electronics classes.

Can you please make a new release and update package on PyPI? I had to build this from sources for list_resources() to be implemented. Current code is good enough to make a release and upload it.

Cheers!

usbtmc.py resp.tobytes version check python < 3.2

In read_raw the python version is checked for tobytes or tostring.
This checkes for pythen 3.0, but tobytes was introduced in 3.2.
`

        if sys.version_info >= (3, 2):
            resp = resp.tobytes()
        else:
            resp = resp.tostring()

`

Agilent U2701A remains in DFU mode (PID=2818)

I am trying to get an Agilent U2701A to run under
-Ubuntu 16.04,
-python 2.7.12,
-pyusb V1.0.2.
-python-usbtmc V0.8

Executing the commands below, I get:

import usbtmc
instr=usbtmc.Instrument(0x0957,0x2818)
print(instr.ask("*IDN?"))
#Traceback (most recent call last):

File "", line 1, in

File "usbtmc/usbtmc.py", line 770, in ask
self.write(message, encoding)
File "usbtmc/usbtmc.py", line 750, in write
self.write_raw(str(message).encode(encoding))
File "usbtmc/usbtmc.py", line 616, in write_raw
self.open()
File "usbtmc/usbtmc.py", line 369, in open
serial = self.device.serial_number
File "/usr/local/lib/python2.7/dist-packages/usb/core.py", line 830, in serial_number
self._serial_number = util.get_string(self, self.iSerialNumber)
File "/usr/local/lib/python2.7/dist-packages/usb/util.py", line 314, in get_string
raise ValueError("The device has no langid")
ValueError: The device has no langid

This initializer does not seem to take the device out of DFU mode, as the PID of the device remains at 2818, and does not change to 2918, shown by lsusb after the above.

However, I can get as far as:

print(usbtmc.list_devices())
[<DEVICE ID 0957:2818 on Bus 001 Address 009>]

I have read and followed the issue: "Agilent U2702A USB scope support"
But that seems to relate to U2702A, and not U2701A. Could it be that:

  1. U2702A has a different command sequence to take it out of DFU mode than U2701A?
  2. Older firmware version on my scope ignores the code to take it out of DFU mode? (it has sat idle for about 10 years)

It is difficult for me to access a Windows computer, but will do if necessary to get Wireshark report.
Thanks for the answers.

Thanks for any answers.

Why you can use vendor ID 0x1334 to find instruments?

According to the specification vender id is chosen by manufacturer, however you use 0x1334 as select condition in function list_devices.
I have checked the company list provided by usb-if, where no one is assigned to 0x1334.

Sound weird.

read_stb() btag mismatch

If you call read_stb() more than ~128 times, there's a btag mismatch.

I was able to fix the problem by changing this line:
rstb_btag = (self.last_rstb_btag % 128) + 1
to
rstb_btag = (self.last_rstb_btag + 1) % 128

Uploading patched v0.8 on pypi

Hi,
Thanks for the great support on USBTMC instrument. Is there any chance that you upload your latest (patched for some quirky instruments like the Keysight U2722A) version of this repo to PyPI?
It would streamline the installlation procedure because now it has to be done from github. To make it worse, it's not directly apparent that v0.8 on PyPI is not the 0.8 on the repo :)

Keysight USB PWMs Random timeouts and then total failure

I have multiple systems each with 2 Keysight USB 2021 power meters. They run fine for days, and then suddenly they will get a timeout and then the only way to get the system back is to power cycle everything. I've made sure we have the latest libusb, and also the latest usbtmc.07, it got better when we updated to the usb core that had multi-processing support, now it fails about every 7 days, previous was every 3.

We are not sure if the Keysight is failing or there is another issue. Any advice is appreciated.

Traceback (most recent call last):
  File "/home/dab2admin/GMV_USBTMC/proxy_USB_TCP_smart.py", line 100, in handle
    instrument = openDevice(dictionary, configuration)
  File "/home/dab2admin/GMV_USBTMC/proxy_USB_TCP_smart.py", line 163, in openDevice
    deviceSerial = configuration.getSerial(instr)
  File "/home/dab2admin/GMV_USBTMC/proxy_USB_TCP_smart.py", line 84, in getSerial
    IDNresponse = instrument.ask("*IDN?").split(",")
  File "/usr/local/lib/python2.7/dist-packages/usbtmc/usbtmc.py", line 584, in ask
    return self.read(num, encoding)
  File "/usr/local/lib/python2.7/dist-packages/usbtmc/usbtmc.py", line 567, in read
    return self.read_raw(num).decode(encoding).rstrip('\r\n')
  File "/usr/local/lib/python2.7/dist-packages/usbtmc/usbtmc.py", line 516, in read_raw
    resp = self.bulk_in_ep.read(read_len+USBTMC_HEADER_SIZE+3, timeout = self.timeout)
  File "/usr/local/lib/python2.7/dist-packages/usb/core.py", line 402, in read
    return self.device.read(self, size_or_buffer, timeout)
  File "/usr/local/lib/python2.7/dist-packages/usb/core.py", line 988, in read
    self.__get_timeout(timeout))
  File "/usr/local/lib/python2.7/dist-packages/usb/backend/libusb1.py", line 833, in bulk_read
    timeout)
  File "/usr/local/lib/python2.7/dist-packages/usb/backend/libusb1.py", line 936, in __read
    _check(retval)
  File "/usr/local/lib/python2.7/dist-packages/usb/backend/libusb1.py", line 595, in _check
    raise USBError(_strerror(ret), ret, _libusb_errno[ret])
USBError: [Errno 110] Operation timed out
2016-11-29 16:27:52,556 - DEBUG - Closing socket
^C

usbtmc Access Denied

Hi,
sudo usbtmc-shell --backend python_usbtmc USB::0x1ab1::0x0588::INSTR
Runs fine, without sudo I get access denied.
I added the udev rule, added group usbtmc, added usbtmc group to user.
Running Ubuntu 16.04.
I'm assuming I did something wrong... :(

usb.core.USBError: (ERRno 32) Pipe error

Hello everybody
I‘ve installed in my Raspberry pi 3 the usbtmc driver and all what it needs to communicate with a Siglent 1102CML+ oscilloscope. Everything seemed to be alright (it’s already connected i can use the basic commands like :RUN :STOP *IDN? ..) until i try to acquire data from it, or when i write another command even if it’s wrong written, i always receive this kind of error : usb.core.USBError: (ERRno 32) Pipe error . Is there any solution to fix it ?

unpack_from requires a buffer of at least 4 bytes

Hello,

On a fresh install and with running ipython in Arch Linux with sudo, I get the following output with a DS1104Z scope:

Python 3.6.2 (default, Jul 20 2017, 03:52:27)
Type "copyright", "credits" or "license" for more information.

IPython 5.3.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import usbtmc

In [2]: instr = usbtmc.Instrument("USB::6833::1230::DS1ZA153401099::INSTR")

In [3]: print(instr.ask(b"*IDN?"))
---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
<ipython-input-3-9a8437ac9ff7> in <module>()
----> 1 print(instr.ask(b"*IDN?"))

/usr/lib/python3.6/site-packages/python_usbtmc-0.8-py3.6.egg/usbtmc/usbtmc.py in ask(self, message, num, encoding)
    752                 self.lock()
    753             self.write(message, encoding)
--> 754             return self.read(num, encoding)
    755         finally:
    756             if self.advantest_quirk and not was_locked:

/usr/lib/python3.6/site-packages/python_usbtmc-0.8-py3.6.egg/usbtmc/usbtmc.py in read(self, num, encoding)
    735     def read(self, num=-1, encoding='utf-8'):
    736         "Read string from instrument"
--> 737         return self.read_raw(num).decode(encoding).rstrip('\r\n')
    738 
    739     def ask(self, message, num=-1, encoding='utf-8'):

/usr/lib/python3.6/site-packages/python_usbtmc-0.8-py3.6.egg/usbtmc/usbtmc.py in read_raw(self, num)
    664                     pass # do nothing, the packet has no header if it isn't the first
    665                 else:
--> 666                     msgid, btag, btaginverse, transfer_size, transfer_attributes, data = self.unpack_dev_dep_resp_header(resp)
    667 
    668 

/usr/lib/python3.6/site-packages/python_usbtmc-0.8-py3.6.egg/usbtmc/usbtmc.py in unpack_dev_dep_resp_header(self, data)
    588 
    589     def unpack_dev_dep_resp_header(self, data):
--> 590         msgid, btag, btaginverse = self.unpack_bulk_in_header(data)
    591         transfer_size, transfer_attributes = struct.unpack_from('<LBxxx', data, 4)
    592         data = data[USBTMC_HEADER_SIZE:transfer_size+USBTMC_HEADER_SIZE]

/usr/lib/python3.6/site-packages/python_usbtmc-0.8-py3.6.egg/usbtmc/usbtmc.py in unpack_bulk_in_header(self, data)
    584 
    585     def unpack_bulk_in_header(self, data):
--> 586         msgid, btag, btaginverse = struct.unpack_from('BBBx', data)
    587         return (msgid, btag, btaginverse)
    588 

error: unpack_from requires a buffer of at least 4 bytes

In [4]: 

I've tried adding a b to the argument to pass it in as a byte data, but this is of no help.
Have you seen this issue before? Any help would be greatly appreciated.

Thanks!

FreeBSD problem with reset

Hi,

On FreeBSD the reset issued during connect is no good - and prevents usctmc from working (throws exception). If I remove/disable the exception is works fine.

I suspect that you've has/seen the same problem with eg Windows ?
At lease I can see that usbtmc.py line 255 has the following construction:

if os.name == 'posix':
self.device.reset()

That needs to be extended to specificly check for FreeBSD (using os.platform or os.uname ???)

Please let me know if you need more info
/Uffe

Problems getting a Rigol DSA1020 to respond properly

I've got a small program that I'm using to try and connect up to a Rigol Spectrum Analyzer.

import usbtmc
listOfDevices = usbtmc.list_devices()
for device in listOfDevices:
print hex(device.idVendor), hex(device.idProduct)

instrument = usbtmc.Instrument(0x0400,0x09c4)
print instrument
print instrument.ask("*IDN?")

When running it I get this output. Even after chmodding 777 /dev/usbtmc2 I still need to sudo which is interesting.

sandford@MikeLinux ~/projects $ sudo python usbtmc_test.py
0x400 0x9c4
<usbtmc.usbtmc.Instrument object at 0x7f3a78e1d750>
Traceback (most recent call last):
File "usbtmc_test.py", line 11, in
print instrument.ask("*IDN?")
File "/usr/local/lib/python2.7/dist-packages/python_usbtmc-0.1-py2.7.egg/usbtmc/usbtmc.py", line 346, in ask
return self.read(num, encoding)
File "/usr/local/lib/python2.7/dist-packages/python_usbtmc-0.1-py2.7.egg/usbtmc/usbtmc.py", line 341, in read
return self.read_raw(num).decode(encoding).rstrip('\r\n')
File "/usr/local/lib/python2.7/dist-packages/python_usbtmc-0.1-py2.7.egg/usbtmc/usbtmc.py", line 309, in read_raw
msgid, btag, btaginverse, transfer_size, transfer_attributes, data = self.unpack_dev_dep_resp_header(bytearray(resp))
File "/usr/local/lib/python2.7/dist-packages/python_usbtmc-0.1-py2.7.egg/usbtmc/usbtmc.py", line 259, in unpack_dev_dep_resp_header
msgid, btag, btaginverse = self.unpack_bulk_in_header(data[0:4])
File "/usr/local/lib/python2.7/dist-packages/python_usbtmc-0.1-py2.7.egg/usbtmc/usbtmc.py", line 255, in unpack_bulk_in_header
msgid, btag, btaginverse = struct.unpack('BBBx', data[0:4])
struct.error: unpack requires a string argument of length 4
sandford@MikeLinux ~/projects $

So then I modified the source to print out the data going in to unpack_bulk_in_header, did "sudo python setup.py install" and re-ran and saw this:

sandford@MikeLinux ~/projects $ sudo python usbtmc_test.py
0x400 0x9c4
<usbtmc.usbtmc.Instrument object at 0x7fd0cc66c750>
[bytearray(b'\x02\x02\xfd\x00')]
Traceback (most recent call last):
File "usbtmc_test.py", line 11, in
print instrument.ask("*IDN?")
File "/usr/local/lib/python2.7/dist-packages/python_usbtmc-0.1-py2.7.egg/usbtmc/usbtmc.py", line 347, in ask
return self.read(num, encoding)
File "/usr/local/lib/python2.7/dist-packages/python_usbtmc-0.1-py2.7.egg/usbtmc/usbtmc.py", line 342, in read
return self.read_raw(num).decode(encoding).rstrip('\r\n')
File "/usr/local/lib/python2.7/dist-packages/python_usbtmc-0.1-py2.7.egg/usbtmc/usbtmc.py", line 310, in read_raw
msgid, btag, btaginverse, transfer_size, transfer_attributes, data = self.unpack_dev_dep_resp_header(bytearray(resp))
File "/usr/local/lib/python2.7/dist-packages/python_usbtmc-0.1-py2.7.egg/usbtmc/usbtmc.py", line 260, in unpack_dev_dep_resp_header
msgid, btag, btaginverse = self.unpack_bulk_in_header(data[0:4])
File "/usr/local/lib/python2.7/dist-packages/python_usbtmc-0.1-py2.7.egg/usbtmc/usbtmc.py", line 256, in unpack_bulk_in_header
msgid, btag, btaginverse = struct.unpack('BBBx', data[0:4])
struct.error: unpack requires a string argument of length 4
sandford@MikeLinux ~/projects $

There are four bytes in that array but the last one is a null. I'm not terribly familiar with the code or usbtmc as a standard so I'm afraid I don't really know what to do here. Any help is greatly appreciated.

Should Instrument.__del__() and close() not exist?

I have been getting somewhat random python errors due to dereferencing deleted objects. The answer seems to be not to have either __del__() or close() functions in the Instrument class (and thus not call usb.util.dispose_resources()) because Python deletes things in unpredictable orders. Just calling close() causes the same problems even with __del__() removed.

See: https://stackoverflow.com/questions/50574201/memory-corruption-on-exit-or-stupid-user-error

read_raw not working with DS1000Z firmware 00.04.03.02.03

Hi Alex

My Rigol DS1000Z scope was working fine with usbtmc, but read_raw is now broken with the latest commit (bfc3c4c). The computer is a Mac Mini running Ubuntu 15.10 (not OS X).

Tracing back, the problem was introduced by the changes between commits a4c8970 and b19ef5d. These were actually to fix a quirk with read_raw with the Rigol DS1000Z and DS1052E. I suspect the problem is that this fix is not needed for the DS1000Z with the latest Rigol firmware (00.04.03.02.03) and in fact doesn't work with it. Unfortunately, the scope doesn't allow me to roll back to the previous firmware to confirm this.

The following test program retrieves one million samples and works fine with firmware 00.04.03.02.03 and commit a4c8970:

from usbtmc import Instrument
instr = Instrument(0x1ab1, 0x04ce) # Rigol DS1000Z
instr.write(":RUN")
instr.write(":ACQ:MDEP 1200000")
instr.write("TIM:SCAL 0.00001")
instr.write(":STOP")
instr.write(":WAV:SOUR CHAN1")
instr.write(":WAV:MODE RAW")
instr.write(":WAV:FORM BYTE")    
instr.write(":WAV:STOP 1000000")
instr.write(":WAV:STAR 1")         
instr.write(":WAV:DATA?")
data = instr.read_raw()
print data
print len(data)

I am avoiding the problem with the latest commit by disabling the Rigol quirk:

73c73
< RIGOL_QUIRK_PIDS = [0x04ce, 0x0588]

---
> RIGOL_QUIRK_PIDS = [0x0588]

Cheers
Jon

Update VID/PID for U2722A

"Firmware" Mode:
0957:4218 Agilent Technologies, Inc.

"USBTMC" Mode:
0957:4118 Agilent Technologies, Inc.

TypeError because list_devices() / usb.core.find() returns generator instead of sequence

Using PyUSB 1.0.0-beta-2 from http://sourceforge.net/projects/pyusb/files/latest/download with libusb-win32-bin-1.2.6.0 in Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:15:05) [MSC v.1600 32 bit (Intel)] on Windows 7 (32 bit) the following error occurs when creating an usbtmc.Instrument():

  File "I:\Python34\lib\site-packages\usbtmc\usbtmc.py", line 182, in __init__
    self.device = find_device(self.idVendor, self.idProduct, self.iSerial)
  File "I:\Python34\lib\site-packages\usbtmc\usbtmc.py", line 88, in find_device
    if len(devs) == 0:
TypeError: object of type 'generator' has no len()

This refers to https://github.com/python-ivi/python-usbtmc/blob/master/usbtmc/usbtmc.py#L132

Generating a list may be a temporary workaround:
devs = list(list_devices())

Instrument does not recover after timeout; all subsequent commands also time out

When a read from my instrument hits the timeout, my session with that instrument does not recover.
All subsequent commands and reads also result in timeout.

For example:

>>> import usbtmc
>>> instr = usbtmc.Instrument(0x0699, 0x3000)
>>> instr.ask('*IDN?')
'TEKTRONIX, FCA3000, 379751, V1.28 25 Aug 2010 11:52'
>>> instr.ask('MEAS:FREQ?')  # instrument responds too slow
...
usb.core.USBError: [Errno 110] Operation timed out
>>> instr.ask('*IDN?')  # insrument should reply quickly
...
usb.core.USBError: [Errno 110] Operation timed out

I have seen this behaviour with a Tektronix FCA3000 and Thorlabs PM100D.
I'm using the latest version of python-usbtmc from Github.
Debian 9.6 - Python 3.5.3 - PyUSB 1.0.0 - libusb 1.0.21 - Linux 4.9.110

Looking at USB traces with Wireshark, I notice that after a timeout, python-usbtmc automatically sends an ABORT_BULK_IN sequence to the device. However the USBTMC specification requires that the host reads from the Bulk-IN endpoint as part of this sequence but python-usbtmc seems to skip that step.

I modified python-usbtmc to read the Bulk-IN endpoint during the ABORT_BULK_IN sequence. With this change, my instrument recovers from timeout and answers quickly to subsequent commands.
I will submit a pull request ...

Document how to use on OS X

The following works for me on OS X 10.9:

# Install prerequisites

$ sudo easy_install pyusb
(...) Installed /Library/Python/2.7/site-packages/pyusb-1.0.0b2-py2.7.egg

$ sudo easy_install libusb1
(...) Installed /Library/Python/2.7/site-packages/libusb1-1.3.0-py2.7.egg

$ brew install libusb

# Install python-usbtmc

$ git clone https://github.com/python-ivi/python-usbtmc.git
$ cd python-usbtmc
$ sudo python ./setup.py install
(...) Installed /Library/Python/2.7/site-packages/python_usbtmc-0.6-py2.7.egg

# Use python-usbtmc

$ python
(...)
>>> import usbtmc
>>> usbtmc.list_devices()
[<DEVICE ID 1ab1:04ce on Bus 253 Address 005>]

Note that I am using https://github.com/Homebrew/homebrew to install libusb.

error: package directory 'usbtmc' does not exist

I'm attempting to install usbtmc on my Raspberry Pi, but I get this error during the installation: error: package directory 'usbtmc' does not exist.

sudo python /home/pi/Documents/python-usbtmc-master/setup.py install

running install
running bdist_egg
running egg_info
writing python_usbtmc.egg-info/PKG-INFO
writing top-level names to python_usbtmc.egg-info/top_level.txt
writing dependency_links to python_usbtmc.egg-info/dependency_links.txt
error: package directory 'usbtmc' does not exist

I'm not experienced with Python, so I am not sure why this isn't working for me.

usbtmc error on Raspberry Pi 3

I am trying to install the usbtmc package on a Raspberry Pi 3. I extracted the package and used sudo python3 setup.py install in the terminal window to install, and it was successful. Now I am trying to run this bit of code:

import usbtmc
instr = usbtmc.Instrument(0x2a8d, 0x5c18)
print(instr.ask("*IDN?"))

I am receiving the error:

AttributeError: 'Endpoint' object has no attribute 'clear_halt'

So I think something might be wrong in the way I installed it? Any help is appreciated.

Overflow during instrument initialization Chroma Power supply

Hi,

I am trying to run a simple example, but even if the device is enumerated properly with:

>>> usbtmc.list_devices()
[<DEVICE ID 1698:0837 on Bus 003 Address 005>]

The initialization code fails with an overflow.

  File "./chroma.py", line 7, in <module>
    supply = ivi.chroma.chroma62012p8060('USB::5784::2103::009000000571::INSTR')
  File "/usr/local/lib/python3.5/dist-packages/ivi/chroma/chroma62012p8060.py", line 35, in __init__
    super(chroma62012p8060, self).__init__(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/ivi/chroma/chroma62000p.py", line 37, in __init__
    super(chroma62000p, self).__init__(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/ivi/chroma/chromaBaseDCPwr.py", line 43, in __init__
    super(chromaBaseDCPwr, self).__init__(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/ivi/scpi/dcpwr.py", line 48, in __init__
    super(Base, self).__init__(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/ivi/extra/common.py", line 33, in __init__
    super(SerialNumber, self).__init__(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/ivi/scpi/common.py", line 104, in __init__
    super(SelfTest, self).__init__(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/ivi/dcpwr.py", line 56, in __init__
    super(Base, self).__init__(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/ivi/ivi.py", line 1691, in __init__
    self.initialize(resource, id_query, reset, **kw)
  File "/usr/local/lib/python3.5/dist-packages/ivi/scpi/dcpwr.py", line 89, in _initialize
    self._clear()
  File "/usr/local/lib/python3.5/dist-packages/ivi/ivi.py", line 2000, in _clear
    return self._interface.clear()
  File "/usr/local/lib/python3.5/dist-packages/python_usbtmc-0.8-py3.5.egg/usbtmc/usbtmc.py", line 690, in clear
  File "/usr/local/lib/python3.5/dist-packages/python_usbtmc-0.8-py3.5.egg/usbtmc/usbtmc.py", line 349, in open
  File "/usr/local/lib/python3.5/dist-packages/python_usbtmc-0.8-py3.5.egg/usbtmc/usbtmc.py", line 699, in clear
  File "/usr/local/lib/python3.5/dist-packages/usb/core.py", line 1043, in ctrl_transfer
    self.__get_timeout(timeout))
  File "/usr/local/lib/python3.5/dist-packages/usb/backend/libusb1.py", line 883, in ctrl_transfer
    timeout))
  File "/usr/local/lib/python3.5/dist-packages/usb/backend/libusb1.py", line 595, in _check
    raise USBError(_strerror(ret), ret, _libusb_errno[ret])
usb.core.USBError: [Errno 75] Overflow

I Added some printout of the ctrl_transfers as they go, it is the last one that produces the overflow:

 PatchFile "/usr/local/lib/python3.5/dist-packages/usb/backend/libusb1.py", line 883, in ctrl_transfer
 
   print ("SPS",                        dev_handle.handle,
                                        bmRequestType,
                                        bRequest,
                                        wValue,
                                        wIndex,
                                        cast(addr, POINTER(c_ubyte)),
                                        length,
                                        timeout)

SPS c_void_p(49390048) 128 6 768 0 <pyvisa.ctwrapper.types.LP_c_ubyte object at 0x7fd9effa0f28> 254 1000
4
SPS c_void_p(49390048) 128 6 771 1033 <pyvisa.ctwrapper.types.LP_c_ubyte object at 0x7fd9effa0f28> 255 1000
26
**SPS c_void_p(49390048) 161 5 0 0 <pyvisa.ctwrapper.types.LP_c_ubyte object at 0x7fd9effa0f28> 1 5000
-8**

Thanks in advance

module can't find Oscilloscope

Hey there and thank you so much for that splendid module you've set up!

I used python-usbtmc earlier in the year to set up a piece of code to read out my oscilloscope (Tektronix TDS2000b) and it wokred just fine.
Recently I've gotten a new pair of Oscis (GW Instek GDS-1104B) and tried to get my code working with them aswell but unfortunately the usbtmc won't find my device, stating an Error like this:
" raise UsbtmcException("Device not found", 'init')"
This Error occurs no matter if hex or dec VID/PID input and no matter if python's been running with sudo or without
I've followed the instructions in the manual (groupadd and usbtmc.rules) and am running python 2.7.9/3.4.2 (either version doesn't work) on a Raspbian 4.4.34-v7 raspi.

The list when using usbtmc.list_devices() is completely empty, is that supposed to be like this?
This leads me to the feeling that the module isn't loading the .rules file correctly, is that right?

Do you have any other idea what to try/do/fix?

binary encoding

Is there a way to send 16-bit binary data to the device using usbtmc? I get this error:

I am doing the following with a Keysight 33600:

import usbtmc
instr =  usbtmc.Instrument(2391, ...)
instr.write('DATA:ARB:DAC myArb, #2640123456789012345678901234567890123456789012345678901234567890123\n')
instr.write('DATA:ARB:DAC myArb2, #264012345678901234567890123456789012345678901234567890123456789012\x80\n')

The first one works well, but for the second I get the following error:
'-101,"Invalid character"'

From C++ using pybind11, I get also this error:

Error writing command DATA:ARB:DAC myArb2,#264012345678901234567890123456789012345678901234567890123456789123�
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 87: invalid start byte

If use write_raw instead, I get this: TypeError: can't concat str to bytes

Connection via python-usbtmc to Yokogawa osciloscope DL9040

Hi, I am trying to connect a Yokogawa model DL9040 osciloscope to a Windows 10 Laptop to control it and be able to send commands and retrieve data from the instrument via Python 2.7. I have checked numerous posts but haven´t been able to connect via python. I use spyder 3.23 and anaconda prompt. I have installed python_usbtmc-0.8-py2.7.egg . I have also installed setup.py and libusb. The problem is that I cannot get the instrument ID for communicating with it in python. The instrument has a driver and I have installed it. So I can establish a connection via Yokogawa software and access some functions there with their user interface. The connection in the Yokogawa software states it is a usbtmc and gives the serial 91F836795. However I cannot manage to establish communication using python usbtmc.

I use this code to get the list of usb connected but do not get the name of the Yokogawa USB which I believe should look like: USB::0x0957::0x1755::INSTR"
import usbtmc
import visa
rm= visa.ResourceManager()
rm.list_resources()

Any suggestion or any link that explains how to connect using python-usbtmc with troubleshooting?

How is it possible to connect to a device via a generic FTDI USB to serial converter?

usb 1-3: new full-speed USB device number 5 using xhci_hcd
usb 1-3: New USB device found, idVendor=0403, idProduct=6001, bcdDevice= 6.00
usb 1-3: New USB device strings: Mfr=1, Product=2, SerialNumber=3
usb 1-3: Product: FT232R USB UART
usb 1-3: Manufacturer: FTDI
usb 1-3: SerialNumber: A107PG6S
ftdi_sio 1-3:1.0: FTDI USB Serial Device converter detected
usb 1-3: Detected FT232RL
usb 1-3: FTDI USB Serial Device converter now attached to ttyUSB0

The device behind this converter is an Itech 8800 series electronic load. It is set to RS-232: 38400 8N1.

Currently a list command returns no devices.

(How) can one use such a USB-to-serial device with python-usbtmc?

Agilent / Keysight U2355A power-up init support ?

Dear Developer (Alex ?)

I have followed the thread for the U2702A and we have a similar issue with a U2355A -
after power-up it requires a 'jump-start' from Windows with Agilent-Measurements-Manager
before it is recognized as usbtmc device under Linux.

I checked USB traffic with wireshark and the situation is different wrt. U2702A.

Would you be willing to have a look ?

We would really like to avoid the windows detour in our Linux based lab setup.

With thanks for python-usbtmc as it already is
and best regards

Thorsten Siedenburg, RWTH Aachen, Physics Ib

pyusb doesnt have enough permissionsto detach kernel driver

Hi,

I am trying to run usbtmc as nonroot in linux mint 15.

I have set the permissions with an udev rule as described in the index. I can do things like:

echo "*idn?" >> /dev/usbtmc0

and cat /dev/usbtmv0

However I get the following error when running as non root:

In [1]: import usbtmc

In [2]: device = usbtmc.list_devices()[0]

In [3]: device
Out[3]: <usb.core.Device at 0x13c5d50>

In [4]: instr = usbtmc.Instrument(device)
---------------------------------------------------------------------------
USBError                                  Traceback (most recent call last)
<ipython-input-4-830fc6de9693> in <module>()
----> 1 instr = usbtmc.Instrument(device)

/usr/local/lib/python2.7/dist-packages/python_usbtmc-0.1-py2.7.egg/usbtmc/usbtmc.pyc in __init__(self, *args, **kwargs)
    163 
    164         # initialize device
--> 165         if self.device.is_kernel_driver_active(0):
    166             self.device.detach_kernel_driver(0)
    167 

/usr/local/lib/python2.7/dist-packages/usb/core.pyc in is_kernel_driver_active(self, interface)
    717         """If a kernel driver is active, and the object will be unable to perform I/O.
    718         """
--> 719         self._ctx.managed_open()
    720         return self._ctx.backend.is_kernel_driver_active(self._ctx.handle,
    721                 self._ctx.get_interface(self, interface).bInterfaceNumber)

/usr/local/lib/python2.7/dist-packages/usb/core.pyc in managed_open(self)
     68     def managed_open(self):
     69         if self.handle is None:
---> 70             self.handle = self.backend.open_device(self.dev)
     71         return self.handle
     72 

/usr/local/lib/python2.7/dist-packages/usb/backend/libusb1.pyc in open_device(self, dev)
    731     @methodtrace(_logger)
    732     def open_device(self, dev):
--> 733         return _DeviceHandle(dev)
    734 
    735     @methodtrace(_logger)

/usr/local/lib/python2.7/dist-packages/usb/backend/libusb1.pyc in __init__(self, dev)
    616         self.handle = _libusb_device_handle()
    617         self.devid = dev.devid
--> 618         _check(_lib.libusb_open(self.devid, byref(self.handle)))
    619 
    620 class _IsoTransferHandler(object):

/usr/local/lib/python2.7/dist-packages/usb/backend/libusb1.pyc in _check(retval)
    569         if retval.value < 0:
    570            ret = retval.value
--> 571            raise USBError(_str_error[ret], ret, _libusb_errno[ret])
    572     return retval
    573 

USBError: [Errno 13] Access denied (insufficient permissions)

Agilent U2761A Support

Thanks so much for this module! Super helpful.

I'm trying to enable access to the U2761A from Agilent (Keysight). I see your code sending over commands to switch the other U27* devices from firmware mode to usbtmc. I've tried adding the idProduct (0x3B18 -> 0x3C18) for the U2761A and can successfully see the device, but when I try to open the instrument, I cannot switch it from firmware mode. I'm assuming I am not sending the correct info to switch it over (there's 1 wIndex different between your U2701A and U2772A devices). Do you know the correct data to send for the U2761A, or know how I can figure it out?

[Windows] usb.core.USBError: [Errno None] libusb0-dll:err [claim_interface] could not claim interface 1, invalid configuration 0

Hello,

I was working on a test for a device (LadyBug LB5918A Power Sensor) and decided to use python source code that a peer had already written to communicate with it. The code was only tested in a linux environment and being the masochist I am I decided to see if I could at least just identify the device on windows. After using pip to install pyusb & usbtmc, creating an inf filter with libusb-win32, I ran a brief test script to see if I could just query the device ("*IDN?"). Here's the section of the init from the API were the code fails.

try:
	self.PID = PID
	self.VID = VID
	# Initialize USBTMC interface with the LadyBug.
	self.instr =  usbtmc.Instrument(self.VID, self.PID)
	#self.instr =  usbtmc.Instrument(0x1A0D, 0x15D8)
	self.connected = True
	self.log.debug('Connecting to device with VID: '+str(self.VID)+' and PID: '+str(self.PID))
	self._send('SYST:PRES DEF')
	self.log.debug(str(self._request('*IDN?')))
	#self.clearErr()
except Exception as e: 
	self.exceptionHandler(e)

And the __send() function

def _send(self,msg):
		self.log.debug(str('Writing: '+str(msg)))
		self.instr.write(msg+'\n')
		err = str(self.instr.ask('SYST:ERR?\n'))
		if err != '+0,"No error"':
			self.log.debug(str('LadyBug Error: '+str(err)))

The error message I get in return is as follows

2018-08-03 15:29:08,970 :: ladyBug(DEBUG) :: __init__
2018-08-03 15:29:08,996 :: ladyBug(DEBUG) :: Connecting to device with VID: 6669 and PID: 5592
2018-08-03 15:29:08,997 :: ladyBug(DEBUG) :: Writing: SYST:PRES DEF
Traceback (most recent call last):
  File "ladyBug-test.py", line 10, in <module>
    lb = ladyBug.meter(0x1a0d,0x15d8,True)
  File "C:\Users\jonathan.bensing\LadyBug-API\ladyBug.py", line 49, in __init__
    self.exceptionHandler(e)
  File "C:\Users\jonathan.bensing\LadyBug-API\ladyBug.py", line 249, in exceptionHandler
    self.instr.open()
  File "C:\Python27\lib\site-packages\usbtmc\usbtmc.py", line 313, in open
    usb.util.claim_interface(self.device, self.iface)
  File "C:\Python27\lib\site-packages\usb\util.py", line 205, in claim_interface
    device._ctx.managed_claim_interface(device, interface)
  File "C:\Python27\lib\site-packages\usb\core.py", line 102, in wrapper
    return f(self, *args, **kwargs)
  File "C:\Python27\lib\site-packages\usb\core.py", line 167, in managed_claim_interface
    self.backend.claim_interface(self.handle, i)
  File "C:\Python27\lib\site-packages\usb\backend\libusb0.py", line 521, in claim_interface
    _check(_lib.usb_claim_interface(dev_handle, intf))
  File "C:\Python27\lib\site-packages\usb\backend\libusb0.py", line 431, in _check
    raise USBError(errmsg, ret)
usb.core.USBError: [Errno None] libusb0-dll:err [claim_interface] could not claim interface 1, invalid configuration 0

After a lot of googling, I couldn’t seem to find any conclusive reason why this shouldn’t work on windows seeing that I had followed all the steps correctly for both PyUSB and USBTMC setup. I tried just the PyUSB module to identify the device which I was able to do and I then tried to write to the device commands which I know I was most likely doing wrong. I did notice that for most of the examples of PyUSB, the set_configuration() function was used a lot to attach to a device. One post that had a similar error said that set_configuration(1) should be used and in a rather fluke way I was able to get the device working, so below is the script that cause the device to function properly.

myVendorId =0x1a0d
myProductId=0x15d8
import usb.core
dev = usb.core.find(idVendor=myVendorId, idProduct=myProductId)
print dev
dev.set_configuration(1)
import ladyBug
lb = ladyBug.meter(0x1a0d,0x15d8,True)
exit()

So I then decided to go through the USBTMC api to see where the issue may be occurring. I believe that the culprit is here in the open() function:

    def open(self):
        if self.connected:
            return
        # initialize device
        # find first USBTMC interface
        for cfg in self.device:
            for iface in cfg:
                if (self.device.idVendor == 0x1334) or \
                   (iface.bInterfaceClass == USBTMC_bInterfaceClass and
                    iface.bInterfaceSubClass == USBTMC_bInterfaceSubClass):
                    self.cfg = cfg
                    self.iface = iface
                    break
                else:
                    continue
            break
        if self.iface is None:
            raise UsbtmcException("Not a USBTMC device", 'init')
        try:
            self.old_cfg = self.device.get_active_configuration()
        except usb.core.USBError:
            # ignore exception if configuration is not set
            pass
        if self.old_cfg is not None and self.old_cfg.bConfigurationValue == self.cfg.bConfigurationValue:
            # already set to correct configuration
            # release kernel driver on USBTMC interface
            self._release_kernel_driver(self.iface.bInterfaceNumber)
        else:
            # wrong configuration or configuration not set
            # release all kernel drivers
            if self.old_cfg is not None:
                for iface in self.old_cfg:
                    self._release_kernel_driver(iface.bInterfaceNumber)
            # set proper configuration
            self.device.set_configuration(self.cfg)

        # claim interface
        usb.util.claim_interface(self.device, self.iface)

After stepping through the code manually, the issue is where self.device.set_configuration(self.cfg) is never being called. I’m not sure the reasoning behind having the configuration not being set, because it seems that (on windows at least) the old_cfg bConfigurationValue will always be the same as the active cfg bConfigurationValue. And within the usbtmc code I simple moved self.device.set_configuration(self.cfg) out of the if statement so that the device will always be set.

        if self.old_cfg is not None and self.old_cfg.bConfigurationValue == self.cfg.bConfigurationValue:
            # already set to correct configuration

            # release kernel driver on USBTMC interface
            self._release_kernel_driver(self.iface.bInterfaceNumber)
        else:
            # wrong configuration or configuration not set

            # release all kernel drivers
            if self.old_cfg is not None:
                for iface in self.old_cfg:
                    self._release_kernel_driver(iface.bInterfaceNumber)

        # set proper configuration
        self.device.set_configuration(self.cfg)

I’m not sure if this is intended but I believe that this is how it should be in the code. I hope this helps!

Jon

Getting a a struct error after writing

Hello, thanks for providing such a great resource; I'm having an issue though.

In the frequency for loop, the third one, the program crashes after 85 iterations with the log provided below. This is my first Python script, so I'm not sure how to debug Python just yet.

I've gone through the source and the issue seems to stem from the variable self.last_btag. After 85 iterations, using the functions I have the value of the variable would have been incremented (85 * 3) times = 255, hence the error.

Am I supposed to reset the value of self.last_btag somewhere?

Thanks!

EDIT: Calling lcr.last_btag = 0 in the loop fixes the problem temporarily, will test latest git commit when I can.

from time import sleep
import usbtmc
import serial

lcr = usbtmc.Instrument(2391, 2313)

Arduino = serial.Serial('/dev/tty.usbmodem1421', 38400, timeout=10)


for i in range(0, 4):
    print()
    for R1 in range(0, 64):
        # Instruct Arduino to change rheostat wiper
        Arduino.write(b'1')
        sleep(0.1)
        for f in range(0, 99):
            lcr.write(":TRIG:IMM")
            # TEMPOARY FIX: lcr.last_btag = 0
            sleep(0.1)
            data = lcr.ask("FETC:IMP:FORM?")
            sleep(0.1)
            print(str(R1) + "," + str(f) + "," + data)

Error Log:

  File "build/bdist.macosx-10.10-intel/egg/usbtmc/usbtmc.py", line 479, in write
  File "build/bdist.macosx-10.10-intel/egg/usbtmc/usbtmc.py", line 410, in write_raw
  File "build/bdist.macosx-10.10-intel/egg/usbtmc/usbtmc.py", line 359, in pack_dev_dep_msg_out_header
  File "build/bdist.macosx-10.10-intel/egg/usbtmc/usbtmc.py", line 356, in pack_bulk_out_header
struct.error: ubyte format requires 0 <= number <= 255

usb.core.USBError: [Errno None] Configuration not set

Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)] on win32
libusb 1.2.6.0 installed for device with Zadig
pyusb and python-usbtmc first installed with pip

Trying the following

    import usbtmc
    import time, sys
    instr =  usbtmc.Instrument(0x1ab1, 0x04ce)
    print(instr.ask("*IDN?"))
    time.sleep(0.2)
    print( "Trigger status:", instr.ask(":TRIGger:STAtus?") )
    time.sleep(0.5)
    print( "Setting single trigger mode.", instr.ask(":SINGle") )
    time.sleep(0.5)
    print( "Trigger status:", instr.ask(":TRIGger:STAtus?") )
    sys.exit()

Results in

    print(instr.ask("*IDN?"))
  File "C:\Program Files\Python35\lib\site-packages\usbtmc\usbtmc.py", line 575, in ask
    self.write(message, encoding)
  File "C:\Program Files\Python35\lib\site-packages\usbtmc\usbtmc.py", line 555, in write
    self.write_raw(str(message).encode(encoding))
  File "C:\Program Files\Python35\lib\site-packages\usbtmc\usbtmc.py", line 464, in write_raw
    self.open()
  File "C:\Program Files\Python35\lib\site-packages\usbtmc\usbtmc.py", line 281, in open
    self.old_cfg = self.device.get_active_configuration()
  File "C:\Program Files\Python35\lib\site-packages\usb\core.py", line 875, in get_active_configuration
    return self._ctx.get_active_configuration(self)
  File "C:\Program Files\Python35\lib\site-packages\usb\core.py", line 102, in wrapper
    return f(self, *args, **kwargs)
  File "C:\Program Files\Python35\lib\site-packages\usb\core.py", line 242, in get_active_configuration
    raise USBError('Configuration not set')
usb.core.USBError: [Errno None] Configuration not set

Same with python_usbtmc-0.7-py3.5.egg from https://pypi.python.org/pypi/python-usbtmc installed with easy_install python_usbtmc-0.7-py3.5.egg

   print(instr.ask("*IDN?"))
  File "C:\Program Files\Python35\lib\site-packages\python_usbtmc-0.7-py3.5.egg\usbtmc\usbtmc.py", line 575, in ask
  File "C:\Program Files\Python35\lib\site-packages\python_usbtmc-0.7-py3.5.egg\usbtmc\usbtmc.py", line 555, in write
  File "C:\Program Files\Python35\lib\site-packages\python_usbtmc-0.7-py3.5.egg\usbtmc\usbtmc.py", line 464, in write_raw
  File "C:\Program Files\Python35\lib\site-packages\python_usbtmc-0.7-py3.5.egg\usbtmc\usbtmc.py", line 281, in open
  File "C:\Program Files\Python35\lib\site-packages\usb\core.py", line 875, in get_active_configuration
    return self._ctx.get_active_configuration(self)
  File "C:\Program Files\Python35\lib\site-packages\usb\core.py", line 102, in wrapper
    return f(self, *args, **kwargs)
  File "C:\Program Files\Python35\lib\site-packages\usb\core.py", line 242, in get_active_configuration
    raise USBError('Configuration not set')
usb.core.USBError: [Errno None] Configuration not set

Let me know how to provide further debug info.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.