【发布时间】:2016-04-12 04:48:27
【问题描述】:
我正在制作小型应用程序,它将使用 chrome 打包应用程序从 USB 设备获取输入数据。想法是,当我按下 USB 设备上的按钮时,它将接收传入流量,对其进行分析并根据输入做出反应。 我从在线教程/代码中尝试了几种设备和技术,并遇到了很多问题,但在解决了这些问题后,我终于开始使用索尼 playstation 3 pad。设备是通过隐藏连接的,但这就是我所能完成的。按下任何按钮都不会输入任何输入,到目前为止我不知道这是什么原因。 Stackoverflow、谷歌手册和互联网似乎对此没有任何答案。这是我的代码:
manifest.json:
{
"manifest_version": 2,
"name": "HID Input Analyzer",
"version": "1.0",
"app": {
"background": {
"scripts": [ "background.js" ],
"persistent": true
}
},
"permissions": ["hid", {
"usbDevices": [
{ "vendorId": 1356 , "productId": 616 }
]
}
]
}
background.js
chrome.app.runtime.onLaunched.addListener(function() {
chrome.app.window.create('mychromeapp.html', {
singleton: true,
id: "Input analyzer"
});
});
mychromeapp.html
<!DOCTYPE html>
<html>
<head>
<title>HID Input Analyzer</title>
</head>
<body>
<input type="text" id="mytext" />
<script src="mychromeapp.js"></script>
</body>
</html>
mychromeapp.js
var MY_HID_VENDOR_ID = 0x09da; // 4660 in hexadecimal!
var MY_HID_PRODUCT_ID = 0x8090;
var DEVICE_INFO = {"vendorId": MY_HID_VENDOR_ID, "productId": MY_HID_PRODUCT_ID };
var connectionId = null;
function arrayBufferToString(array) {
return String.fromCharCode.apply(null, new Uint8Array(array));
}
var myDevicePoll = function() {
var size = 64;
var i = 0;
if (chrome.runtime.lastError) {console.log(chrome.runtime.lastError);}
chrome.hid.receive(connectionId, function(data) {
console.log("::" + connectionId);
if (data != null) {
// Convert Byte into Ascii to follow the format of our device
myText.value = arrayBufferToString(data);
console.log('Data: ' + myText.value);
}
setTimeout(myDevicePoll, 0);
});
}
function initializeHid(pollHid) {
// brackets are empty for purpose because permissions are given in manifest.json
chrome.hid.getDevices({}, function(devices) {
if (!devices || !devices.length) {
console.log('device not found');
if (chrome.runtime.lastError) {console.log(chrome.runtime.lastError);}
return;
}
console.log('Found device with deviceId: ' + devices[0].deviceId);
myHidDevice = devices[0].deviceId;
// Connect to the HID device
chrome.hid.connect(myHidDevice, function(connection) {
console.log('Connected to the HID device with connectionId: ' + connection.connectionId);
connectionId = connection.connectionId;
// Poll the USB HID Interrupt pipe
pollHid();
});
});
}
initializeHid(myDevicePoll);
console.log("Trying to connect to HID USB ...");
var myText = document.getElementById("mytext");
myText.value = "Ready";
控制台日志如下所示:
正在尝试连接到 HID USB ...
找到 deviceId 为 23 的设备
使用 connectionId: 31 连接到 HID 设备
在分析我的代码(尤其是最后一个文件)后,我猜 chrome.hid.receive 函数没有从设备获取任何数据,但我不知道为什么。不幸的是,谷歌的手册做得很差,缺乏好的例子使得编码变得困难。我希望有人可以帮助我解决问题 - 我已经坐了 3 天了:(
卡雷格。
【问题讨论】:
标签: javascript google-chrome usb google-chrome-app hid