Trouble using PyUSB to read from usb device in different systems - python

I have written a small python script to read data from a digital thermometer, and everything works just fine in my computer. however, i need to run this same script in other systems, but i keep getting a "[Errno 10060] Operation timed out" error.
in the second computer i can see the device, it's endpoints and everything, but it's when i try to read from it that i'm getting the error.
this is the code (i intentionally did not set the configuration for the device, as i'm trying to speed up the reading, and in my system it proved not to be necessary):
import usb.core
def get_temp(T):
# find our device
dev = usb.core.find(idVendor=0x04d9, idProduct=0xe000)
# was it found?
if dev is None:
raise ValueError('Device not found')
# poll the thermometer for current temperature
t = dev.read(0x83, 32) # gets 32 bytes from ENDPOINT address 0x83
so, in the computer where i wrote this, it works as expected, and it returns a nice 32-byte array. but in other systems, i got the error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\usb\core.py", line 402, in read
return self.device.read(self, size_or_buffer, timeout)
File "C:\Python27\lib\site-packages\usb\core.py", line 988, in read
self.__get_timeout(timeout))
File "C:\Python27\lib\site-packages\usb\backend\libusb1.py", line 851, in
intr_read
timeout)
File "C:\Python27\lib\site-packages\usb\backend\libusb1.py", line 936, in
__read
_check(retval)
File "C:\Python27\lib\site-packages\usb\backend\libusb1.py", line 595, in
_check
raise USBError(_strerror(ret), ret, _libusb_errno[ret])
usb.core.USBError: [Errno 10060] Operation timed out
i tried also setting device configuration this time, but still same error.
any ideas on what i might be missing?
edit: this is my output log with PYUSB_DEBUG environment variable set to debug:
>>> dev.read(0x83,32)
2019-01-11 10:35:06,951 DEBUG:usb.backend.libusb1:_LibUSB.get_configuration(<usb.backend.libusb1._DeviceHandle object at 0x02A2A610>)
2019-01-11 10:35:06,953 DEBUG:usb.backend.libusb1:_LibUSB.get_configuration_descriptor(<usb.backend.libusb1._Device object at 0x02A2A650>, 0)
2019-01-11 10:35:06,954 DEBUG:usb.backend.libusb1:_LibUSB.get_interface_descriptor(<usb.backend.libusb1._Device object at 0x02A2A650>, 0, 0, 0)
2019-01-11 10:35:06,956 DEBUG:usb.backend.libusb1:_LibUSB.get_configuration_descriptor(<usb.backend.libusb1._Device object at 0x02A2A650>, 0)
2019-01-11 10:35:06,957 DEBUG:usb.backend.libusb1:_LibUSB.get_endpoint_descriptor(<usb.backend.libusb1._Device object at 0x02A2A650>, 0, 0, 0, 0)
2019-01-11 10:35:06,957 DEBUG:usb.backend.libusb1:_LibUSB.get_interface_descriptor(<usb.backend.libusb1._Device object at 0x02A2A650>, 0, 0, 0)
2019-01-11 10:35:06,957 DEBUG:usb.backend.libusb1:_LibUSB.get_configuration_descriptor(<usb.backend.libusb1._Device object at 0x02A2A650>, 0)
2019-01-11 10:35:06,957 DEBUG:usb.backend.libusb1:_LibUSB.claim_interface(<usb.backend.libusb1._DeviceHandle object at 0x02A2A610>, 0)
2019-01-11 10:35:06,957 DEBUG:usb.backend.libusb1:_LibUSB.intr_read(<usb.backend.libusb1._DeviceHandle object at 0x02A2A610>, 131, 0, array('B', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), 1000)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\usb\core.py", line 988, in read
self.__get_timeout(timeout))
File "C:\Python27\lib\site-packages\usb\_debug.py", line 60, in do_trace
return f(*args, **named_args)
File "C:\Python27\lib\site-packages\usb\backend\libusb1.py", line 851, in intr_read
timeout)
File "C:\Python27\lib\site-packages\usb\backend\libusb1.py", line 936, in __read
_check(retval)
File "C:\Python27\lib\site-packages\usb\backend\libusb1.py", line 595, in _check
raise USBError(_strerror(ret), ret, _libusb_errno[ret])
usb.core.USBError: [Errno 10060] Operation timed out
>>>

Related

I have a Python script that is not working in python3

I have a script:
if (enviar_ftp(mounted_usb) >= 0): # ML: enviar_ftp()->enviar_ftp(ser)
# Se agrega la captura de schedule online
s = get_schedule_online(get_id())
log("Programa en servidor: {0}".format(s))
if (s != ""):
save_programa(s)
enviar_situacion(get_id(), get_programa(), get_free_space()[3], 0, 0, str(100-int(get_free_space()[4])), battery_status(voltaje), voltaje, 0, 0)
# ser_write("<txt>\n")
else:
log('enviar_ftp() failed') # ser_write("<txn>\n")
Works fine in python2 but in python3 I get:
Traceback (most recent call last):
File "/home/pi/main.py", line 511, in <module>
app_main()
File "/home/pi/main.py", line 499, in app_main
send_pics()
File "/home/pi/main.py", line 241, in send_pics
enviar_situacion(get_id(), get_programa(), get_free_space()[3], 0, 0, str(100-int(get_free_space()[4])), battery_status(voltaje), voltaje, 0, 0)
TypeError: 'NoneType' object is not subscriptable
Any ideas?
Expect the script to work!!

How to override an array in a modelica system with OMPython?

I'm working on a project, using openmodelica. I'm trying to simulate the system multiple times and i wrote a python script to automatize it. I also override parameters on each iteration of the simulation, but if i try to override an array i'll get this on console:
Traceback (most recent call last):
File "pythonScripts/testing.py", line 164, in <module>
startSimulation(5,2,1,4, noFault,flyZone[1])
File "pythonScripts/testing.py", line 118, in startSimulation
vars = omc.sendExpression("readSimulationResult(\"System_res.mat\",{time})")
File "/home/francesco/.local/lib/python3.8/site-packages/OMPython/__init__.py", line 779, in sendExpression
answer = OMTypedParser.parseString(result)
File "/home/francesco/.local/lib/python3.8/site-packages/OMPython/OMTypedParser.py", line 120, in parseString
res = omcGrammar.parseString(string)
File "/home/francesco/.local/lib/python3.8/site-packages/pyparsing/core.py", line 1143, in parse_string
raise exc.with_traceback(None)
pyparsing.exceptions.ParseException: Expected end of text, found '(' (at char 4), (line:1, col:5)
This is an example of how i did it:
def startSimulation(n, intr, miss, statObs, fault, flyZone):
with open("newValues.txt", 'wt') as f:
f.write("const.N="+str(n)+"\n")
f.write("const.nIntr="+str(intr)+"\n")
f.write("const.nRocket="+str(miss)+"\n")
f.write("const.nStatObs="+str(statObs)+"\n")
f.write("fault.transMatrix[4,4]="+str(fault)+"\n")
f.write("const.flyZone[3]="+flyZone+"\n")
f.flush()
os.fsync(f)
os.system("./System -overrideFile=newValues.txt >> LogOverride")
noFault = "[1, 0, 0, 0; 1, 0, 0, 0; 1, 0, 0, 0; 1, 0, 0, 0]"
flyZone = ["{100,100,100}","{150,150,150}","{200,200,200}"]
startSimulation(5,2,1,4, noFault,flyZone[1])
Any suggestion?
OpenModelica will expand arrays into scalars when the C code is generated so you need to override each of the array elements separately in newValues.txt:
fault.transMatrix[1,1]=1
fault.transMatrix[1,2]=0
fault.transMatrix[1,3]=0
fault.transMatrix[1,4]=0
fault.transMatrix[2,1]=1
fault.transMatrix[2,2]=0
fault.transMatrix[2,3]=0
fault.transMatrix[2,4]=0
...

ZeroDivisionError: division by zero in chess.py

I have created an chess seeing video and when it completes i got an error
ZeroDivisionError: division by zero
my whole code: https://onlinegdb.com/HJR_9t2nD
board = [ ['Rb', 'Nb', 'Bb', 'Qb', 'Kb', 'Bb', 'Nb', 'Rb'], #8
['Pb', 'Pb', 'Pb', 'Pb', 'Pb', 'Pb', 'Pb', 'Pb'], #7
[ 0, 0, 0, 0, 0, 0, 0, 0], #6
[ 0, 0, 0, 0, 0, 0, 0, 0], #5
[ 0, 0, 0, 0, 0, 0, 0, 0], #4
[ 0, 0, 0, 0, 0, 0, 0, 0], #3
['Pw', 'Pw', 'Pw', 'Pw', 'Pw', 'Pw', 'Pw', 'Pw'], #2
['Rw', 'Nw', 'Bw', 'Qw', 'Kw', 'Bw', 'Nw', 'Rw'] ]#1
# a b c d e f g h
def isOccupiedby(board,x,y,color):
if board[x / y]==0:
#the square has nothing on it.
return False
Here's full error
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Python37\lib\threading.py", line 926, in _bootstrap_inner
self.run()
File "C:\Python37\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "chess.py", line 1054, in negamax
moves = allMoves(position, colorsign)
File "chess.py", line 842, in allMoves
listofpieces = getallpieces(position,color)
File "chess.py", line 831, in getallpieces
if isOccupiedby(board,i,j,color):
File "chess.py", line 458, in isOccupiedby
if board[x / y]==0:
ZeroDivisionError: division by zero
Traceback (most recent call last):
File "chess.py", line 1713, in <module>
createShades([])
File "chess.py", line 955, in createShades
if isCheck(position,'white'):
File "chess.py", line 801, in isCheck
return isAttackedby(position,x,y,enemy)
File "chess.py", line 496, in isAttackedby
findPossibleSquares(position,x,y,True)) #The true argument
File "chess.py", line 569, in findPossibleSquares
if isOccupiedby(board,kx,y,enemy_color):
File "chess.py", line 458, in isOccupiedby
if board[x / y]==0:
ZeroDivisionError: division by zero
/ is the division operator. If the divisor is zero, you will get an exception.
Very likely you tried to access an element of the grid. If board is a list of lists, you must use the subscription operator twice in a row. Since the grid is organized in rows, the first subscription index is y and the second is x:
if board[x / y]==0:
if board[y][x]==0:

python rotate an image around an axis

I thought I had found the solution to my probelm (and the code) fro Idan:
MoviePy + Vapory code
from moviepy.editor import concatenate, ImageClip, VideoClip
from vapory import *
img_path = "E:/Programming/Python/coffee.png"
img_clip = ImageClip(img_path)
W, H = img_clip.w, img_clip.h
AR = 1.0*W/H
t_rev = 2.0
t_half = t_rev/2.0 # The time required for a half revolution
t_still = 0.8 # How long (in seconds) to hold the half rotated image still
cam = Camera('location', [ 0, 0, -1],
'look_at', [ 0, 0, 0])
light = LightSource([0, 0, -1]) # Light at camera location
bg = Background('color', [0, 0, 0]) # Black background
def scene(t):
""" Returns the scene at time 't' (in seconds) """
s = Scene(camera = cam, objects = [light, bg])
s = s.add_objects([
Box([0, 0, 0],
[W, H, 0],
Texture(Pigment(ImageMap('"{}"'.format(img_path), 'once')),
Finish('ambient', 1.0)),
'translate', [-0.5, -0.5, 0],
'scale', [AR, 1, 0],
'rotate', [0, (360/t_rev)*t, 0])])
return s
def make_frame(t):
return scene(t).render(width=W, height=H, antialiasing=0.1)
still_1 = VideoClip(make_frame).to_ImageClip(t=0).set_duration(t_still)
half_1 = VideoClip(make_frame).subclip(0, t_half)
still_2 = VideoClip(make_frame).to_ImageClip(t=t_half).set_duration(t_still)
half_2 = VideoClip(make_frame).subclip(t_half, t_rev)
final_clip = concatenate([still_1, half_1, still_2, half_2])
final_clip.write_gif("E:/Programming/Python/coffee_rot.gif", fps=15)
BUT when I try to run it with Python 3.6 I get (full traceback):
Hope this makes things clearer
Traceback (most recent call last):
File "C:\Users\Us\AppData\Local\Programs\Python\Python36\test2a.py", line 44, in <module>
still_1 = VideoClip(make_frame).to_ImageClip(t=0).set_duration(t_still)
File "C:\Users\Us\AppData\Local\Programs\Python\Python36\lib\site-packages\moviepy\video\VideoClip.py", line 86, in __init__
self.size = self.get_frame(0).shape[:2][::-1]
File "<decorator-gen-10>", line 2, in get_frame
File "C:\Users\Us\AppData\Local\Programs\Python\Python36\lib\site-packages\moviepy\decorators.py", line 89, in wrapper
return f(*new_a, **new_kw)
File "C:\Users\Us\AppData\Local\Programs\Python\Python36\lib\site-packages\moviepy\Clip.py", line 94, in get_frame
return self.make_frame(t)
File "C:\Users\Us\AppData\Local\Programs\Python\Python36\test2a.py", line 41, in make_frame
return scene(t).render(width=W, height=H, antialiasing=0.1)
File "C:\Users\Us\AppData\Local\Programs\Python\Python36\lib\site-packages\vapory\vapory.py", line 102, in render
quality, antialiasing, remove_temp)
File "C:\Users\Us\AppData\Local\Programs\Python\Python36\lib\site-packages\vapory\io.py", line 106, in render_povstring
stdout=subprocess.PIPE)
File "C:\Users\Us\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 710, in __init__
restore_signals, start_new_session)
File "C:\Users\Us\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 998, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
Searches find similar errors but none relevant to my situation. Help much appreciated. Idan are you still there?
Could comment re windows file paths be expanded a little?

How to make exception to a missing attribute in <class, list>?

After reading my data, I use to following script:
for sample in record.samples:
print(type(sample))
I get:
<class 'vcf.model._Call'>
With this:
print(sample)
I get:
Call(sample=MA605, CallData(GT=0/0, AD=[13, 0], DP=13, GQ=0, PB=None, PC=None, PG=0/0, PI=None, PL=[0, 0, 228], PW=0/0))
Call(sample=MA611, CallData(GT=0/0, AD=[57, 0], DP=57, GQ=0, PB=None, PC=None, PG=0/0, PI=None, PL=[0, 0, 1369], PW=0/0))
Call(sample=MA622, CallData(GT=0/1, AD=[67, 14], DP=81, GQ=99, PB=None, PC=None, PG=0/1, PI=None, PL=[229, 0, 2535], PW=0/1))
Call(sample=MA625, CallData(GT=0/0, AD=[58, 0], DP=58, GQ=0, PB=None, PC=None, PG=0/0, PI=None, PL=[0, 0, 590], PW=0/0))
Call(sample=MA629, CallData(GT=1|0, AD=[24, 5], DP=29, GQ=67, PB=.,., PC=1.0, PG=1|0, PI=5060, PL=[67, 0, 952], PW=1|0))
Call(sample=Ncm8, CallData(GT=0/0, AD=[7, 0], DP=7, GQ=0, PB=None, PC=None, PG=0/0, PI=None, PL=[0, 0, 147
I am trying to write the output to a file using:
output.write("{}\t{}\t{}\t{}\t{}"
.format(contig1, pos1, ref_allele1, all_alleles1, all_freq1))
for sample in record.samples:
output.write("\t{}\t{}".format(sample['GT'], sample['PI']))
Everything is working well, but I have some line that have PI field missing - which means PI is totally missing and is not (PI = None). When my script hists that line I get AttributeError:
Traceback (most recent call last):
File "/home/everestial007/PycharmProjects/stitcher/pHASE-Stitcher-Markov/pHASE-Stitcher_stage01-4_nonInteractive-MarkovModel.py", line 221, in <module>
phase_block_index = record.genotype('2ms02g')['PI']
File "/home/everestial007/anaconda3/lib/python3.5/site-packages/vcf/model.py", line 104, in __getitem__
return getattr(self.data, key)
AttributeError: 'CallData' object has no attribute 'PI'
How, can I set the PI value to period (.) when it is not in my data (record.sample)?
I tried several method. One of method I though would work is:
output.write("\t{}\t{}".format(sample['GT'] or None, sample['PI'] or None))
But, still failing.
Any, suggestions.
Thanks,
You can try sample.get('PI') or '.'.
Get returns by default None, when a key is not defined.

Categories

Resources