Skip to content

Commit

Permalink
feat: add package with web-HID support
Browse files Browse the repository at this point in the history
  • Loading branch information
nytamin committed Apr 27, 2021
1 parent d5bffc1 commit 1f27199
Show file tree
Hide file tree
Showing 15 changed files with 458 additions and 0 deletions.
3 changes: 3 additions & 0 deletions packages/webhid-demo/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
FROM nginx

COPY dist /usr/share/nginx/html
21 changes: 21 additions & 0 deletions packages/webhid-demo/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2017 SuperFly.tv

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
31 changes: 31 additions & 0 deletions packages/webhid-demo/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"name": "@xkeys/webhid-demo",
"version": "5.0.0-alpha.0",
"private": true,
"license": "MIT",
"homepage": "https://github.com/SuperFlyTV/xkeys#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/SuperFlyTV/xkeys.git"
},
"bugs": {
"url": "https://github.com/SuperFlyTV/xkeys/issues"
},
"author": {
"name": "Johan Nyman",
"email": "[email protected]",
"url": "https://github.com/nytamin"
},
"scripts": {
"start": "webpack serve --mode development --color",
"build": "rimraf dist && cross-env NODE_ENV=production webpack --progress"
},
"dependencies": {
"@xkeys/webhid": "*",
"buffer": "^6.0.3"
},
"devDependencies": {
"copy-webpack-plugin": "^7.0.0",
"ts-loader": "^8.0.17"
}
}
37 changes: 37 additions & 0 deletions packages/webhid-demo/public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<!DOCTYPE>
<html lang="en">

<head>
<title>X-keys WebHID demo</title>
</head>

<body>
<h1>X-keys WebHID demo</h1>
<h3>
Based on <a href="https://github.com/SuperFlyTV/xkeys">@xkeys</a>
</h3>
<h3>
Getting started
</h3>
<p>Requirements:</p>
<ul>
<li>Chrome &gt; 89 (enabled by default)</li>
<li>Chrome &lt; 89: Go to <b>chrome://flags</b> and enable "Experimental Web Platform features", then restart your
browser</li>
</ul>
<p>
<i>Note: For linux, you need to ensure udev is setup with the correct device permissions for the hidraw driver.</i>
</p>
<p>
<button href="#" id="consent-button">Select device</button>
</p>
<p>
<button href="#" id="close-button">Close device</button>
</p>

<div id="log" style="white-space: pre; background: #ffffff; border: 1px solid grey;"></div>

<script src="app.js" type="text/javascript"></script>
</body>

</html>
72 changes: 72 additions & 0 deletions packages/webhid-demo/src/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { getOpenedXKeysPanels, requestXkeysPanels, setupXkeysPanel, XKeys } from '@xkeys/webhid'

function appendLog(str: string) {
const logElm = document.getElementById('log')
if (logElm) {
logElm.textContent = `${str}\n${logElm.textContent}`
}
}

let currentXkeys: XKeys | null = null

async function openDevice(device: HIDDevice): Promise<void> {
const xkeys = await setupXkeysPanel(device)

currentXkeys = xkeys

appendLog(`Connected to "${xkeys.info.name}"`)

xkeys.on('down', (btnIndex: number) => {
appendLog(`Button ${btnIndex} down`)
xkeys.setBacklight(btnIndex, 'blue')
})
xkeys.on('up', (btnIndex: number) => {
appendLog(`Button ${btnIndex} up`)
xkeys.setBacklight(btnIndex, null)
})
}

window.addEventListener('load', async () => {
appendLog('Page loaded')

// Attempt to open a previously selected device:
const devices = await getOpenedXKeysPanels()
if (devices.length > 0) {
appendLog(`"${devices[0].productName}" already granted in a previous session`)
console.log(devices[0])
openDevice(devices[0]).catch(console.error)
}
})

const consentButton = document.getElementById('consent-button')
consentButton?.addEventListener('click', async () => {
if (currentXkeys) {
appendLog('Closing device')
await currentXkeys.close()
currentXkeys = null
}
let devices: HIDDevice[]
// Prompt for a device
try {
appendLog('Asking user for permissions...')
devices = await requestXkeysPanels()
} catch (error) {
appendLog(`No device access granted: ${error}`)
return
}
if (devices.length === 0) {
appendLog('No device was selected')
return
}
appendLog(`Access granted to "${devices[0].productName}"`)
openDevice(devices[0]).catch(console.error)
})

const closeButton = document.getElementById('close-button')
closeButton?.addEventListener('click', async () => {
if (currentXkeys) {
appendLog('Closing device')
await currentXkeys.close()
currentXkeys = null
}
})
17 changes: 17 additions & 0 deletions packages/webhid-demo/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"extends": "../../tsconfig.json",
"include": [
"./src/**/*"
],
"compilerOptions": {
"outDir": "./dist",
"lib": [
"es6",
"dom"
],
"types": [
"jest",
"w3c-web-hid"
]
}
}
66 changes: 66 additions & 0 deletions packages/webhid-demo/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/* eslint-disable node/no-extraneous-require */
const path = require('path')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const { ProvidePlugin } = require('webpack')

module.exports = {
// Where to fine the source code
context: path.join(__dirname, '/src'),

// No source map for production build
devtool: 'source-map',

entry: path.join(__dirname, '/src/app.ts'),

optimization: {
// We no not want to minimize our code.
minimize: false,
},

output: {
// The destination file name concatenated with hash (generated whenever you change your code).
// The hash is really useful to let the browser knows when it should get a new bundle
// or use the one in cache
filename: 'app.js',

// The destination folder where to put the output bundle
path: path.join(__dirname, '/dist'),

// Wherever resource (css, js, img) you call <script src="..."></script>,
// or css, or img use this path as the root
publicPath: '/',

// At some point you'll have to debug your code, that's why I'm giving you
// for free a source map file to make your life easier
sourceMapFilename: 'main.map',
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
devServer: {
contentBase: path.join(__dirname, '/public'),
// match the output path
publicPath: '/',
// match the output `publicPath`
historyApiFallback: true,
},

module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/,
},
],
},

plugins: [
new CopyWebpackPlugin({
patterns: [{ from: path.join(__dirname, '/public'), to: path.join(__dirname, '/dist') }],
}),
new ProvidePlugin({
Buffer: ['buffer', 'Buffer'],
}),
],
}
21 changes: 21 additions & 0 deletions packages/webhid/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2017 SuperFly.tv

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
3 changes: 3 additions & 0 deletions packages/webhid/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# X-keys - Node.js

This folder contains the Node.js-specific implementation of the X-keys library.
8 changes: 8 additions & 0 deletions packages/webhid/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const base = require('../../jest.config.base')
const packageJson = require('./package')

module.exports = {
...base,
name: packageJson.name,
displayName: packageJson.name,
}
48 changes: 48 additions & 0 deletions packages/webhid/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
{
"name": "@xkeys/webhid",
"version": "2.0.0",
"description": "An npm module for interfacing with the X-keys in the browser",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"license": "MIT",
"homepage": "https://github.com/SuperFlyTV/xkeys",
"repository": {
"type": "git",
"url": "git+https://github.com/SuperFlyTV/xkeys.git"
},
"bugs": {
"url": "https://github.com/SuperFlyTV/xkeys/issues"
},
"author": {
"name": "Johan Nyman",
"email": "[email protected]",
"url": "https://github.com/nytamin"
},
"keywords": [
"xkeys",
"x-keys",
"hid",
"usb",
"hardware",
"interface",
"controller"
],
"scripts": {
"build": "rimraf dist && yarn build:main",
"build:main": "tsc -p tsconfig.json"
},
"files": [
"dist"
],
"dependencies": {
"@xkeys/api": "*",
"@xkeys/core": "*",
"@types/w3c-web-hid": "^1.0.0",
"buffer": "^6.0.3",
"detect-browser": "^5.2.0",
"p-queue": "^6.6.2"
},
"engines": {
"node": ">=10.10"
}
}
5 changes: 5 additions & 0 deletions packages/webhid/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export * from '@xkeys/api'
export { XKeys, describeEvent } from '@xkeys/core'

export * from './web-hid-wrapper'
export * from './methods'
Loading

0 comments on commit 1f27199

Please sign in to comment.