Getting input report in pywinusb - pywinusb

I am using pywinusb to send/get data from Custom HID device. I can successfully send data but cant get it. Any suggestions? I tried to debug using Microsoft Message Analyzer and can see the data there but not in the script. Product/Vendor Ids, report id etc are correct.
Here the code,
from pywinusb import hid
from time import sleep
devicefilter = hid.HidDeviceFilter(vendor_id=0x0483, product_id=0x572A)
devices = devicefilter.get_devices()
print ("devices:", devices)
hid_device = devices[0]
print ("hid_device:", hid_device)
hid_device.open()
out_report = hid_device.find_output_reports()
in_report = hid_device.find_input_reports()
print("out_report:", out_report)
print("out_report[0]:",out_report[0])
print("in_report:", in_report)
print("in_report[0]:",in_report[0])
txBuffer = [0x55] * 64
txBuffer[0] = 0x01 # Report ID
rxBuffer = [0x00] * 64
rxBuffer[0] = 0x02 # Report ID
print(txBuffer)
print(rxBuffer)
out_report[0].set_raw_data(txBuffer)
in_report[0].set_raw_data(rxBuffer)
while 1:
out_report[0].send()
rxBuffer = in_report[0].get()
print("rxBuffer:", rxBuffer)
sleep(1)
hid_device.close()

I'm no expert on this my self but I have a similar sounding application Here is what I do. I don't explicitly create an input report but rather attach an input report handler to the usb receive buffer.
import pywinusb.hid as hid
# handler called when a report is received
def rx_handler(data):
print 'recv: ', data
def scan_hiddevice():
""" Scans for and returns the HID device. """
devices = hid.HidDeviceFilter( vendor_id = vendor_id).get_devices()
if not devices:
print "scan_hiddevice: No device connected."
return None
else:
device = devices[0]
#print("scan_hiddevice: found %s", device )
return device
return None
def setup_hiddevice():
"""Creates a new HID device, opens it and attaches a receive data handler"""
hid_device = scan_hiddevice()
hid_device.open()
hid_device.set_raw_data_handler(rx_handler)
return hid_device
def main(verbose=True):
hid_device = setup_hiddevice()
while (True):
#wait for data
I hope this can be of some use.

Related

How use "android.net.wifi.NetworkSpecifier.Builder" with jnius?

The issue is:
I was using "android.net.wifi.WifiConfiguration" for connecting to WIFI like this:
Correctly Working.
from jnius import autoclass
ssid = str("ssid_name")
print("app says-->connecting to wifi:",ssid)
String = autoclass('java.lang.String')
WifiConfigure = autoclass('android.net.wifi.WifiConfiguration')
PythonActivity = autoclass('org.kivy.android.PythonActivity')
activity = PythonActivity.mActivity
service = activity.getSystemService("wifi")
WifiManager = autoclass('android.net.wifi.WifiManager')
WifiConfig = WifiConfigure()
> # # # #
Connectname = String(ssid)
connectkey = String("Wifi Password")
WifiConfig.SSID = "\""+Connectname.toString()+"\""
WifiConfig.hiddenSSID = True
WifiConfig.preSharedKey ="\""+ connectkey.toString()+"\""
added = WifiManager.addNetwork(WifiConfig)
WifiManager.enableNetwork(added, True)`
But after API 29 that java library is deprecated, and I need to deploy on Play Store the Android App Bundle with at least API 30.
So:
On site https://developer.android.com they speaking about use "android.net.wifi.NetworkSpecifier.Builder" instead of "android.net.wifi.WifiConfiguration", is there anyone to tell me how to use integrate with jnius and autoclass?
I expect python programmers to help me solve the problem
You cannot programmatically connect to Wi-Fi after API 30.

ROS fail to publish to a different message type

I wrote a node called translater that basically doesn't do anything except for translating one message type to another.
It subscribes to a the topic pose_before and publishes to another topic pose_after.
The topic pose_before is of message type "PoseWithCovarianceStamped" and pose_after is "TransformStamped".
The issue is that all values in pose_after remain 0 when they're being published, but when I try to print the values inside the callback they do respond correctly.
#!/usr/bin/env python
import rospy
from geometry_msgs.msg import PoseWithCovarianceStamped
from geometry_msgs.msg import TransformStamped
def callback(data):
TransformStamped().transform.translation.x = data.pose.pose.position.x
TransformStamped().transform.translation.y = data.pose.pose.position.y
TransformStamped().transform.translation.z = data.pose.pose.position.z
TransformStamped().transform.rotation.x = data.pose.pose.orientation.x
TransformStamped().transform.rotation.y = data.pose.pose.orientation.y
TransformStamped().transform.rotation.z = data.pose.pose.orientation.z
TransformStamped().transform.rotation.w = data.pose.pose.orientation.w
def listener():
pub = rospy.Publisher('pose_after', TransformStamped, queue_size=40)
pose_after = TransformStamped()
rospy.init_node('translater', anonymous=True)
rospy.loginfo("Publishing pose_after")
rospy.Subscriber('pose_before', PoseWithCovarianceStamped, callback)
rate = rospy.Rate(40)
pose_after.header.stamp = rospy.Time.now()
pose_after.child_frame_id = 'base_footprint'
print(pose_after.transform.translation.x) # this prints (0,0)
while not rospy.is_shutdown():
pub.publish(pose_after)
rate.sleep()
if __name__ == '__main__':
try:
listener()
except rospy.ROSInterruptException:
pass
When I put the print line in callback then it actually is able to print the correct values, so I'm wondering why the values are lost outside of the callback. I've also tried assigning a global variable inside the callback but still didn't work.

pyUSB - delayed sending to the device?

I have an ESC printer.
I made a simple script to send data to the device, but after changing the content of the script - 1x the previous version of the subtitles is printed, and then, when called again, the current one.
As if the data from the USB was cached somewhere.
How can I make some FLUSH?
test.py
usb_= Connector(showUsbDevices=False)
usb_.send(b'I LOVE YOU')
connector:
class Connector:
def __init__(self, idVendor=0x0123, idProduct=0x1234, showUsbDevices=False):
self.idVendor = idVendor
self.idProduct = idProduct
if showUsbDevices:
pass
self.device = self.FindAndConnect()
if self.device is not None:
#if self.device.is_kernel_driver_active(0):
#self.device.detach_kernel_driver(0)
#self.device.detach_kernel_driver(1)
self.device.reset()
self.device.set_configuration()
self.cfg = self.device.get_active_configuration()
data_itfs = list(usb.util.find_descriptor(self.cfg, find_all=True,custom_match=lambda e: (e.bInterfaceClass == 0xA)))
intf = data_itfs[0]
self.device.set_interface_altsetting(intf)
itf_num = intf.bInterfaceNumber
print ("inf descriptor:===============", intf)
print("numer:===============",itf_num)
self.messageOut = usb.util.find_descriptor(intf, custom_match=lambda e: not (e.bEndpointAddress & 0x80))
self.messageIn = usb.util.find_descriptor(intf, custom_match=lambda e: (e.bEndpointAddress & 0x80))
#print(">>>>>>>>>>>>>>>>>>>Message Out",self.messageOut)
#print(">>>>>>>>>>>>>>>>>>>Message In",self.messageIn)
#print(repr(self.cfg))
def __del__(self):
if self.device is not None:
usb.util.dispose_resources(self.device)
def send(self, data):
#print ("endpoint_out",self.messageOut)
if self.device is not None:
print(data.decode("IBM852"))
self.messageOut.write(data)
#self.device.write(1,data,100)
#dane = self.messageIn.read(300)
#print("IN|->",dane)
def FindAndConnect(self):
device=usb.core.find(idVendor=self.idVendor, idProduct=self.idProduct)
if device is None:
raise ValueError('Not found idVendor 0x%04x i idProduct 0x%04x' % (self.idVendor,self.idProduct))
print('Printer found idVendor 0x%04x i idProduct 0x%04x.... ' %(self.idVendor,self.idProduct))
return device
so when I run a test script that says
I LOVE YOU
I get
ILOVE YOU
when I change the inscription to
I HATE YOU and run the script
another copy is printed I LOVE YOU
and only the next start-up gives: I HATE YOU
What is it? Where's the bug?
I found it! Its:
self.device.reset() at finalizer:
def __del__(self):
if self.device is not None:
self.device.reset() ############### <<<< THIS IS THE KEY>>>> (added to all code)
usb.util.dispose_resources(self.device)

Using WaitForMultipleObjects() with ACE_SOCK_Stream - get event only when there's data

Is it possible to use WaitForMultipleObjects() with ACE_SOCK_Stream, and make it return only when there's data to read from it?
I tried to following:
// set some params
DWORD handlesCount = 1;
DWORD timeoutMs = 5 * 1000;
HANDLE* handles = new HANDLE[handlesCount];
handles[0] = sock_stream.get_handle();
while (true) {
int ret = WaitForMultipleObjects(handlesCount, handles, false, timeoutMs);
std::cout << "Result: " << ret << std::endl;
But the WaitForMultipleObjects() returns immediately the socket stream index, indicating that its ready (it prints 0 in an endless loop).
The socket is accepted via a ACE_SOCK_Acceptor (ACE_SOCK_Acceptor->accept()).
How do I make WaitForMultipleObjects() wait until the socket has data to read?
The socket handle is not suitable for use in WFMO. You should use WSAEventSelect to associate the desired event(s) with an event handle that's registered with WFMO.
Since you are also familiar with ACE, you can check the source code for ace/WFMO_Reactor.cpp, register_handler() method to see a use-case and how it works with WFMO.

Problem - Sending postscript data to printer using ExtEscape

I'm trying to send postscript data to the printer using ExtEscape, but the printer didn't respond at all for the following code (1st ExtEscape returned true. 2nd ExtEscape also returned true, but no print came out). I appreciate any help.
escapeCode = POSTSCRIPT_PASSTHROUGH;
if (bReturn = ExtEscape( printerDC, QUERYESCSUPPORT, sizeof(int),
(LPCSTR)&escapeCode, 0, NULL ) <= 0)
return;
bReturn = ExtEscape(
hdcPrint,
escapeCode,
sizeof(temp_out_ptr),
temp_out_ptr, // this contains postscript data
0,
NULL
);
Did you know using this method your data will be inserted into the middle of the drivers PostScript output.
If you want to spool a whole PostScript file directly to the printer bypassing the printer driver then you need something like this:
HANDLE ph = 0;
OpenPrinter(PrinterName, &ph, NULL);
DOC_INFO_1 di;
di.pDatatype = _T("RAW");
di.pDocName = DocumentName;
di.pOutputFile = NULL;
StartDocPrinter(ph, 1, (LPBYTE)(&di));
StartPagePrinter(ph);
DWORD dwWritten;
WritePrinter(ph, Data, LengthOfData, &dwWritten);
EndPagePrinter(ph);
EndDocPrinter(ph);
ClosePrinter(ph);

Resources