Reputation: 61
I am working on serial port communication. Requirement is to communicate with hardware through serial port using javascript. I am looking into chrome WEB-USB-API right now
Using this API I was able to connect to the device. Now I want to send commands to the connected device can someone guide me on this?
device.controlTransferOut({requestType: 'class',recipient:'interface',request: 0x22,value: 0x01,index: 0x02})
The above code is given on web-usb-api documentation page but could not get on how to send any command through it.
Any guidance related to javascript and serial port communication will be really helpful.
Upvotes: 2
Views: 3846
Reputation: 6093
Some background on the USB protocol and the USB CDC-ACM (a fancy name for "serial") protocol is necessary as context here: Control transfers send and received small amounts of data, usually to enable and disable device features. The control transfer being sent in the snippet above comes from the USB CDC-ACM protocol and is a SET_CONTROL_LINE_STATE command. When sent to an actual USB serial adapter it tells the adapter to assert the DTR signal on the serial line which allows the connected serial device to detect that the host is ready to receive data. In a device which is simply emulating a USB serial adapter, like the one this example was written for, it is simply an indication that all the host software has been initialized and it is ready for the device to send data.
Now, with that background in place it should be clear that this is not how you send your own commands to your device. The device is expecting them to be sent as data on the virtual serial port, not as control signals about its state. For this you want to use the transferOut()
function. This accepts two parameters, the first is the endpoint number on which to send the data and the second is the data itself. In the example from the blog post only the transferIn()
function is used. In this example it is reading 64 bytes from endpoint 5. While it isn't shown in the article the endpoint for sending data back to the device is endpoint 4. For your own device you should inspect the USB device descriptors to determine the appropriate endpoints for sending and receiving data. These descriptors are available under the configurations
property of the USBDevice object.
Upvotes: 3