Web Serial library and demo (#125)

- reworked smartknobjs into separate smartknobjs-node and
smartknobjs-webserial packages
- configured CI to build and deploy webserial example to
https://scottbez1.github.io/smartknob/
This commit is contained in:
Scott Bezek 2023-06-20 00:13:25 -07:00 committed by GitHub
parent 948297fa82
commit 1d2458b28a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
62 changed files with 6135 additions and 5649 deletions

View File

@ -2,7 +2,17 @@ name: Export Electronics
on:
push:
paths:
- 'electronics'
- 'util'
- 'scripts'
- '.github/workflows/electronics.yml'
pull_request:
paths:
- 'electronics'
- 'util'
- 'scripts'
- '.github/workflows/electronics.yml'
jobs:
export-electronics:

62
.github/workflows/js.yml vendored Normal file
View File

@ -0,0 +1,62 @@
name: JS
on:
push:
paths:
- 'software/js'
- 'proto'
- '.github/workflows/js.yml'
pull_request:
paths:
- 'software/js'
- 'proto'
- '.github/workflows/js.yml'
workflow_dispatch:
permissions:
contents: read
pages: write
id-token: write
# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
concurrency:
group: "pages"
cancel-in-progress: false
jobs:
# Build job
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Set up Node
uses: actions/setup-node@v3
with:
node-version: 18
- name: Install dependencies
working-directory: software/js
run: npm ci
- name: Build
working-directory: software/js
run: PUBLIC_URL="/smartknob" npm run build
- name: Setup Pages
uses: actions/configure-pages@v3
- name: Upload artifact
uses: actions/upload-pages-artifact@v1
with:
path: './software/js/packages/example-webserial-timeline/build'
# Deployment job
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
if: github.repository == 'scottbez1/smartknob' && github.ref == 'refs/heads/master'
runs-on: ubuntu-latest
needs: build
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v2

View File

@ -2,7 +2,19 @@ name: PlatformIO CI
on:
push:
paths:
- 'firmware'
- 'proto'
- 'thirdparty/nanopb'
- 'platformio.ini'
- '.github/workflows/pio.yml'
pull_request:
paths:
- 'firmware'
- 'proto'
- 'thirdparty/nanopb'
- 'platformio.ini'
- '.github/workflows/pio.yml'
jobs:
pio-build:

View File

@ -9,4 +9,8 @@
"editor.formatOnType": false,
"editor.formatOnSave": true,
"editor.formatOnSaveMode": "file",
"files.associations": {
"cstddef": "cpp",
"limits": "cpp"
},
}

File diff suppressed because it is too large Load Diff

View File

@ -9,20 +9,23 @@
},
"scripts": {
"build": "npm run build --workspaces --if-present",
"demo": "concurrently \"npm -w demo-frontend start\" \"npm -w demo-backend start\"",
"example": "npm -w example run main"
"example-cli": "npm -w example-cli run main",
"example-webserial-basic": "npm -w example-webserial-basic run start",
"example-webserial-timeline": "npm -w example-webserial-timeline run start"
},
"author": "",
"license": "Apache-2.0",
"//": "NOTE: Workspaces listed in dependency order; intentionally not alphabetical!",
"workspaces": [
"packages/smartknobjs-proto",
"packages/smartknobjs",
"packages/demo-backend",
"packages/demo-frontend",
"packages/example"
"packages/smartknobjs-core",
"packages/smartknobjs-node",
"packages/smartknobjs-webserial",
"packages/example-cli",
"packages/example-webserial-basic",
"packages/example-webserial-timeline"
],
"devDependencies": {
"concurrently": "^7.6.0",
"eslint-config-prettier": "^8.5.0"
}
}

View File

@ -1,77 +0,0 @@
import SerialPort = require('serialport')
import {SmartKnob} from 'smartknobjs'
import {PB} from 'smartknobjs-proto'
import {Server, Socket} from 'socket.io'
const io = new Server(parseInt(process.env.PORT ?? '3001'))
const start = async () => {
const ports = await SerialPort.list()
const matchingPorts = ports.filter((portInfo) => {
// Implement a check for your device's vendor+product+serial
// (this is more robust than the alternative of just hardcoding a "path" like "/dev/ttyUSB0")
return (
(portInfo.vendorId?.toLowerCase() === '1a86'.toLowerCase() &&
portInfo.productId?.toLowerCase() === '7523'.toLowerCase()) ||
(portInfo.vendorId?.toLowerCase() === '303a'.toLowerCase() &&
portInfo.productId?.toLowerCase() === '1001'.toLowerCase())
// && portInfo.serialNumber === 'DEADBEEF'
)
})
if (matchingPorts.length < 1) {
console.error(`No smartknob usb serial port found! ${JSON.stringify(ports, undefined, 4)}`)
return
} else if (matchingPorts.length > 1) {
console.error(`Multiple smartknob usb serial ports found: ${JSON.stringify(matchingPorts, undefined, 4)}`)
return
}
const portInfo = matchingPorts[0]
console.info('Connecting to ', portInfo)
let lastLoggedState: PB.ISmartKnobState | undefined
const smartknob = new SmartKnob(portInfo.path, (message: PB.FromSmartKnob) => {
if (message.payload === 'log' && message.log) {
console.log('LOG', message.log.msg)
} else if (message.payload === 'smartknobState' && message.smartknobState) {
const state = PB.SmartKnobState.toObject(message.smartknobState as PB.SmartKnobState, {defaults: true})
io.emit('state', {pb: message.smartknobState})
if (
message.smartknobState.currentPosition !== lastLoggedState?.currentPosition ||
Math.abs((message.smartknobState.subPositionUnit ?? 0) - (lastLoggedState?.subPositionUnit ?? 0)) > 1
) {
console.log(`State:\n${JSON.stringify(state, undefined, 4)}`)
lastLoggedState = message.smartknobState
}
}
})
smartknob.sendConfig(
PB.SmartKnobConfig.create({
detentStrengthUnit: 1,
endstopStrengthUnit: 1,
position: 0,
minPosition: -5,
maxPosition: 5,
positionWidthRadians: (10 * Math.PI) / 180,
snapPoint: 1.1,
text: 'From TS!',
}),
)
let currentSocket: Socket | null = null
io.on('connection', (socket) => {
if (currentSocket !== null) {
currentSocket.disconnect(true)
}
currentSocket = socket
socket.on('set_config', (config) => {
console.log(config)
smartknob.sendConfig(config)
})
})
}
start()

View File

@ -1,43 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

View File

@ -1,25 +0,0 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View File

@ -1,15 +0,0 @@
import { ReportHandler } from 'web-vitals';
const reportWebVitals = (onPerfEntry?: ReportHandler) => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;

View File

@ -1,26 +0,0 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
]
}

View File

@ -1,5 +1,5 @@
{
"name": "example",
"name": "example-cli",
"version": "0.1.0",
"description": "SmartKnob Interface Example",
"main": "dist/index.js",
@ -14,7 +14,8 @@
"license": "Apache-2.0",
"dependencies": {
"serialport": "^9.2.4",
"smartknobjs": "^1.0.0"
"smartknobjs-proto": "^1.0.0",
"smartknobjs-webserial": "^1.0.0"
},
"devDependencies": {
"@types/serialport": "^8.0.2",

View File

@ -1,17 +1,14 @@
import SerialPort = require('serialport')
import {SmartKnob} from 'smartknobjs'
import {SmartKnobNode} from 'smartknobjs-node'
import {PB} from 'smartknobjs-proto'
const main = async () => {
const ports = await SerialPort.list()
const matchingPorts = ports.filter((portInfo) => {
// Implement a check for your device's vendor+product+serial
// (this is more robust than the alternative of just hardcoding a "path" like "/dev/ttyUSB0")
return (
portInfo.vendorId?.toLowerCase() === '1a86'.toLowerCase() &&
portInfo.productId?.toLowerCase() === '7523'.toLowerCase()
// && portInfo.serialNumber === 'DEADBEEF'
return SmartKnobNode.USB_DEVICE_FILTERS.some(
(f) =>
f.usbVendorId.toString(16) === portInfo.vendorId && f.usbProductId.toString(16) === portInfo.productId,
)
})
@ -19,22 +16,27 @@ const main = async () => {
console.error(`No smartknob usb serial port found! ${JSON.stringify(ports, undefined, 4)}`)
return
} else if (matchingPorts.length > 1) {
console.error(`Multiple smartknob usb serial ports found: ${JSON.stringify(matchingPorts, undefined, 4)}`)
console.error(
`Multiple possible smartknob usb serial ports found: ${JSON.stringify(matchingPorts, undefined, 4)}`,
)
return
}
const portInfo = matchingPorts[0]
let lastLoggedState: PB.ISmartKnobState | undefined
const smartknob = new SmartKnob(portInfo.path, (message: PB.FromSmartKnob) => {
const smartknob = new SmartKnobNode(portInfo.path, (message: PB.FromSmartKnob) => {
if (message.payload === 'log' && message.log) {
console.log('LOG', message.log.msg)
} else if (message.payload === 'smartknobState' && message.smartknobState) {
// Only log if it's a significant change (major position change, or at least 5 degrees)
const radianChange = (message.smartknobState.subPositionUnit ?? 0) * (message.smartknobState.config?.positionWidthRadians ?? 0) - (lastLoggedState?.subPositionUnit ?? 0) * (lastLoggedState?.config?.positionWidthRadians ?? 0)
const radianChange =
(message.smartknobState.subPositionUnit ?? 0) *
(message.smartknobState.config?.positionWidthRadians ?? 0) -
(lastLoggedState?.subPositionUnit ?? 0) * (lastLoggedState?.config?.positionWidthRadians ?? 0)
if (
message.smartknobState.currentPosition !== lastLoggedState?.currentPosition ||
Math.abs(radianChange)*180/Math.PI > 5
(Math.abs(radianChange) * 180) / Math.PI > 5
) {
console.log(
`State:\n${JSON.stringify(
@ -53,7 +55,7 @@ const main = async () => {
endstopStrengthUnit: 1,
position: 0,
subPositionUnit: 0,
positionNonce: Math.floor(Math.random()*255), // Pick a random nonce to force a position reset on start
positionNonce: Math.floor(Math.random() * 255), // Pick a random nonce to force a position reset on start
minPosition: 0,
maxPosition: 4,
positionWidthRadians: (10 * Math.PI) / 180,

View File

@ -1,5 +1,5 @@
{
"name": "demo-frontend",
"name": "example-webserial-basic",
"version": "0.1.0",
"private": true,
"dependencies": {
@ -19,7 +19,7 @@
"react-dom": "^18.2.0",
"react-scripts": "^5.0.1",
"smartknobjs-proto": "^1.0.0",
"socket.io-client": "^4.5.4",
"smartknobjs-webserial": "^1.0.0",
"typescript": "^4.9.3",
"web-vitals": "^2.1.4"
},
@ -49,6 +49,7 @@
},
"proxy": "http://localhost:3001",
"devDependencies": {
"@types/lodash": "^4.14.191"
"@types/lodash": "^4.14.191",
"@types/w3c-web-serial": "^1.0.3"
}
}

View File

Before

Width:  |  Height:  |  Size: 3.8 KiB

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta name="description" content="Interactive SmartKnob demo using Web Serial" />
<title>SmartKnob Demo</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>

View File

@ -0,0 +1,301 @@
import React, {useEffect, useState} from 'react'
import Typography from '@mui/material/Typography'
import Container from '@mui/material/Container'
import {PB} from 'smartknobjs-proto'
import {Box, Button, CardActions, Paper, TextField} from '@mui/material'
import {NoUndefinedField} from './util'
import {SmartKnobWebSerial} from 'smartknobjs-webserial'
type Config = NoUndefinedField<PB.ISmartKnobConfig>
const defaultConfig: Config = {
position: 0,
subPositionUnit: 0,
positionNonce: Math.floor(Math.random() * 255),
minPosition: 0,
maxPosition: 20,
positionWidthRadians: (15 * Math.PI) / 180,
detentStrengthUnit: 0.5,
endstopStrengthUnit: 1,
snapPoint: 0.7,
text: 'Hello from\nweb serial!',
detentPositions: [],
snapPointBias: 0,
}
export type AppProps = object
export const App: React.FC<AppProps> = () => {
const [smartKnob, setSmartKnob] = useState<SmartKnobWebSerial | null>(null)
const [smartKnobState, setSmartKnobState] = useState<NoUndefinedField<PB.ISmartKnobState>>(
PB.SmartKnobState.toObject(PB.SmartKnobState.create({config: PB.SmartKnobConfig.create()}), {
defaults: true,
}) as NoUndefinedField<PB.ISmartKnobState>,
)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [smartKnobConfig, setSmartKnobConfig] = useState<Config>(defaultConfig)
useEffect(() => {
console.log('send config', smartKnobConfig)
smartKnob?.sendConfig(PB.SmartKnobConfig.create(smartKnobConfig))
}, [
smartKnob,
smartKnobConfig.position,
smartKnobConfig.subPositionUnit,
smartKnobConfig.positionNonce,
smartKnobConfig.minPosition,
smartKnobConfig.maxPosition,
smartKnobConfig.positionWidthRadians,
smartKnobConfig.detentStrengthUnit,
smartKnobConfig.endstopStrengthUnit,
smartKnobConfig.snapPoint,
smartKnobConfig.text,
smartKnobConfig.detentPositions,
smartKnobConfig.snapPointBias,
])
const [pendingSmartKnobConfig, setPendingSmartKnobConfig] = useState<{[P in keyof Config]: string}>(() => {
return Object.fromEntries(Object.entries(defaultConfig).map(([key, value]) => [key, String(value)])) as {
[P in keyof Config]: string
}
})
const connectToSerial = async () => {
try {
if (navigator.serial) {
const serialPort = await navigator.serial.requestPort({
filters: SmartKnobWebSerial.USB_DEVICE_FILTERS,
})
serialPort.addEventListener('disconnect', () => {
setSmartKnob(null)
})
const smartKnob = new SmartKnobWebSerial(serialPort, (message) => {
if (message.payload === 'smartknobState' && message.smartknobState !== null) {
const state = PB.SmartKnobState.create(message.smartknobState)
const stateObj = PB.SmartKnobState.toObject(state, {
defaults: true,
}) as NoUndefinedField<PB.ISmartKnobState>
setSmartKnobState(stateObj)
} else if (message.payload === 'log' && message.log !== null) {
console.log('LOG from smartknob', message.log?.msg)
}
})
setSmartKnob(smartKnob)
const loop = smartKnob.openAndLoop()
console.log('FIXME')
smartKnob.sendConfig(PB.SmartKnobConfig.create(smartKnobConfig))
await loop
} else {
console.error('Web Serial API is not supported in this browser.')
setSmartKnob(null)
}
} catch (error) {
console.error('Error with serial port:', error)
setSmartKnob(null)
}
}
return (
<>
<Container component="main" maxWidth="lg">
<Paper variant="outlined" sx={{my: {xs: 3, md: 6}, p: {xs: 2, md: 3}}}>
<Typography component="h1" variant="h5">
Basic SmartKnob Web Serial Demo
</Typography>
{smartKnob !== null ? (
<>
<Box
component="form"
sx={{
'& .MuiTextField-root': {m: 1, width: '25ch'},
}}
noValidate
autoComplete="off"
onSubmit={(event) => {
event.preventDefault()
setSmartKnobConfig({
position: parseInt(pendingSmartKnobConfig.position) || 0,
subPositionUnit: parseFloat(pendingSmartKnobConfig.subPositionUnit) || 0,
positionNonce: parseInt(pendingSmartKnobConfig.positionNonce) || 0,
minPosition: parseInt(pendingSmartKnobConfig.minPosition) || 0,
maxPosition: parseInt(pendingSmartKnobConfig.maxPosition) || 0,
positionWidthRadians:
parseFloat(pendingSmartKnobConfig.positionWidthRadians) || 0,
detentStrengthUnit: parseFloat(pendingSmartKnobConfig.detentStrengthUnit) || 0,
endstopStrengthUnit:
parseFloat(pendingSmartKnobConfig.endstopStrengthUnit) || 0,
snapPoint: parseFloat(pendingSmartKnobConfig.snapPoint) || 0,
text: pendingSmartKnobConfig.text,
detentPositions: [],
snapPointBias: parseFloat(pendingSmartKnobConfig.snapPointBias) || 0,
})
}}
>
<TextField
label="Position"
value={pendingSmartKnobConfig.position}
type="number"
onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
setPendingSmartKnobConfig((cur) => {
return {
...cur,
position: event.target.value,
}
})
}}
/>
<TextField
label="Sub-position unit"
value={pendingSmartKnobConfig.subPositionUnit}
type="number"
onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
setPendingSmartKnobConfig((cur) => {
return {
...cur,
subPositionUnit: event.target.value,
}
})
}}
/>
<TextField
label="Position nonce"
value={pendingSmartKnobConfig.positionNonce}
type="number"
onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
setPendingSmartKnobConfig((cur) => {
return {
...cur,
positionNonce: event.target.value,
}
})
}}
/>
<br />
<TextField
label="Min position"
value={pendingSmartKnobConfig.minPosition}
type="number"
onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
setPendingSmartKnobConfig((cur) => {
return {
...cur,
minPosition: event.target.value,
}
})
}}
/>
<TextField
label="Max position"
value={pendingSmartKnobConfig.maxPosition}
type="number"
onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
setPendingSmartKnobConfig((cur) => {
return {
...cur,
maxPosition: event.target.value,
}
})
}}
/>
<br />
<TextField
label="Position width (radians)"
value={pendingSmartKnobConfig.positionWidthRadians}
type="number"
onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
setPendingSmartKnobConfig((cur) => {
return {
...cur,
positionWidthRadians: event.target.value,
}
})
}}
/>
<br />
<TextField
label="Detent strength unit"
value={pendingSmartKnobConfig.detentStrengthUnit}
type="number"
onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
setPendingSmartKnobConfig((cur) => {
return {
...cur,
detentStrengthUnit: event.target.value,
}
})
}}
/>
<TextField
label="Endstop strength unit"
value={pendingSmartKnobConfig.endstopStrengthUnit}
type="number"
onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
setPendingSmartKnobConfig((cur) => {
return {
...cur,
endstopStrengthUnit: event.target.value,
}
})
}}
/>
<br />
<TextField
label="Snap point"
value={pendingSmartKnobConfig.snapPoint}
type="number"
onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
setPendingSmartKnobConfig((cur) => {
return {
...cur,
snapPoint: event.target.value,
}
})
}}
/>
<TextField
label="Snap point bias"
value={pendingSmartKnobConfig.snapPointBias}
type="number"
onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
setPendingSmartKnobConfig((cur) => {
return {
...cur,
snapPointBias: event.target.value,
}
})
}}
/>
<br />
<TextField
label="Text"
value={pendingSmartKnobConfig.text}
multiline
onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
setPendingSmartKnobConfig((cur) => {
return {
...cur,
text: event.target.value,
}
})
}}
/>
<br />
<Button type="submit" variant="contained">
Apply
</Button>
</Box>
<pre>{JSON.stringify(smartKnobState, undefined, 2)}</pre>
</>
) : navigator.serial ? (
<CardActions>
<Button onClick={connectToSerial} variant="contained">
Connect via Web Serial
</Button>
</CardActions>
) : (
<Typography>
Sorry, Web Serial API isn't available in your browser. Try the latest version of Chrome.
</Typography>
)}
</Paper>
</Container>
</>
)
}

View File

@ -0,0 +1,22 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import {App} from './App'
import '@fontsource/roboto/300.css'
import '@fontsource/roboto/400.css'
import '@fontsource/roboto/500.css'
import '@fontsource/roboto/700.css'
import CssBaseline from '@mui/material/CssBaseline'
import {createTheme, ThemeProvider} from '@mui/material/styles'
const theme = createTheme()
const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement)
root.render(
<React.StrictMode>
<ThemeProvider theme={theme}>
<CssBaseline />
<App />
</ThemeProvider>
</React.StrictMode>,
)

View File

@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "es6",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"]
}

View File

@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

View File

@ -0,0 +1,46 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).

View File

@ -0,0 +1,55 @@
{
"name": "example-webserial-timeline",
"version": "0.1.0",
"private": true,
"dependencies": {
"@emotion/react": "^11.10.5",
"@emotion/styled": "^11.10.5",
"@fontsource/roboto": "^4.5.8",
"@mui/material": "^5.10.16",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.18.4",
"@types/react": "^18.0.25",
"@types/react-dom": "^18.0.9",
"lodash": "^4.17.21",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "^5.0.1",
"smartknobjs-proto": "^1.0.0",
"smartknobjs-webserial": "^1.0.0",
"typescript": "^4.9.3",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "PORT=3000 react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"proxy": "http://localhost:3001",
"devDependencies": {
"@types/lodash": "^4.14.191",
"@types/w3c-web-serial": "^1.0.3"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta name="description" content="Interactive SmartKnob demo using Web Serial" />
<title>SmartKnob Demo</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>

View File

@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

View File

@ -1,16 +1,15 @@
import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react'
import io from 'socket.io-client'
import Typography from '@mui/material/Typography'
import Container from '@mui/material/Container'
import ToggleButton from '@mui/material/ToggleButton'
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup'
import {PB} from 'smartknobjs-proto'
import {VideoInfo} from './types'
import {Card, CardContent} from '@mui/material'
import {Button, CardActions, Paper} from '@mui/material'
import {exhaustiveCheck, findNClosest, lerp, NoUndefinedField} from './util'
import {groupBy, parseInt} from 'lodash'
const socket = io()
import _ from 'lodash'
import {SmartKnobWebSerial} from 'smartknobjs-webserial'
const MIN_ZOOM = 0.01
const MAX_ZOOM = 60
@ -40,8 +39,7 @@ export type AppProps = {
info: VideoInfo
}
export const App: React.FC<AppProps> = ({info}) => {
const [isConnected, setIsConnected] = useState(socket.connected)
const [smartKnob, setSmartKnob] = useState<SmartKnobWebSerial | null>(null)
const [smartKnobState, setSmartKnobState] = useState<NoUndefinedField<PB.ISmartKnobState>>(
PB.SmartKnobState.toObject(PB.SmartKnobState.create({config: PB.SmartKnobConfig.create()}), {
defaults: true,
@ -65,8 +63,9 @@ export const App: React.FC<AppProps> = ({info}) => {
})
useEffect(() => {
console.log('send config', smartKnobConfig)
socket.emit('set_config', smartKnobConfig)
smartKnob?.sendConfig(PB.SmartKnobConfig.create(smartKnobConfig))
}, [
smartKnob,
smartKnobConfig.position,
smartKnobConfig.subPositionUnit,
smartKnobConfig.positionNonce,
@ -85,7 +84,7 @@ export const App: React.FC<AppProps> = ({info}) => {
currentFrame: 0,
})
const [interfaceState, setInterfaceState] = useState<InterfaceState>({
zoomTimelinePixelsPerFrame: 0.1,
zoomTimelinePixelsPerFrame: 0.3,
})
const totalPositions = Math.ceil(
@ -104,10 +103,17 @@ export const App: React.FC<AppProps> = ({info}) => {
const position = (playbackState.currentFrame * smartKnobConfig.zoomTimelinePixelsPerFrame) / PIXELS_PER_POSITION
return Math.round(position)
}, [playbackState.currentFrame, smartKnobConfig.zoomTimelinePixelsPerFrame])
const nClosestMemo = useMemo(() => {
return findNClosest(Object.keys(detentPositions).map(parseInt), scrollPositionWholeMemo, 5).sort(
const [nClosest, setNClosest] = useState<Array<number>>([])
useEffect(() => {
const calculated = findNClosest(Object.keys(detentPositions).map(parseInt), scrollPositionWholeMemo, 5).sort(
(a, b) => a - b,
)
setNClosest((cur) => {
if (_.isEqual(cur, calculated)) {
return cur
}
return calculated
})
}, [scrollPositionWholeMemo])
const changeMode = useCallback(
@ -119,11 +125,11 @@ export const App: React.FC<AppProps> = ({info}) => {
const positionWhole = Math.round(position)
const subPositionUnit = position - positionWhole
return {
position,
position: positionWhole,
subPositionUnit,
positionNonce: (curConfig.positionNonce + 1) % 256,
minPosition: 0,
maxPosition: Math.trunc(
maxPosition: Math.round(
((info.totalFrames - 1) * curConfig.zoomTimelinePixelsPerFrame) / PIXELS_PER_POSITION,
),
positionWidthRadians: (8 * Math.PI) / 180,
@ -140,7 +146,7 @@ export const App: React.FC<AppProps> = ({info}) => {
} else if (newMode === Mode.Frames) {
setSmartKnobConfig((curConfig) => {
return {
position: playbackState.currentFrame,
position: Math.floor(playbackState.currentFrame),
subPositionUnit: 0,
positionNonce: (curConfig.positionNonce + 1) % 256,
minPosition: 0,
@ -164,10 +170,10 @@ export const App: React.FC<AppProps> = ({info}) => {
positionNonce: (curConfig.positionNonce + 1) % 256,
minPosition: playbackState.currentFrame === 0 ? 0 : -6,
maxPosition: playbackState.currentFrame === info.totalFrames - 1 ? 0 : 6,
positionWidthRadians: (60 * Math.PI) / 180,
positionWidthRadians: (30 * Math.PI) / 180,
detentStrengthUnit: 1,
endstopStrengthUnit: 1,
snapPoint: 0.55,
snapPoint: 0.5,
text: Mode.Speed,
detentPositions: [],
snapPointBias: 0.4,
@ -181,6 +187,9 @@ export const App: React.FC<AppProps> = ({info}) => {
},
[detentPositions, info.totalFrames, playbackState],
)
useEffect(() => {
changeMode(Mode.Scroll)
}, [])
useEffect(() => {
if (smartKnobState.config.text === '') {
@ -222,7 +231,7 @@ export const App: React.FC<AppProps> = ({info}) => {
subPositionUnit,
positionNonce: (curConfig.positionNonce + 1) % 256,
minPosition: 0,
maxPosition: Math.trunc(
maxPosition: Math.round(
((info.totalFrames - 1) * interfaceState.zoomTimelinePixelsPerFrame) / PIXELS_PER_POSITION,
),
zoomTimelinePixelsPerFrame: interfaceState.zoomTimelinePixelsPerFrame,
@ -231,7 +240,7 @@ export const App: React.FC<AppProps> = ({info}) => {
return {
...curConfig,
...positionInfo,
detentPositions: nClosestMemo,
detentPositions: nClosest,
}
})
} else if (currentMode === Mode.Frames) {
@ -268,7 +277,7 @@ export const App: React.FC<AppProps> = ({info}) => {
}
}, [
detentPositions,
nClosestMemo,
nClosest,
info.totalFrames,
smartKnobState.config.text,
smartKnobState.currentPosition,
@ -314,90 +323,102 @@ export const App: React.FC<AppProps> = ({info}) => {
}
}, [smartKnobState.config.text, isPlaying])
// Socket.io subscription
useEffect(() => {
socket.on('connect', () => {
setIsConnected(true)
})
socket.on('disconnect', () => {
setIsConnected(false)
})
socket.on('state', (input: {pb: PB.SmartKnobState}) => {
const {pb: state} = input
const stateObj = PB.SmartKnobState.toObject(state, {
defaults: true,
}) as NoUndefinedField<PB.ISmartKnobState>
setSmartKnobState(stateObj)
})
return () => {
socket.off('connect')
socket.off('disconnect')
socket.off('state')
const connectToSerial = async () => {
try {
if (navigator.serial) {
const serialPort = await navigator.serial.requestPort({
filters: SmartKnobWebSerial.USB_DEVICE_FILTERS,
})
serialPort.addEventListener('disconnect', () => {
setSmartKnob(null)
})
const smartKnob = new SmartKnobWebSerial(serialPort, (message) => {
if (message.payload === 'smartknobState' && message.smartknobState !== null) {
const state = PB.SmartKnobState.create(message.smartknobState)
const stateObj = PB.SmartKnobState.toObject(state, {
defaults: true,
}) as NoUndefinedField<PB.ISmartKnobState>
setSmartKnobState(stateObj)
} else if (message.payload === 'log' && message.log !== null) {
console.log('LOG from smartknob', message.log?.msg)
}
})
setSmartKnob(smartKnob)
await smartKnob.openAndLoop()
} else {
console.error('Web Serial API is not supported in this browser.')
setSmartKnob(null)
}
} catch (error) {
console.error('Error with serial port:', error)
setSmartKnob(null)
}
}, [])
}
return (
<>
<Container component="main" maxWidth="md">
<Card>
<CardContent>
<Typography component="h1" variant="h5">
Video Playback Control Demo
</Typography>
{isConnected || (
<Typography component="h6" variant="h6">
[Not connected]
<Container component="main" maxWidth="lg">
<Paper variant="outlined" sx={{my: {xs: 3, md: 6}, p: {xs: 2, md: 3}}}>
<Typography component="h1" variant="h5">
Video Playback Control Demo
</Typography>
{smartKnob !== null ? (
<>
<ToggleButtonGroup
color="primary"
value={smartKnobConfig.text}
exclusive
onChange={(e, value: Mode | null) => {
if (value === null) {
return
}
changeMode(value)
}}
aria-label="Mode"
>
{Object.keys(Mode).map((mode) => (
<ToggleButton value={mode} key={mode}>
{mode}
</ToggleButton>
))}
</ToggleButtonGroup>
<Typography>
Frame {Math.trunc(playbackState.currentFrame)} / {info.totalFrames - 1}
<br />
Speed {playbackState.speed}
</Typography>
)}
<ToggleButtonGroup
color="primary"
value={smartKnobConfig.text}
exclusive
onChange={(e, value: Mode | null) => {
if (value === null) {
return
}
changeMode(value)
}}
aria-label="Mode"
>
{Object.keys(Mode).map((mode) => (
<ToggleButton value={mode} key={mode}>
{mode}
</ToggleButton>
))}
</ToggleButtonGroup>
<Timeline
info={info}
currentFrame={playbackState.currentFrame}
zoomTimelinePixelsPerFrame={interfaceState.zoomTimelinePixelsPerFrame}
adjustZoom={(factor) => {
setInterfaceState((cur) => {
const newZoom = Math.min(
Math.max(cur.zoomTimelinePixelsPerFrame * factor, MIN_ZOOM),
MAX_ZOOM,
)
console.log(factor, newZoom)
return {
...cur,
zoomTimelinePixelsPerFrame: newZoom,
}
})
}}
/>
</>
) : navigator.serial ? (
<CardActions>
<Button onClick={connectToSerial} variant="contained">
Connect via Web Serial
</Button>
</CardActions>
) : (
<Typography>
Frame {Math.trunc(playbackState.currentFrame)} / {info.totalFrames - 1}
<br />
Speed {playbackState.speed}
Sorry, Web Serial API isn't available in your browser. Try the latest version of Chrome.
</Typography>
</CardContent>
</Card>
<Timeline
info={info}
currentFrame={playbackState.currentFrame}
zoomTimelinePixelsPerFrame={interfaceState.zoomTimelinePixelsPerFrame}
adjustZoom={(factor) => {
setInterfaceState((cur) => {
const newZoom = Math.min(
Math.max(cur.zoomTimelinePixelsPerFrame * factor, MIN_ZOOM),
MAX_ZOOM,
)
console.log(factor, newZoom)
return {
...cur,
zoomTimelinePixelsPerFrame: newZoom,
}
})
}}
/>
<Card>
<CardContent>
<div>{JSON.stringify(smartKnobConfig)}</div>
</CardContent>
</Card>
)}
<pre>{JSON.stringify(smartKnobConfig, undefined, 2)}</pre>
</Paper>
</Container>
</>
)

View File

@ -1,7 +1,6 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import {App} from './App'
import reportWebVitals from './reportWebVitals'
import '@fontsource/roboto/300.css'
import '@fontsource/roboto/400.css'
import '@fontsource/roboto/500.css'
@ -27,8 +26,3 @@ root.render(
</ThemeProvider>
</React.StrictMode>,
)
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals()

View File

@ -0,0 +1 @@
/// <reference types="react-scripts" />

View File

@ -0,0 +1,29 @@
export const exhaustiveCheck = (x: never): never => {
throw new Error("Didn't expect to get here", x)
}
export const isSome = <T>(v: T | null | undefined): v is T => {
return v !== null && v !== undefined
}
export const lerp = (value: number, inMin: number, inMax: number, min: number, max: number): number => {
// Map the input value from the input range to the output range
value = ((value - inMin) / (inMax - inMin)) * (max - min) + min
// Clamp the mapped value between the minimum and maximum range
return Math.min(Math.max(value, min), max)
}
export type NoUndefinedField<T> = {
[P in keyof T]-?: NoUndefinedField<NonNullable<T[P]>>
}
export function findNClosest(numbers: number[], target: number, n: number): number[] {
// First, we sort the numbers in ascending order based on their absolute difference
// from the target number. This means that the numbers that are closest to the target
// will come first in the sorted array.
const sortedNumbers = numbers.sort((a, b) => Math.abs(a - target) - Math.abs(b - target))
// Next, we return the first N numbers from the sorted array as the N closest numbers.
return sortedNumbers.slice(0, n)
}

View File

@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "es6",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"]
}

View File

@ -1,105 +0,0 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Projects */
// "incremental": true, /* Enable incremental compilation */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es5", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
// "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "paths" :{
// "*": ["./src/typings/*", "./*"]
// },
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": ["src/typings"], /* Specify multiple folders that act like `./node_modules/@types`. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "resolveJsonModule": true, /* Enable importing .json files */
// "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
"allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
/* Emit */
"declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
"outDir": "./dist", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */
"noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
"noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
"strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
// "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
// "noUnussedParameters": true, /* Raise an error when a function parameter isn't read */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
"noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
"noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
"noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
},
"include": ["src"],
"exclude": ["node_modules"]
}

View File

@ -1,32 +1,26 @@
{
"name": "demo-backend",
"version": "0.1.0",
"description": "",
"name": "smartknobjs-core",
"version": "1.0.0",
"description": "SmartKnob Interface Core",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "tsc",
"format": "prettier --write \"**/*.+(js|ts|json)\"",
"lint": "eslint --ext .js,.ts .",
"start": "PORT=3001 ts-node src/index.ts"
"lint": "eslint --ext .js,.ts ."
},
"author": "",
"license": "Apache-2.0",
"dependencies": {
"serialport": "^9.2.4",
"smartknobjs": "^1.0.0",
"socket.io": "^4.5.4"
"crc-32": "^1.2.0",
"smartknobjs-proto": "^1.0.0"
},
"devDependencies": {
"@types/express": "^4.17.14",
"@types/node": "^18.11.10",
"@types/serialport": "^8.0.2",
"@typescript-eslint/eslint-plugin": "^5.40.1",
"@typescript-eslint/parser": "^5.40.1",
"eslint": "^8.25.0",
"nodemon": "^2.0.20",
"prettier": "^2.4.1",
"ts-node": "^10.2.1",
"typescript": "^4.9.3"
"typescript": "^4.8.4"
}
}

View File

@ -0,0 +1,43 @@
// Based on https://github.com/tcr/node-cobs/blob/master/index.js
export function encode(buf: Uint8Array) {
const dest = [0]
let code_ptr = 0
let code = 0x01
const finish = (incllast?: boolean) => {
dest[code_ptr] = code
code_ptr = dest.length
incllast !== false && dest.push(0x00)
code = 0x01
}
for (let i = 0; i < buf.length; i++) {
if (buf[i] == 0) {
finish()
} else {
dest.push(buf[i])
code += 1
if (code == 0xff) {
finish()
}
}
}
finish(false)
return Uint8Array.from(dest)
}
export function decode(buf: Uint8Array) {
const dest: number[] = []
for (let i = 0; i < buf.length; ) {
const code = buf[i++]
for (let j = 1; j < code; j++) {
dest.push(buf[i++])
}
if (code < 0xff && i < buf.length) {
dest.push(0)
}
}
return Uint8Array.from(dest)
}

View File

@ -1,5 +1,4 @@
import SerialPort = require('serialport')
import {decode as cobsDecode, encode as cobsEncode} from 'cobs'
import {encode as cobsEncode, decode as cobsDecode} from './cobs'
import * as CRC32 from 'crc-32'
import {PB} from 'smartknobjs-proto'
@ -7,85 +6,64 @@ import {PB} from 'smartknobjs-proto'
const PROTOBUF_PROTOCOL_VERSION = 1
export type MessageCallback = (message: PB.FromSmartKnob) => void
export type SendBytes = (packet: Uint8Array) => void
type QueueEntry = {
nonce: number
encodedToSmartknobPayload: Uint8Array
}
const sleep = (millis: number) => {
return new Promise((resolve) => {
setTimeout(resolve, millis)
})
}
export {cobsEncode, cobsDecode}
export class SmartKnob {
export class SmartKnobCore {
private static readonly RETRY_MILLIS = 250
private static readonly BAUD = 921600
public static readonly BAUD = 921600
public static readonly USB_DEVICE_FILTERS = [
// CH340
{
usbVendorId: 0x1a86,
usbProductId: 0x7523,
},
// ESP32-S3
{
usbVendorId: 0x303a,
usbProductId: 0x1001,
},
]
private port: SerialPort | null
private onMessage: MessageCallback
private buffer: Buffer
private sendBytes: SendBytes
private outgoingQueue: QueueEntry[] = []
private readonly outgoingQueue: QueueEntry[] = []
private lastNonce = 1
private retryTimeout: NodeJS.Timeout | null = null
private retryTimeout: ReturnType<typeof setTimeout> | null = null
protected portAvailable = false
private currentConfig: PB.SmartKnobConfig
constructor(serialPath: string | null, onMessage: MessageCallback) {
this.onMessage = onMessage
this.buffer = Buffer.alloc(0)
if (serialPath !== null) {
this.port = new SerialPort(serialPath, {
baudRate: SmartKnob.BAUD,
})
this.port.on('data', (data: Buffer) => {
this.buffer = Buffer.concat([this.buffer, data])
this.processBuffer()
})
} else {
this.port = null
}
this.currentConfig = PB.SmartKnobConfig.create({})
private buffer = new Uint8Array()
constructor(onMessage: MessageCallback, sendBytes: SendBytes) {
this.lastNonce = Math.floor(Math.random() * (2 ^ (32 - 1)))
}
/**
* Perform a hard reset of the MCU. Takes a few seconds.
*/
public async hardReset(): Promise<void> {
if (this.port === null) {
console.warn("Not connected to SmartKnob, so hard reset isn't possible")
return
}
this.outgoingQueue = []
this.port.set({rts: true, dtr: false})
await sleep(200)
this.port.set({rts: true, dtr: true})
await sleep(200)
return
this.onMessage = onMessage
this.sendBytes = sendBytes
}
public sendConfig(config: PB.SmartKnobConfig): void {
this.sendMessage(
this.enqueueMessage(
PB.ToSmartknob.create({
smartknobConfig: config,
}),
)
}
private processBuffer(): void {
protected onReceivedData(data: Uint8Array) {
this.buffer = Uint8Array.from([...this.buffer, ...data])
let i: number
// Iterate 0-delimited packets
while ((i = this.buffer.indexOf(0)) != -1) {
const raw_buffer = this.buffer.slice(0, i)
const packet = cobsDecode(raw_buffer) as Buffer
const raw_buffer = this.buffer.subarray(0, i)
const packet = cobsDecode(raw_buffer)
this.buffer = this.buffer.slice(i + 1)
if (packet.length <= 4) {
console.debug(`Received short packet ${this.buffer.slice(0, i)}`)
@ -110,14 +88,12 @@ export class SmartKnob {
console.warn(`Invalid protobuf message ${payload}`)
return
}
if (message.protocolVersion !== PROTOBUF_PROTOCOL_VERSION) {
console.warn(
`Invalid protocol version. Expected ${PROTOBUF_PROTOCOL_VERSION}, received ${message.protocolVersion}`,
)
return
}
if (message.payload === 'ack') {
const nonce = message.ack?.nonce ?? undefined
if (nonce === undefined) {
@ -126,13 +102,12 @@ export class SmartKnob {
this.handleAck(nonce)
}
}
this.onMessage(message)
}
}
private sendMessage(message: PB.ToSmartknob) {
if (this.port === null) {
private enqueueMessage(message: PB.ToSmartknob) {
if (!this.portAvailable) {
return
}
message.protocolVersion = PROTOBUF_PROTOCOL_VERSION
@ -161,12 +136,12 @@ export class SmartKnob {
this.outgoingQueue.shift()
this.serviceQueue()
} else {
console.debug(`Ignoring unexpected ack for nonce ${nonce}`)
console.log(`Ignoring unexpected ack for nonce ${nonce}`)
}
}
private serviceQueue(): void {
if (this.port === null) {
if (!this.portAvailable) {
return
}
if (this.retryTimeout !== null) {
@ -176,22 +151,33 @@ export class SmartKnob {
if (this.outgoingQueue.length === 0) {
return
}
const {encodedToSmartknobPayload: payload} = this.outgoingQueue[0]
const crc = CRC32.buf(payload)
const crcBuffer = Buffer.from([crc & 0xff, (crc >>> 8) & 0xff, (crc >>> 16) & 0xff, (crc >>> 24) & 0xff])
const packet = Buffer.concat([payload, crcBuffer])
const crcArray = [crc & 0xff, (crc >>> 8) & 0xff, (crc >>> 16) & 0xff, (crc >>> 24) & 0xff]
const encodedDelimitedPacket = Buffer.concat([cobsEncode(packet), Buffer.from([0])])
const packet = new Uint8Array(payload.length + 4)
packet.set(payload, 0)
packet.set(crcArray, payload.length)
const cobsEncodedPacket = cobsEncode(packet)
const encodedDelimitedPacket = new Uint8Array(cobsEncodedPacket.length + 1)
encodedDelimitedPacket.set(cobsEncodedPacket, 0)
encodedDelimitedPacket.set([0], cobsEncodedPacket.length)
this.retryTimeout = setTimeout(() => {
this.retryTimeout = null
console.log(`Retrying ToSmartknob...`)
this.serviceQueue()
}, SmartKnob.RETRY_MILLIS)
}, SmartKnobCore.RETRY_MILLIS)
console.debug(`Sent ${payload.length} byte packet with CRC ${(crc >>> 0).toString(16)}`)
this.port.write(encodedDelimitedPacket)
console.debug(
`Sent ${payload.length} byte payload with CRC ${(crc >>> 0).toString(16)} (${
cobsEncodedPacket.length
} bytes encoded)`,
encodedDelimitedPacket,
)
this.sendBytes(encodedDelimitedPacket)
}
}

View File

@ -0,0 +1,105 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Projects */
// "incremental": true, /* Enable incremental compilation */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es6" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
// "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
/* Modules */
"module": "commonjs" /* Specify what module code is generated. */,
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "paths" :{
// "*": ["./src/typings/*", "./*"]
// },
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": ["src/typings"], /* Specify multiple folders that act like `./node_modules/@types`. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "resolveJsonModule": true, /* Enable importing .json files */
// "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
"allowJs": true /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */,
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
/* Emit */
"declaration": true /* Generate .d.ts files from TypeScript and JavaScript files in your project. */,
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
"outDir": "./dist" /* Specify an output folder for all emitted files. */,
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */
"noEmitOnError": true /* Disable emitting files if any type checking errors are reported. */,
// "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */,
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
/* Type Checking */
"strict": true /* Enable all strict type-checking options. */,
"noImplicitAny": true /* Enable error reporting for expressions and declarations with an implied `any` type.. */,
"strictNullChecks": true /* When type checking, take into account `null` and `undefined`. */,
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
// "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
// "noUnussedParameters": true, /* Raise an error when a function parameter isn't read */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
"noImplicitReturns": true /* Enable error reporting for codepaths that do not explicitly return in a function. */,
"noFallthroughCasesInSwitch": true /* Enable error reporting for fallthrough cases in switch statements. */,
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
"noImplicitOverride": true /* Ensure overriding members in derived classes are marked with an override modifier. */,
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
},
"include": ["src"],
"exclude": ["node_modules"]
}

View File

@ -0,0 +1,19 @@
// .eslintrc
{
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 12,
"sourceType": "module"
},
"plugins": ["@typescript-eslint"],
"extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended", "prettier"],
"rules": {
"@typescript-eslint/no-unused-vars": "error",
"@typescript-eslint/consistent-type-definitions": ["error", "type"]
},
"env": {
"node": true
}
}

View File

@ -0,0 +1,10 @@
{
"printWidth": 120,
"tabWidth": 4,
"useTabs": false,
"semi": false,
"singleQuote": true,
"trailingComma": "all",
"bracketSpacing": false,
"arrowParens": "always"
}

View File

@ -1,7 +1,7 @@
{
"name": "smartknobjs",
"name": "smartknobjs-node",
"version": "1.0.0",
"description": "SmartKnob Interface Library",
"description": "SmartKnob Interface Library for Node.js",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
@ -12,13 +12,11 @@
"author": "",
"license": "Apache-2.0",
"dependencies": {
"cobs": "^0.2.1",
"crc-32": "^1.2.0",
"serialport": "^9.2.4",
"smartknobjs-core": "^1.0.0",
"smartknobjs-proto": "^1.0.0"
},
"devDependencies": {
"@types/serialport": "^8.0.2",
"@typescript-eslint/eslint-plugin": "^5.40.1",
"@typescript-eslint/parser": "^5.40.1",
"eslint": "^8.25.0",

View File

@ -0,0 +1,19 @@
import SerialPort = require('serialport')
import {MessageCallback, SmartKnobCore} from 'smartknobjs-core'
export class SmartKnobNode extends SmartKnobCore {
private port: SerialPort | null
constructor(serialPath: string, onMessage: MessageCallback) {
super(onMessage, (packet: Uint8Array) => {
this.port?.write(Buffer.from(packet))
})
this.port = new SerialPort(serialPath, {
baudRate: SmartKnobCore.BAUD,
})
this.port.on('data', (data) => {
this.onReceivedData(data)
})
this.portAvailable = true
}
}

View File

@ -0,0 +1,105 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Projects */
// "incremental": true, /* Enable incremental compilation */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es6" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
// "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
/* Modules */
"module": "commonjs" /* Specify what module code is generated. */,
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "paths" :{
// "*": ["./src/typings/*", "./*"]
// },
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": ["src/typings"], /* Specify multiple folders that act like `./node_modules/@types`. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "resolveJsonModule": true, /* Enable importing .json files */
// "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
"allowJs": true /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */,
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
/* Emit */
"declaration": true /* Generate .d.ts files from TypeScript and JavaScript files in your project. */,
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
"outDir": "./dist" /* Specify an output folder for all emitted files. */,
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */
"noEmitOnError": true /* Disable emitting files if any type checking errors are reported. */,
// "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */,
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
/* Type Checking */
"strict": true /* Enable all strict type-checking options. */,
"noImplicitAny": true /* Enable error reporting for expressions and declarations with an implied `any` type.. */,
"strictNullChecks": true /* When type checking, take into account `null` and `undefined`. */,
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
// "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
// "noUnussedParameters": true, /* Raise an error when a function parameter isn't read */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
"noImplicitReturns": true /* Enable error reporting for codepaths that do not explicitly return in a function. */,
"noFallthroughCasesInSwitch": true /* Enable error reporting for fallthrough cases in switch statements. */,
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
"noImplicitOverride": true /* Ensure overriding members in derived classes are marked with an override modifier. */,
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
},
"include": ["src"],
"exclude": ["node_modules"]
}

View File

@ -0,0 +1,19 @@
// .eslintrc
{
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 12,
"sourceType": "module"
},
"plugins": ["@typescript-eslint"],
"extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended", "prettier"],
"rules": {
"@typescript-eslint/no-unused-vars": "error",
"@typescript-eslint/consistent-type-definitions": ["error", "type"]
},
"env": {
"node": true
}
}

View File

@ -0,0 +1,10 @@
{
"printWidth": 120,
"tabWidth": 4,
"useTabs": false,
"semi": false,
"singleQuote": true,
"trailingComma": "all",
"bracketSpacing": false,
"arrowParens": "always"
}

View File

@ -0,0 +1,27 @@
{
"name": "smartknobjs-webserial",
"version": "1.0.0",
"description": "SmartKnob Interface Library for Web Serial",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "tsc",
"format": "prettier --write \"**/*.+(js|ts|json)\"",
"lint": "eslint --ext .js,.ts ."
},
"author": "",
"license": "Apache-2.0",
"dependencies": {
"smartknobjs-core": "^1.0.0",
"smartknobjs-proto": "^1.0.0"
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^5.40.1",
"@typescript-eslint/parser": "^5.40.1",
"@types/w3c-web-serial": "^1.0.3",
"eslint": "^8.25.0",
"prettier": "^2.4.1",
"ts-node": "^10.2.1",
"typescript": "^4.8.4"
}
}

View File

@ -0,0 +1,57 @@
import {MessageCallback, SmartKnobCore} from 'smartknobjs-core'
export class SmartKnobWebSerial extends SmartKnobCore {
private port: SerialPort | null
private writer: WritableStreamDefaultWriter<Uint8Array> | undefined = undefined
constructor(port: SerialPort, onMessage: MessageCallback) {
super(onMessage, (packet: Uint8Array) => {
this.writer?.write(packet).catch((e) => {
console.error('Error writing serial', e)
this.port?.close()
this.port = null
this.portAvailable = false
})
})
this.port = port
this.portAvailable = true
this.port.addEventListener('disconnect', () => {
console.log('shutting down on disconnect')
this.port = null
this.portAvailable = false
})
}
public async openAndLoop() {
if (this.port === null) {
return
}
await this.port.open({baudRate: SmartKnobCore.BAUD})
if (this.port.readable === null || this.port.writable === null) {
throw new Error('Port missing readable or writable!')
}
const reader = this.port.readable.getReader()
try {
this.writer = this.port.writable.getWriter()
try {
// eslint-disable-next-line no-constant-condition
while (true) {
const {value, done} = await reader.read()
if (done) {
break
}
if (value !== undefined) {
this.onReceivedData(value)
}
}
} finally {
console.log('Releasing writer')
this.writer?.releaseLock()
}
} finally {
console.log('Releasing reader')
reader.releaseLock()
}
}
}

View File

@ -0,0 +1,105 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Projects */
// "incremental": true, /* Enable incremental compilation */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es6" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
// "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
/* Modules */
"module": "commonjs" /* Specify what module code is generated. */,
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "paths" :{
// "*": ["./src/typings/*", "./*"]
// },
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": ["src/typings"], /* Specify multiple folders that act like `./node_modules/@types`. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "resolveJsonModule": true, /* Enable importing .json files */
// "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
"allowJs": true /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */,
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
/* Emit */
"declaration": true /* Generate .d.ts files from TypeScript and JavaScript files in your project. */,
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
"outDir": "./dist" /* Specify an output folder for all emitted files. */,
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */
"noEmitOnError": true /* Disable emitting files if any type checking errors are reported. */,
// "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */,
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
/* Type Checking */
"strict": true /* Enable all strict type-checking options. */,
"noImplicitAny": true /* Enable error reporting for expressions and declarations with an implied `any` type.. */,
"strictNullChecks": true /* When type checking, take into account `null` and `undefined`. */,
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
// "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
// "noUnussedParameters": true, /* Raise an error when a function parameter isn't read */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
"noImplicitReturns": true /* Enable error reporting for codepaths that do not explicitly return in a function. */,
"noFallthroughCasesInSwitch": true /* Enable error reporting for fallthrough cases in switch statements. */,
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
"noImplicitOverride": true /* Ensure overriding members in derived classes are marked with an override modifier. */,
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
},
"include": ["src"],
"exclude": ["node_modules"]
}

View File

@ -1,4 +0,0 @@
declare module 'cobs' {
export function decode(buf: Buffer): Buffer
export function encode(buf: Buffer, zeroFrame?: boolean): Buffer
}

View File

@ -1,105 +0,0 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Projects */
// "incremental": true, /* Enable incremental compilation */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es5", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
// "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "paths" :{
// "*": ["./src/typings/*", "./*"]
// },
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": ["src/typings"], /* Specify multiple folders that act like `./node_modules/@types`. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "resolveJsonModule": true, /* Enable importing .json files */
// "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
"allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
/* Emit */
"declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
"outDir": "./dist", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */
"noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
"noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
"strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
// "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
// "noUnussedParameters": true, /* Raise an error when a function parameter isn't read */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
"noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
"noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
"noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
},
"include": ["src"],
"exclude": ["node_modules"]
}