Could not claim interface pyusb - pyusb

I'm trying to use pyusb over usblib1.0 to read the data from an old Ps2 mouse using a Ps2 to USB adapter that represents it as a HID device.
I am able to access the device, but when I try to send it the GET_REPORT request over control transfer, it shows me this error:
[Errno None] b'libusb0-dll:err [claim_interface] could not claim interface 0, win error: The parameter is incorrect.\r\n'
Here is my code:
import usb.core as core
import time
from usb.core import USBError as USBError
dev = core.find(idVendor=0x13ba, idProduct=0x0018, address=0x03)
interface = 0
endpoint = dev[0][(interface, 0)][0]
dev.set_configuration()
collected = 0
attempts = 50
while collected < attempts:
try:
print(dev.ctrl_transfer(0b10100001, 0x01, wValue=100, data_or_wLength=64))
collected += 1
except USBError as e:
print(e)
time.sleep(0.1)
I'm using python 3.x in windows 10 (Lenovo g-510 if it matters to anyone)
The driver I installed is a usblib-win32 using Zadig
Any help will be appreciated!
Thanks
EDIT:
Tried using WIN-USB so that It'll work with usblib-1.0
It didn't find the device. Returned None from the usb.core.fןnd() function
Continuing with WIN-USB with usblib-1.0, I successfully found the device, but no it appears to have no configuration.
dev.set_configuration()
returns:
File "C:\Users\Idan Stark\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\backend\libusb1.py", line 595, in _check
raise USBError(_strerror(ret), ret, _libusb_errno[ret])
usb.core.USBError: [Errno 2] Entity not found
Any help will be appreciated, in usblib-1.0 or usblib-0.1, anything to make this work! Thank you!

Related

grpc._channel._InactiveRpcError: _InactiveRpcError of RPC that terminated with: status = StatusCode.INTERNAL

This is a gRPC service & client python program. After running the client script it throwing this error. I am pretty new to using APIs/ gRPC in particular. It would be great if I get to know what might be the problem. Installed gRPC library & few supporting libraries too.
Even though the server is running correctly, the communication through gRPC is terminating with the INTERNAL error status code. Running it on localhost.
return _end_unary_response_blocking(state, call, False, None)
File "/home/mark/anaconda3/envs/custom-model-server/lib/python3.8/site-packages/grpc/_channel.py", line 849, in _end_unary_response_blocking
raise _InactiveRpcError(state)
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
status = StatusCode.INTERNAL
details = "indices[0,350] = 1650751580 is not in [0, 30522)
[[{{node tf_bert_for_sequence_classification/bert/embeddings/Gather}}]]"
debug_error_string = "{"created":"#1629922773.170809502","description":"Error received from peer ipv4:127.0.0.1:8001","file":"src/core/lib/surface/call.cc","file_line":1066,"grpc_message":"indices[0,350] = 1650751580 is not in [0, 30522)\n\t [[{{node tf_bert_for_sequence_classification/bert/embeddings/Gather}}]]","grpc_status":13}"
'''
The solution for this was to check the byte array that was being passed to the function and make sure the length we were taking was of the array itself not in bytes. So we were able to do:
dimensions = len(byte_array)//4

Failed to connect to BigQuery with Python - ServiceUnavailable

querying data from BigQuery has been working for me. Then I updated my google packages (e. g. google-cloud-bigquery) and suddenly I could no longer download data. Unfortunately, I don't know the old version of the package I was using any more. Now, I'm using version '1.26.1' of google-cloud-bigquery.
Here is my code which was running:
from google.cloud import bigquery
from google.oauth2 import service_account
import pandas as pd
KEY_FILE_LOCATION = "path_to_json"
PROCECT_ID = 'bigquery-123454'
credentials = service_account.Credentials.from_service_account_file(KEY_FILE_LOCATION)
client = bigquery.Client(credentials= credentials,project=PROCECT_ID)
query_job = client.query("""
SELECT
x,
y
FROM
`bigquery-123454.624526435.ga_sessions_*`
WHERE
_TABLE_SUFFIX BETWEEN '20200501' AND '20200502'
""")
results = query_job.result()
df = results.to_dataframe()
Except of the last line df = results.to_dataframe() the code works perfectly. Now I get a weired error which consists of three parts:
Part 1:
_InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
status = StatusCode.UNAVAILABLE
details = "failed to connect to all addresses"
debug_error_string = "{"created":"#1596627109.629000000","description":"Failed to pick subchannel","file":"src/core/ext/filters/client_channel/client_channel.cc","file_line":3948,"referenced_errors":[{"created":"#1596627109.629000000","description":"failed to connect to all addresses","file":"src/core/ext/filters/client_channel/lb_policy/pick_first/pick_first.cc","file_line":394,"grpc_status":14}]}"
>
Part 2:
ServiceUnavailable: 503 failed to connect to all addresses
Part 3:
RetryError: Deadline of 600.0s exceeded while calling functools.partial(<function _wrap_unary_errors.<locals>.error_remapped_callable at 0x0000000010BD3C80>, table_reference {
project_id: "bigquery-123454"
dataset_id: "_a0003e6c1ab4h23rfaf0d9cf49ac0e90083ca349e"
table_id: "anon2d0jth_f891_40f5_8c63_76e21ab5b6f5"
}
requested_streams: 1
read_options {
}
format: ARROW
parent: "projects/bigquery-123454"
, metadata=[('x-goog-request-params', 'table_reference.project_id=bigquery-123454&table_reference.dataset_id=_a0003e6c1abanaw4egacf0d9cf49ac0e90083ca349e'), ('x-goog-api-client', 'gl-python/3.7.3 grpc/1.30.0 gax/1.22.0 gapic/1.0.0')]), last exception: 503 failed to connect to all addresses
I don't have an explanation for this error. I don't think it has something to do with me updating the packages.
Once I had problems with the proxy but these problems caused another/different error.
My colleague said that the project "bigquery-123454" is still available in BigQuery.
Any ideas?
Thanks for your help in advance!
503 error occurs when there is a network issue. Try again after some time or retry the job.
You can read more about the error on Google Cloud Page
I found the answer:
After downgrading the package "google-cloud-bigquery" from version 1.26.1 to 1.18.1 the code worked again! So the new package caused the errors.
I downgraded the package using pip install google-cloud-bigquery==1.18.1 --force-reinstall

Error with win32com.client.GetObject when connecting to SAP GUI

Dears,
first of all this is the first time I ask a question on Stackoverflow so forgive me if I'm not following the right way to do this.
I kindly ask for your help as I'm facing an issue with win32com.
I'm trying to connect to SAP GUI in order to automate certain tasks.
import win32com.client
SapGuiAuto = win32com.client.GetObject('SAPGUI')
I get the following error (until yesterday everything was working fine..):
Traceback (most recent call last):
File "C:/Users/xxxxx/AppData/Roaming/JetBrains/PyCharmCE2020.1/scratches/PySAPscript.py", line 157, in <module>
SAP_OP()
File "C:/Users/xxxxx/AppData/Roaming/JetBrains/PyCharmCE2020.1/scratches/PySAPscript.py", line 18, in SAP_OP
SapGuiAuto = win32com.client.GetObject('SAPGUI')
File "C:\Users\xxxxx\PycharmProjects\yyyyyy\venv\lib\site-packages\win32com\client\__init__.py", line 72, in GetObject
return Moniker(Pathname, clsctx)
File "C:\Users\xxxxxx\PycharmProjects\yyyyyyy\venv\lib\site-packages\win32com\client\__init__.py", line 87, in Moniker
moniker, i, bindCtx = pythoncom.MkParseDisplayName(Pathname)
pywintypes.com_error: (-2147221020, 'Invalid syntax.', None, None)
I've found some documentation about this issue which suggests using pythoncom.CoInitialize():
Using win32com with multithreading
However I can't figure out how to use this function for my purpose.
Thank you for your help!
Considering, that you have variables (SAP_Path, SAP_system_id, SAP_group) or (SAP_Path,
SAP_sid, SAP_instance_no) instead...
shell = win32com.client.Dispatch("WScript.Shell")
call(SAP_Path + " /R/" + SAP_system_id + "/G/" + SAP_group)
OR: call(SAP_Path + " " + SAP_sid + " " + SAP_instance_no)
sap_gui_obj = win32com.client.GetObject("SAPGUI")
application = sap_gui_obj.GetScriptingEngine
connection = application.children(application.connections.count - 1)
session = connection.children(0)
session.findById("wnd[0]").maximize()
Then connect to your base.
I also encountered this problem recently.
The startup permissions of sap and python are not the same.
For example, both of these should be run with administrator rights, or run with ordinary user rights.
I do not guarantee that this method will solve your problem, but you can try :)
I had the same issue when trying to run SAP GUI Script triggered from Flask (desktop) application. Solution that works for me is to embrace the code operating with SAP GUI with pythoncom.CoInitialize() and pythoncom.CoUinitialize() statements:
def display_document():
import win32com.client
import pythoncom
pythoncom.CoInitialize()
sap_gui = win32com.client.GetObject("SAPGUI")
sap_app = sap_gui.GetScriptingEngine
sap_conn = sap_app.Children(0)
sap_session = sap_conn.Children(0)
sap_session.StartTransaction("FB03")
pythoncom.CoUninitialize()

Receive data from host computer using Circuit Python on Circuit Playground Express

I am using a Circuit Playground Express from Adafruit, and I'm programming it with Circuit Python.
I want to read data transmitted from the computer to which the Circuit Playground Express is connected via USB. Using input() works fine, but I would rather get the buffer of the serial instead, so that the loop would go on while there's no input. Something like serial.read().
import serial does not work on Circuit Python, or maybe I must install something. Is there anything else I could do to read the serial buffer using Circuit Python?
Aiden's answer lead me in the right direction and I found a nice (and slightly different) example of how to use supervisor.runtime.serial_bytes_available from Adafruit here (specifically lines 89-95): https://learn.adafruit.com/AT-Hand-Raiser/circuitpython-code
A minimum working example for code.py that takes the input and formats a new string in the form "RX: string" is
import supervisor
print("listening...")
while True:
if supervisor.runtime.serial_bytes_available:
value = input().strip()
# Sometimes Windows sends an extra (or missing) newline - ignore them
if value == "":
continue
print("RX: {}".format(value))
Tested on: Adafruit CircuitPython 4.1.0 on 2019-08-02; Adafruit ItsyBitsy M0 Express with samd21g18. Messages sent using the serial connection in mu-editor on macOS.
Sample output
main.py output:
listening...
hello!
RX: hello!
I got a simple example to work based on above posts, not sure how stable or useful it is, but still posting it here:
CircuitPython Code:
import supervisor
while True:
if supervisor.runtime.serial_bytes_available:
value = input().strip()
print(f"Received: {value}\r")
PC Code
import time
import serial
ser = serial.Serial('COM6', 115200) # open serial port
command = b'hello\n\r'
print(f"Sending Command: [{command}]")
ser.write(command) # write a string
ended = False
reply = b''
for _ in range(len(command)):
a = ser.read() # Read the loopback chars and ignore
while True:
a = ser.read()
if a== b'\r':
break
else:
reply += a
time.sleep(0.01)
print(f"Reply was: [{reply}]")
ser.close()
c:\circuitpythontest>python TEST1.PY
Sending Command: [b'hello\n\r']
Reply was: [b'Received: hello']
This is now somewhat possible!
In the January stable release of CircuitPython 3.1.2 the function serial_bytes_available was added to the supervisor module.
This allows you to poll the availability of serial bytes.
For example in the CircuitPython firmware (i.e. boot.py) a serial echo example would be:
import supervisor
def serial_read():
if supervisor.runtime.serial_bytes_available():
value = input()
print(value)
and ensure when you create the serial device object on the host side you set the timeout wait to be very small (i.e. 0.01).
i.e in python:
import serial
ser = serial.Serial(
'/dev/ttyACM0',
baudrate=115200,
timeout=0.01)
ser.write(b'HELLO from CircuitPython\n')
x = ser.readlines()
print("received: {}".format(x))

Twisted IRC Bot connection lost repeatedly to localhost

I am trying to implement an IRC Bot on a local server. The bot that I am using is identical to the one found at Eric Florenzano's Blog. This is the simplified code (which should run)
import sys
import re
from twisted.internet import reactor
from twisted.words.protocols import irc
from twisted.internet import protocol
class MomBot(irc.IRCClient):
def _get_nickname(self):
return self.factory.nickname
nickname = property(_get_nickname)
def signedOn(self):
print "attempting to sign on"
self.join(self.factory.channel)
print "Signed on as %s." % (self.nickname,)
def joined(self, channel):
print "attempting to join"
print "Joined %s." % (channel,)
def privmsg(self, user, channel, msg):
if not user:
return
if self.nickname in msg:
msg = re.compile(self.nickname + "[:,]* ?", re.I).sub('', msg)
prefix = "%s: " % (user.split('!', 1)[0], )
else:
prefix = ''
self.msg(self.factory.channel, prefix + "hello there")
class MomBotFactory(protocol.ClientFactory):
protocol = MomBot
def __init__(self, channel, nickname='YourMomDotCom', chain_length=3,
chattiness=1.0, max_words=10000):
self.channel = channel
self.nickname = nickname
self.chain_length = chain_length
self.chattiness = chattiness
self.max_words = max_words
def startedConnecting(self, connector):
print "started connecting on {0}:{1}"
.format(str(connector.host),str(connector.port))
def clientConnectionLost(self, connector, reason):
print "Lost connection (%s), reconnecting." % (reason,)
connector.connect()
def clientConnectionFailed(self, connector, reason):
print "Could not connect: %s" % (reason,)
if __name__ == "__main__":
chan = sys.argv[1]
reactor.connectTCP("localhost", 6667, MomBotFactory('#' + chan,
'YourMomDotCom', 2, chattiness=0.05))
reactor.run()
I added the startedConnection method in the client factory, which it is reaching and printing out the proper address:host. It then disconnects and enters the clientConnectionLost and prints the error:
Lost connection ([Failure instance: Traceback (failure with no frames):
<class 'twisted.internet.error.ConnectionDone'>: Connection was closed cleanly.
]), reconnecting.
If working properly it should log into the appropriate channel, specified as the first arg in the command (e.g. python module2.py botwar. would be channel #botwar.). It should respond with "hello there" if any one in the channel sends anything.
I have NGIRC running on the server, and it works if I connect from mIRC or any other IRC client.
I am unable to find a resolution as to why it is continually disconnecting. Any help on why would be greatly appreciated. Thank you!
One thing you may want to do is make sure you will see any error output produced by the server when your bot connects to it. My hunch is that the problem has something to do with authentication, or perhaps an unexpected difference in how ngirc handles one of the login/authentication commands used by IRCClient.
One approach that almost always applies is to capture a traffic log. Use a tool like tcpdump or wireshark.
Another approach you can try is to enable logging inside the Twisted application itself. Use twisted.protocols.policies.TrafficLoggingFactory for this:
from twisted.protocols.policies import TrafficLoggingFactory
appFactory = MomBotFactory(...)
logFactory = TrafficLoggingFactory(appFactory, "irc-")
reactor.connectTCP(..., logFactory)
This will log output to files starting with "irc-" (a different file for each connection).
You can also hook directly into your protocol implementation, at any one of several levels. For example, to display any bytes received at all:
class MomBot(irc.IRCClient):
def dataReceived(self, bytes):
print "Got", repr(bytes)
# Make sure to up-call - otherwise all of the IRC logic is disabled!
return irc.IRCClient.dataReceived(self, bytes)
With one of those approaches in place, hopefully you'll see something like:
:irc.example.net 451 * :Connection not registered
which I think means... you need to authenticate? Even if you see something else, hopefully this will help you narrow in more closely on the precise cause of the connection being closed.
Also, you can use tcpdump or wireshark to capture the traffic log between ngirc and one of the working IRC clients (eg mIRC) and then compare the two logs. Whatever different commands mIRC is sending should make it clear what changes you need to make to your bot.