I try to read characteristic data out of an BLE based Sensor. Therefore i use the pygatt module
import pygatt
adapter = pygatt.GATTToolBackend()
try:
adapter.start()
device = adapter.connect("2B:01:56:6C:F4:E6")
value= device.char_read("00007502-0000-1000-8000-00805f9b34fb")
finally:
adapter.stop()
Everytime i try to run this in my Linux console (with Python 2.7.16) i get an error :
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/pi/.local/lib/python2.7/site-packages/pygatt/backends/gatttool/device.py", line 17, in wrapper
return func(self, *args, **kwargs)
File "/home/pi/.local/lib/python2.7/site-packages/pygatt/backends/gatttool/device.py", line 40, in char_read
return self._backend.char_read(self, uuid, *args, **kwargs)
File "/home/pi/.local/lib/python2.7/site-packages/pygatt/backends/gatttool/gatttool.py", line 50, in wrapper
return func(self, *args, **kwargs)
File "/home/pi/.local/lib/python2.7/site-packages/pygatt/backends/gatttool/gatttool.py", line 593, in char_read
self.sendline('char-read-uuid %s' % uuid)
File "/usr/lib/python2.7/contextlib.py", line 24, in __exit__
self.gen.next()
File "/home/pi/.local/lib/python2.7/site-packages/pygatt/backends/gatttool/gatttool.py", line 191, in event
self.wait(event, timeout)
File "/home/pi/.local/lib/python2.7/site-packages/pygatt/backends/gatttool/gatttool.py", line 157, in wait
raise NotificationTimeout()
pygatt.exceptions.NotificationTimeout: None
I am completely lost on this error. Do you know how to fix this ?
Any help on this much appreciated. Thanks in advance...
Since I was facing the same problem and nobody out there seemed to have this problem...
Well, the problem was that the requested UUID characteristic didn't exist/was invalid. Make sure that you've typed it right or that you haven't clipped some part off when copying from putty or similar (Totally not speaking from experience! Of course!)
If you are pasting a characteristic UUID from the internet or a similar device, maybe your device don't have this UUID.
OR
This could (not tested, but should make sense) also happen if you write to an UUID which is non-writeable (read-only/subscribe-only).
If you're sure that everything is right and that you have triple-checked the UUID with a dedicated sniffer or simply a BLE Scanner on your Phone, then the device is probably closing the connection too fast.
TROUBLESHOOTING:
You can manually connect with the device and issue commands using:
gatttool -I
When you are inside the program, type:
connect aa:bb:cc:dd:ee:ff
And then, before the connection closes:
char-read-uuid xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
and analyse what happens. If it works there, it should also work in python.
Related
I'm working on interfacing an old Optical Spectrum Analyzer Anritsu MS9710B with a RS232 connection. A year ago, I managed to comunicate with him, send SCPI command using pyvisa and receive data. Today, I execute the exact same code with libraries up to date and I get an error Timeout when I query IDN or anything. The RS232-USB drivers are ok, I manage to open a communication but a query or read fail.
I changed the parameter to "RS232C" on the OSA parameters and my communication parameters are the same between OSA and program. Following advices from the forum, I tried the connection with NI-VISA where I get the same error. I tried to change timeout parameter, write_termination and read_termination but there isn't any change. The manual is very hard to understand termination value, but when it worked I didn't add anything.
I don't know anymore what to do.
Any advices and help would be warmly welcome to fix my problem !
import pyvisa
from pyvisa.constants import StopBits, Parity
rm = pyvisa.ResourceManager()
print(rm.list_resources())
my_instrument = rm.open_resource('ASRL5::INSTR')
my_instrument.baud_rate=9600
my_instrument.data_bits=8
my_instrument.parity=Parity.even
my_instrument.stop_bits=StopBits.one
my_instrument.write('*IDN?')
print(my_instrument.read())```
'''
('ASRL5::INSTR',)
Traceback (most recent call last):
File "PremiereComm.py", line 26, in <module>
print(my_instrument.read())
File "C:\Program Files\Python38\lib\site-packages\pyvisa\resources\messagebased.py", line 486, in read
message = self._read_raw().decode(enco)
File "C:\Program Files\Python38\lib\site-packages\pyvisa\resources\messagebased.py", line 442, in _read_raw
chunk, status = self.visalib.read(self.session, size)
File "C:\Program Files\Python38\lib\site-packages\pyvisa\ctwrapper\functions.py", line 2337, in read
ret = library.viRead(session, buffer, count, byref(return_count))
File "C:\Program Files\Python38\lib\site-packages\pyvisa\ctwrapper\highlevel.py", line 222, in _return_handler
return self.handle_return_value(session, ret_value) # type: ignore
File "C:\Program Files\Python38\lib\site-packages\pyvisa\highlevel.py", line 251, in handle_return_value
raise errors.VisaIOError(rv)
pyvisa.errors.VisaIOError: VI_ERROR_TMO (-1073807339): Timeout expired before operation completed.
>>> '''
I am still quite new to USB protocol, and I need help extracting data from a digital multimeter using a USB connection and Python on my Raspberry Pi. Here I have a very basic Python script for reading from a generic USB device, and note that the idVendor and idProduct variables are correct for the multimeter I am using:
import usb.core
dev=usb.core.find(idVendor=0x067b,idProduct=0x2303)
ep=dev[0].interfaces()[0].endpoints()[0]
i=dev[0].interfaces()[0].bInterfaceNumber
dev.reset()
if dev.is_kernal_driver_active(i):
dev.detach_kernal_driver(i)
dev.set_configuration()
eaddr=ep.bEndpointAddress
r=dev.read(eaddr,1024)
print(len(r))
When I try to execute the script while the multimeter is reading a voltage, I receive the following error message:
Traceback (most recent call last):
File "usbRead.py", line 6, in <module>
dev.reset()
File "/home/pi/.local/lib/python2.7/site-packages/usb/core.py", line 949, in reset
self._ctx.managed_open()
File "/home/pi/.local/lib/python2.7/site-packages/usb/core.py", line 113, in wrapper
return f(self, *args, **kwargs)
File "/home/pi/.local/lib/python2.7/site-packages/usb/core.py", line 131, in managed_open
self.handle = self.backend.open_device(self.dev)
File "/home/pi/.local/lib/python2.7/site-packages/usb/backend/libusb1.py", line 804, in open_device
return _DeviceHandle(dev)
File "/home/pi/.local/lib/python2.7/site-packages/usb/backend/libusb1.py", line 652, in __init__
_check(_lib.libusb_open(self.devid, byref(self.handle)))
File "/home/pi/.local/lib/python2.7/site-packages/usb/backend/libusb1.py", line 604, in _check
raise USBError(_strerror(ret), ret, _libusb_errno[ret])
usb.core.USBError: [Errno 13] Access denied (insufficient permissions)
------------------
(program exited with code: 1)
Press return to continue
My apologies if this is an amateur question, but I've been trying my best to solve the insufficient permissions problem, but every solution I could find is filled with jargon that I'm hopeless in understanding. There was one thread that discussed changing things in a "rule file", and when I tried that, I ended up completely bricking the Raspberry Pi I was using!
Please help a novice like me on how I can be able to get data from this USB multimeter. Thank you so much in advance! I can answer questions for additional information as best I can.
I'm trying to connect a POS receipt printer to python and have been using python-escpos to do so. I'm running windows 10.
My code in my file 'print.py' is:
from escpos.printer import Usb
p = Usb(0x0456,0x0808)
p.text('Hello World\n')
but when i run it i get the following error log:
Traceback (most recent call last):
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 223, in get_interface_and_endpoint
return self._ep_info[endpoint_address]
KeyError: 1
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "print.py", line 5, in <module>
p.text('Hello World\n')
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\escpos\escpos.py", line 437, in text
self._raw(txt.encode())
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\escpos\printer.py", line 73, in _raw
self.device.write(self.out_ep, msg, self.timeout)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 940, in write
intf, ep = self._ctx.setup_request(self, endpoint)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 102, in wrapper
return f(self, *args, **kwargs)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 215, in setup_request
intf, ep = self.get_interface_and_endpoint(device, endpoint_address)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 102, in wrapper
return f(self, *args, **kwargs)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 225, in get_interface_and_endpoint
for intf in self.get_active_configuration(device):
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 102, in wrapper
return f(self, *args, **kwargs)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 239, in get_active_configuration
bConfigurationValue=self.backend.get_configuration(self.handle)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\backend\libusb0.py", line 510, in get_configuration
100)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\backend\libusb0.py", line 593, in ctrl_transfer
timeout
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\backend\libusb0.py", line 431, in _check
raise USBError(errmsg, ret)
usb.core.USBError: [Errno None] b'libusb0-dll:err [control_msg] sending control message failed, win error: A device which does not exist was specified.\r\n\n'
Does anyone know what i need to do to make this work.
I have installed libusb into my System32 and SysWOW64 folders, aswell as installing a libusb-32 driver for my printer with zadig.
The printer i'm using is a 'Hoin 58mm POS Printer'.
I would be grateful if someone could explain to me why i'm having this error and how to solve it!
Firstly, you can check this link for the complete thread.
As suggested by KM4YRI,
I ran into the same No backend available exception when trying to follow the tutorial on a Windows 7 machine. The following worked for me, per one of the StackOverflow replies:
1. Download the latest Windows binary: https://sourceforge.net/projects/libusb/files/libusb-1.0/libusb-1.0.21/libusb-1.0.21.7z/download
2. Unzip using 7zip into a temp dir
3. If on 64-bit Windows, copy `MS64\dll\libusb-1.0.dll` into `C:\windows\system32`. If on 32-bit windows, copy `MS32\dll\libusb-1.0.dll` into `C:\windows\SysWOW64`.
I've verified the above answer on Windows-10 64-bit version.
I had a tight experience with that error using at least 3 different USB Storage Devices. After hours of trials I ended up to a feeling that USB transmission errors are the cause of this error.
The USB bus will return it in a random pattern for a low quality connection as if a device remove has presumably happened.
In my scenario I was bulk writing sectors to a \\.\PhysicalDriveN device and I noticed that after a short period the connection reestablished and the file handle was still valid and going.
To overcome the error I've ended up with the following steps:
Seek To File Position;
Write Sector;
For any 433 error:
250 ms delay;
Seek To file Position, ignoring ERROR_NO_SUCH_DEVICE and ERROR_NOT_READY errors and trying for at least 1000 ms before giving up;
Read Sector, ignoring ERROR_NO_SUCH_DEVICE and ERROR_NOT_READY errors and retrying for up to 1000 ms before giving up;
Specially for my scenario: I've compared input buffer and read buffer and stop if matching;
Repeat the whole procedure up to 5 times.
So the idea here is the following: The device driver returns ERROR_NO_SUCH_DEVICE assuming a device remove scenario, but still in a pending state. As the problem is simply quality of physical connection, the link continues and the bus driver starts a renegotiation, in which case a ERROR_NOT_READY is temporarily returned. When the link is stable and negotiated, communication continues without the need to reopen the device handle.
I would recommend adding a sleep statement of a second or two in between the instantiation of the USB printer, and the attempt to print to it. e.g:
from escpos.printer import Usb
from time import sleep
p = Usb(0x0456,0x0808)
sleep(1)
p.text('Hello World\n')
I wanted to write an iptables script in Python. Rather than calling iptables itself I wanted to use the python-iptables package. However I'm having a hard time getting some basic rules setup. I wanted to use the filter chain to accept incoming TCP traffic on port 1234. So I wrote this:
import iptc
chain = iptc.Chain(iptc.TABLE_FILTER,"INPUT")
rule = iptc.Rule()
target = iptc.Target(rule,"ACCEPT")
match = iptc.Match(rule,'tcp')
match.dport='1234'
rule.add_match(match)
rule.target = target
chain.insert_rule(rule)
However when I run this I get this thrown back at me:
Traceback (most recent call last):
File "testing.py", line 9, in <module>
chain.insert_rule(rule)
File "/usr/local/lib/python2.6/dist-packages/iptc/__init__.py", line 1133, in insert_rule
self.table.insert_entry(self.name, rbuf, position)
File "/usr/local/lib/python2.6/dist-packages/iptc/__init__.py", line 1166, in new
obj.refresh()
File "/usr/local/lib/python2.6/dist-packages/iptc/__init__.py", line 1230, in refresh
self._free()
File "/usr/local/lib/python2.6/dist-packages/iptc/__init__.py", line 1224, in _free
self.commit()
File "/usr/local/lib/python2.6/dist-packages/iptc/__init__.py", line 1219, in commit
raise IPTCError("can't commit: %s" % (self.strerror()))
iptc.IPTCError: can't commit: Invalid argument
Exception AttributeError: "'NoneType' object has no attribute 'get_errno'" in <bound method Table.__del__ of <iptc.Table object at 0x7fcad56cc550>> ignored
Does anyone have experience with python-iptables that could enlighten on what I did wrong?
Oh, just noticed this one. Can you give the latest head from github a shot? I've fixed tons of bugs and updated python-iptables to work with the latest iptables version. If you still experience issues please open a ticket on github.
One thing that sure is not quite right is that you don't set the protocol in the rule:
import iptc
chain = iptc.Chain(iptc.TABLE_FILTER,"INPUT")
rule = iptc.Rule()
Set protocol e.g. here:
rule.protocol = 'tcp'
and then you should be all right:
target = iptc.Target(rule,"ACCEPT")
match = iptc.Match(rule,'tcp')
match.dport='1234'
rule.add_match(match)
rule.target = target
chain.insert_rule(rule)
I'm trying to make a script to launch my custom script when my usb stick connected.
I found nice python script here but when it calls GetAllProperties() method I get an exception:
ERROR:dbus.connection:Exception in handler for D-Bus signal: Traceback
(most recent call last): File
"/usr/lib/python2.7/site-packages/dbus/connection.py", line 214, in
maybe_handle_message
self._handler(*args, **kwargs) File "./hal-automount", line 31, in device_added
properties = self.udi_to_device(udi).GetAllProperties()
File "/usr/lib/python2.7/site-packages/dbus/proxies.py", line 68, in
__call__
return self._proxy_method(*args, **keywords) File "/usr/lib/python2.7/site-packages/dbus/proxies.py", line 140, in
__call__
**keywords) File "/usr/lib/python2.7/site-packages/dbus/connection.py", line 630, in
call_blocking
message, timeout) DBusException: org.freedesktop.DBus.Error.AccessDenied: Rejected send message, 3
matched rules; type="method_call", sender=":1.39539" (uid=0 pid=9527
comm="python) interface="(unset)" member="getAllProperties" error
name="(unset)" requested_reply=0 destination=":1.8" (uid=0 pid=3039
comm="/usr/sbin/hald))
OS: openSuSE 11.4
I didn't work with DBus before, can you give me a hint what's wrong?
Thanks.
Your DBus method call failed due to access policy. It is probably because you called a method without specifying any interface. Looks like a bug in the script you tried to use (DBus methods should always be called via an interface).
Try replacing:
def udi_to_device(self, udi):
return self.bus.get_object("org.freedesktop.Hal", udi)
With:
def udi_to_device(self, udi):
obj = self.bus.get_object("org.freedesktop.Hal", udi)
return dbus.Interface(obj, dbus_interface='org.freedesktop.Hal.Device')
BTW: HAL is now obsolete, you should probably switch to udisks. See http://www.freedesktop.org/wiki/Software/hal