Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4f0db8e66e | ||
|
|
7cc6e46afe | ||
|
|
7b63ff3a1a | ||
|
|
6124dee2db | ||
|
|
cbbfcdc99e | ||
|
|
b77f5f105f | ||
|
|
743424dc01 | ||
|
|
1b131d7ea7 | ||
|
|
df9ee3b57f | ||
|
|
3bd7ee8586 | ||
|
|
828f480424 | ||
|
|
e285bdb999 | ||
|
|
0b75d1c62e | ||
|
|
b02e14ecdf | ||
|
|
f135c31904 | ||
|
|
396e77ac38 | ||
|
|
17cd942148 | ||
|
|
1a44443c41 | ||
|
|
89e8545d80 | ||
|
|
f4d12e0b7a | ||
|
|
9bb2f9da74 | ||
|
|
121aeadbd8 | ||
|
|
e0046ede81 | ||
|
|
571eec24d3 | ||
|
|
0e75256520 | ||
|
|
882d7d0b5b | ||
|
|
486120d9c0 | ||
|
|
d81664ba7c | ||
|
|
3e36cc551f | ||
|
|
7e387ea541 | ||
|
|
46c9f1c722 | ||
|
|
32045ffa61 | ||
|
|
1d9e52b92f | ||
|
|
f0ed581b3d | ||
|
|
62551a2f88 | ||
|
|
d4d8d8be09 | ||
|
|
3ce8f47905 | ||
|
|
1fe10cf615 | ||
|
|
856d2ea49a | ||
|
|
d24bd93084 | ||
|
|
1802ca12fd | ||
|
|
87f6c7db95 | ||
|
|
ec0cc7d2e4 | ||
|
|
169d981e6f | ||
|
|
2fb8995e68 | ||
|
|
3a3e339aca | ||
|
|
cd2c1d73c0 | ||
|
|
d89de5e6fc | ||
|
|
8fbb9e4d9f | ||
|
|
61505c2375 | ||
|
|
8c96763a8a | ||
|
|
748a76cf06 | ||
|
|
ff6e971f62 | ||
|
|
bcff45da56 | ||
|
|
ec1a146449 | ||
|
|
63d2724f35 | ||
|
|
7c0d5af821 | ||
|
|
ca06dc025f | ||
|
|
60098bba46 | ||
|
|
358b53c0be | ||
|
|
47b90603e2 | ||
|
|
af16cd43c8 | ||
|
|
e9510bcfa0 | ||
|
|
dedc8cace4 | ||
|
|
35da7d4874 | ||
|
|
d02990d5fc | ||
|
|
dd98fe5579 | ||
|
|
7178e614b1 | ||
|
|
0029dad2f2 | ||
|
|
08b1b92f52 | ||
|
|
24d920c5bf | ||
|
|
f396a21999 | ||
|
|
2782d406dd | ||
|
|
5865cd9d21 | ||
|
|
6bc462210f | ||
|
|
f356624502 | ||
|
|
287c9c63f6 | ||
|
|
ac4933449b | ||
|
|
2a0d466cf3 | ||
|
|
0772285761 | ||
|
|
2539b9ad23 | ||
|
|
2d56431fe2 | ||
|
|
4dbeb432ec | ||
|
|
4f4d951610 | ||
|
|
3d20472c7f | ||
|
|
c502941251 | ||
|
|
885ac1e77c |
@@ -1,3 +1,80 @@
|
||||
{
|
||||
"editor.formatOnSave": true
|
||||
"editor.formatOnSave": true,
|
||||
"cmake.sourceDirectory": "${workspaceFolder}/src-serial",
|
||||
"cmake.buildDirectory": "${workspaceFolder}/src-serial/build",
|
||||
"files.associations": {
|
||||
"xstring": "cpp",
|
||||
"algorithm": "cpp",
|
||||
"atomic": "cpp",
|
||||
"bit": "cpp",
|
||||
"cctype": "cpp",
|
||||
"clocale": "cpp",
|
||||
"cmath": "cpp",
|
||||
"compare": "cpp",
|
||||
"concepts": "cpp",
|
||||
"cstddef": "cpp",
|
||||
"cstdint": "cpp",
|
||||
"cstdio": "cpp",
|
||||
"cstdlib": "cpp",
|
||||
"cstring": "cpp",
|
||||
"ctime": "cpp",
|
||||
"cwchar": "cpp",
|
||||
"exception": "cpp",
|
||||
"initializer_list": "cpp",
|
||||
"ios": "cpp",
|
||||
"iosfwd": "cpp",
|
||||
"istream": "cpp",
|
||||
"iterator": "cpp",
|
||||
"limits": "cpp",
|
||||
"memory": "cpp",
|
||||
"new": "cpp",
|
||||
"ostream": "cpp",
|
||||
"sstream": "cpp",
|
||||
"stdexcept": "cpp",
|
||||
"streambuf": "cpp",
|
||||
"string": "cpp",
|
||||
"system_error": "cpp",
|
||||
"tuple": "cpp",
|
||||
"type_traits": "cpp",
|
||||
"typeinfo": "cpp",
|
||||
"utility": "cpp",
|
||||
"vector": "cpp",
|
||||
"xfacet": "cpp",
|
||||
"xiosbase": "cpp",
|
||||
"xlocale": "cpp",
|
||||
"xlocinfo": "cpp",
|
||||
"xlocnum": "cpp",
|
||||
"xmemory": "cpp",
|
||||
"xstddef": "cpp",
|
||||
"xtr1common": "cpp",
|
||||
"xutility": "cpp",
|
||||
"array": "cpp",
|
||||
"functional": "cpp",
|
||||
"list": "cpp",
|
||||
"set": "cpp",
|
||||
"unordered_map": "cpp",
|
||||
"xhash": "cpp",
|
||||
"xtree": "cpp",
|
||||
"charconv": "cpp",
|
||||
"chrono": "cpp",
|
||||
"complex": "cpp",
|
||||
"deque": "cpp",
|
||||
"format": "cpp",
|
||||
"forward_list": "cpp",
|
||||
"iomanip": "cpp",
|
||||
"iostream": "cpp",
|
||||
"locale": "cpp",
|
||||
"map": "cpp",
|
||||
"mutex": "cpp",
|
||||
"numeric": "cpp",
|
||||
"optional": "cpp",
|
||||
"queue": "cpp",
|
||||
"ratio": "cpp",
|
||||
"stop_token": "cpp",
|
||||
"thread": "cpp",
|
||||
"xlocbuf": "cpp",
|
||||
"xlocmes": "cpp",
|
||||
"xlocmon": "cpp",
|
||||
"xloctime": "cpp"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2022 4yn
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,17 +1,81 @@
|
||||
<img align="right" alt="logo" width="100" height="100" src="public/icon.png">
|
||||
|
||||
# slidershim
|
||||
# [slidershim](https://github.com/4yn/slidershim)
|
||||
|
||||
Software adapter for various Chunithm slider controllers with a built-in Brokenithm web controller. Has support for keyboard/gamepad output and LED lighting.
|
||||
Software adapter for various Chunithm slider controllers with a built-in Brokenithm web controller. Has support for keyboard/gamepad output and LED lighting. Requires Windows 8 or later.
|
||||
|
||||
[Download link](https://github.com/4yn/slidershim/releases/latest)
|
||||
[Download link](https://github.com/4yn/slidershim/releases/latest) | [Demo Video (Brokestalgia)](https://youtu.be/1PEtBP3cOew) | [UMIGURI setup instructions](https://user-images.githubusercontent.com/8877057/175786037-c0c3238b-5032-4d69-833c-5fb147d85734.mp4)
|
||||
|
||||
<img width="300" alt="screenshot" src="res/screenshots/demo.png">
|
||||
> Starting 0.2.0, there are reports that windows defender may block this software. You may need to disable windows defender the first time you run slidershim. If you are not comfortable with this, you can [download an older version here](https://github.com/4yn/slidershim/releases/tag/v0.1.4) that is known to be OK with windows defender.
|
||||
|
||||
<img alt="screenshot" src="res/screenshots/demo.png">
|
||||
|
||||
## Changelog
|
||||
|
||||
- v0.6.0
|
||||
- Support Laverita v3. Thanks @sr1canskhsia
|
||||
- v0.5.1
|
||||
- Support SSL/wss if brokenithm used with tunnelling. Thanks @kokarare1212
|
||||
- v0.5.0
|
||||
- Support for Yubideck 3.0 firmware
|
||||
- v0.4.3
|
||||
- Make Yubideck USB reports more flexible when reading data
|
||||
- v0.4.2
|
||||
- Fix HORI Project Diva gamepad slider output order
|
||||
- v0.4.1
|
||||
- Fix misplaced checkbox label (clicking on "use DirectInput" would check "disable air" instead)
|
||||
- Make Yuancon USB reports more flexible when reading data
|
||||
- v0.4.0
|
||||
- Add DirectInput keyboard emulation using [oblitum/Interception](https://github.com/oblitum/Interception)
|
||||
- Add slide LED support for some controllers
|
||||
|
||||
<details>
|
||||
|
||||
<summary>Older changelog</summary>
|
||||
|
||||
- v0.3.1
|
||||
- Fix wrong key in UMIGURI keyboard layout
|
||||
- v0.3.0
|
||||
- Add UMIGURI LED controller server support
|
||||
- Add UMIGURI default keyboard layout
|
||||
- v0.2.8
|
||||
- Add slider only layout (no buttons) for Project Diva gamepad output
|
||||
- Add options button to Project Diva gamepad output
|
||||
- v0.2.7
|
||||
- Add HORI Project Diva gamepad output and lighting mode
|
||||
- v0.2.6
|
||||
- Add Yubideck controller support
|
||||
- Add option to change Brokenithm sever port
|
||||
- v0.2.5
|
||||
- Add 6k and 4k keyboard output options
|
||||
- Add settings for reactive LED colors
|
||||
- v0.2.4
|
||||
- Restore support for older tablet devices for brokenithm by compiling brokenithm JS with older babel preset
|
||||
- Fix keys staying pressed even after brokenithm controller is closed
|
||||
- New Brokestalgia 28k web touch controller option
|
||||
- v0.2.3
|
||||
- Fix first and last buttons not working with brokenithm
|
||||
- Add option to disable air strings for controllers
|
||||
- Add option to slow down lighting updates
|
||||
- v0.2.2
|
||||
- Retcon serial slider name
|
||||
- Fix crash on some systems due to time math
|
||||
- Add link to repo
|
||||
- v0.2.1
|
||||
- Reactive + Rainbow mode
|
||||
- Fixed byte order for serial slider lights
|
||||
- v0.2.0
|
||||
- Added support for serial slider protocol
|
||||
- Added 16 key keyboard layout
|
||||
- v0.1.4
|
||||
- Initial public release
|
||||
|
||||
</details>
|
||||
|
||||
## Setup Instructions
|
||||
|
||||
1. [Download here](https://github.com/4yn/slidershim/releases/latest)
|
||||
2. Extract to any location you like.
|
||||
2. Run the msi installer (recommended for first run) or extract zip to any location you like.
|
||||
3. Run `slidershim.exe`.
|
||||
4. Pick your input device, output method and preferred lighting.
|
||||
5. Click apply.
|
||||
@@ -29,9 +93,10 @@ Software adapter for various Chunithm slider controllers with a built-in Brokeni
|
||||
|
||||
1. Set the device option to "Brokenithm" and apply.
|
||||
2. Allow firewall access to `slidershim.exe`
|
||||
> For more info on setting up firewall, check out [instructions at brokenithm-kb](https://github.com/4yn/brokenithm-kb#setup)
|
||||
3. Connect a touch device to the same wifi or local network as your windows machine
|
||||
> Windows hotspot works too, but make sure to give "public" firewall access
|
||||
4. Open the web controller in your tablet device web browser. One of the links should work.
|
||||
4. Open the web controller in your touch device web browser. One of the links should work.
|
||||
1. Either manually type in the IP address if you know what IP it is;
|
||||
2. Or scan the generated "Broknenithm QR" to get a list of clickable links and save some typing.
|
||||
5. (Optional) Add the webpage to home screen and/or enable guided access to avoid accidentally exiting the web controller.
|
||||
@@ -40,14 +105,24 @@ Software adapter for various Chunithm slider controllers with a built-in Brokeni
|
||||
|
||||

|
||||
|
||||
Voltex layout disables air tower, Neardayo layout enables air tower.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
<details>
|
||||
<summary><strong>slidershim crashes when I am running it for the first time</strong></summary>
|
||||
|
||||
- Use the .msi installer file instead of the .zip. You may be missing some windows addons that the installer will take care of (specifically Edge WebView).
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>My controller is not recognised</strong></summary>
|
||||
|
||||
- slidershim supports the GAMO2 Tasoller on HID firmware and Yuancon Laverita v2 controllers on HID firmware.
|
||||
- slidershim supports the GAMO2 Tasoller, Yuancon Laverita v2 and ZhouSensor 大四 / Yubideck controllers on HID firmware.
|
||||
- If you are using a Tasoller controller, make sure it has the correct HID firmware installed.
|
||||
- If your hardware controller is not one of these, it will not work.
|
||||
- If you have a device that communicates using serial protocol, chances are it will work with the "Slider over Serial" option
|
||||
- Hotplug is not supported. If you plugged in the controller after starting slidershim, re-connect your controller by just clicking the "Apply" button (even if it is grey).
|
||||
|
||||
</details>
|
||||
@@ -60,6 +135,13 @@ Software adapter for various Chunithm slider controllers with a built-in Brokeni
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>Keyboard / XBOX Controller output feels sluggish</strong></summary>
|
||||
|
||||
- Increase output polling rate. This does not change how fast your controller is updated, but it does reduce lag with keyboard / XBOX controller simulation.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>The Brokenithm controller cannot be loaded</strong></summary>
|
||||
|
||||
@@ -78,6 +160,14 @@ Software adapter for various Chunithm slider controllers with a built-in Brokeni
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>slidershim 0.2.0 crashes right after I turn it on</strong></summary>
|
||||
|
||||
- I'm not sure why this happens. I suspect some cases are because of windows defender and other antivirus software stopping the process while running.
|
||||
- Try disabling antivirus or using an [older version of slidershim](https://github.com/4yn/slidershim/releases/tag/v0.1.4).
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>I am still having problems</strong></summary>
|
||||
|
||||
@@ -95,14 +185,34 @@ Software adapter for various Chunithm slider controllers with a built-in Brokeni
|
||||
|
||||
## Technical Information
|
||||
|
||||
- Built with Rust, [tauri](https://github.com/tauri-apps/tauri) + [Svelte](https://github.com/sveltejs/svelte), [rusb](https://github.com/a1ien/rusb), [hyper](https://github.com/hyperium/hyper/), [tokio-](https://github.com/snapview/tokio-tungstenite)[tungstenite](https://github.com/snapview/tungstenite-rs) and [serialport](https://crates.io/crates/serialport)
|
||||
- USB device polling is done on a dedicated thread while everything else is done on a async runtime.
|
||||
- Built with Rust, [tauri](https://github.com/tauri-apps/tauri) + [Svelte](https://github.com/sveltejs/svelte), [rusb](https://github.com/a1ien/rusb), [vigem](https://github.com/ViGEm/ViGEmClient)[-client](https://github.com/CasualX/vigem-client), [hyper](https://github.com/hyperium/hyper/), [tokio-](https://github.com/snapview/tokio-tungstenite)[tungstenite](https://github.com/snapview/tungstenite-rs), [serialport](https://crates.io/crates/serialport), [dtolnay/cxx](https://github.com/dtolnay/cxx), [wjwwood/serial](https://github.com/wjwwood/serial), [oblitum/Interception](https://github.com/oblitum/Interception) and [bozbez/interception-rs](https://github.com/bozbez/interception-rs)
|
||||
- USB device and serial polling is done on a dedicated thread while everything else is done on a async runtime.
|
||||
|
||||
### Building from Source
|
||||
|
||||
1. Install [Visual Studio Community 2019/2022](https://visualstudio.microsoft.com/vs/) with C++ developer kit
|
||||
2. Install [rustup](https://rustup.rs/) with nightly toolchain
|
||||
3. Install [node.js](https://nodejs.org/en/download/) and [yarn](https://www.npmjs.com/package/yarn)
|
||||
4. (Optional) Setup [VSCode](https://code.visualstudio.com/) with [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=matklad.rust-analyzer)
|
||||
5. Clone this repository
|
||||
6. (Optional) If using powershell, `Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass` to whitelist `yarn` script
|
||||
7. `yarn install`
|
||||
8. `yarn tauri dev` / `yarn tauri build`
|
||||
|
||||
### Repository Layout
|
||||
|
||||
- [`public`](./public) / [`src`](./src): Svelte frontend
|
||||
- [`src-tauri`](./src-tauri): Tauri adapter between frontend and backend
|
||||
- [`src-slider_io`](./src-slider_io): Backend logic for handling usb, brokenithm, output emulation and lighting.
|
||||
- [`src-wwserial`](./src-wwserial): FFI to [wjwwood/serial](https://github.com/wjwwood/serial) using [dtolnay/cxx](https://github.com/dtolnay/cxx). For some reason [serialport](https://crates.io/crates/serialport) does not work well with hardware devices, so we use this as an alternative.
|
||||
- [`src-interception`](./src-interception): Vendored [bozbez/interception-rs](https://github.com/bozbez/interception-rs) that statically links against [oblitum/Interception](https://github.com/oblitum/Interception) for DirectInput keyboard emulation.
|
||||
- [`res`](./res): Miscellaneous tools such as Brokenithm QR parser and keyboard layout visualisation.
|
||||
|
||||
## Planned Features
|
||||
|
||||
- Major:
|
||||
- Support AC slider serial protocol
|
||||
- Output and LED websocket adapters when UMIGURI comes out
|
||||
- ✅ DONE: Support AC slider serial protocol
|
||||
- ✅ DONE: Output and LED websocket adapters when UMIGURI comes out
|
||||
- QOL:
|
||||
- Documentation
|
||||
- Comprehensive logging and error handling
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
"@rollup/plugin-commonjs": "^17.0.0",
|
||||
"@rollup/plugin-node-resolve": "^11.0.0",
|
||||
"@rollup/plugin-typescript": "^8.0.0",
|
||||
"@tauri-apps/cli": "^1.0.0-beta.10",
|
||||
"@tauri-apps/cli": "^1.0.4",
|
||||
"@tsconfig/svelte": "^2.0.0",
|
||||
"rollup": "^2.3.4",
|
||||
"rollup-plugin-css-only": "^3.1.0",
|
||||
@@ -27,7 +27,7 @@
|
||||
"typescript": "^4.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "^1.0.0-beta.8",
|
||||
"@tauri-apps/api": "^1.0.2",
|
||||
"sharp": "^0.30.0",
|
||||
"sirv-cli": "^2.0.0"
|
||||
}
|
||||
|
||||
@@ -16,10 +16,6 @@ body {
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
pre {
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 1rem;
|
||||
@@ -75,10 +71,32 @@ body {
|
||||
|
||||
.main {
|
||||
margin-top: 2rem;
|
||||
height: calc(100% - 2rem);
|
||||
display: flex;
|
||||
flex-flow: column nowrap;
|
||||
align-items: stretch;
|
||||
justify-content: flex-start;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.preview-row {
|
||||
flex: 0 1;
|
||||
}
|
||||
|
||||
.options {
|
||||
padding: 0.5rem 0.25rem;
|
||||
|
||||
flex: 1 1;
|
||||
display: flex;
|
||||
flex-flow: column nowrap;
|
||||
align-items: stretch;
|
||||
justify-content: flex-start;
|
||||
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.buttons-row {
|
||||
flex: 0 1;
|
||||
}
|
||||
|
||||
.row,
|
||||
@@ -106,6 +124,10 @@ body {
|
||||
flex: 2 2 0;
|
||||
}
|
||||
|
||||
.comment {
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.serverlist {
|
||||
width: 100%;
|
||||
max-height: 5rem;
|
||||
@@ -113,6 +135,11 @@ body {
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.iplist {
|
||||
font-family: monospace;
|
||||
white-space: pre;
|
||||
}
|
||||
|
||||
input,
|
||||
select {
|
||||
width: 100%;
|
||||
@@ -156,19 +183,52 @@ button.primary {
|
||||
|
||||
.air {
|
||||
height: 2rem;
|
||||
position: relative;
|
||||
|
||||
border-radius: 0.5rem 0.5rem 0 0;
|
||||
overflow: clip;
|
||||
|
||||
background: #000;
|
||||
}
|
||||
|
||||
.air-btn, .air-led {
|
||||
height: 2rem;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
.air-led {
|
||||
flex-flow: row nowrap;
|
||||
}
|
||||
|
||||
.air-led-left, .air-led-right {
|
||||
display: flex;
|
||||
flex-flow: column-reverse nowrap;
|
||||
align-items: stretch;
|
||||
justify-content: flex-start;
|
||||
|
||||
border-radius: 0.5rem 0.5rem 0 0;
|
||||
overflow: clip;
|
||||
flex: 1;
|
||||
}
|
||||
.air-data {
|
||||
.air-led-data {
|
||||
flex: 1 0;
|
||||
}
|
||||
.air-data-0 {
|
||||
background: #000;
|
||||
|
||||
.air-led-space {
|
||||
flex: 14;
|
||||
}
|
||||
|
||||
.air-btn {
|
||||
background: #0008;
|
||||
flex-flow: column-reverse nowrap;
|
||||
}
|
||||
|
||||
.air-data {
|
||||
flex: 1 0;
|
||||
}
|
||||
.air-data-1 {
|
||||
background: #0aa;
|
||||
|
||||
@@ -1,334 +1,528 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<style>
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<style>
|
||||
body {
|
||||
max-width: 1200px;
|
||||
margin: 2rem auto;
|
||||
padding: 0 1rem;
|
||||
font: 18px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
|
||||
"Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji",
|
||||
"Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
|
||||
color: #444;
|
||||
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
h1,
|
||||
h2,
|
||||
h3 {
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
body {
|
||||
max-width: 650px;
|
||||
margin: 40px auto;
|
||||
padding: 0 10px;
|
||||
font: 18px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
|
||||
"Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji",
|
||||
"Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
|
||||
color: #444;
|
||||
}
|
||||
h1,
|
||||
h2,
|
||||
h3 {
|
||||
line-height: 1.2;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
body {
|
||||
color: #ccc;
|
||||
background: black;
|
||||
}
|
||||
a:link {
|
||||
color: #5bf;
|
||||
}
|
||||
a:visited {
|
||||
color: #ccf;
|
||||
}
|
||||
color: #ccc;
|
||||
background: black;
|
||||
}
|
||||
|
||||
.layout {
|
||||
display: grid;
|
||||
|
||||
width: 36rem;
|
||||
height: 13rem;
|
||||
margin-bottom: 2rem;
|
||||
|
||||
gap: 0.5rem;
|
||||
|
||||
grid: 1.5rem 8.5rem 2rem / 32rem 3.5rem;
|
||||
grid-template-areas:
|
||||
"t a"
|
||||
"b a"
|
||||
"e a";
|
||||
a:link {
|
||||
color: #5bf;
|
||||
}
|
||||
|
||||
.name {
|
||||
display: flex;
|
||||
flex: row nowrap;
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
|
||||
grid-area: t;
|
||||
a:visited {
|
||||
color: #ccf;
|
||||
}
|
||||
}
|
||||
|
||||
.ground {
|
||||
grid-area: b;
|
||||
display: grid;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
.layout {
|
||||
display: grid;
|
||||
|
||||
gap: 0.25rem;
|
||||
width: 36rem;
|
||||
height: 13rem;
|
||||
margin-bottom: 1rem;
|
||||
|
||||
font-size: 1.5rem;
|
||||
font-family: monospace;
|
||||
}
|
||||
gap: 0.5rem;
|
||||
|
||||
.ground div {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
grid: 1.5rem 8.5rem 2rem / 32rem 3.5rem;
|
||||
grid-template-areas:
|
||||
"t a"
|
||||
"b a"
|
||||
"e a";
|
||||
}
|
||||
|
||||
background-color: #ff04;
|
||||
}
|
||||
.name {
|
||||
display: flex;
|
||||
flex: row nowrap;
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
|
||||
.ground.ground-32 {
|
||||
grid: repeat(2, 1fr) / repeat(16, 1fr);
|
||||
}
|
||||
grid-area: t;
|
||||
}
|
||||
|
||||
.ground.ground-16 {
|
||||
grid: repeat(1, 1fr) / repeat(16, 1fr);
|
||||
}
|
||||
.ground {
|
||||
grid-area: b;
|
||||
display: grid;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
|
||||
.ground.ground-8 {
|
||||
grid: repeat(1, 1fr) / repeat(8, 1fr);
|
||||
}
|
||||
gap: 0.25rem;
|
||||
|
||||
.ground.ground-voltex {
|
||||
grid: repeat(2, 1fr) / repeat(8, 1fr);
|
||||
grid-template-areas:
|
||||
"ll lr a b c d rl rr"
|
||||
"ll lr fl fl fr fr rl rr";
|
||||
}
|
||||
font-size: 1.5rem;
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
.air {
|
||||
grid-area: a;
|
||||
.ground div {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
|
||||
display: grid;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: #ff04;
|
||||
}
|
||||
|
||||
grid: repeat(6, 1fr) / repeat(1, 1fr);
|
||||
gap: 0.25rem;
|
||||
.ground.ground-32 {
|
||||
grid: repeat(2, 1fr) / repeat(16, 1fr);
|
||||
}
|
||||
|
||||
font-family: monospace;
|
||||
}
|
||||
.ground.ground-16 {
|
||||
grid: repeat(1, 1fr) / repeat(16, 1fr);
|
||||
}
|
||||
|
||||
.air div {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
.ground.ground-8 {
|
||||
grid: repeat(1, 1fr) / repeat(8, 1fr);
|
||||
}
|
||||
|
||||
background-color: #0ff4;
|
||||
}
|
||||
.ground.ground-6 {
|
||||
grid: repeat(1, 1fr) / 3fr 2fr 3fr 3fr 2fr 3fr;
|
||||
}
|
||||
|
||||
.air.air-single {
|
||||
grid: repeat(1, 1fr) / repeat(1, 1fr);
|
||||
}
|
||||
.ground.ground-4 {
|
||||
grid: repeat(1, 1fr) / repeat(4, 1fr);
|
||||
}
|
||||
|
||||
.air.air-voltex {
|
||||
grid-template-areas:
|
||||
"rr"
|
||||
"rl"
|
||||
"rl"
|
||||
"lr"
|
||||
"lr"
|
||||
"ll";
|
||||
}
|
||||
.ground.ground-1 {
|
||||
grid: repeat(1, 1fr) / repeat(1, 1fr);
|
||||
}
|
||||
|
||||
.extra {
|
||||
grid-area: e;
|
||||
.ground.ground-voltex {
|
||||
grid: repeat(2, 1fr) / repeat(8, 1fr);
|
||||
grid-template-areas:
|
||||
"ll lr a b c d rl rr"
|
||||
"ll lr fl fl fr fr rl rr";
|
||||
}
|
||||
|
||||
display: grid;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
.ground.ground-diva {
|
||||
grid: repeat(2, 1fr) / repeat(4, 1fr);
|
||||
grid-template-areas:
|
||||
"sl sl sl sl"
|
||||
"a b c d";
|
||||
}
|
||||
|
||||
grid: repeat(1, 1fr) / repeat(3, 1fr);
|
||||
gap: 0.25rem;
|
||||
.air {
|
||||
grid-area: a;
|
||||
|
||||
font-family: monospace;
|
||||
}
|
||||
display: grid;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
|
||||
.extra div {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
grid: repeat(6, 1fr) / repeat(1, 1fr);
|
||||
gap: 0.25rem;
|
||||
|
||||
background-color: #f004;
|
||||
}
|
||||
</style>
|
||||
<title>Slidershim Layouts</title>
|
||||
</head>
|
||||
<body>
|
||||
<div class="layout">
|
||||
<div class="name">Keyboard 32-zone, Tasoller Layout</div>
|
||||
<div class="ground ground-32">
|
||||
<div>1</div>
|
||||
<div>Q</div>
|
||||
<div>2</div>
|
||||
<div>W</div>
|
||||
<div>3</div>
|
||||
<div>E</div>
|
||||
<div>4</div>
|
||||
<div>R</div>
|
||||
<div>5</div>
|
||||
<div>T</div>
|
||||
<div>6</div>
|
||||
<div>Y</div>
|
||||
<div>7</div>
|
||||
<div>U</div>
|
||||
<div>8</div>
|
||||
<div>I</div>
|
||||
<div>A</div>
|
||||
<div>Z</div>
|
||||
<div>S</div>
|
||||
<div>X</div>
|
||||
<div>D</div>
|
||||
<div>C</div>
|
||||
<div>F</div>
|
||||
<div>V</div>
|
||||
<div>G</div>
|
||||
<div>B</div>
|
||||
<div>H</div>
|
||||
<div>N</div>
|
||||
<div>J</div>
|
||||
<div>M</div>
|
||||
<div>K</div>
|
||||
<div>,</div>
|
||||
</div>
|
||||
<div class="air">
|
||||
<div>]</div>
|
||||
<div>[</div>
|
||||
<div>;</div>
|
||||
<div>.</div>
|
||||
<div>'</div>
|
||||
<div>/</div>
|
||||
</div>
|
||||
<div class="extra">
|
||||
<div>[enter]</div>
|
||||
<div>[space]</div>
|
||||
<div>[esc]</div>
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
.air div {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
|
||||
background-color: #0ff4;
|
||||
}
|
||||
|
||||
.air.air-single {
|
||||
grid: repeat(1, 1fr) / repeat(1, 1fr);
|
||||
}
|
||||
|
||||
.air.air-voltex {
|
||||
grid-template-areas:
|
||||
"rr"
|
||||
"rl"
|
||||
"rl"
|
||||
"lr"
|
||||
"lr"
|
||||
"ll";
|
||||
}
|
||||
|
||||
.extra {
|
||||
grid-area: e;
|
||||
|
||||
display: grid;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
|
||||
grid: repeat(1, 1fr) / repeat(3, 1fr);
|
||||
gap: 0.25rem;
|
||||
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
.extra div {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
|
||||
background-color: #f004;
|
||||
}
|
||||
</style>
|
||||
<title>Slidershim Layouts</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="layout">
|
||||
<div class="name">Keyboard 32-zone, Tasoller Layout</div>
|
||||
<div class="ground ground-32">
|
||||
<div>1</div>
|
||||
<div>Q</div>
|
||||
<div>2</div>
|
||||
<div>W</div>
|
||||
<div>3</div>
|
||||
<div>E</div>
|
||||
<div>4</div>
|
||||
<div>R</div>
|
||||
<div>5</div>
|
||||
<div>T</div>
|
||||
<div>6</div>
|
||||
<div>Y</div>
|
||||
<div>7</div>
|
||||
<div>U</div>
|
||||
<div>8</div>
|
||||
<div>I</div>
|
||||
<div>A</div>
|
||||
<div>Z</div>
|
||||
<div>S</div>
|
||||
<div>X</div>
|
||||
<div>D</div>
|
||||
<div>C</div>
|
||||
<div>F</div>
|
||||
<div>V</div>
|
||||
<div>G</div>
|
||||
<div>B</div>
|
||||
<div>H</div>
|
||||
<div>N</div>
|
||||
<div>J</div>
|
||||
<div>M</div>
|
||||
<div>K</div>
|
||||
<div>,</div>
|
||||
</div>
|
||||
<div class="air">
|
||||
<div>]</div>
|
||||
<div>[</div>
|
||||
<div>;</div>
|
||||
<div>.</div>
|
||||
<div>'</div>
|
||||
<div>/</div>
|
||||
</div>
|
||||
<div class="extra">
|
||||
<div>[enter]</div>
|
||||
<div>[space]</div>
|
||||
<div>[esc]</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="layout">
|
||||
<div class="name">Keyboard 32-zone, Yuancon Layout</div>
|
||||
<div class="ground ground-32">
|
||||
<div>5</div>
|
||||
<div>3</div>
|
||||
<div>1</div>
|
||||
<div>Y</div>
|
||||
<div>W</div>
|
||||
<div>U</div>
|
||||
<div>S</div>
|
||||
<div>Q</div>
|
||||
<div>O</div>
|
||||
<div>M</div>
|
||||
<div>K</div>
|
||||
<div>I</div>
|
||||
<div>G</div>
|
||||
<div>E</div>
|
||||
<div>C</div>
|
||||
<div>A</div>
|
||||
<div>6</div>
|
||||
<div>4</div>
|
||||
<div>2</div>
|
||||
<div>Z</div>
|
||||
<div>X</div>
|
||||
<div>V</div>
|
||||
<div>T</div>
|
||||
<div>R</div>
|
||||
<div>P</div>
|
||||
<div>N</div>
|
||||
<div>L</div>
|
||||
<div>J</div>
|
||||
<div>H</div>
|
||||
<div>F</div>
|
||||
<div>D</div>
|
||||
<div>B</div>
|
||||
</div>
|
||||
<div class="air">
|
||||
<div>;</div>
|
||||
<div>\</div>
|
||||
<div>]</div>
|
||||
<div>[</div>
|
||||
<div>=</div>
|
||||
<div>-</div>
|
||||
</div>
|
||||
<div class="extra">
|
||||
<div>[enter]</div>
|
||||
<div>[space]</div>
|
||||
<div>[esc]</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="layout">
|
||||
<div class="name">Keyboard 32-zone, UMIGURI Layout</div>
|
||||
<div class="ground ground-32">
|
||||
<div>1</div>
|
||||
<div>Q</div>
|
||||
<div>2</div>
|
||||
<div>W</div>
|
||||
<div>3</div>
|
||||
<div>E</div>
|
||||
<div>4</div>
|
||||
<div>R</div>
|
||||
<div>5</div>
|
||||
<div>T</div>
|
||||
<div>6</div>
|
||||
<div>Y</div>
|
||||
<div>7</div>
|
||||
<div>U</div>
|
||||
<div>8</div>
|
||||
<div>I</div>
|
||||
<div>A</div>
|
||||
<div>Z</div>
|
||||
<div>S</div>
|
||||
<div>X</div>
|
||||
<div>D</div>
|
||||
<div>C</div>
|
||||
<div>F</div>
|
||||
<div>V</div>
|
||||
<div>G</div>
|
||||
<div>B</div>
|
||||
<div>H</div>
|
||||
<div>N</div>
|
||||
<div>J</div>
|
||||
<div>M</div>
|
||||
<div>K</div>
|
||||
<div>9</div>
|
||||
</div>
|
||||
<div class="air">
|
||||
<div>.</div>
|
||||
<div>,</div>
|
||||
<div>P</div>
|
||||
<div>L</div>
|
||||
<div>O</div>
|
||||
<div>0</div>
|
||||
</div>
|
||||
<div class="extra">
|
||||
<div>[enter]</div>
|
||||
<div>[space]</div>
|
||||
<div>[esc]</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="layout">
|
||||
</div>
|
||||
|
||||
<div class="layout">
|
||||
<div class="name">Keyboard 16-zone, Linear</div>
|
||||
<div class="ground ground-16">
|
||||
<div>A</div>
|
||||
<div>Z</div>
|
||||
<div>S</div>
|
||||
<div>X</div>
|
||||
<div>D</div>
|
||||
<div>C</div>
|
||||
<div>F</div>
|
||||
<div>V</div>
|
||||
<div>G</div>
|
||||
<div>B</div>
|
||||
<div>H</div>
|
||||
<div>N</div>
|
||||
<div>J</div>
|
||||
<div>M</div>
|
||||
<div>K</div>
|
||||
<div>,</div>
|
||||
</div>
|
||||
<div class="air">
|
||||
<div>]</div>
|
||||
<div>[</div>
|
||||
<div>;</div>
|
||||
<div>.</div>
|
||||
<div>'</div>
|
||||
<div>/</div>
|
||||
</div>
|
||||
<div class="extra">
|
||||
<div>[enter]</div>
|
||||
<div>[space]</div>
|
||||
<div>[esc]</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="layout">
|
||||
<div class="name">Keyboard 8-zone, Linear</div>
|
||||
<div class="ground ground-8">
|
||||
<div>A</div>
|
||||
<div>S</div>
|
||||
<div>D</div>
|
||||
<div>F</div>
|
||||
<div>J</div>
|
||||
<div>K</div>
|
||||
<div>L</div>
|
||||
<div>;</div>
|
||||
</div>
|
||||
<div class="air air-single">
|
||||
<div>
|
||||
<span style="writing-mode: vertical-lr">[space]</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="layout">
|
||||
<div class="name">Keyboard 32-zone, Yuancon Layout</div>
|
||||
<div class="ground ground-32">
|
||||
<div>5</div>
|
||||
<div>3</div>
|
||||
<div>1</div>
|
||||
<div>Y</div>
|
||||
<div>W</div>
|
||||
<div>U</div>
|
||||
<div>S</div>
|
||||
<div>Q</div>
|
||||
<div>O</div>
|
||||
<div>M</div>
|
||||
<div>K</div>
|
||||
<div>I</div>
|
||||
<div>G</div>
|
||||
<div>E</div>
|
||||
<div>C</div>
|
||||
<div>A</div>
|
||||
<div>6</div>
|
||||
<div>4</div>
|
||||
<div>2</div>
|
||||
<div>Z</div>
|
||||
<div>X</div>
|
||||
<div>V</div>
|
||||
<div>T</div>
|
||||
<div>R</div>
|
||||
<div>P</div>
|
||||
<div>N</div>
|
||||
<div>L</div>
|
||||
<div>J</div>
|
||||
<div>H</div>
|
||||
<div>F</div>
|
||||
<div>D</div>
|
||||
<div>B</div>
|
||||
</div>
|
||||
<div class="air">
|
||||
<div>;</div>
|
||||
<div>\</div>
|
||||
<div>]</div>
|
||||
<div>[</div>
|
||||
<div>=</div>
|
||||
<div>-</div>
|
||||
</div>
|
||||
<div class="extra">
|
||||
<div>[enter]</div>
|
||||
<div>[space]</div>
|
||||
<div>[esc]</div>
|
||||
<div class="extra">
|
||||
<div>[disabled]</div>
|
||||
<div>[disabled]</div>
|
||||
<div>[disabled]</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="layout">
|
||||
<div class="name">Keyboard 6-zone, Linear</div>
|
||||
<div class="ground ground-6">
|
||||
<div>S</div>
|
||||
<div>D</div>
|
||||
<div>F</div>
|
||||
<div>J</div>
|
||||
<div>K</div>
|
||||
<div>L</div>
|
||||
</div>
|
||||
<div class="air air-single">
|
||||
<div>
|
||||
<span style="writing-mode: vertical-lr">[space]</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="layout">
|
||||
<div class="name">Keyboard 8-zone, Deemo Layout</div>
|
||||
<div class="ground ground-8">
|
||||
<div>A</div>
|
||||
<div>S</div>
|
||||
<div>D</div>
|
||||
<div>F</div>
|
||||
<div>J</div>
|
||||
<div>K</div>
|
||||
<div>L</div>
|
||||
<div>;</div>
|
||||
</div>
|
||||
<div class="air air-single">
|
||||
<div>
|
||||
<span style="writing-mode: vertical-lr">[space]</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="extra">
|
||||
<div>[disabled]</div>
|
||||
<div>[disabled]</div>
|
||||
<div>[disabled]</div>
|
||||
<div class="extra">
|
||||
<div>[disabled]</div>
|
||||
<div>[disabled]</div>
|
||||
<div>[disabled]</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="layout">
|
||||
<div class="name">Keyboard 4-zone, Linear</div>
|
||||
<div class="ground ground-4">
|
||||
<div>D</div>
|
||||
<div>F</div>
|
||||
<div>J</div>
|
||||
<div>K</div>
|
||||
</div>
|
||||
<div class="air air-single">
|
||||
<div>
|
||||
<span style="writing-mode: vertical-lr">[space]</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="layout">
|
||||
<div class="name">Keyboard 10-zone, Voltex/Neardayo Layout</div>
|
||||
<div class="ground ground-voltex">
|
||||
<div style="grid-area: ll">W</div>
|
||||
<div style="grid-area: lr">E</div>
|
||||
<div style="grid-area: rl">O</div>
|
||||
<div style="grid-area: rr">P</div>
|
||||
<div style="grid-area: a">D</div>
|
||||
<div style="grid-area: b">F</div>
|
||||
<div style="grid-area: c">J</div>
|
||||
<div style="grid-area: d">K</div>
|
||||
<div style="grid-area: fl">C</div>
|
||||
<div style="grid-area: fr">M</div>
|
||||
</div>
|
||||
<div class="air air-voltex">
|
||||
<div style="grid-area: rr">P</div>
|
||||
<div style="grid-area: rl">O</div>
|
||||
<div style="grid-area: lr">E</div>
|
||||
<div style="grid-area: ll">W</div>
|
||||
</div>
|
||||
<div class="extra">
|
||||
<div>1</div>
|
||||
<div>[esc]</div>
|
||||
<div>[enter]</div>
|
||||
<div class="extra">
|
||||
<div>[disabled]</div>
|
||||
<div>[disabled]</div>
|
||||
<div>[disabled]</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="layout">
|
||||
<div class="name">Keyboard 10-zone, Voltex/Neardayo Layout</div>
|
||||
<div class="ground ground-voltex">
|
||||
<div style="grid-area: ll">W</div>
|
||||
<div style="grid-area: lr">E</div>
|
||||
<div style="grid-area: rl">O</div>
|
||||
<div style="grid-area: rr">P</div>
|
||||
<div style="grid-area: a">D</div>
|
||||
<div style="grid-area: b">F</div>
|
||||
<div style="grid-area: c">J</div>
|
||||
<div style="grid-area: d">K</div>
|
||||
<div style="grid-area: fl">C</div>
|
||||
<div style="grid-area: fr">M</div>
|
||||
</div>
|
||||
<div class="air air-voltex">
|
||||
<div style="grid-area: rr">P</div>
|
||||
<div style="grid-area: rl">O</div>
|
||||
<div style="grid-area: lr">E</div>
|
||||
<div style="grid-area: ll">W</div>
|
||||
</div>
|
||||
<div class="extra">
|
||||
<div>1</div>
|
||||
<div>[esc]</div>
|
||||
<div>[enter]</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="layout">
|
||||
<div class="name">XBOX 360 Gamepad, Voltex/Neardayo Layout</div>
|
||||
<div class="ground ground-voltex">
|
||||
<div style="grid-area: ll">LS<br /><<</div>
|
||||
<div style="grid-area: lr">LS<br />>></div>
|
||||
<div style="grid-area: rl">RS<br /><<</div>
|
||||
<div style="grid-area: rr">RS<br />>></div>
|
||||
<div style="grid-area: a">A</div>
|
||||
<div style="grid-area: b">B</div>
|
||||
<div style="grid-area: c">X</div>
|
||||
<div style="grid-area: d">Y</div>
|
||||
<div style="grid-area: fl">LB</div>
|
||||
<div style="grid-area: fr">RB</div>
|
||||
</div>
|
||||
<div class="air air-voltex">
|
||||
<div style="grid-area: rr">RS></div>
|
||||
<div style="grid-area: rl">RS<</div>
|
||||
<div style="grid-area: lr">LS></div>
|
||||
<div style="grid-area: ll">LS<</div>
|
||||
</div>
|
||||
<div class="extra">
|
||||
<div>[start]</div>
|
||||
<div>[back]</div>
|
||||
<div>[guide]</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="layout">
|
||||
<div class="name">DS4, HORI DIVA FT ASC Layout</div>
|
||||
<div class="ground ground-diva">
|
||||
<div style="grid-area: sl">[slider]</div>
|
||||
<div style="grid-area: a">Triangle</div>
|
||||
<div style="grid-area: b">Square</div>
|
||||
<div style="grid-area: c">Cross</div>
|
||||
<div style="grid-area: d">Circle</div>
|
||||
</div>
|
||||
<div class="air air-single">
|
||||
<div>
|
||||
<span style="writing-mode: vertical-lr">[disabled]</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="layout">
|
||||
<div class="name">XBOX 360 Gamepad, Voltex/Neardayo Layout</div>
|
||||
<div class="ground ground-voltex">
|
||||
<div style="grid-area: ll">LS<br /><<</div>
|
||||
<div style="grid-area: lr">LS<br />>></div>
|
||||
<div style="grid-area: rl">RS<br /><<</div>
|
||||
<div style="grid-area: rr">RS<br />>></div>
|
||||
<div style="grid-area: a">A</div>
|
||||
<div style="grid-area: b">B</div>
|
||||
<div style="grid-area: c">X</div>
|
||||
<div style="grid-area: d">Y</div>
|
||||
<div style="grid-area: fl">LB</div>
|
||||
<div style="grid-area: fr">RB</div>
|
||||
</div>
|
||||
<div class="air air-voltex">
|
||||
<div style="grid-area: rr">RS></div>
|
||||
<div style="grid-area: rl">RS<</div>
|
||||
<div style="grid-area: lr">LS></div>
|
||||
<div style="grid-area: ll">LS<</div>
|
||||
</div>
|
||||
<div class="extra">
|
||||
<div>[start]</div>
|
||||
<div>[back]</div>
|
||||
<div>[guide]</div>
|
||||
<div class="extra">
|
||||
<div>[options]</div>
|
||||
<div>[disabled]</div>
|
||||
<div>[disabled]</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="layout">
|
||||
<div class="name">DS4, HORI DIVA FT ASC Slider Only Layout</div>
|
||||
<div class="ground ground-1">
|
||||
<div>[slider]</div>
|
||||
</div>
|
||||
<div class="air air-single">
|
||||
<div>
|
||||
<span style="writing-mode: vertical-lr">[disabled]</span>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
<div class="extra">
|
||||
<div>[options]</div>
|
||||
<div>[disabled]</div>
|
||||
<div>[disabled]</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
|
Before Width: | Height: | Size: 57 KiB After Width: | Height: | Size: 66 KiB |
|
Before Width: | Height: | Size: 26 KiB After Width: | Height: | Size: 24 KiB |
@@ -39,25 +39,22 @@
|
||||
<ul class="links"></ul>
|
||||
<script>
|
||||
(function () {
|
||||
const search = window.location.search;
|
||||
if (search.slice(0, 3) !== "?d=" || search.length <= 3) {
|
||||
return;
|
||||
}
|
||||
const ul = document.querySelector(".links");
|
||||
search
|
||||
.slice(3)
|
||||
.split(";")
|
||||
.map((x) => atob(x))
|
||||
.forEach((ip) => {
|
||||
const li = document.createElement("li");
|
||||
const a = document.createElement("a");
|
||||
a.innerText = ip;
|
||||
a.setAttribute("target", "_blank");
|
||||
a.setAttribute("rel", "noopener");
|
||||
a.href = `http://${ip}:1606/`;
|
||||
li.appendChild(a);
|
||||
ul.appendChild(li);
|
||||
});
|
||||
var params = new URLSearchParams(window.location.search);
|
||||
var d = params.get("d") || "";
|
||||
var p = params.get("p") || "1606";
|
||||
var ul = document.querySelector(".links");
|
||||
d.split(";").forEach(function (aip) {
|
||||
var ip = atob(aip);
|
||||
console.log(aip, ip);
|
||||
var li = document.createElement("li");
|
||||
var a = document.createElement("a");
|
||||
a.innerText = "".concat(ip, ":").concat(p);
|
||||
a.setAttribute("target", "_blank");
|
||||
a.setAttribute("rel", "noopener");
|
||||
a.href = "http://".concat(ip, ":").concat(p, "/");
|
||||
li.appendChild(a);
|
||||
ul.appendChild(li);
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
target/
|
||||
@@ -0,0 +1,140 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 3
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "1.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.0.73"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11"
|
||||
|
||||
[[package]]
|
||||
name = "interception"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"cc",
|
||||
"num_enum",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num_enum"
|
||||
version = "0.5.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf5395665662ef45796a4ff5486c5d41d29e0c09640af4c5f17fd94ee2c119c9"
|
||||
dependencies = [
|
||||
"num_enum_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num_enum_derive"
|
||||
version = "0.5.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3b0498641e53dd6ac1a4f22547548caa6864cc4933784319cd1775271c5a46ce"
|
||||
dependencies = [
|
||||
"proc-macro-crate",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro-crate"
|
||||
version = "1.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e17d47ce914bf4de440332250b0edd23ce48c005f59fab39d3335866b114f11a"
|
||||
dependencies = [
|
||||
"thiserror",
|
||||
"toml",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.40"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dd96a1e8ed2596c337f8eae5f24924ec83f5ad5ab21ea8e455d3566c69fbcaf7"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3bcdf212e9776fbcb2d23ab029360416bb1706b1aea2d1a5ba002727cbcab804"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.140"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc855a42c7967b7c369eb5860f7164ef1f6f81c20c7cc1141f2a604e18723b03"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.140"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6f2122636b9fe3b81f1cb25099fcf2d3f542cdb1d45940d56c713158884a05da"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "1.0.98"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c50aef8a904de4c23c788f104b7dddc7d6f79c647c7c8ce4cc8f73eb0ca773dd"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "1.0.31"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bd829fe32373d27f76265620b5309d0340cb8550f523c1dda251d6298069069a"
|
||||
dependencies = [
|
||||
"thiserror-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror-impl"
|
||||
version = "1.0.31"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0396bc89e626244658bef819e22d0cc459e795a5ebe878e6ec336d1674a8d79a"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml"
|
||||
version = "0.5.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8d82e1a7758622a465f8cee077614c73484dac5b836c02ff6a40d5d1010324d7"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "15c61ba63f9235225a22310255a29b806b907c9b8c964bcbd0a2c70f3f2deea7"
|
||||
@@ -0,0 +1,13 @@
|
||||
[package]
|
||||
name = "interception"
|
||||
version = "0.1.0"
|
||||
edition = "2018"
|
||||
publish = false
|
||||
|
||||
[build-dependencies]
|
||||
cc = "1.0"
|
||||
|
||||
[dependencies]
|
||||
bitflags = "1.2.1"
|
||||
num_enum = "0.5.0"
|
||||
serde = { version = "1.0.114", features = ["derive"] }
|
||||
@@ -0,0 +1,173 @@
|
||||
Derived from https://github.com/bozbez/interception-sys and https://github.com/bozbez/interception-rs
|
||||
|
||||
Repackaged to link statically with https://github.com/oblitum/Interception 1.0.1 instead of using dynamic library.
|
||||
|
||||
Interception is licensed under LGPL 3.0 for non-commercial use. Interception-sys and interception-rs according to its Cargo.toml are licensed under LGPL 3.0.
|
||||
|
||||
```
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
|
||||
This version of the GNU Lesser General Public License incorporates
|
||||
the terms and conditions of version 3 of the GNU General Public
|
||||
License, supplemented by the additional permissions listed below.
|
||||
|
||||
0. Additional Definitions.
|
||||
|
||||
As used herein, "this License" refers to version 3 of the GNU Lesser
|
||||
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
||||
General Public License.
|
||||
|
||||
"The Library" refers to a covered work governed by this License,
|
||||
other than an Application or a Combined Work as defined below.
|
||||
|
||||
An "Application" is any work that makes use of an interface provided
|
||||
by the Library, but which is not otherwise based on the Library.
|
||||
Defining a subclass of a class defined by the Library is deemed a mode
|
||||
of using an interface provided by the Library.
|
||||
|
||||
A "Combined Work" is a work produced by combining or linking an
|
||||
Application with the Library. The particular version of the Library
|
||||
with which the Combined Work was made is also called the "Linked
|
||||
Version".
|
||||
|
||||
The "Minimal Corresponding Source" for a Combined Work means the
|
||||
Corresponding Source for the Combined Work, excluding any source code
|
||||
for portions of the Combined Work that, considered in isolation, are
|
||||
based on the Application, and not on the Linked Version.
|
||||
|
||||
The "Corresponding Application Code" for a Combined Work means the
|
||||
object code and/or source code for the Application, including any data
|
||||
and utility programs needed for reproducing the Combined Work from the
|
||||
Application, but excluding the System Libraries of the Combined Work.
|
||||
|
||||
1. Exception to Section 3 of the GNU GPL.
|
||||
|
||||
You may convey a covered work under sections 3 and 4 of this License
|
||||
without being bound by section 3 of the GNU GPL.
|
||||
|
||||
2. Conveying Modified Versions.
|
||||
|
||||
If you modify a copy of the Library, and, in your modifications, a
|
||||
facility refers to a function or data to be supplied by an Application
|
||||
that uses the facility (other than as an argument passed when the
|
||||
facility is invoked), then you may convey a copy of the modified
|
||||
version:
|
||||
|
||||
a) under this License, provided that you make a good faith effort to
|
||||
ensure that, in the event an Application does not supply the
|
||||
function or data, the facility still operates, and performs
|
||||
whatever part of its purpose remains meaningful, or
|
||||
|
||||
b) under the GNU GPL, with none of the additional permissions of
|
||||
this License applicable to that copy.
|
||||
|
||||
3. Object Code Incorporating Material from Library Header Files.
|
||||
|
||||
The object code form of an Application may incorporate material from
|
||||
a header file that is part of the Library. You may convey such object
|
||||
code under terms of your choice, provided that, if the incorporated
|
||||
material is not limited to numerical parameters, data structure
|
||||
layouts and accessors, or small macros, inline functions and templates
|
||||
(ten or fewer lines in length), you do both of the following:
|
||||
|
||||
a) Give prominent notice with each copy of the object code that the
|
||||
Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the object code with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
4. Combined Works.
|
||||
|
||||
You may convey a Combined Work under terms of your choice that,
|
||||
taken together, effectively do not restrict modification of the
|
||||
portions of the Library contained in the Combined Work and reverse
|
||||
engineering for debugging such modifications, if you also do each of
|
||||
the following:
|
||||
|
||||
a) Give prominent notice with each copy of the Combined Work that
|
||||
the Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
c) For a Combined Work that displays copyright notices during
|
||||
execution, include the copyright notice for the Library among
|
||||
these notices, as well as a reference directing the user to the
|
||||
copies of the GNU GPL and this license document.
|
||||
|
||||
d) Do one of the following:
|
||||
|
||||
0) Convey the Minimal Corresponding Source under the terms of this
|
||||
License, and the Corresponding Application Code in a form
|
||||
suitable for, and under terms that permit, the user to
|
||||
recombine or relink the Application with a modified version of
|
||||
the Linked Version to produce a modified Combined Work, in the
|
||||
manner specified by section 6 of the GNU GPL for conveying
|
||||
Corresponding Source.
|
||||
|
||||
1) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (a) uses at run time
|
||||
a copy of the Library already present on the user's computer
|
||||
system, and (b) will operate properly with a modified version
|
||||
of the Library that is interface-compatible with the Linked
|
||||
Version.
|
||||
|
||||
e) Provide Installation Information, but only if you would otherwise
|
||||
be required to provide such information under section 6 of the
|
||||
GNU GPL, and only to the extent that such information is
|
||||
necessary to install and execute a modified version of the
|
||||
Combined Work produced by recombining or relinking the
|
||||
Application with a modified version of the Linked Version. (If
|
||||
you use option 4d0, the Installation Information must accompany
|
||||
the Minimal Corresponding Source and Corresponding Application
|
||||
Code. If you use option 4d1, you must provide the Installation
|
||||
Information in the manner specified by section 6 of the GNU GPL
|
||||
for conveying Corresponding Source.)
|
||||
|
||||
5. Combined Libraries.
|
||||
|
||||
You may place library facilities that are a work based on the
|
||||
Library side by side in a single library together with other library
|
||||
facilities that are not Applications and are not covered by this
|
||||
License, and convey such a combined library under terms of your
|
||||
choice, if you do both of the following:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work based
|
||||
on the Library, uncombined with any other library facilities,
|
||||
conveyed under the terms of this License.
|
||||
|
||||
b) Give prominent notice with the combined library that part of it
|
||||
is a work based on the Library, and explaining where to find the
|
||||
accompanying uncombined form of the same work.
|
||||
|
||||
6. Revised Versions of the GNU Lesser General Public License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions
|
||||
of the GNU Lesser General Public License from time to time. Such new
|
||||
versions will be similar in spirit to the present version, but may
|
||||
differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Library as you received it specifies that a certain numbered version
|
||||
of the GNU Lesser General Public License "or any later version"
|
||||
applies to it, you have the option of following the terms and
|
||||
conditions either of that published version or of any later version
|
||||
published by the Free Software Foundation. If the Library as you
|
||||
received it does not specify a version number of the GNU Lesser
|
||||
General Public License, you may choose any version of the GNU Lesser
|
||||
General Public License ever published by the Free Software Foundation.
|
||||
|
||||
If the Library as you received it specifies that a proxy can decide
|
||||
whether future versions of the GNU Lesser General Public License shall
|
||||
apply, that proxy's public statement of acceptance of any version is
|
||||
permanent authorization for you to choose that version for the
|
||||
Library.
|
||||
```
|
||||
@@ -0,0 +1,11 @@
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-changed=include/interception.h");
|
||||
println!("cargo:rerun-if-changed=src/interception.c");
|
||||
cc::Build::new()
|
||||
.define("INTERCEPTION_STATIC", None)
|
||||
.file("src/interception.c")
|
||||
.include("include/")
|
||||
.compile("interception");
|
||||
|
||||
println!("cargo:rustc-link-lib=static=interception");
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
#ifndef _INTERCEPTION_H_
|
||||
#define _INTERCEPTION_H_
|
||||
|
||||
#ifdef INTERCEPTION_STATIC
|
||||
#define INTERCEPTION_API
|
||||
#else
|
||||
#if defined _WIN32 || defined __CYGWIN__
|
||||
#ifdef INTERCEPTION_EXPORT
|
||||
#ifdef __GNUC__
|
||||
#define INTERCEPTION_API __attribute__((dllexport))
|
||||
#else
|
||||
#define INTERCEPTION_API __declspec(dllexport)
|
||||
#endif
|
||||
#else
|
||||
#ifdef __GNUC__
|
||||
#define INTERCEPTION_API __attribute__((dllimport))
|
||||
#else
|
||||
#define INTERCEPTION_API __declspec(dllimport)
|
||||
#endif
|
||||
#endif
|
||||
#else
|
||||
#if __GNUC__ >= 4
|
||||
#define INTERCEPTION_API __attribute__ ((visibility("default")))
|
||||
#else
|
||||
#define INTERCEPTION_API
|
||||
#endif
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define INTERCEPTION_MAX_KEYBOARD 10
|
||||
|
||||
#define INTERCEPTION_MAX_MOUSE 10
|
||||
|
||||
#define INTERCEPTION_MAX_DEVICE ((INTERCEPTION_MAX_KEYBOARD) + (INTERCEPTION_MAX_MOUSE))
|
||||
|
||||
#define INTERCEPTION_KEYBOARD(index) ((index) + 1)
|
||||
|
||||
#define INTERCEPTION_MOUSE(index) ((INTERCEPTION_MAX_KEYBOARD) + (index) + 1)
|
||||
|
||||
typedef void *InterceptionContext;
|
||||
|
||||
typedef int InterceptionDevice;
|
||||
|
||||
typedef int InterceptionPrecedence;
|
||||
|
||||
typedef unsigned short InterceptionFilter;
|
||||
|
||||
typedef int (*InterceptionPredicate)(InterceptionDevice device);
|
||||
|
||||
enum InterceptionKeyState
|
||||
{
|
||||
INTERCEPTION_KEY_DOWN = 0x00,
|
||||
INTERCEPTION_KEY_UP = 0x01,
|
||||
INTERCEPTION_KEY_E0 = 0x02,
|
||||
INTERCEPTION_KEY_E1 = 0x04,
|
||||
INTERCEPTION_KEY_TERMSRV_SET_LED = 0x08,
|
||||
INTERCEPTION_KEY_TERMSRV_SHADOW = 0x10,
|
||||
INTERCEPTION_KEY_TERMSRV_VKPACKET = 0x20
|
||||
};
|
||||
|
||||
enum InterceptionFilterKeyState
|
||||
{
|
||||
INTERCEPTION_FILTER_KEY_NONE = 0x0000,
|
||||
INTERCEPTION_FILTER_KEY_ALL = 0xFFFF,
|
||||
INTERCEPTION_FILTER_KEY_DOWN = INTERCEPTION_KEY_UP,
|
||||
INTERCEPTION_FILTER_KEY_UP = INTERCEPTION_KEY_UP << 1,
|
||||
INTERCEPTION_FILTER_KEY_E0 = INTERCEPTION_KEY_E0 << 1,
|
||||
INTERCEPTION_FILTER_KEY_E1 = INTERCEPTION_KEY_E1 << 1,
|
||||
INTERCEPTION_FILTER_KEY_TERMSRV_SET_LED = INTERCEPTION_KEY_TERMSRV_SET_LED << 1,
|
||||
INTERCEPTION_FILTER_KEY_TERMSRV_SHADOW = INTERCEPTION_KEY_TERMSRV_SHADOW << 1,
|
||||
INTERCEPTION_FILTER_KEY_TERMSRV_VKPACKET = INTERCEPTION_KEY_TERMSRV_VKPACKET << 1
|
||||
};
|
||||
|
||||
enum InterceptionMouseState
|
||||
{
|
||||
INTERCEPTION_MOUSE_LEFT_BUTTON_DOWN = 0x001,
|
||||
INTERCEPTION_MOUSE_LEFT_BUTTON_UP = 0x002,
|
||||
INTERCEPTION_MOUSE_RIGHT_BUTTON_DOWN = 0x004,
|
||||
INTERCEPTION_MOUSE_RIGHT_BUTTON_UP = 0x008,
|
||||
INTERCEPTION_MOUSE_MIDDLE_BUTTON_DOWN = 0x010,
|
||||
INTERCEPTION_MOUSE_MIDDLE_BUTTON_UP = 0x020,
|
||||
|
||||
INTERCEPTION_MOUSE_BUTTON_1_DOWN = INTERCEPTION_MOUSE_LEFT_BUTTON_DOWN,
|
||||
INTERCEPTION_MOUSE_BUTTON_1_UP = INTERCEPTION_MOUSE_LEFT_BUTTON_UP,
|
||||
INTERCEPTION_MOUSE_BUTTON_2_DOWN = INTERCEPTION_MOUSE_RIGHT_BUTTON_DOWN,
|
||||
INTERCEPTION_MOUSE_BUTTON_2_UP = INTERCEPTION_MOUSE_RIGHT_BUTTON_UP,
|
||||
INTERCEPTION_MOUSE_BUTTON_3_DOWN = INTERCEPTION_MOUSE_MIDDLE_BUTTON_DOWN,
|
||||
INTERCEPTION_MOUSE_BUTTON_3_UP = INTERCEPTION_MOUSE_MIDDLE_BUTTON_UP,
|
||||
|
||||
INTERCEPTION_MOUSE_BUTTON_4_DOWN = 0x040,
|
||||
INTERCEPTION_MOUSE_BUTTON_4_UP = 0x080,
|
||||
INTERCEPTION_MOUSE_BUTTON_5_DOWN = 0x100,
|
||||
INTERCEPTION_MOUSE_BUTTON_5_UP = 0x200,
|
||||
|
||||
INTERCEPTION_MOUSE_WHEEL = 0x400,
|
||||
INTERCEPTION_MOUSE_HWHEEL = 0x800
|
||||
};
|
||||
|
||||
enum InterceptionFilterMouseState
|
||||
{
|
||||
INTERCEPTION_FILTER_MOUSE_NONE = 0x0000,
|
||||
INTERCEPTION_FILTER_MOUSE_ALL = 0xFFFF,
|
||||
|
||||
INTERCEPTION_FILTER_MOUSE_LEFT_BUTTON_DOWN = INTERCEPTION_MOUSE_LEFT_BUTTON_DOWN,
|
||||
INTERCEPTION_FILTER_MOUSE_LEFT_BUTTON_UP = INTERCEPTION_MOUSE_LEFT_BUTTON_UP,
|
||||
INTERCEPTION_FILTER_MOUSE_RIGHT_BUTTON_DOWN = INTERCEPTION_MOUSE_RIGHT_BUTTON_DOWN,
|
||||
INTERCEPTION_FILTER_MOUSE_RIGHT_BUTTON_UP = INTERCEPTION_MOUSE_RIGHT_BUTTON_UP,
|
||||
INTERCEPTION_FILTER_MOUSE_MIDDLE_BUTTON_DOWN = INTERCEPTION_MOUSE_MIDDLE_BUTTON_DOWN,
|
||||
INTERCEPTION_FILTER_MOUSE_MIDDLE_BUTTON_UP = INTERCEPTION_MOUSE_MIDDLE_BUTTON_UP,
|
||||
|
||||
INTERCEPTION_FILTER_MOUSE_BUTTON_1_DOWN = INTERCEPTION_MOUSE_BUTTON_1_DOWN,
|
||||
INTERCEPTION_FILTER_MOUSE_BUTTON_1_UP = INTERCEPTION_MOUSE_BUTTON_1_UP,
|
||||
INTERCEPTION_FILTER_MOUSE_BUTTON_2_DOWN = INTERCEPTION_MOUSE_BUTTON_2_DOWN,
|
||||
INTERCEPTION_FILTER_MOUSE_BUTTON_2_UP = INTERCEPTION_MOUSE_BUTTON_2_UP,
|
||||
INTERCEPTION_FILTER_MOUSE_BUTTON_3_DOWN = INTERCEPTION_MOUSE_BUTTON_3_DOWN,
|
||||
INTERCEPTION_FILTER_MOUSE_BUTTON_3_UP = INTERCEPTION_MOUSE_BUTTON_3_UP,
|
||||
|
||||
INTERCEPTION_FILTER_MOUSE_BUTTON_4_DOWN = INTERCEPTION_MOUSE_BUTTON_4_DOWN,
|
||||
INTERCEPTION_FILTER_MOUSE_BUTTON_4_UP = INTERCEPTION_MOUSE_BUTTON_4_UP,
|
||||
INTERCEPTION_FILTER_MOUSE_BUTTON_5_DOWN = INTERCEPTION_MOUSE_BUTTON_5_DOWN,
|
||||
INTERCEPTION_FILTER_MOUSE_BUTTON_5_UP = INTERCEPTION_MOUSE_BUTTON_5_UP,
|
||||
|
||||
INTERCEPTION_FILTER_MOUSE_WHEEL = INTERCEPTION_MOUSE_WHEEL,
|
||||
INTERCEPTION_FILTER_MOUSE_HWHEEL = INTERCEPTION_MOUSE_HWHEEL,
|
||||
|
||||
INTERCEPTION_FILTER_MOUSE_MOVE = 0x1000
|
||||
};
|
||||
|
||||
enum InterceptionMouseFlag
|
||||
{
|
||||
INTERCEPTION_MOUSE_MOVE_RELATIVE = 0x000,
|
||||
INTERCEPTION_MOUSE_MOVE_ABSOLUTE = 0x001,
|
||||
INTERCEPTION_MOUSE_VIRTUAL_DESKTOP = 0x002,
|
||||
INTERCEPTION_MOUSE_ATTRIBUTES_CHANGED = 0x004,
|
||||
INTERCEPTION_MOUSE_MOVE_NOCOALESCE = 0x008,
|
||||
INTERCEPTION_MOUSE_TERMSRV_SRC_SHADOW = 0x100
|
||||
};
|
||||
|
||||
typedef struct
|
||||
{
|
||||
unsigned short state;
|
||||
unsigned short flags;
|
||||
short rolling;
|
||||
int x;
|
||||
int y;
|
||||
unsigned int information;
|
||||
} InterceptionMouseStroke;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
unsigned short code;
|
||||
unsigned short state;
|
||||
unsigned int information;
|
||||
} InterceptionKeyStroke;
|
||||
|
||||
typedef char InterceptionStroke[sizeof(InterceptionMouseStroke)];
|
||||
|
||||
InterceptionContext INTERCEPTION_API interception_create_context(void);
|
||||
|
||||
void INTERCEPTION_API interception_destroy_context(InterceptionContext context);
|
||||
|
||||
InterceptionPrecedence INTERCEPTION_API interception_get_precedence(InterceptionContext context, InterceptionDevice device);
|
||||
|
||||
void INTERCEPTION_API interception_set_precedence(InterceptionContext context, InterceptionDevice device, InterceptionPrecedence precedence);
|
||||
|
||||
InterceptionFilter INTERCEPTION_API interception_get_filter(InterceptionContext context, InterceptionDevice device);
|
||||
|
||||
void INTERCEPTION_API interception_set_filter(InterceptionContext context, InterceptionPredicate predicate, InterceptionFilter filter);
|
||||
|
||||
InterceptionDevice INTERCEPTION_API interception_wait(InterceptionContext context);
|
||||
|
||||
InterceptionDevice INTERCEPTION_API interception_wait_with_timeout(InterceptionContext context, unsigned long milliseconds);
|
||||
|
||||
int INTERCEPTION_API interception_send(InterceptionContext context, InterceptionDevice device, const InterceptionStroke *stroke, unsigned int nstroke);
|
||||
|
||||
int INTERCEPTION_API interception_receive(InterceptionContext context, InterceptionDevice device, InterceptionStroke *stroke, unsigned int nstroke);
|
||||
|
||||
unsigned int INTERCEPTION_API interception_get_hardware_id(InterceptionContext context, InterceptionDevice device, void *hardware_id_buffer, unsigned int buffer_size);
|
||||
|
||||
int INTERCEPTION_API interception_is_invalid(InterceptionDevice device);
|
||||
|
||||
int INTERCEPTION_API interception_is_keyboard(InterceptionDevice device);
|
||||
|
||||
int INTERCEPTION_API interception_is_mouse(InterceptionDevice device);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,317 @@
|
||||
#![ allow( dead_code, unused_imports, non_upper_case_globals, non_snake_case, deref_nullptr ) ]
|
||||
|
||||
/* automatically generated by rust-bindgen 0.54.1 */
|
||||
|
||||
pub const INTERCEPTION_MAX_KEYBOARD: u32 = 10;
|
||||
pub const INTERCEPTION_MAX_MOUSE: u32 = 10;
|
||||
pub const INTERCEPTION_MAX_DEVICE: u32 = 20;
|
||||
pub type InterceptionContext = *mut ::std::os::raw::c_void;
|
||||
pub type InterceptionDevice = ::std::os::raw::c_int;
|
||||
pub type InterceptionPrecedence = ::std::os::raw::c_int;
|
||||
pub type InterceptionFilter = ::std::os::raw::c_ushort;
|
||||
pub type InterceptionPredicate = ::std::option::Option<
|
||||
unsafe extern "C" fn(device: InterceptionDevice) -> ::std::os::raw::c_int,
|
||||
>;
|
||||
pub const InterceptionKeyState_INTERCEPTION_KEY_DOWN: InterceptionKeyState = 0;
|
||||
pub const InterceptionKeyState_INTERCEPTION_KEY_UP: InterceptionKeyState = 1;
|
||||
pub const InterceptionKeyState_INTERCEPTION_KEY_E0: InterceptionKeyState = 2;
|
||||
pub const InterceptionKeyState_INTERCEPTION_KEY_E1: InterceptionKeyState = 4;
|
||||
pub const InterceptionKeyState_INTERCEPTION_KEY_TERMSRV_SET_LED: InterceptionKeyState = 8;
|
||||
pub const InterceptionKeyState_INTERCEPTION_KEY_TERMSRV_SHADOW: InterceptionKeyState = 16;
|
||||
pub const InterceptionKeyState_INTERCEPTION_KEY_TERMSRV_VKPACKET: InterceptionKeyState = 32;
|
||||
pub type InterceptionKeyState = u32;
|
||||
pub const InterceptionFilterKeyState_INTERCEPTION_FILTER_KEY_NONE: InterceptionFilterKeyState = 0;
|
||||
pub const InterceptionFilterKeyState_INTERCEPTION_FILTER_KEY_ALL: InterceptionFilterKeyState =
|
||||
65535;
|
||||
pub const InterceptionFilterKeyState_INTERCEPTION_FILTER_KEY_DOWN: InterceptionFilterKeyState = 1;
|
||||
pub const InterceptionFilterKeyState_INTERCEPTION_FILTER_KEY_UP: InterceptionFilterKeyState = 2;
|
||||
pub const InterceptionFilterKeyState_INTERCEPTION_FILTER_KEY_E0: InterceptionFilterKeyState = 4;
|
||||
pub const InterceptionFilterKeyState_INTERCEPTION_FILTER_KEY_E1: InterceptionFilterKeyState = 8;
|
||||
pub const InterceptionFilterKeyState_INTERCEPTION_FILTER_KEY_TERMSRV_SET_LED:
|
||||
InterceptionFilterKeyState = 16;
|
||||
pub const InterceptionFilterKeyState_INTERCEPTION_FILTER_KEY_TERMSRV_SHADOW:
|
||||
InterceptionFilterKeyState = 32;
|
||||
pub const InterceptionFilterKeyState_INTERCEPTION_FILTER_KEY_TERMSRV_VKPACKET:
|
||||
InterceptionFilterKeyState = 64;
|
||||
pub type InterceptionFilterKeyState = u32;
|
||||
pub const InterceptionMouseState_INTERCEPTION_MOUSE_LEFT_BUTTON_DOWN: InterceptionMouseState = 1;
|
||||
pub const InterceptionMouseState_INTERCEPTION_MOUSE_LEFT_BUTTON_UP: InterceptionMouseState = 2;
|
||||
pub const InterceptionMouseState_INTERCEPTION_MOUSE_RIGHT_BUTTON_DOWN: InterceptionMouseState = 4;
|
||||
pub const InterceptionMouseState_INTERCEPTION_MOUSE_RIGHT_BUTTON_UP: InterceptionMouseState = 8;
|
||||
pub const InterceptionMouseState_INTERCEPTION_MOUSE_MIDDLE_BUTTON_DOWN: InterceptionMouseState = 16;
|
||||
pub const InterceptionMouseState_INTERCEPTION_MOUSE_MIDDLE_BUTTON_UP: InterceptionMouseState = 32;
|
||||
pub const InterceptionMouseState_INTERCEPTION_MOUSE_BUTTON_1_DOWN: InterceptionMouseState = 1;
|
||||
pub const InterceptionMouseState_INTERCEPTION_MOUSE_BUTTON_1_UP: InterceptionMouseState = 2;
|
||||
pub const InterceptionMouseState_INTERCEPTION_MOUSE_BUTTON_2_DOWN: InterceptionMouseState = 4;
|
||||
pub const InterceptionMouseState_INTERCEPTION_MOUSE_BUTTON_2_UP: InterceptionMouseState = 8;
|
||||
pub const InterceptionMouseState_INTERCEPTION_MOUSE_BUTTON_3_DOWN: InterceptionMouseState = 16;
|
||||
pub const InterceptionMouseState_INTERCEPTION_MOUSE_BUTTON_3_UP: InterceptionMouseState = 32;
|
||||
pub const InterceptionMouseState_INTERCEPTION_MOUSE_BUTTON_4_DOWN: InterceptionMouseState = 64;
|
||||
pub const InterceptionMouseState_INTERCEPTION_MOUSE_BUTTON_4_UP: InterceptionMouseState = 128;
|
||||
pub const InterceptionMouseState_INTERCEPTION_MOUSE_BUTTON_5_DOWN: InterceptionMouseState = 256;
|
||||
pub const InterceptionMouseState_INTERCEPTION_MOUSE_BUTTON_5_UP: InterceptionMouseState = 512;
|
||||
pub const InterceptionMouseState_INTERCEPTION_MOUSE_WHEEL: InterceptionMouseState = 1024;
|
||||
pub const InterceptionMouseState_INTERCEPTION_MOUSE_HWHEEL: InterceptionMouseState = 2048;
|
||||
pub type InterceptionMouseState = u32;
|
||||
pub const InterceptionFilterMouseState_INTERCEPTION_FILTER_MOUSE_NONE:
|
||||
InterceptionFilterMouseState = 0;
|
||||
pub const InterceptionFilterMouseState_INTERCEPTION_FILTER_MOUSE_ALL: InterceptionFilterMouseState =
|
||||
65535;
|
||||
pub const InterceptionFilterMouseState_INTERCEPTION_FILTER_MOUSE_LEFT_BUTTON_DOWN:
|
||||
InterceptionFilterMouseState = 1;
|
||||
pub const InterceptionFilterMouseState_INTERCEPTION_FILTER_MOUSE_LEFT_BUTTON_UP:
|
||||
InterceptionFilterMouseState = 2;
|
||||
pub const InterceptionFilterMouseState_INTERCEPTION_FILTER_MOUSE_RIGHT_BUTTON_DOWN:
|
||||
InterceptionFilterMouseState = 4;
|
||||
pub const InterceptionFilterMouseState_INTERCEPTION_FILTER_MOUSE_RIGHT_BUTTON_UP:
|
||||
InterceptionFilterMouseState = 8;
|
||||
pub const InterceptionFilterMouseState_INTERCEPTION_FILTER_MOUSE_MIDDLE_BUTTON_DOWN:
|
||||
InterceptionFilterMouseState = 16;
|
||||
pub const InterceptionFilterMouseState_INTERCEPTION_FILTER_MOUSE_MIDDLE_BUTTON_UP:
|
||||
InterceptionFilterMouseState = 32;
|
||||
pub const InterceptionFilterMouseState_INTERCEPTION_FILTER_MOUSE_BUTTON_1_DOWN:
|
||||
InterceptionFilterMouseState = 1;
|
||||
pub const InterceptionFilterMouseState_INTERCEPTION_FILTER_MOUSE_BUTTON_1_UP:
|
||||
InterceptionFilterMouseState = 2;
|
||||
pub const InterceptionFilterMouseState_INTERCEPTION_FILTER_MOUSE_BUTTON_2_DOWN:
|
||||
InterceptionFilterMouseState = 4;
|
||||
pub const InterceptionFilterMouseState_INTERCEPTION_FILTER_MOUSE_BUTTON_2_UP:
|
||||
InterceptionFilterMouseState = 8;
|
||||
pub const InterceptionFilterMouseState_INTERCEPTION_FILTER_MOUSE_BUTTON_3_DOWN:
|
||||
InterceptionFilterMouseState = 16;
|
||||
pub const InterceptionFilterMouseState_INTERCEPTION_FILTER_MOUSE_BUTTON_3_UP:
|
||||
InterceptionFilterMouseState = 32;
|
||||
pub const InterceptionFilterMouseState_INTERCEPTION_FILTER_MOUSE_BUTTON_4_DOWN:
|
||||
InterceptionFilterMouseState = 64;
|
||||
pub const InterceptionFilterMouseState_INTERCEPTION_FILTER_MOUSE_BUTTON_4_UP:
|
||||
InterceptionFilterMouseState = 128;
|
||||
pub const InterceptionFilterMouseState_INTERCEPTION_FILTER_MOUSE_BUTTON_5_DOWN:
|
||||
InterceptionFilterMouseState = 256;
|
||||
pub const InterceptionFilterMouseState_INTERCEPTION_FILTER_MOUSE_BUTTON_5_UP:
|
||||
InterceptionFilterMouseState = 512;
|
||||
pub const InterceptionFilterMouseState_INTERCEPTION_FILTER_MOUSE_WHEEL:
|
||||
InterceptionFilterMouseState = 1024;
|
||||
pub const InterceptionFilterMouseState_INTERCEPTION_FILTER_MOUSE_HWHEEL:
|
||||
InterceptionFilterMouseState = 2048;
|
||||
pub const InterceptionFilterMouseState_INTERCEPTION_FILTER_MOUSE_MOVE:
|
||||
InterceptionFilterMouseState = 4096;
|
||||
pub type InterceptionFilterMouseState = u32;
|
||||
pub const InterceptionMouseFlag_INTERCEPTION_MOUSE_MOVE_RELATIVE: InterceptionMouseFlag = 0;
|
||||
pub const InterceptionMouseFlag_INTERCEPTION_MOUSE_MOVE_ABSOLUTE: InterceptionMouseFlag = 1;
|
||||
pub const InterceptionMouseFlag_INTERCEPTION_MOUSE_VIRTUAL_DESKTOP: InterceptionMouseFlag = 2;
|
||||
pub const InterceptionMouseFlag_INTERCEPTION_MOUSE_ATTRIBUTES_CHANGED: InterceptionMouseFlag = 4;
|
||||
pub const InterceptionMouseFlag_INTERCEPTION_MOUSE_MOVE_NOCOALESCE: InterceptionMouseFlag = 8;
|
||||
pub const InterceptionMouseFlag_INTERCEPTION_MOUSE_TERMSRV_SRC_SHADOW: InterceptionMouseFlag = 256;
|
||||
pub type InterceptionMouseFlag = u32;
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Default, Copy, Clone)]
|
||||
pub struct InterceptionMouseStroke {
|
||||
pub state: ::std::os::raw::c_ushort,
|
||||
pub flags: ::std::os::raw::c_ushort,
|
||||
pub rolling: ::std::os::raw::c_short,
|
||||
pub x: ::std::os::raw::c_int,
|
||||
pub y: ::std::os::raw::c_int,
|
||||
pub information: ::std::os::raw::c_uint,
|
||||
}
|
||||
#[test]
|
||||
fn bindgen_test_layout_InterceptionMouseStroke() {
|
||||
assert_eq!(
|
||||
::std::mem::size_of::<InterceptionMouseStroke>(),
|
||||
20usize,
|
||||
concat!("Size of: ", stringify!(InterceptionMouseStroke))
|
||||
);
|
||||
assert_eq!(
|
||||
::std::mem::align_of::<InterceptionMouseStroke>(),
|
||||
4usize,
|
||||
concat!("Alignment of ", stringify!(InterceptionMouseStroke))
|
||||
);
|
||||
assert_eq!(
|
||||
unsafe { &(*(::std::ptr::null::<InterceptionMouseStroke>())).state as *const _ as usize },
|
||||
0usize,
|
||||
concat!(
|
||||
"Offset of field: ",
|
||||
stringify!(InterceptionMouseStroke),
|
||||
"::",
|
||||
stringify!(state)
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
unsafe { &(*(::std::ptr::null::<InterceptionMouseStroke>())).flags as *const _ as usize },
|
||||
2usize,
|
||||
concat!(
|
||||
"Offset of field: ",
|
||||
stringify!(InterceptionMouseStroke),
|
||||
"::",
|
||||
stringify!(flags)
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
unsafe { &(*(::std::ptr::null::<InterceptionMouseStroke>())).rolling as *const _ as usize },
|
||||
4usize,
|
||||
concat!(
|
||||
"Offset of field: ",
|
||||
stringify!(InterceptionMouseStroke),
|
||||
"::",
|
||||
stringify!(rolling)
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
unsafe { &(*(::std::ptr::null::<InterceptionMouseStroke>())).x as *const _ as usize },
|
||||
8usize,
|
||||
concat!(
|
||||
"Offset of field: ",
|
||||
stringify!(InterceptionMouseStroke),
|
||||
"::",
|
||||
stringify!(x)
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
unsafe { &(*(::std::ptr::null::<InterceptionMouseStroke>())).y as *const _ as usize },
|
||||
12usize,
|
||||
concat!(
|
||||
"Offset of field: ",
|
||||
stringify!(InterceptionMouseStroke),
|
||||
"::",
|
||||
stringify!(y)
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
&(*(::std::ptr::null::<InterceptionMouseStroke>())).information as *const _ as usize
|
||||
},
|
||||
16usize,
|
||||
concat!(
|
||||
"Offset of field: ",
|
||||
stringify!(InterceptionMouseStroke),
|
||||
"::",
|
||||
stringify!(information)
|
||||
)
|
||||
);
|
||||
}
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Default, Copy, Clone)]
|
||||
pub struct InterceptionKeyStroke {
|
||||
pub code: ::std::os::raw::c_ushort,
|
||||
pub state: ::std::os::raw::c_ushort,
|
||||
pub information: ::std::os::raw::c_uint,
|
||||
}
|
||||
#[test]
|
||||
fn bindgen_test_layout_InterceptionKeyStroke() {
|
||||
assert_eq!(
|
||||
::std::mem::size_of::<InterceptionKeyStroke>(),
|
||||
8usize,
|
||||
concat!("Size of: ", stringify!(InterceptionKeyStroke))
|
||||
);
|
||||
assert_eq!(
|
||||
::std::mem::align_of::<InterceptionKeyStroke>(),
|
||||
4usize,
|
||||
concat!("Alignment of ", stringify!(InterceptionKeyStroke))
|
||||
);
|
||||
assert_eq!(
|
||||
unsafe { &(*(::std::ptr::null::<InterceptionKeyStroke>())).code as *const _ as usize },
|
||||
0usize,
|
||||
concat!(
|
||||
"Offset of field: ",
|
||||
stringify!(InterceptionKeyStroke),
|
||||
"::",
|
||||
stringify!(code)
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
unsafe { &(*(::std::ptr::null::<InterceptionKeyStroke>())).state as *const _ as usize },
|
||||
2usize,
|
||||
concat!(
|
||||
"Offset of field: ",
|
||||
stringify!(InterceptionKeyStroke),
|
||||
"::",
|
||||
stringify!(state)
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
&(*(::std::ptr::null::<InterceptionKeyStroke>())).information as *const _ as usize
|
||||
},
|
||||
4usize,
|
||||
concat!(
|
||||
"Offset of field: ",
|
||||
stringify!(InterceptionKeyStroke),
|
||||
"::",
|
||||
stringify!(information)
|
||||
)
|
||||
);
|
||||
}
|
||||
pub type InterceptionStroke = [::std::os::raw::c_char; 20usize];
|
||||
extern "C" {
|
||||
pub fn interception_create_context() -> InterceptionContext;
|
||||
}
|
||||
extern "C" {
|
||||
pub fn interception_destroy_context(context: InterceptionContext);
|
||||
}
|
||||
extern "C" {
|
||||
pub fn interception_get_precedence(
|
||||
context: InterceptionContext,
|
||||
device: InterceptionDevice,
|
||||
) -> InterceptionPrecedence;
|
||||
}
|
||||
extern "C" {
|
||||
pub fn interception_set_precedence(
|
||||
context: InterceptionContext,
|
||||
device: InterceptionDevice,
|
||||
precedence: InterceptionPrecedence,
|
||||
);
|
||||
}
|
||||
extern "C" {
|
||||
pub fn interception_get_filter(
|
||||
context: InterceptionContext,
|
||||
device: InterceptionDevice,
|
||||
) -> InterceptionFilter;
|
||||
}
|
||||
extern "C" {
|
||||
pub fn interception_set_filter(
|
||||
context: InterceptionContext,
|
||||
predicate: InterceptionPredicate,
|
||||
filter: InterceptionFilter,
|
||||
);
|
||||
}
|
||||
extern "C" {
|
||||
pub fn interception_wait(context: InterceptionContext) -> InterceptionDevice;
|
||||
}
|
||||
extern "C" {
|
||||
pub fn interception_wait_with_timeout(
|
||||
context: InterceptionContext,
|
||||
milliseconds: ::std::os::raw::c_ulong,
|
||||
) -> InterceptionDevice;
|
||||
}
|
||||
extern "C" {
|
||||
pub fn interception_send(
|
||||
context: InterceptionContext,
|
||||
device: InterceptionDevice,
|
||||
stroke: *const InterceptionStroke,
|
||||
nstroke: ::std::os::raw::c_uint,
|
||||
) -> ::std::os::raw::c_int;
|
||||
}
|
||||
extern "C" {
|
||||
pub fn interception_receive(
|
||||
context: InterceptionContext,
|
||||
device: InterceptionDevice,
|
||||
stroke: *mut InterceptionStroke,
|
||||
nstroke: ::std::os::raw::c_uint,
|
||||
) -> ::std::os::raw::c_int;
|
||||
}
|
||||
extern "C" {
|
||||
pub fn interception_get_hardware_id(
|
||||
context: InterceptionContext,
|
||||
device: InterceptionDevice,
|
||||
hardware_id_buffer: *mut ::std::os::raw::c_void,
|
||||
buffer_size: ::std::os::raw::c_uint,
|
||||
) -> ::std::os::raw::c_uint;
|
||||
}
|
||||
extern "C" {
|
||||
pub fn interception_is_invalid(device: InterceptionDevice) -> ::std::os::raw::c_int;
|
||||
}
|
||||
extern "C" {
|
||||
pub fn interception_is_keyboard(device: InterceptionDevice) -> ::std::os::raw::c_int;
|
||||
}
|
||||
extern "C" {
|
||||
pub fn interception_is_mouse(device: InterceptionDevice) -> ::std::os::raw::c_int;
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
#include <stdio.h>
|
||||
#include <windows.h>
|
||||
#include <winioctl.h>
|
||||
|
||||
#include "interception.h"
|
||||
|
||||
#define IOCTL_SET_PRECEDENCE CTL_CODE(FILE_DEVICE_UNKNOWN, 0x801, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
#define IOCTL_GET_PRECEDENCE CTL_CODE(FILE_DEVICE_UNKNOWN, 0x802, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
#define IOCTL_SET_FILTER CTL_CODE(FILE_DEVICE_UNKNOWN, 0x804, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
#define IOCTL_GET_FILTER CTL_CODE(FILE_DEVICE_UNKNOWN, 0x808, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
#define IOCTL_SET_EVENT CTL_CODE(FILE_DEVICE_UNKNOWN, 0x810, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
#define IOCTL_WRITE CTL_CODE(FILE_DEVICE_UNKNOWN, 0x820, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
#define IOCTL_READ CTL_CODE(FILE_DEVICE_UNKNOWN, 0x840, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
#define IOCTL_GET_HARDWARE_ID CTL_CODE(FILE_DEVICE_UNKNOWN, 0x880, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
|
||||
typedef struct _KEYBOARD_INPUT_DATA
|
||||
{
|
||||
USHORT UnitId;
|
||||
USHORT MakeCode;
|
||||
USHORT Flags;
|
||||
USHORT Reserved;
|
||||
ULONG ExtraInformation;
|
||||
} KEYBOARD_INPUT_DATA, *PKEYBOARD_INPUT_DATA;
|
||||
|
||||
typedef struct _MOUSE_INPUT_DATA
|
||||
{
|
||||
USHORT UnitId;
|
||||
USHORT Flags;
|
||||
USHORT ButtonFlags;
|
||||
USHORT ButtonData;
|
||||
ULONG RawButtons;
|
||||
LONG LastX;
|
||||
LONG LastY;
|
||||
ULONG ExtraInformation;
|
||||
} MOUSE_INPUT_DATA, *PMOUSE_INPUT_DATA;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
void *handle;
|
||||
void *unempty;
|
||||
} *InterceptionDeviceArray;
|
||||
|
||||
InterceptionContext interception_create_context(void)
|
||||
{
|
||||
InterceptionDeviceArray device_array = 0;
|
||||
char device_name[] = "\\\\.\\interception00";
|
||||
DWORD bytes_returned;
|
||||
InterceptionDevice i;
|
||||
|
||||
device_array = (InterceptionDeviceArray)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, INTERCEPTION_MAX_DEVICE * sizeof(*((InterceptionDeviceArray) 0)));
|
||||
if(!device_array) return 0;
|
||||
|
||||
for(i = 0; i < INTERCEPTION_MAX_DEVICE; ++i)
|
||||
{
|
||||
HANDLE zero_padded_handle[2] = {0};
|
||||
|
||||
sprintf(&device_name[sizeof(device_name) - 3], "%02d", i);
|
||||
|
||||
device_array[i].handle = CreateFileA(device_name, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
|
||||
|
||||
if (device_array[i].handle == INVALID_HANDLE_VALUE) {
|
||||
interception_destroy_context(device_array);
|
||||
return 0;
|
||||
}
|
||||
|
||||
device_array[i].unempty = CreateEventA(NULL, TRUE, FALSE, NULL);
|
||||
|
||||
if(device_array[i].unempty == NULL)
|
||||
{
|
||||
interception_destroy_context(device_array);
|
||||
return 0;
|
||||
}
|
||||
|
||||
zero_padded_handle[0] = device_array[i].unempty;
|
||||
|
||||
if(!DeviceIoControl(device_array[i].handle, IOCTL_SET_EVENT, zero_padded_handle, sizeof(zero_padded_handle), NULL, 0, &bytes_returned, NULL))
|
||||
{
|
||||
interception_destroy_context(device_array);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
return device_array;
|
||||
}
|
||||
|
||||
void interception_destroy_context(InterceptionContext context)
|
||||
{
|
||||
InterceptionDeviceArray device_array = (InterceptionDeviceArray)context;
|
||||
unsigned int i;
|
||||
|
||||
if(!context) return;
|
||||
|
||||
for(i = 0; i < INTERCEPTION_MAX_DEVICE; ++i)
|
||||
{
|
||||
if(device_array[i].handle != INVALID_HANDLE_VALUE)
|
||||
CloseHandle(device_array[i].handle);
|
||||
|
||||
if(device_array[i].unempty != NULL)
|
||||
CloseHandle(device_array[i].unempty);
|
||||
}
|
||||
|
||||
HeapFree(GetProcessHeap(), 0, context);
|
||||
}
|
||||
|
||||
InterceptionPrecedence interception_get_precedence(InterceptionContext context, InterceptionDevice device)
|
||||
{
|
||||
InterceptionDeviceArray device_array = (InterceptionDeviceArray)context;
|
||||
InterceptionPrecedence precedence = 0;
|
||||
DWORD bytes_returned;
|
||||
|
||||
if(context && device_array[device - 1].handle)
|
||||
DeviceIoControl(device_array[device - 1].handle, IOCTL_GET_PRECEDENCE, NULL, 0, (LPVOID)&precedence, sizeof(InterceptionPrecedence), &bytes_returned, NULL);
|
||||
|
||||
return precedence;
|
||||
}
|
||||
|
||||
void interception_set_precedence(InterceptionContext context, InterceptionDevice device, InterceptionPrecedence precedence)
|
||||
{
|
||||
InterceptionDeviceArray device_array = (InterceptionDeviceArray)context;
|
||||
DWORD bytes_returned;
|
||||
|
||||
if(context && device_array[device - 1].handle)
|
||||
DeviceIoControl(device_array[device - 1].handle, IOCTL_SET_PRECEDENCE, (LPVOID)&precedence, sizeof(InterceptionPrecedence), NULL, 0, &bytes_returned, NULL);
|
||||
}
|
||||
|
||||
InterceptionFilter interception_get_filter(InterceptionContext context, InterceptionDevice device)
|
||||
{
|
||||
InterceptionDeviceArray device_array = (InterceptionDeviceArray)context;
|
||||
InterceptionFilter filter = 0;
|
||||
DWORD bytes_returned;
|
||||
|
||||
if(context && device_array[device - 1].handle)
|
||||
DeviceIoControl(device_array[device - 1].handle, IOCTL_GET_FILTER, NULL, 0, (LPVOID)&filter, sizeof(InterceptionFilter), &bytes_returned, NULL);
|
||||
|
||||
return filter;
|
||||
}
|
||||
|
||||
void interception_set_filter(InterceptionContext context, InterceptionPredicate interception_predicate, InterceptionFilter filter)
|
||||
{
|
||||
InterceptionDeviceArray device_array = (InterceptionDeviceArray)context;
|
||||
InterceptionDevice i;
|
||||
DWORD bytes_returned;
|
||||
|
||||
if(context)
|
||||
for(i = 0; i < INTERCEPTION_MAX_DEVICE; ++i)
|
||||
if(device_array[i].handle && interception_predicate(i + 1))
|
||||
DeviceIoControl(device_array[i].handle, IOCTL_SET_FILTER, (LPVOID)&filter, sizeof(InterceptionFilter), NULL, 0, &bytes_returned, NULL);
|
||||
}
|
||||
|
||||
InterceptionDevice interception_wait(InterceptionContext context)
|
||||
{
|
||||
return interception_wait_with_timeout(context, INFINITE);
|
||||
}
|
||||
|
||||
InterceptionDevice interception_wait_with_timeout(InterceptionContext context, unsigned long milliseconds)
|
||||
{
|
||||
InterceptionDeviceArray device_array = (InterceptionDeviceArray)context;
|
||||
HANDLE wait_handles[INTERCEPTION_MAX_DEVICE];
|
||||
DWORD i, j, k;
|
||||
|
||||
if(!context) return 0;
|
||||
|
||||
for(i = 0, j = 0; i < INTERCEPTION_MAX_DEVICE; ++i)
|
||||
{
|
||||
if (device_array[i].unempty)
|
||||
wait_handles[j++] = device_array[i].unempty;
|
||||
}
|
||||
|
||||
k = WaitForMultipleObjects(j, wait_handles, FALSE, milliseconds);
|
||||
|
||||
if(k == WAIT_FAILED || k == WAIT_TIMEOUT) return 0;
|
||||
|
||||
for(i = 0, j = 0; i < INTERCEPTION_MAX_DEVICE; ++i)
|
||||
{
|
||||
if (device_array[i].unempty)
|
||||
if (k == j++)
|
||||
break;
|
||||
}
|
||||
|
||||
return i + 1;
|
||||
}
|
||||
|
||||
int interception_send(InterceptionContext context, InterceptionDevice device, const InterceptionStroke *stroke, unsigned int nstroke)
|
||||
{
|
||||
InterceptionDeviceArray device_array = (InterceptionDeviceArray)context;
|
||||
DWORD strokeswritten = 0;
|
||||
|
||||
if(context == 0 || nstroke == 0 || interception_is_invalid(device) || !device_array[device - 1].handle) return 0;
|
||||
|
||||
if(interception_is_keyboard(device))
|
||||
{
|
||||
PKEYBOARD_INPUT_DATA rawstrokes = (PKEYBOARD_INPUT_DATA)HeapAlloc(GetProcessHeap(), 0, nstroke * sizeof(KEYBOARD_INPUT_DATA));
|
||||
unsigned int i;
|
||||
|
||||
if(!rawstrokes) return 0;
|
||||
|
||||
for(i = 0; i < nstroke; ++i)
|
||||
{
|
||||
InterceptionKeyStroke *key_stroke = (InterceptionKeyStroke *) stroke;
|
||||
|
||||
rawstrokes[i].UnitId = 0;
|
||||
rawstrokes[i].MakeCode = key_stroke[i].code;
|
||||
rawstrokes[i].Flags = key_stroke[i].state;
|
||||
rawstrokes[i].Reserved = 0;
|
||||
rawstrokes[i].ExtraInformation = key_stroke[i].information;
|
||||
}
|
||||
|
||||
DeviceIoControl(device_array[device - 1].handle, IOCTL_WRITE, rawstrokes,(DWORD)nstroke * sizeof(KEYBOARD_INPUT_DATA), NULL, 0, &strokeswritten, NULL);
|
||||
|
||||
HeapFree(GetProcessHeap(), 0, rawstrokes);
|
||||
|
||||
strokeswritten /= sizeof(KEYBOARD_INPUT_DATA);
|
||||
}
|
||||
else
|
||||
{
|
||||
PMOUSE_INPUT_DATA rawstrokes = (PMOUSE_INPUT_DATA)HeapAlloc(GetProcessHeap(), 0, nstroke * sizeof(MOUSE_INPUT_DATA));
|
||||
unsigned int i;
|
||||
|
||||
if(!rawstrokes) return 0;
|
||||
|
||||
for(i = 0; i < nstroke; ++i)
|
||||
{
|
||||
InterceptionMouseStroke *mouse_stroke = (InterceptionMouseStroke *) stroke;
|
||||
|
||||
rawstrokes[i].UnitId = 0;
|
||||
rawstrokes[i].Flags = mouse_stroke[i].flags;
|
||||
rawstrokes[i].ButtonFlags = mouse_stroke[i].state;
|
||||
rawstrokes[i].ButtonData = mouse_stroke[i].rolling;
|
||||
rawstrokes[i].RawButtons = 0;
|
||||
rawstrokes[i].LastX = mouse_stroke[i].x;
|
||||
rawstrokes[i].LastY = mouse_stroke[i].y;
|
||||
rawstrokes[i].ExtraInformation = mouse_stroke[i].information;
|
||||
}
|
||||
|
||||
DeviceIoControl(device_array[device - 1].handle, IOCTL_WRITE, rawstrokes, (DWORD)nstroke * sizeof(MOUSE_INPUT_DATA), NULL, 0, &strokeswritten, NULL);
|
||||
|
||||
HeapFree(GetProcessHeap(), 0, rawstrokes);
|
||||
|
||||
strokeswritten /= sizeof(MOUSE_INPUT_DATA);
|
||||
}
|
||||
|
||||
return strokeswritten;
|
||||
}
|
||||
|
||||
int interception_receive(InterceptionContext context, InterceptionDevice device, InterceptionStroke *stroke, unsigned int nstroke)
|
||||
{
|
||||
InterceptionDeviceArray device_array = (InterceptionDeviceArray)context;
|
||||
DWORD strokesread = 0;
|
||||
|
||||
if(context == 0 || nstroke == 0 || interception_is_invalid(device) || !device_array[device - 1].handle) return 0;
|
||||
|
||||
if(interception_is_keyboard(device))
|
||||
{
|
||||
PKEYBOARD_INPUT_DATA rawstrokes = (PKEYBOARD_INPUT_DATA)HeapAlloc(GetProcessHeap(), 0, nstroke * sizeof(KEYBOARD_INPUT_DATA));
|
||||
unsigned int i;
|
||||
|
||||
if(!rawstrokes) return 0;
|
||||
|
||||
DeviceIoControl(device_array[device - 1].handle, IOCTL_READ, NULL, 0, rawstrokes, (DWORD)nstroke * sizeof(KEYBOARD_INPUT_DATA), &strokesread, NULL);
|
||||
|
||||
strokesread /= sizeof(KEYBOARD_INPUT_DATA);
|
||||
|
||||
for(i = 0; i < (unsigned int)strokesread; ++i)
|
||||
{
|
||||
InterceptionKeyStroke *key_stroke = (InterceptionKeyStroke *) stroke;
|
||||
|
||||
key_stroke[i].code = rawstrokes[i].MakeCode;
|
||||
key_stroke[i].state = rawstrokes[i].Flags;
|
||||
key_stroke[i].information = rawstrokes[i].ExtraInformation;
|
||||
}
|
||||
|
||||
HeapFree(GetProcessHeap(), 0, rawstrokes);
|
||||
}
|
||||
else
|
||||
{
|
||||
PMOUSE_INPUT_DATA rawstrokes = (PMOUSE_INPUT_DATA)HeapAlloc(GetProcessHeap(), 0, nstroke * sizeof(MOUSE_INPUT_DATA));
|
||||
unsigned int i;
|
||||
|
||||
if(!rawstrokes) return 0;
|
||||
|
||||
DeviceIoControl(device_array[device - 1].handle, IOCTL_READ, NULL, 0, rawstrokes, (DWORD)nstroke * sizeof(MOUSE_INPUT_DATA), &strokesread, NULL);
|
||||
|
||||
strokesread /= sizeof(MOUSE_INPUT_DATA);
|
||||
|
||||
for(i = 0; i < (unsigned int)strokesread; ++i)
|
||||
{
|
||||
InterceptionMouseStroke *mouse_stroke = (InterceptionMouseStroke *) stroke;
|
||||
|
||||
mouse_stroke[i].flags = rawstrokes[i].Flags;
|
||||
mouse_stroke[i].state = rawstrokes[i].ButtonFlags;
|
||||
mouse_stroke[i].rolling = rawstrokes[i].ButtonData;
|
||||
mouse_stroke[i].x = rawstrokes[i].LastX;
|
||||
mouse_stroke[i].y = rawstrokes[i].LastY;
|
||||
mouse_stroke[i].information = rawstrokes[i].ExtraInformation;
|
||||
}
|
||||
|
||||
HeapFree(GetProcessHeap(), 0, rawstrokes);
|
||||
}
|
||||
|
||||
return strokesread;
|
||||
}
|
||||
|
||||
unsigned int interception_get_hardware_id(InterceptionContext context, InterceptionDevice device, void *hardware_id_buffer, unsigned int buffer_size)
|
||||
{
|
||||
InterceptionDeviceArray device_array = (InterceptionDeviceArray)context;
|
||||
DWORD output_size = 0;
|
||||
|
||||
if(context == 0 || interception_is_invalid(device) || !device_array[device - 1].handle) return 0;
|
||||
|
||||
DeviceIoControl(device_array[device - 1].handle, IOCTL_GET_HARDWARE_ID, NULL, 0, hardware_id_buffer, buffer_size, &output_size, NULL);
|
||||
|
||||
return output_size;
|
||||
}
|
||||
|
||||
int interception_is_invalid(InterceptionDevice device)
|
||||
{
|
||||
return !interception_is_keyboard(device) && !interception_is_mouse(device);
|
||||
}
|
||||
|
||||
int interception_is_keyboard(InterceptionDevice device)
|
||||
{
|
||||
return device >= INTERCEPTION_KEYBOARD(0) && device <= INTERCEPTION_KEYBOARD(INTERCEPTION_MAX_KEYBOARD - 1);
|
||||
}
|
||||
|
||||
int interception_is_mouse(InterceptionDevice device)
|
||||
{
|
||||
return device >= INTERCEPTION_MOUSE(0) && device <= INTERCEPTION_MOUSE(INTERCEPTION_MAX_MOUSE - 1);
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
#[macro_use]
|
||||
extern crate bitflags;
|
||||
|
||||
mod bindings;
|
||||
use bindings as raw;
|
||||
pub mod scancode;
|
||||
|
||||
pub use scancode::ScanCode;
|
||||
|
||||
use std::convert::{TryFrom, TryInto};
|
||||
use std::default::Default;
|
||||
use std::time::Duration;
|
||||
use std::vec::Vec;
|
||||
|
||||
pub type Device = i32;
|
||||
pub type Precedence = i32;
|
||||
|
||||
pub enum Filter {
|
||||
MouseFilter(MouseFilter),
|
||||
KeyFilter(KeyFilter),
|
||||
}
|
||||
|
||||
pub type Predicate = extern "C" fn(device: Device) -> bool;
|
||||
|
||||
bitflags! {
|
||||
pub struct MouseState: u16 {
|
||||
const LEFT_BUTTON_DOWN = 1;
|
||||
const LEFT_BUTTON_UP = 2;
|
||||
|
||||
const RIGHT_BUTTON_DOWN = 4;
|
||||
const RIGHT_BUTTON_UP = 8;
|
||||
|
||||
const MIDDLE_BUTTON_DOWN = 16;
|
||||
const MIDDLE_BUTTON_UP = 32;
|
||||
|
||||
const BUTTON_4_DOWN = 64;
|
||||
const BUTTON_4_UP = 128;
|
||||
|
||||
const BUTTON_5_DOWN = 256;
|
||||
const BUTTON_5_UP = 512;
|
||||
|
||||
const WHEEL = 1024;
|
||||
const HWHEEL = 2048;
|
||||
|
||||
// MouseFilter only
|
||||
const MOVE = 4096;
|
||||
}
|
||||
}
|
||||
|
||||
pub type MouseFilter = MouseState;
|
||||
|
||||
bitflags! {
|
||||
pub struct MouseFlags: u16 {
|
||||
const MOVE_RELATIVE = 0;
|
||||
const MOVE_ABSOLUTE = 1;
|
||||
|
||||
const VIRTUAL_DESKTOP = 2;
|
||||
const ATTRIBUTES_CHANGED = 4;
|
||||
|
||||
const MOVE_NO_COALESCE = 8;
|
||||
|
||||
const TERMSRV_SRC_SHADOW = 256;
|
||||
}
|
||||
}
|
||||
|
||||
bitflags! {
|
||||
pub struct KeyState: u16 {
|
||||
const DOWN = 0;
|
||||
const UP = 1;
|
||||
|
||||
const E0 = 2;
|
||||
const E1 = 3;
|
||||
|
||||
const TERMSRV_SET_LED = 8;
|
||||
const TERMSRV_SHADOW = 16;
|
||||
const TERMSRV_VKPACKET = 32;
|
||||
}
|
||||
}
|
||||
|
||||
bitflags! {
|
||||
pub struct KeyFilter: u16 {
|
||||
const DOWN = 1;
|
||||
const UP = 2;
|
||||
|
||||
const E0 = 4;
|
||||
const E1 = 8;
|
||||
|
||||
const TERMSRV_SET_LED = 16;
|
||||
const TERMSRV_SHADOW = 32;
|
||||
const TERMSRV_VKPACKET = 64;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub enum Stroke {
|
||||
Mouse {
|
||||
state: MouseState,
|
||||
flags: MouseFlags,
|
||||
rolling: i16,
|
||||
x: i32,
|
||||
y: i32,
|
||||
information: u32,
|
||||
},
|
||||
|
||||
Keyboard {
|
||||
code: ScanCode,
|
||||
state: KeyState,
|
||||
information: u32,
|
||||
},
|
||||
}
|
||||
|
||||
impl TryFrom<raw::InterceptionMouseStroke> for Stroke {
|
||||
type Error = &'static str;
|
||||
|
||||
fn try_from(raw_stroke: raw::InterceptionMouseStroke) -> Result<Self, Self::Error> {
|
||||
let state = match MouseState::from_bits(raw_stroke.state) {
|
||||
Some(state) => state,
|
||||
None => return Err("Extra bits in raw mouse state"),
|
||||
};
|
||||
|
||||
let flags = match MouseFlags::from_bits(raw_stroke.flags) {
|
||||
Some(flags) => flags,
|
||||
None => return Err("Extra bits in raw mouse flags"),
|
||||
};
|
||||
|
||||
Ok(Stroke::Mouse {
|
||||
state: state,
|
||||
flags: flags,
|
||||
rolling: raw_stroke.rolling,
|
||||
x: raw_stroke.x,
|
||||
y: raw_stroke.y,
|
||||
information: raw_stroke.information,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<raw::InterceptionKeyStroke> for Stroke {
|
||||
type Error = &'static str;
|
||||
|
||||
fn try_from(raw_stroke: raw::InterceptionKeyStroke) -> Result<Self, Self::Error> {
|
||||
let state = match KeyState::from_bits(raw_stroke.state) {
|
||||
Some(state) => state,
|
||||
None => return Err("Extra bits in raw keyboard state"),
|
||||
};
|
||||
|
||||
let code = match ScanCode::try_from(raw_stroke.code) {
|
||||
Ok(code) => code,
|
||||
Err(_) => ScanCode::Esc,
|
||||
};
|
||||
|
||||
Ok(Stroke::Keyboard {
|
||||
code: code,
|
||||
state: state,
|
||||
information: raw_stroke.information,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<Stroke> for raw::InterceptionMouseStroke {
|
||||
type Error = &'static str;
|
||||
|
||||
fn try_from(stroke: Stroke) -> Result<Self, Self::Error> {
|
||||
if let Stroke::Mouse {
|
||||
state,
|
||||
flags,
|
||||
rolling,
|
||||
x,
|
||||
y,
|
||||
information,
|
||||
} = stroke
|
||||
{
|
||||
Ok(raw::InterceptionMouseStroke {
|
||||
state: state.bits(),
|
||||
flags: flags.bits(),
|
||||
rolling: rolling,
|
||||
x: x,
|
||||
y: y,
|
||||
information: information,
|
||||
})
|
||||
} else {
|
||||
Err("Stroke must be a mouse stroke")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<Stroke> for raw::InterceptionKeyStroke {
|
||||
type Error = &'static str;
|
||||
|
||||
fn try_from(stroke: Stroke) -> Result<Self, Self::Error> {
|
||||
if let Stroke::Keyboard {
|
||||
code,
|
||||
state,
|
||||
information,
|
||||
} = stroke
|
||||
{
|
||||
Ok(raw::InterceptionKeyStroke {
|
||||
code: code as u16,
|
||||
state: state.bits(),
|
||||
information: information,
|
||||
})
|
||||
} else {
|
||||
Err("Stroke must be a keyboard stroke")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Interception {
|
||||
ctx: raw::InterceptionContext,
|
||||
}
|
||||
|
||||
impl Interception {
|
||||
pub fn new() -> Option<Self> {
|
||||
let ctx = unsafe { raw::interception_create_context() };
|
||||
|
||||
if ctx == std::ptr::null_mut() {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(Interception { ctx: ctx })
|
||||
}
|
||||
|
||||
pub fn get_precedence(&self, device: Device) -> Precedence {
|
||||
unsafe { raw::interception_get_precedence(self.ctx, device) }
|
||||
}
|
||||
|
||||
pub fn set_precedence(&self, device: Device, precedence: Precedence) {
|
||||
unsafe { raw::interception_set_precedence(self.ctx, device, precedence) }
|
||||
}
|
||||
|
||||
pub fn get_filter(&self, device: Device) -> Filter {
|
||||
if is_invalid(device) {
|
||||
return Filter::KeyFilter(KeyFilter::empty());
|
||||
}
|
||||
|
||||
let raw_filter = unsafe { raw::interception_get_filter(self.ctx, device) };
|
||||
if is_mouse(device) {
|
||||
let filter = match MouseFilter::from_bits(raw_filter) {
|
||||
Some(filter) => filter,
|
||||
None => MouseFilter::empty(),
|
||||
};
|
||||
|
||||
Filter::MouseFilter(filter)
|
||||
} else {
|
||||
let filter = match KeyFilter::from_bits(raw_filter) {
|
||||
Some(filter) => filter,
|
||||
None => KeyFilter::empty(),
|
||||
};
|
||||
|
||||
Filter::KeyFilter(filter)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_filter(&self, predicate: Predicate, filter: Filter) {
|
||||
let filter = match filter {
|
||||
Filter::MouseFilter(filter) => filter.bits(),
|
||||
Filter::KeyFilter(filter) => filter.bits(),
|
||||
};
|
||||
|
||||
unsafe {
|
||||
let predicate = std::mem::transmute(Some(predicate));
|
||||
raw::interception_set_filter(self.ctx, predicate, filter)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn wait(&self) -> Device {
|
||||
unsafe { raw::interception_wait(self.ctx) }
|
||||
}
|
||||
|
||||
pub fn wait_with_timeout(&self, duration: Duration) -> Device {
|
||||
let millis = match u32::try_from(duration.as_millis()) {
|
||||
Ok(m) => m,
|
||||
Err(_) => u32::MAX,
|
||||
};
|
||||
|
||||
unsafe { raw::interception_wait_with_timeout(self.ctx, millis) }
|
||||
}
|
||||
|
||||
pub fn send(&self, device: Device, strokes: &[Stroke]) -> i32 {
|
||||
if is_mouse(device) {
|
||||
self.send_internal::<raw::InterceptionMouseStroke>(device, strokes)
|
||||
} else if is_keyboard(device) {
|
||||
self.send_internal::<raw::InterceptionKeyStroke>(device, strokes)
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
fn send_internal<T: TryFrom<Stroke>>(&self, device: Device, strokes: &[Stroke]) -> i32 {
|
||||
let mut raw_strokes = Vec::new();
|
||||
|
||||
for stroke in strokes {
|
||||
if let Ok(raw_stroke) = T::try_from(*stroke) {
|
||||
raw_strokes.push(raw_stroke)
|
||||
}
|
||||
}
|
||||
|
||||
let ptr = raw_strokes.as_ptr();
|
||||
let len = match u32::try_from(raw_strokes.len()) {
|
||||
Ok(l) => l,
|
||||
Err(_) => u32::MAX,
|
||||
};
|
||||
|
||||
unsafe { raw::interception_send(self.ctx, device, std::mem::transmute(ptr), len) }
|
||||
}
|
||||
|
||||
pub fn receive(&self, device: Device, strokes: &mut [Stroke]) -> i32 {
|
||||
if is_mouse(device) {
|
||||
self.receive_internal::<raw::InterceptionMouseStroke>(device, strokes)
|
||||
} else if is_keyboard(device) {
|
||||
self.receive_internal::<raw::InterceptionKeyStroke>(device, strokes)
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
fn receive_internal<T: TryInto<Stroke> + Default + Copy>(
|
||||
&self,
|
||||
device: Device,
|
||||
strokes: &mut [Stroke],
|
||||
) -> i32 {
|
||||
let mut raw_strokes: Vec<T> = Vec::with_capacity(strokes.len());
|
||||
raw_strokes.resize_with(strokes.len(), Default::default);
|
||||
|
||||
let ptr = raw_strokes.as_ptr();
|
||||
let len = match u32::try_from(raw_strokes.len()) {
|
||||
Ok(l) => l,
|
||||
Err(_) => u32::MAX,
|
||||
};
|
||||
|
||||
let num_read =
|
||||
unsafe { raw::interception_receive(self.ctx, device, std::mem::transmute(ptr), len) };
|
||||
|
||||
let mut num_valid: i32 = 0;
|
||||
for i in 0..num_read {
|
||||
if let Ok(stroke) = raw_strokes[i as usize].try_into() {
|
||||
strokes[num_valid as usize] = stroke;
|
||||
num_valid += 1;
|
||||
}
|
||||
}
|
||||
|
||||
num_valid
|
||||
}
|
||||
|
||||
pub fn get_hardware_id(&self, device: Device, buffer: &mut [u8]) -> u32 {
|
||||
let ptr = buffer.as_mut_ptr();
|
||||
let len = match u32::try_from(buffer.len()) {
|
||||
Ok(l) => l,
|
||||
Err(_) => u32::MAX,
|
||||
};
|
||||
|
||||
unsafe {
|
||||
raw::interception_get_hardware_id(self.ctx, device, std::mem::transmute(ptr), len)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Interception {
|
||||
fn drop(&mut self) {
|
||||
unsafe { raw::interception_destroy_context(self.ctx) }
|
||||
}
|
||||
}
|
||||
|
||||
pub extern "C" fn is_invalid(device: Device) -> bool {
|
||||
unsafe { raw::interception_is_invalid(device) != 0 }
|
||||
}
|
||||
|
||||
pub extern "C" fn is_keyboard(device: Device) -> bool {
|
||||
unsafe { raw::interception_is_keyboard(device) != 0 }
|
||||
}
|
||||
|
||||
pub extern "C" fn is_mouse(device: Device) -> bool {
|
||||
unsafe { raw::interception_is_mouse(device) != 0 }
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
use num_enum::TryFromPrimitive;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
// ref: https://handmade.network/wiki/2823-keyboard_inputs_-_scancodes,_raw_input,_text_input,_key_names
|
||||
#[derive(Serialize, Deserialize, Hash, Debug, Eq, PartialEq, Copy, Clone, TryFromPrimitive)]
|
||||
#[repr(u16)]
|
||||
pub enum ScanCode {
|
||||
Esc = 0x01,
|
||||
|
||||
Num1 = 0x02,
|
||||
Num2 = 0x03,
|
||||
Num3 = 0x04,
|
||||
Num4 = 0x05,
|
||||
Num5 = 0x06,
|
||||
Num6 = 0x07,
|
||||
Num7 = 0x08,
|
||||
Num8 = 0x09,
|
||||
Num9 = 0x0A,
|
||||
Num0 = 0x0B,
|
||||
|
||||
Minus = 0x0C,
|
||||
Equals = 0x0D,
|
||||
Backspace = 0x0E,
|
||||
|
||||
Tab = 0x0F,
|
||||
|
||||
Q = 0x10,
|
||||
W = 0x11,
|
||||
E = 0x12,
|
||||
R = 0x13,
|
||||
T = 0x14,
|
||||
Y = 0x15,
|
||||
U = 0x16,
|
||||
I = 0x17,
|
||||
O = 0x18,
|
||||
P = 0x19,
|
||||
|
||||
LeftBracket = 0x1A,
|
||||
RightBracket = 0x1B,
|
||||
Enter = 0x1C,
|
||||
|
||||
LeftControl = 0x1D,
|
||||
|
||||
A = 0x1E,
|
||||
S = 0x1F,
|
||||
D = 0x20,
|
||||
F = 0x21,
|
||||
G = 0x22,
|
||||
H = 0x23,
|
||||
J = 0x24,
|
||||
K = 0x25,
|
||||
L = 0x26,
|
||||
|
||||
SemiColon = 0x27,
|
||||
Apostrophe = 0x28,
|
||||
Grave = 0x29,
|
||||
LeftShift = 0x2A,
|
||||
BackSlash = 0x2B,
|
||||
|
||||
Z = 0x2C,
|
||||
X = 0x2D,
|
||||
C = 0x2E,
|
||||
V = 0x2F,
|
||||
B = 0x30,
|
||||
N = 0x31,
|
||||
M = 0x32,
|
||||
|
||||
Comma = 0x33,
|
||||
Period = 0x34,
|
||||
Slash = 0x35,
|
||||
RightShift = 0x36,
|
||||
NumpadMultiply = 0x37,
|
||||
LeftAlt = 0x38,
|
||||
Space = 0x39,
|
||||
CapsLock = 0x3A,
|
||||
|
||||
F1 = 0x3B,
|
||||
F2 = 0x3C,
|
||||
F3 = 0x3D,
|
||||
F4 = 0x3E,
|
||||
F5 = 0x3F,
|
||||
F6 = 0x40,
|
||||
F7 = 0x41,
|
||||
F8 = 0x42,
|
||||
F9 = 0x43,
|
||||
F10 = 0x44,
|
||||
|
||||
NumLock = 0x45,
|
||||
ScrollLock = 0x46,
|
||||
|
||||
Numpad7 = 0x47,
|
||||
Numpad8 = 0x48,
|
||||
Numpad9 = 0x49,
|
||||
|
||||
NumpadMinus = 0x4A,
|
||||
|
||||
Numpad4 = 0x4B,
|
||||
Numpad5 = 0x4C,
|
||||
Numpad6 = 0x4D,
|
||||
|
||||
NumpadPlus = 0x4E,
|
||||
|
||||
Numpad1 = 0x4F,
|
||||
Numpad2 = 0x50,
|
||||
Numpad3 = 0x51,
|
||||
Numpad0 = 0x52,
|
||||
|
||||
NumpadPeriod = 0x53,
|
||||
AltPrintScreen = 0x54, /* Alt + print screen. */
|
||||
Int1 = 0x56, /* Key between the left shift and Z. */
|
||||
|
||||
F11 = 0x57,
|
||||
F12 = 0x58,
|
||||
|
||||
Oem1 = 0x5A, /* VK_OEM_WSCTRL */
|
||||
Oem2 = 0x5B, /* VK_OEM_FINISH */
|
||||
Oem3 = 0x5C, /* VK_OEM_JUMP */
|
||||
|
||||
EraseEOF = 0x5D,
|
||||
|
||||
Oem4 = 0x5E, /* VK_OEM_BACKTAB */
|
||||
Oem5 = 0x5F, /* VK_OEM_AUTO */
|
||||
|
||||
Zoom = 0x62,
|
||||
Help = 0x63,
|
||||
|
||||
F13 = 0x64,
|
||||
F14 = 0x65,
|
||||
F15 = 0x66,
|
||||
F16 = 0x67,
|
||||
F17 = 0x68,
|
||||
F18 = 0x69,
|
||||
F19 = 0x6A,
|
||||
F20 = 0x6B,
|
||||
F21 = 0x6C,
|
||||
F22 = 0x6D,
|
||||
F23 = 0x6E,
|
||||
|
||||
Oem6 = 0x6F, /* VK_OEM_PA3 */
|
||||
Katakana = 0x70,
|
||||
Oem7 = 0x71, /* VK_OEM_RESET */
|
||||
F24 = 0x76,
|
||||
|
||||
SBCSChar = 0x77,
|
||||
Convert = 0x79,
|
||||
NonConvert = 0x7B, /* VK_OEM_PA1 */
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
/target/
|
||||
@@ -0,0 +1,46 @@
|
||||
[package]
|
||||
name = "slider_io"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
# logging
|
||||
log = "0.4.14"
|
||||
env_logger = "0.9.0"
|
||||
|
||||
# threads
|
||||
parking_lot = "0.12.0"
|
||||
atomic_float = "0.1.0"
|
||||
|
||||
# async
|
||||
futures = "0.3.19"
|
||||
futures-util = "0.3.19"
|
||||
async-trait = "0.1.52"
|
||||
tokio = { version="1.16.1", features= ["rt-multi-thread","macros"] }
|
||||
tokio-util = "0.6.9"
|
||||
|
||||
# UI
|
||||
serde_json = "1.0"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
directories = "4.0.1"
|
||||
image = "0.23.14"
|
||||
|
||||
# device and system
|
||||
rusb = "0.9.0"
|
||||
serialport = "4.0.1"
|
||||
wwserial = {path = "../src-wwserial" }
|
||||
vigem-client = { version = "0.1.2", features = ["unstable"] }
|
||||
winapi = "0.3.9"
|
||||
interception = {path = "../src-interception" }
|
||||
ipconfig = "0.3.0"
|
||||
|
||||
# webserver
|
||||
hyper = { version="0.14.16", features= ["server", "http1", "http2", "tcp", "stream", "runtime"] }
|
||||
phf = { version = "0.10.1", features = ["macros"] }
|
||||
tungstenite = { version="0.16.0", default-features=false }
|
||||
tokio-tungstenite = "0.16.1"
|
||||
|
||||
# webserver utils
|
||||
base64 = "0.13.0"
|
||||
palette = "0.6.0"
|
||||
qrcode = { version="0.12.0", features= ["image"] }
|
||||
@@ -0,0 +1,15 @@
|
||||
max_width = 100
|
||||
hard_tabs = false
|
||||
tab_spaces = 2
|
||||
newline_style = "Auto"
|
||||
use_small_heuristics = "Default"
|
||||
reorder_imports = true
|
||||
reorder_modules = true
|
||||
remove_nested_parens = true
|
||||
edition = "2018"
|
||||
merge_derives = true
|
||||
use_try_shorthand = false
|
||||
use_field_init_shorthand = false
|
||||
force_explicit_abi = true
|
||||
imports_granularity = "Crate"
|
||||
wrap_comments = true
|
||||
@@ -0,0 +1,46 @@
|
||||
extern crate slider_io;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use std::{future::Future, io, time::Duration};
|
||||
|
||||
use tokio::{select, time::sleep};
|
||||
|
||||
use slider_io::shared::worker::{AsyncHaltableJob, AsyncHaltableWorker};
|
||||
|
||||
struct CounterJob;
|
||||
|
||||
#[async_trait]
|
||||
impl AsyncHaltableJob for CounterJob {
|
||||
async fn run<F: Future<Output = ()> + Send>(self, stop_signal: F) {
|
||||
let job_a = async {
|
||||
println!("Start job A");
|
||||
let mut x = 0;
|
||||
loop {
|
||||
x += 1;
|
||||
println!("{}", x);
|
||||
sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
};
|
||||
let job_b = async move {
|
||||
println!("Start job B");
|
||||
stop_signal.await;
|
||||
println!("Stop signal hit at job B");
|
||||
};
|
||||
|
||||
select! {
|
||||
_ = job_a => {},
|
||||
_ = job_b => {},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
env_logger::Builder::new()
|
||||
.filter_level(log::LevelFilter::Debug)
|
||||
.init();
|
||||
|
||||
let _worker = AsyncHaltableWorker::new("counter", CounterJob);
|
||||
let mut input = String::new();
|
||||
io::stdin().read_line(&mut input).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
extern crate slider_io;
|
||||
|
||||
use std::io;
|
||||
|
||||
use slider_io::{
|
||||
device::{brokenithm::BrokenithmJob, config::BrokenithmSpec},
|
||||
shared::worker::AsyncHaltableWorker,
|
||||
state::SliderState,
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
env_logger::Builder::new()
|
||||
.filter_level(log::LevelFilter::Debug)
|
||||
.init();
|
||||
|
||||
let state = SliderState::new();
|
||||
|
||||
let _worker = AsyncHaltableWorker::new(
|
||||
"brokenithm",
|
||||
BrokenithmJob::new(&state, &BrokenithmSpec::Nostalgia, &false, &1606),
|
||||
);
|
||||
let mut input = String::new();
|
||||
io::stdin().read_line(&mut input).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
extern crate slider_io;
|
||||
|
||||
use std::io;
|
||||
|
||||
use slider_io::{config::Config, context::Context};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
env_logger::Builder::new()
|
||||
.filter_level(log::LevelFilter::Debug)
|
||||
.init();
|
||||
|
||||
let config = Config::from_str(
|
||||
r##"{
|
||||
"deviceMode": "brokenithm",
|
||||
"outputMode": "kb-32-tasoller",
|
||||
"ledMode": "none",
|
||||
"disableAirStrings": false,
|
||||
"divaSerialPort": "COM1",
|
||||
"divaBrightness": 63,
|
||||
"brokenithmPort": 1606,
|
||||
"keyboardSensitivity": 20,
|
||||
"keyboardDirectInput": true,
|
||||
"outputPolling": "100",
|
||||
"outputWebsocketUrl": "localhost:3000",
|
||||
"ledFaster": false,
|
||||
"ledColorActive": "#ff00ff",
|
||||
"ledColorInactive": "#ffff00",
|
||||
"ledSensitivity": 20,
|
||||
"ledWebsocketUrl": "localhost:3001",
|
||||
"ledSerialPort": "COM5"
|
||||
}"##,
|
||||
)
|
||||
.unwrap();
|
||||
println!("{:?}", config);
|
||||
|
||||
#[allow(unused_variables)]
|
||||
let ctx = Context::new(config);
|
||||
|
||||
println!("Press enter to quit");
|
||||
let mut input = String::new();
|
||||
io::stdin().read_line(&mut input).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
extern crate slider_io;
|
||||
|
||||
use std::io;
|
||||
|
||||
use slider_io::{device::diva, shared::worker::ThreadJob, state::SliderState};
|
||||
|
||||
fn main() {
|
||||
env_logger::Builder::new()
|
||||
.filter_level(log::LevelFilter::Debug)
|
||||
.init();
|
||||
|
||||
let state = SliderState::new();
|
||||
let mut job = diva::DivaSliderJob::new(&state, &"COM1".to_string(), 0x3f);
|
||||
|
||||
let ok = job.setup();
|
||||
while ok {
|
||||
job.tick();
|
||||
}
|
||||
|
||||
// let state = SliderState::new();
|
||||
|
||||
// let timer = LoopTimer::new();
|
||||
// let _worker = ThreadWorker::new(
|
||||
// "d",
|
||||
// diva::DivaSliderJob::new(&state, &"COM4".to_string(), 0x3f),
|
||||
// timer,
|
||||
// );
|
||||
|
||||
println!("Press enter to quit");
|
||||
let mut input = String::new();
|
||||
io::stdin().read_line(&mut input).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
use std::{mem, ptr};
|
||||
use winapi::um::{commapi::*, fileapi::*, minwinbase::*, synchapi::*, winbase::*, winnt::*};
|
||||
|
||||
fn main() {
|
||||
unsafe {
|
||||
let mut port: Vec<u16> = vec![];
|
||||
port.extend("COM4".encode_utf16());
|
||||
port.push(0);
|
||||
|
||||
let handle = CreateFileW(
|
||||
port.as_ptr(),
|
||||
GENERIC_READ | GENERIC_WRITE,
|
||||
0,
|
||||
ptr::null_mut(),
|
||||
OPEN_EXISTING,
|
||||
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
|
||||
0 as HANDLE,
|
||||
);
|
||||
|
||||
let mut overlapped_read: OVERLAPPED = mem::zeroed();
|
||||
overlapped_read.hEvent = CreateEventW(ptr::null_mut(), 1, 0, ptr::null_mut());
|
||||
let mut overlapped_write: OVERLAPPED = mem::zeroed();
|
||||
overlapped_write.hEvent = CreateEventW(ptr::null_mut(), 0, 0, ptr::null_mut());
|
||||
|
||||
SetupComm(handle, 4096, 4096);
|
||||
|
||||
let mut timeouts: COMMTIMEOUTS = mem::zeroed();
|
||||
GetCommTimeouts(handle, &mut timeouts);
|
||||
|
||||
SetCommMask(handle, 0x80); // EV_ERR
|
||||
|
||||
let mut dcb: DCB = mem::zeroed();
|
||||
GetCommState(handle, &mut dcb);
|
||||
|
||||
dcb.BaudRate = 115200;
|
||||
dcb.ByteSize = 8;
|
||||
dcb.Parity = NOPARITY;
|
||||
dcb.set_fParity(0);
|
||||
dcb.StopBits = ONESTOPBIT;
|
||||
dcb.set_fBinary(1);
|
||||
|
||||
PurgeComm(
|
||||
handle,
|
||||
PURGE_TXCLEAR | PURGE_TXABORT | PURGE_RXCLEAR | PURGE_RXABORT,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
extern crate slider_io;
|
||||
|
||||
use std::{thread::sleep, time::Duration};
|
||||
|
||||
fn main() {
|
||||
let mut sp = serialport::new("COM4", 115200).open().unwrap();
|
||||
sp.write_request_to_send(true).unwrap();
|
||||
sp.write_data_terminal_ready(true).unwrap();
|
||||
|
||||
sleep(Duration::from_millis(100));
|
||||
println!("tx");
|
||||
let res = sp.write(&[0xff, 0x01, 0x00, 0xf1]).unwrap();
|
||||
println!("tx {}", res);
|
||||
|
||||
loop {
|
||||
sleep(Duration::from_millis(100));
|
||||
println!("rx");
|
||||
let mut buf = [0u8; 4];
|
||||
let res = sp.read(&mut buf).unwrap();
|
||||
println!("rx {} {:?}", res, buf);
|
||||
}
|
||||
}
|
||||
|
||||
// use serial2::SerialPort;
|
||||
|
||||
// fn main() {
|
||||
// let sp = SerialPort::open("COM4", 115200).unwrap();
|
||||
// println!("Tx");
|
||||
// let res = sp.write("data".as_bytes()).unwrap();
|
||||
// println!("Tx {}", res);
|
||||
// loop {
|
||||
// println!("Rx");
|
||||
// let mut buf = [0u8; 5];
|
||||
// let res = sp.read(&mut buf).unwrap();
|
||||
// // let res = sp.read(&mut buf).unwrap_or_else(|e| {
|
||||
// // println!("Err {}", e);
|
||||
// // 0
|
||||
// // });
|
||||
// println!("Rx {} {:?}", res, buf);
|
||||
// }
|
||||
|
||||
// let mut sp = serialport::new("COM4", 115200).open().unwrap();
|
||||
// println!("Tx");
|
||||
// let res = sp.write("data".as_bytes()).unwrap();
|
||||
// println!("Tx {}", res);
|
||||
// loop {
|
||||
// println!("Rx");
|
||||
// let mut buf = [0u8; 5];
|
||||
// let res = sp.read(&mut buf).unwrap();
|
||||
// println!("Rx {} {:?}", res, buf);
|
||||
// }
|
||||
// }
|
||||
|
||||
// use serialport::SerialPort;
|
||||
// use std::time::Duration;
|
||||
// use tokio::{
|
||||
// io::{self, AsyncReadExt, AsyncWriteExt},
|
||||
// time::sleep,
|
||||
// };
|
||||
// use tokio_serial::SerialPortBuilderExt;
|
||||
|
||||
// #[tokio::main]
|
||||
// async fn main() -> io::Result<()> {
|
||||
// let mut sp = tokio_serial::new("COM4", 115200)
|
||||
// .open_native_async()
|
||||
// .unwrap();
|
||||
|
||||
// sp.write_request_to_send(true).unwrap();
|
||||
// sp.write_data_terminal_ready(true).unwrap();
|
||||
// // sp.set_timeout(Duration::from_millis(1000))?;
|
||||
// let (mut rx_port, mut tx_port) = tokio::io::split(sp);
|
||||
|
||||
// // tx_port.write(&[41, 42, 43, 44]).await?;
|
||||
// // let mut buf = [0u8; 10];
|
||||
// // let res = rx_port.read(&mut buf).await?;
|
||||
// // println!("{}, {:?}", res, buf);
|
||||
|
||||
// loop {
|
||||
// let mut buf = [0u8; 10];
|
||||
// let res = rx_port.read(&mut buf).await?;
|
||||
// println!("{}, {:?}", res, buf);
|
||||
// }
|
||||
|
||||
// // let mut serial_reader =
|
||||
// // tokio_util::codec::FramedRead::new(rx_port,
|
||||
// // tokio_util::codec::BytesCodec::new()); let serial_sink =
|
||||
// // tokio_util::codec::FramedWrite::new(tx_port,
|
||||
// // tokio_util::codec::BytesCodec::new());
|
||||
|
||||
// // println!("Tx");
|
||||
// // let res = tx.write("data".as_bytes()).await?;
|
||||
// // println!("Sent {}", res);
|
||||
// // sleep(Duration::from_millis(1000)).await;
|
||||
// // loop {
|
||||
// // let mut buffer = [0u8; 1];
|
||||
// // println!("Rx");
|
||||
// // let res = rx.read(&mut buffer).await;
|
||||
// // println!("{:?} {:?}", res, buffer);
|
||||
// // }
|
||||
|
||||
// Ok(())
|
||||
// }
|
||||
@@ -1,4 +1,4 @@
|
||||
// extern crate slidershim;
|
||||
extern crate slider_io;
|
||||
|
||||
use serialport::available_ports;
|
||||
use std::io;
|
||||
@@ -7,5 +7,5 @@ fn main() {
|
||||
let res = available_ports();
|
||||
println!("{:?}", res);
|
||||
let mut input = String::new();
|
||||
let string = io::stdin().read_line(&mut input).unwrap();
|
||||
io::stdin().read_line(&mut input).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
extern crate slider_io;
|
||||
|
||||
use std::io;
|
||||
|
||||
use slider_io::config::Config;
|
||||
|
||||
fn main() {
|
||||
env_logger::Builder::new()
|
||||
.filter_level(log::LevelFilter::Debug)
|
||||
.init();
|
||||
|
||||
// voltex?
|
||||
let config = Config::from_str(
|
||||
r#"{
|
||||
"deviceMode": "yuancon",
|
||||
"outputMode": "gamepad-voltex",
|
||||
"outputPolling": "60",
|
||||
"keyboardSensitivity": 50,
|
||||
"ledMode": "reactive-voltex",
|
||||
"ledSensitivity": 50
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
println!("{:?}", config);
|
||||
|
||||
// serial?
|
||||
let config = Config::from_str(
|
||||
r#"{
|
||||
"deviceMode": "yuancon",
|
||||
"outputMode": "kb-32-tasoller",
|
||||
"outputPolling": "60",
|
||||
"keyboardSensitivity": 50,
|
||||
"ledMode": "serial",
|
||||
"ledSerialPort": "COM5"
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
println!("{:?}", config);
|
||||
|
||||
// basic
|
||||
let config = Config::from_str(
|
||||
r#"{
|
||||
"deviceMode": "yuancon",
|
||||
"outputMode": "kb-32-tasoller",
|
||||
"keyboardSensitivity": 50,
|
||||
"outputPolling": "60",
|
||||
"ledMode": "reactive-8",
|
||||
"ledSensitivity": 50
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
println!("{:?}", config);
|
||||
|
||||
// tasoller/
|
||||
let config = Config::from_str(
|
||||
r#"{
|
||||
"deviceMode": "tasoller-two",
|
||||
"outputMode": "kb-32-tasoller",
|
||||
"outputPolling": "60",
|
||||
"keyboardSensitivity": 50,
|
||||
"ledMode": "reactive-8",
|
||||
"ledSensitivity": 50
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
println!("{:?}", config);
|
||||
|
||||
// let manager = Context::new(config);
|
||||
|
||||
let mut input = String::new();
|
||||
io::stdin().read_line(&mut input).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
extern crate slider_io;
|
||||
|
||||
use std::{io, thread::sleep, time::Duration};
|
||||
|
||||
use slider_io::shared::{
|
||||
utils::LoopTimer,
|
||||
worker::{ThreadJob, ThreadWorker},
|
||||
};
|
||||
|
||||
struct TestJob {
|
||||
data: i64,
|
||||
}
|
||||
|
||||
impl ThreadJob for TestJob {
|
||||
fn setup(&mut self) -> bool {
|
||||
self.data = 0;
|
||||
println!("setup {}", self.data);
|
||||
true
|
||||
}
|
||||
fn tick(&mut self) -> bool {
|
||||
self.data += 1;
|
||||
println!("tick {}", self.data);
|
||||
sleep(Duration::from_millis(500));
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestJob {
|
||||
fn drop(&mut self) {
|
||||
self.data = -1;
|
||||
println!("teardown {}", self.data);
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let timer = LoopTimer::new();
|
||||
let _worker = ThreadWorker::new("j", TestJob { data: 1 }, timer);
|
||||
|
||||
let mut input = String::new();
|
||||
io::stdin().read_line(&mut input).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
use log::{info, warn};
|
||||
use serde_json::Value;
|
||||
use std::fs;
|
||||
|
||||
use crate::{
|
||||
device::config::DeviceMode, lighting::config::LightsMode, output::config::OutputMode, system,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Config {
|
||||
pub raw: String,
|
||||
pub device_mode: DeviceMode,
|
||||
pub output_mode: OutputMode,
|
||||
pub lights_mode: LightsMode,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn from_str(s: &str) -> Option<Config> {
|
||||
let v: Value = serde_json::from_str(s).ok()?;
|
||||
|
||||
Some(Config {
|
||||
raw: s.to_string(),
|
||||
device_mode: DeviceMode::from_serde_value(&v)?,
|
||||
output_mode: OutputMode::from_serde_value(&v)?,
|
||||
lights_mode: LightsMode::from_serde_value(&v)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn default() -> Self {
|
||||
Self::from_str(
|
||||
r##"{
|
||||
"deviceMode": "none",
|
||||
"outputMode": "none",
|
||||
"ledMode": "none",
|
||||
"disableAirStrings": false,
|
||||
"divaSerialPort": "COM1",
|
||||
"divaBrightness": 63,
|
||||
"brokenithmPort": 1606,
|
||||
"keyboardSensitivity": 20,
|
||||
"keyboardDirectInput": false,
|
||||
"outputPolling": "100",
|
||||
"outputWebsocketUrl": "localhost:3000",
|
||||
"ledFaster": false,
|
||||
"ledColorActive": "#ff00ff",
|
||||
"ledColorInactive": "#ffff00",
|
||||
"ledColorAirActive": "#0086ed",
|
||||
"ledColorAirInactive": "#000000",
|
||||
"ledSensitivity": 20,
|
||||
"ledWebsocketUrl": "localhost:3001",
|
||||
"ledSerialPort": "COM5"
|
||||
}"##,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn load_saved() -> Option<Self> {
|
||||
let config_path = system::get_config_path()?;
|
||||
if !config_path.exists() {
|
||||
return None;
|
||||
}
|
||||
info!("Config file found at {:?}", config_path);
|
||||
let saved_data = fs::read_to_string(config_path.as_path()).ok()?;
|
||||
return Self::from_str(saved_data.as_str());
|
||||
}
|
||||
|
||||
pub fn load() -> Self {
|
||||
let t = Self::load_saved();
|
||||
warn!("{:?}", t);
|
||||
t.or_else(|| {
|
||||
warn!("Config loading from file failed, using default");
|
||||
Some(Self::default())
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
pub fn save(&self) -> Option<()> {
|
||||
info!("Config saving...");
|
||||
let config_path = system::get_config_path()?;
|
||||
info!("Config saving to {:?}", config_path);
|
||||
fs::write(config_path.as_path(), self.raw.as_str()).unwrap();
|
||||
info!("Config saved");
|
||||
|
||||
Some(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
use atomic_float::AtomicF64;
|
||||
use log::info;
|
||||
use std::sync::{atomic::Ordering, Arc};
|
||||
|
||||
use crate::{
|
||||
config::Config,
|
||||
device::{brokenithm::BrokenithmJob, config::DeviceMode, diva::DivaSliderJob, hid::HidJob},
|
||||
lighting::{config::LightsMode, lighting::LightsJob, umgr_websocket::UmgrWebsocketJob},
|
||||
output::{config::OutputMode, output::OutputJob},
|
||||
shared::{
|
||||
utils::LoopTimer,
|
||||
worker::{AsyncHaltableWorker, AsyncWorker, ThreadWorker},
|
||||
},
|
||||
state::SliderState,
|
||||
};
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub struct Context {
|
||||
state: SliderState,
|
||||
config: Config,
|
||||
device_thread_worker: Option<ThreadWorker>,
|
||||
device_async_worker: Option<AsyncWorker>,
|
||||
device_async_haltable_worker: Option<AsyncHaltableWorker>,
|
||||
output_worker: Option<AsyncWorker>,
|
||||
lights_worker: Option<AsyncWorker>,
|
||||
lights_haltable_worker: Option<AsyncHaltableWorker>,
|
||||
timers: Vec<(&'static str, Arc<AtomicF64>)>,
|
||||
}
|
||||
|
||||
impl Context {
|
||||
pub fn new(config: Config) -> Self {
|
||||
info!("Context creating");
|
||||
info!("Device config {:?}", config.device_mode);
|
||||
info!("Output config {:?}", config.output_mode);
|
||||
info!("Lights config {:?}", config.lights_mode);
|
||||
|
||||
let state = SliderState::new();
|
||||
let mut timers = vec![];
|
||||
|
||||
let (device_thread_worker, device_async_worker, device_async_haltable_worker) =
|
||||
match &config.device_mode {
|
||||
DeviceMode::None => (None, None, None),
|
||||
DeviceMode::Brokenithm {
|
||||
spec,
|
||||
lights_enabled,
|
||||
port,
|
||||
} => (
|
||||
None,
|
||||
None,
|
||||
Some(AsyncHaltableWorker::new(
|
||||
"brokenithm",
|
||||
BrokenithmJob::new(&state, spec, lights_enabled, port),
|
||||
)),
|
||||
),
|
||||
DeviceMode::Hardware { spec, disable_air } => (
|
||||
{
|
||||
let timer = LoopTimer::new();
|
||||
timers.push(("d", timer.fork()));
|
||||
Some(ThreadWorker::new(
|
||||
"device",
|
||||
HidJob::from_config(&state, spec, disable_air),
|
||||
timer,
|
||||
))
|
||||
},
|
||||
None,
|
||||
None,
|
||||
),
|
||||
DeviceMode::DivaSlider { port, brightness } => (
|
||||
{
|
||||
let timer = LoopTimer::new();
|
||||
timers.push(("d", timer.fork()));
|
||||
Some(ThreadWorker::new(
|
||||
"diva",
|
||||
DivaSliderJob::new(&state, port, *brightness),
|
||||
timer,
|
||||
))
|
||||
},
|
||||
None,
|
||||
None,
|
||||
),
|
||||
};
|
||||
let output_worker = match &config.output_mode {
|
||||
OutputMode::None => None,
|
||||
_ => {
|
||||
let timer = LoopTimer::new();
|
||||
timers.push(("o", timer.fork()));
|
||||
Some(AsyncWorker::new(
|
||||
"output",
|
||||
OutputJob::new(&state, &config.output_mode),
|
||||
timer,
|
||||
))
|
||||
}
|
||||
};
|
||||
let (lights_worker, lights_haltable_worker) = match &config.lights_mode {
|
||||
LightsMode::None => (None, None),
|
||||
LightsMode::UmgrWebsocket { faster, port } => (
|
||||
None,
|
||||
Some(AsyncHaltableWorker::new(
|
||||
"lights",
|
||||
UmgrWebsocketJob::new(&state, faster, port),
|
||||
)),
|
||||
),
|
||||
_ => {
|
||||
let timer = LoopTimer::new();
|
||||
timers.push(("l", timer.fork()));
|
||||
(
|
||||
Some(AsyncWorker::new(
|
||||
"lights",
|
||||
LightsJob::new(&state, &config.lights_mode),
|
||||
timer,
|
||||
)),
|
||||
None,
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
Self {
|
||||
state,
|
||||
config,
|
||||
device_thread_worker,
|
||||
device_async_worker,
|
||||
device_async_haltable_worker,
|
||||
output_worker,
|
||||
lights_worker,
|
||||
lights_haltable_worker,
|
||||
timers,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clone_state(&self) -> SliderState {
|
||||
self.state.clone()
|
||||
}
|
||||
|
||||
pub fn timer_state(&self) -> String {
|
||||
self
|
||||
.timers
|
||||
.iter()
|
||||
.map(|(s, f)| format!("{}:{:.1}/s", s, f.load(Ordering::SeqCst)))
|
||||
.collect::<Vec<String>>()
|
||||
.join(" ")
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 5.7 KiB After Width: | Height: | Size: 5.7 KiB |
|
Before Width: | Height: | Size: 4.9 KiB After Width: | Height: | Size: 4.9 KiB |
@@ -0,0 +1,135 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>slidershim-brokenithm</title>
|
||||
<meta charset="utf8" />
|
||||
<meta
|
||||
name="viewport"
|
||||
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"
|
||||
/>
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<link rel="apple-touch-icon" sizes="192x192" href="/icon.png" />
|
||||
<style>
|
||||
#fullscreen {
|
||||
position: fixed;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
top: 0;
|
||||
left: 0;
|
||||
|
||||
background: #000000;
|
||||
color: hotpink;
|
||||
}
|
||||
|
||||
.container {
|
||||
position: fixed;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
top: 0;
|
||||
left: 0;
|
||||
|
||||
display: flex;
|
||||
flex-flow: column nowrap;
|
||||
touch-action: none;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.air-container {
|
||||
/* display: flex; */
|
||||
display: none;
|
||||
flex-flow: column nowrap;
|
||||
align-items: stretch;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.touch-container {
|
||||
display: flex;
|
||||
flex-flow: row nowrap;
|
||||
align-items: stretch;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.grow > * {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.key {
|
||||
flex: 1;
|
||||
border: 1px solid green;
|
||||
}
|
||||
|
||||
.key[data-active] {
|
||||
background-color: hotpink;
|
||||
}
|
||||
|
||||
.key.air[data-active] {
|
||||
background-color: skyblue;
|
||||
}
|
||||
|
||||
canvas {
|
||||
-ms-interpolation-mode: nearest-neighbor;
|
||||
image-rendering: crisp-edges;
|
||||
image-rendering: pixelated;
|
||||
touch-action: none;
|
||||
margin: 0px -1.5625vw;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="fullscreen">
|
||||
<!-- Offset for LED display -->
|
||||
<div class="container">
|
||||
<div class="air-container grow"></div>
|
||||
<div class="touch-container grow">
|
||||
<canvas id="canvas" width="33" height="1"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Hitbox Divs -->
|
||||
<div class="container" id="main">
|
||||
<div class="air-container grow">
|
||||
<div class="air key" data-air="1" data-kflag="5"></div>
|
||||
<div class="air key" data-air="1" data-kflag="4"></div>
|
||||
<div class="air key" data-air="1" data-kflag="3"></div>
|
||||
<div class="air key" data-air="1" data-kflag="2"></div>
|
||||
<div class="air key" data-air="1" data-kflag="1"></div>
|
||||
<div class="air key" data-air="1" data-kflag="0"></div>
|
||||
</div>
|
||||
<div class="touch-container grow">
|
||||
<div class="key" data-kflag="0"></div>
|
||||
<div class="key" data-kflag="1"></div>
|
||||
<div class="key" data-kflag="2"></div>
|
||||
<div class="key" data-kflag="3"></div>
|
||||
<div class="key" data-kflag="4"></div>
|
||||
<div class="key" data-kflag="5"></div>
|
||||
<div class="key" data-kflag="6"></div>
|
||||
<div class="key" data-kflag="7"></div>
|
||||
<div class="key" data-kflag="8"></div>
|
||||
<div class="key" data-kflag="9"></div>
|
||||
<div class="key" data-kflag="10"></div>
|
||||
<div class="key" data-kflag="11"></div>
|
||||
<div class="key" data-kflag="12"></div>
|
||||
<div class="key" data-kflag="13"></div>
|
||||
<div class="key" data-kflag="14"></div>
|
||||
<div class="key" data-kflag="15"></div>
|
||||
<div class="key" data-kflag="16"></div>
|
||||
<div class="key" data-kflag="17"></div>
|
||||
<div class="key" data-kflag="18"></div>
|
||||
<div class="key" data-kflag="19"></div>
|
||||
<div class="key" data-kflag="20"></div>
|
||||
<div class="key" data-kflag="21"></div>
|
||||
<div class="key" data-kflag="22"></div>
|
||||
<div class="key" data-kflag="23"></div>
|
||||
<div class="key" data-kflag="24"></div>
|
||||
<div class="key" data-kflag="25"></div>
|
||||
<div class="key" data-kflag="26"></div>
|
||||
<div class="key" data-kflag="27"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script src="/config.js"></script>
|
||||
<script>
|
||||
var allAir = true;
|
||||
</script>
|
||||
<script src="/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -46,7 +46,7 @@ const compileKey = (key) => {
|
||||
almostLeft: !!prev ? key.offsetLeft + key.offsetWidth / 4 : -99999,
|
||||
almostRight: !!next ? key.offsetLeft + (key.offsetWidth * 3) / 4 : 99999,
|
||||
kflag: parseInt(key.dataset.kflag) + (parseInt(key.dataset.air) ? 32 : 0),
|
||||
isAir: parseInt(key.dataset.air) ? true : false,
|
||||
isAir: parseInt(key.dataset.air) ? true : window.allAir || false,
|
||||
prevKeyRef: prev,
|
||||
prevKeyKflag: prev
|
||||
? parseInt(prev.dataset.kflag) + (parseInt(prev.dataset.air) ? 32 : 0)
|
||||
@@ -70,9 +70,9 @@ const compileKeys = () => {
|
||||
keys = document.getElementsByClassName("key");
|
||||
airKeys = [];
|
||||
touchKeys = [];
|
||||
for (var i = 0, key; i < keys.length; i++) {
|
||||
for (var i = 0; i < keys.length; i++) {
|
||||
const compiledKey = compileKey(keys[i]);
|
||||
if (!compiledKey.isAir) {
|
||||
if (compiledKey.kflag < 32) {
|
||||
touchKeys.push(compiledKey);
|
||||
} else {
|
||||
airKeys.push(compiledKey);
|
||||
@@ -80,6 +80,38 @@ const compileKeys = () => {
|
||||
allKeys.push(compiledKey);
|
||||
}
|
||||
|
||||
touchKeys.memo = {};
|
||||
airKeys.memo = {};
|
||||
|
||||
touchKeys.getAxis = (x, y) => x;
|
||||
airKeys.getAxis = (x, y) => y;
|
||||
|
||||
var getKey = function (x, y) {
|
||||
var c = this.getAxis(x, y);
|
||||
var res = this.memo[c];
|
||||
if (res === undefined) {
|
||||
for (var i = 0; i < this.length; i++) {
|
||||
if (isInside(x, y, this[i])) {
|
||||
res = this[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
this.memo[c] = res;
|
||||
}
|
||||
return res;
|
||||
};
|
||||
|
||||
touchKeys.getKey = getKey;
|
||||
airKeys.getKey = getKey;
|
||||
|
||||
for (var i = 0; i < window.outerWidth; i++) {
|
||||
touchKeys.getKey(i, touchKeys[0].top);
|
||||
}
|
||||
|
||||
for (var i = 0; i < window.outerHeight; i++) {
|
||||
airKeys.getKey(airKeys[0].left, i);
|
||||
}
|
||||
|
||||
if (!config.invert) {
|
||||
// Not inverted
|
||||
topKeys = airKeys;
|
||||
@@ -95,15 +127,9 @@ const compileKeys = () => {
|
||||
|
||||
const getKey = (x, y) => {
|
||||
if (y < midline) {
|
||||
for (var i = 0; i < topKeys.length; i++) {
|
||||
if (isInside(x, y, topKeys[i])) return topKeys[i];
|
||||
}
|
||||
return topKeys.getKey(x, y);
|
||||
} else {
|
||||
for (var i = 0; i < bottomKeys.length; i++) {
|
||||
if (isInside(x, y, bottomKeys[i])) {
|
||||
return bottomKeys[i];
|
||||
}
|
||||
}
|
||||
return bottomKeys.getKey(x, y);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
@@ -197,7 +223,7 @@ var ws = null;
|
||||
var wsTimeout = 0;
|
||||
var wsConnected = false;
|
||||
const wsConnect = () => {
|
||||
ws = new WebSocket("ws://" + location.host + "/ws");
|
||||
ws = new WebSocket((location.protocol == "https:" ? "wss://" : "ws://") + location.host + "/ws");
|
||||
ws.binaryType = "arraybuffer";
|
||||
ws.onopen = () => {
|
||||
ws.send("alive?");
|
||||
@@ -241,9 +267,9 @@ const updateLed = (data) => {
|
||||
canvasData.data[i * 4 + 5] = buf[i * 3 + 1]; // g
|
||||
canvasData.data[i * 4 + 6] = buf[i * 3 + 2]; // b
|
||||
}
|
||||
canvasData.data[0] = buf[0]
|
||||
canvasData.data[1] = buf[1]
|
||||
canvasData.data[2] = buf[2]
|
||||
canvasData.data[0] = buf[0];
|
||||
canvasData.data[1] = buf[1];
|
||||
canvasData.data[2] = buf[2];
|
||||
canvasData.data[128] = buf[90];
|
||||
canvasData.data[129] = buf[91];
|
||||
canvasData.data[130] = buf[92];
|
||||
@@ -18,7 +18,7 @@ use tokio::{
|
||||
use tokio_tungstenite::WebSocketStream;
|
||||
use tungstenite::{handshake, Message};
|
||||
|
||||
use crate::slider_io::{controller_state::FullState, worker::AsyncHaltableJob};
|
||||
use crate::{device::config::BrokenithmSpec, shared::worker::AsyncHaltableJob, state::SliderState};
|
||||
|
||||
// https://levelup.gitconnected.com/handling-websocket-and-http-on-the-same-port-with-rust-f65b770722c9
|
||||
|
||||
@@ -36,6 +36,7 @@ async fn error_response() -> Result<Response<Body>, Infallible> {
|
||||
static BROKENITHM_STR_FILES: phf::Map<&'static str, (&'static str, &'static str)> = phf_map! {
|
||||
"app.js" => (include_str!("./brokenithm-www/app.js"), "text/javascript"),
|
||||
"config.js" => (include_str!("./brokenithm-www/config.js"), "text/javascript"),
|
||||
"index-ns.html" => (include_str!("./brokenithm-www/index-ns.html"), "text/html"),
|
||||
"index-go.html" => (include_str!("./brokenithm-www/index-go.html"), "text/html"),
|
||||
"index.html" => (include_str!("./brokenithm-www/index.html"), "text/html"),
|
||||
};
|
||||
@@ -68,8 +69,8 @@ async fn serve_file(path: &str) -> Result<Response<Body>, Infallible> {
|
||||
|
||||
async fn handle_brokenithm(
|
||||
ws_stream: WebSocketStream<Upgraded>,
|
||||
state: FullState,
|
||||
led_enabled: bool,
|
||||
state: SliderState,
|
||||
lights_enabled: bool,
|
||||
) {
|
||||
let (mut ws_write, mut ws_read) = ws_stream.split();
|
||||
|
||||
@@ -114,15 +115,15 @@ async fn handle_brokenithm(
|
||||
}
|
||||
39 => {
|
||||
if chars[0] == 'b' {
|
||||
let mut controller_state_handle = state_handle.controller_state.lock();
|
||||
for (idx, c) in chars[0..32].iter().enumerate() {
|
||||
controller_state_handle.ground_state[idx] = match *c == '1' {
|
||||
let mut input_handle = state_handle.input.lock();
|
||||
for (idx, c) in chars[1..33].iter().enumerate() {
|
||||
input_handle.ground[idx] = match *c == '1' {
|
||||
false => 0,
|
||||
true => 255,
|
||||
}
|
||||
}
|
||||
for (idx, c) in chars[32..38].iter().enumerate() {
|
||||
controller_state_handle.air_state[idx] = match *c == '1' {
|
||||
for (idx, c) in chars[33..39].iter().enumerate() {
|
||||
input_handle.air[idx] = match *c == '1' {
|
||||
false => 0,
|
||||
true => 1,
|
||||
}
|
||||
@@ -136,12 +137,18 @@ async fn handle_brokenithm(
|
||||
}
|
||||
Message::Close(_) => {
|
||||
info!("Websocket connection closed");
|
||||
let mut input_handle = state_handle.input.lock();
|
||||
input_handle.ground.fill(0);
|
||||
input_handle.air.fill(0);
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Err(e) => {
|
||||
error!("Websocket connection error: {}", e);
|
||||
let mut input_handle = state_handle.input.lock();
|
||||
input_handle.ground.fill(0);
|
||||
input_handle.air.fill(0);
|
||||
break;
|
||||
}
|
||||
},
|
||||
@@ -153,7 +160,7 @@ async fn handle_brokenithm(
|
||||
// info!("Websocket read task done");
|
||||
};
|
||||
|
||||
match led_enabled {
|
||||
match lights_enabled {
|
||||
false => {
|
||||
select! {
|
||||
_ = read_task => {}
|
||||
@@ -163,14 +170,14 @@ async fn handle_brokenithm(
|
||||
true => {
|
||||
let msg_write_handle = msg_write.clone();
|
||||
let state_handle = state.clone();
|
||||
let led_task = async move {
|
||||
let lights_task = async move {
|
||||
loop {
|
||||
let mut led_data = vec![0; 93];
|
||||
let mut lights_data = vec![0; 93];
|
||||
{
|
||||
let led_state_handle = state_handle.led_state.lock();
|
||||
(&mut led_data).copy_from_slice(&led_state_handle.led_state);
|
||||
let lights_handle = state_handle.lights.lock();
|
||||
(&mut lights_data).copy_from_slice(&lights_handle.ground);
|
||||
}
|
||||
msg_write_handle.send(Message::Binary(led_data)).ok();
|
||||
msg_write_handle.send(Message::Binary(lights_data)).ok();
|
||||
|
||||
sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
@@ -179,7 +186,7 @@ async fn handle_brokenithm(
|
||||
select! {
|
||||
_ = read_task => {}
|
||||
_ = write_task => {}
|
||||
_ = led_task => {}
|
||||
_ = lights_task => {}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -187,8 +194,8 @@ async fn handle_brokenithm(
|
||||
|
||||
async fn handle_websocket(
|
||||
mut request: Request<Body>,
|
||||
state: FullState,
|
||||
led_enabled: bool,
|
||||
state: SliderState,
|
||||
lights_enabled: bool,
|
||||
) -> Result<Response<Body>, Infallible> {
|
||||
let res = match handshake::server::create_response_with_body(&request, || Body::empty()) {
|
||||
Ok(res) => {
|
||||
@@ -202,7 +209,7 @@ async fn handle_websocket(
|
||||
)
|
||||
.await;
|
||||
|
||||
handle_brokenithm(ws_stream, state, led_enabled).await;
|
||||
handle_brokenithm(ws_stream, state, lights_enabled).await;
|
||||
}
|
||||
|
||||
Err(e) => {
|
||||
@@ -227,9 +234,9 @@ async fn handle_websocket(
|
||||
async fn handle_request(
|
||||
request: Request<Body>,
|
||||
remote_addr: SocketAddr,
|
||||
state: FullState,
|
||||
ground_only: bool,
|
||||
led_enabled: bool,
|
||||
state: SliderState,
|
||||
spec: BrokenithmSpec,
|
||||
lights_enabled: bool,
|
||||
) -> Result<Response<Body>, Infallible> {
|
||||
let method = request.method();
|
||||
let path = request.uri().path();
|
||||
@@ -246,28 +253,36 @@ async fn handle_request(
|
||||
request.uri().path(),
|
||||
request.headers().contains_key(header::UPGRADE),
|
||||
) {
|
||||
("/", false) | ("/index.html", false) => match ground_only {
|
||||
false => serve_file("index.html").await,
|
||||
true => serve_file("index-go.html").await,
|
||||
("/", false) | ("/index.html", false) => match spec {
|
||||
BrokenithmSpec::Basic => serve_file("index.html").await,
|
||||
BrokenithmSpec::GroundOnly => serve_file("index-go.html").await,
|
||||
BrokenithmSpec::Nostalgia => serve_file("index-ns.html").await,
|
||||
},
|
||||
(filename, false) => serve_file(&filename[1..]).await,
|
||||
("/ws", true) => handle_websocket(request, state, led_enabled).await,
|
||||
("/ws", true) => handle_websocket(request, state, lights_enabled).await,
|
||||
_ => error_response().await,
|
||||
}
|
||||
}
|
||||
|
||||
pub struct BrokenithmJob {
|
||||
state: FullState,
|
||||
ground_only: bool,
|
||||
led_enabled: bool,
|
||||
state: SliderState,
|
||||
spec: BrokenithmSpec,
|
||||
lights_enabled: bool,
|
||||
port: u16,
|
||||
}
|
||||
|
||||
impl BrokenithmJob {
|
||||
pub fn new(state: &FullState, ground_only: &bool, led_enabled: &bool) -> Self {
|
||||
pub fn new(
|
||||
state: &SliderState,
|
||||
spec: &BrokenithmSpec,
|
||||
lights_enabled: &bool,
|
||||
port: &u16,
|
||||
) -> Self {
|
||||
Self {
|
||||
state: state.clone(),
|
||||
ground_only: *ground_only,
|
||||
led_enabled: *led_enabled,
|
||||
spec: spec.clone(),
|
||||
lights_enabled: *lights_enabled,
|
||||
port: *port,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -276,20 +291,22 @@ impl BrokenithmJob {
|
||||
impl AsyncHaltableJob for BrokenithmJob {
|
||||
async fn run<F: Future<Output = ()> + Send>(self, stop_signal: F) {
|
||||
let state = self.state.clone();
|
||||
let ground_only = self.ground_only;
|
||||
let led_enabled = self.led_enabled;
|
||||
let spec = self.spec.clone();
|
||||
let lights_enabled = self.lights_enabled;
|
||||
let make_svc = make_service_fn(|conn: &AddrStream| {
|
||||
let remote_addr = conn.remote_addr();
|
||||
let make_svc_state = state.clone();
|
||||
let make_spec = spec.clone();
|
||||
async move {
|
||||
Ok::<_, Infallible>(service_fn(move |request: Request<Body>| {
|
||||
let svc_state = make_svc_state.clone();
|
||||
handle_request(request, remote_addr, svc_state, ground_only, led_enabled)
|
||||
let spec = make_spec.clone();
|
||||
handle_request(request, remote_addr, svc_state, spec, lights_enabled)
|
||||
}))
|
||||
}
|
||||
});
|
||||
|
||||
let addr = SocketAddr::from(([0, 0, 0, 0], 1606));
|
||||
let addr = SocketAddr::from(([0, 0, 0, 0], self.port));
|
||||
info!("Brokenithm server listening on {}", addr);
|
||||
|
||||
let server = Server::bind(&addr)
|
||||
@@ -0,0 +1,107 @@
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum HardwareSpec {
|
||||
TasollerOne,
|
||||
TasollerTwo,
|
||||
Yuancon,
|
||||
YuanconThree,
|
||||
Yubideck,
|
||||
YubideckThree,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum BrokenithmSpec {
|
||||
Basic,
|
||||
GroundOnly,
|
||||
Nostalgia,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum DeviceMode {
|
||||
None,
|
||||
Hardware {
|
||||
spec: HardwareSpec,
|
||||
disable_air: bool,
|
||||
},
|
||||
Brokenithm {
|
||||
spec: BrokenithmSpec,
|
||||
lights_enabled: bool,
|
||||
port: u16,
|
||||
},
|
||||
DivaSlider {
|
||||
port: String,
|
||||
brightness: u8,
|
||||
},
|
||||
}
|
||||
|
||||
impl DeviceMode {
|
||||
pub fn from_serde_value(v: &Value) -> Option<Self> {
|
||||
Some(match v["deviceMode"].as_str()? {
|
||||
"none" => DeviceMode::None,
|
||||
"tasoller-one" => DeviceMode::Hardware {
|
||||
spec: HardwareSpec::TasollerOne,
|
||||
disable_air: v["disableAirStrings"].as_bool()?,
|
||||
},
|
||||
"tasoller-two" => DeviceMode::Hardware {
|
||||
spec: HardwareSpec::TasollerTwo,
|
||||
disable_air: v["disableAirStrings"].as_bool()?,
|
||||
},
|
||||
"yuancon" => DeviceMode::Hardware {
|
||||
spec: HardwareSpec::Yuancon,
|
||||
disable_air: v["disableAirStrings"].as_bool()?,
|
||||
},
|
||||
"yuancon-three" => DeviceMode::Hardware {
|
||||
spec: HardwareSpec::YuanconThree,
|
||||
disable_air: v["disableAirStrings"].as_bool()?,
|
||||
},
|
||||
"yubideck" => DeviceMode::Hardware {
|
||||
spec: HardwareSpec::Yubideck,
|
||||
disable_air: v["disableAirStrings"].as_bool()?,
|
||||
},
|
||||
"yubideck-three" => DeviceMode::Hardware {
|
||||
spec: HardwareSpec::YubideckThree,
|
||||
disable_air: v["disableAirStrings"].as_bool()?,
|
||||
},
|
||||
"diva" => DeviceMode::DivaSlider {
|
||||
port: v["divaSerialPort"].as_str()?.to_string(),
|
||||
brightness: u8::try_from(v["divaBrightness"].as_i64()?).ok()?,
|
||||
},
|
||||
"brokenithm" => DeviceMode::Brokenithm {
|
||||
spec: match v["disableAirStrings"].as_bool()? {
|
||||
false => BrokenithmSpec::Basic,
|
||||
true => BrokenithmSpec::GroundOnly,
|
||||
},
|
||||
lights_enabled: false,
|
||||
port: u16::try_from(v["brokenithmPort"].as_i64()?)
|
||||
.ok()
|
||||
.or(Some(1606))?,
|
||||
},
|
||||
"brokenithm-led" => DeviceMode::Brokenithm {
|
||||
spec: match v["disableAirStrings"].as_bool()? {
|
||||
false => BrokenithmSpec::Basic,
|
||||
true => BrokenithmSpec::GroundOnly,
|
||||
},
|
||||
lights_enabled: true,
|
||||
port: u16::try_from(v["brokenithmPort"].as_i64()?)
|
||||
.ok()
|
||||
.or(Some(1606))?,
|
||||
},
|
||||
"brokenithm-nostalgia" => DeviceMode::Brokenithm {
|
||||
spec: BrokenithmSpec::Nostalgia,
|
||||
lights_enabled: false,
|
||||
port: u16::try_from(v["brokenithmPort"].as_i64()?)
|
||||
.ok()
|
||||
.or(Some(1606))?,
|
||||
},
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn get_port(&self) -> Option<u16> {
|
||||
match self {
|
||||
DeviceMode::Brokenithm { port, .. } => Some(*port),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
use log::{error, info, warn};
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
time::{Duration, Instant},
|
||||
}; // thread::sleep, time::Duration
|
||||
use wwserial::WwSerial;
|
||||
|
||||
use crate::{shared::worker::ThreadJob, state::SliderState};
|
||||
|
||||
/*
|
||||
Init packet
|
||||
0xff 0x10 0x00 0xf1
|
||||
|
||||
Report of all touch sliders at 16 pressure
|
||||
0xff 0x01 0x20 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0xe0
|
||||
|
||||
Report of all touch sliders at 0-31 pressure
|
||||
0xff 0x01 0x20 0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x0a 0x0b 0x0c 0x0d 0x0e 0x0f 0x10 0x11 0x12 0x13 0x14 0x15 0x16 0x17 0x18 0x19 0x1a 0x1b 0x1c 0x1d 0x1e 0x1f 0x0f
|
||||
*/
|
||||
|
||||
#[derive(Debug)]
|
||||
struct DivaPacket {
|
||||
command: u8,
|
||||
len: u8,
|
||||
data: Vec<u8>,
|
||||
checksum: u8,
|
||||
raw: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl DivaPacket {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
command: 0,
|
||||
len: 0,
|
||||
data: Vec::with_capacity(256),
|
||||
checksum: 0,
|
||||
raw: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn from_bytes(command: u8, data: &[u8]) -> Self {
|
||||
let checksum = 0xffu64
|
||||
+ (command as u64)
|
||||
+ (data.len() as u64)
|
||||
+ data.iter().map(|x| (*x) as u64).sum::<u64>();
|
||||
let checksum = ((0x100 - (checksum & 0xff)) & 0xff) as u8;
|
||||
|
||||
Self {
|
||||
command,
|
||||
len: data.len() as u8,
|
||||
data: data.iter().copied().collect(),
|
||||
checksum: checksum,
|
||||
raw: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn push_raw_escaped(byte: u8, raw: &mut Vec<u8>) {
|
||||
match byte {
|
||||
0xfd => {
|
||||
raw.push(0xfd);
|
||||
raw.push(0xfc);
|
||||
}
|
||||
0xff => {
|
||||
raw.push(0xfd);
|
||||
raw.push(0xfe);
|
||||
}
|
||||
_ => {
|
||||
raw.push(byte);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize(&mut self) -> &Vec<u8> {
|
||||
let mut raw: Vec<u8> = Vec::with_capacity(512);
|
||||
|
||||
raw.push(0xff);
|
||||
Self::push_raw_escaped(self.command, &mut raw);
|
||||
Self::push_raw_escaped(self.len, &mut raw);
|
||||
for i in &self.data {
|
||||
Self::push_raw_escaped(*i, &mut raw);
|
||||
}
|
||||
Self::push_raw_escaped(self.checksum, &mut raw);
|
||||
|
||||
// null pad?
|
||||
// raw.push(0);
|
||||
|
||||
// debug!("Diva serializing {}", raw.len());
|
||||
self.raw = Some(raw);
|
||||
// debug!("Diva serializing {:?}", &self.raw);
|
||||
return self.raw.as_ref().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
enum DivaDeserializerState {
|
||||
ExpectCommand,
|
||||
ExpectLen,
|
||||
ExpectData,
|
||||
ExpectChecksum,
|
||||
Done,
|
||||
}
|
||||
|
||||
struct DivaDeserializer {
|
||||
state: DivaDeserializerState,
|
||||
checksum: u64,
|
||||
escape: u8,
|
||||
len: u8,
|
||||
packet: DivaPacket,
|
||||
}
|
||||
|
||||
impl DivaDeserializer {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
state: DivaDeserializerState::Done,
|
||||
checksum: 0,
|
||||
escape: 0,
|
||||
len: 0,
|
||||
packet: DivaPacket::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize(&mut self, data: &[u8], out: &mut VecDeque<DivaPacket>) {
|
||||
// debug!("Diva deserializing {} {:?}", data.len(), data);
|
||||
for c in data {
|
||||
match c {
|
||||
0xff => {
|
||||
self.packet = DivaPacket::new();
|
||||
self.checksum = 0xff;
|
||||
self.state = DivaDeserializerState::ExpectCommand;
|
||||
self.escape = 0;
|
||||
|
||||
// println!("{} open", c);
|
||||
}
|
||||
0xfd => {
|
||||
self.escape = 1;
|
||||
// println!("esc {}", c);
|
||||
}
|
||||
c => {
|
||||
let c = c + self.escape;
|
||||
self.escape = 0;
|
||||
|
||||
self.checksum += c as u64;
|
||||
match self.state {
|
||||
DivaDeserializerState::ExpectCommand => {
|
||||
self.packet.command = c;
|
||||
self.state = DivaDeserializerState::ExpectLen;
|
||||
|
||||
// println!("cmd {}", c);
|
||||
}
|
||||
DivaDeserializerState::ExpectLen => {
|
||||
self.len = c;
|
||||
self.packet.len = c;
|
||||
self.state = match c {
|
||||
0 => DivaDeserializerState::ExpectChecksum,
|
||||
_ => DivaDeserializerState::ExpectData,
|
||||
};
|
||||
// println!("len {}", c);
|
||||
}
|
||||
DivaDeserializerState::ExpectData => {
|
||||
self.packet.data.push(c);
|
||||
self.len -= 1;
|
||||
|
||||
if self.len == 0 {
|
||||
self.state = DivaDeserializerState::ExpectChecksum;
|
||||
}
|
||||
|
||||
// println!("data {}", c);
|
||||
}
|
||||
DivaDeserializerState::ExpectChecksum => {
|
||||
self.packet.checksum = c;
|
||||
debug_assert!(self.checksum & 0xff == 0);
|
||||
// println!("Packet complete {} {}", self.checksum, c);
|
||||
if self.checksum & 0xff == 0 {
|
||||
out.push_back(DivaPacket::new());
|
||||
std::mem::swap(&mut self.packet, out.back_mut().unwrap());
|
||||
}
|
||||
self.state = DivaDeserializerState::Done;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum DivaSliderBootstrap {
|
||||
Init,
|
||||
AwaitReset,
|
||||
AwaitInfo,
|
||||
ReadLoop,
|
||||
}
|
||||
|
||||
pub struct DivaSliderJob {
|
||||
state: SliderState,
|
||||
port: String,
|
||||
brightness: u8,
|
||||
read_buf: Vec<u8>,
|
||||
in_packets: VecDeque<DivaPacket>,
|
||||
out_packets: VecDeque<DivaPacket>,
|
||||
deserializer: DivaDeserializer,
|
||||
serial_port: Option<WwSerial>,
|
||||
bootstrap: DivaSliderBootstrap,
|
||||
last_lights: Instant,
|
||||
}
|
||||
|
||||
impl DivaSliderJob {
|
||||
pub fn new(state: &SliderState, port: &String, brightness: u8) -> Self {
|
||||
Self {
|
||||
state: state.clone(),
|
||||
port: port.clone(),
|
||||
brightness,
|
||||
read_buf: Vec::with_capacity(1024),
|
||||
in_packets: VecDeque::with_capacity(100),
|
||||
out_packets: VecDeque::with_capacity(100),
|
||||
deserializer: DivaDeserializer::new(),
|
||||
serial_port: None,
|
||||
bootstrap: DivaSliderBootstrap::Init,
|
||||
last_lights: Instant::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ThreadJob for DivaSliderJob {
|
||||
fn setup(&mut self) -> bool {
|
||||
info!(
|
||||
"Serial port for diva slider opening at {} {:?}",
|
||||
self.port.as_str(),
|
||||
115200
|
||||
);
|
||||
|
||||
let serial_port = WwSerial::new(self.port.clone(), 115200, 5, 0, false);
|
||||
if !serial_port.check() {
|
||||
error!("Cannot open serial port at {}", self.port.as_str());
|
||||
return false;
|
||||
}
|
||||
self.serial_port = Some(serial_port);
|
||||
true
|
||||
}
|
||||
|
||||
fn tick(&mut self) -> bool {
|
||||
let mut work = false;
|
||||
|
||||
let serial_port = self.serial_port.as_mut().unwrap();
|
||||
|
||||
self.read_buf.clear();
|
||||
let read_amount = serial_port.read(&mut self.read_buf) as usize;
|
||||
if read_amount > 0 {
|
||||
// debug!("Serial read {} bytes", read_amount);
|
||||
self
|
||||
.deserializer
|
||||
.deserialize(&self.read_buf[0..read_amount], &mut self.in_packets);
|
||||
}
|
||||
|
||||
match self.bootstrap {
|
||||
DivaSliderBootstrap::Init => {
|
||||
info!("Diva sending init");
|
||||
let reset_packet = DivaPacket::from_bytes(0x10, &[]);
|
||||
self.out_packets.push_back(reset_packet);
|
||||
self.bootstrap = DivaSliderBootstrap::AwaitReset;
|
||||
}
|
||||
DivaSliderBootstrap::AwaitReset => {
|
||||
while let Some(ack_packet) = self.in_packets.pop_front() {
|
||||
if ack_packet.command == 0x10 && ack_packet.len == 0x00 && ack_packet.checksum == 0xf1 {
|
||||
info!(
|
||||
"Diva ack init {:#4x} {:?}",
|
||||
ack_packet.command, ack_packet.data
|
||||
);
|
||||
|
||||
info!("Diva sending info");
|
||||
let info_packet = DivaPacket::from_bytes(0xf0, &[]);
|
||||
self.out_packets.push_back(info_packet);
|
||||
self.bootstrap = DivaSliderBootstrap::AwaitInfo;
|
||||
break;
|
||||
} else {
|
||||
warn!(
|
||||
"Unexpected packet {:#4x} {:?}",
|
||||
ack_packet.command, ack_packet.data
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
DivaSliderBootstrap::AwaitInfo => {
|
||||
if let Some(ack_packet) = self.in_packets.pop_front() {
|
||||
info!(
|
||||
"Diva ack info {:#4x} {:?}",
|
||||
ack_packet.command, ack_packet.data
|
||||
);
|
||||
|
||||
info!("Diva sending start");
|
||||
let start_packet = DivaPacket::from_bytes(0x03, &[]);
|
||||
self.out_packets.push_back(start_packet);
|
||||
self.bootstrap = DivaSliderBootstrap::ReadLoop;
|
||||
self.last_lights = Instant::now();
|
||||
}
|
||||
}
|
||||
DivaSliderBootstrap::ReadLoop => {
|
||||
while let Some(data_packet) = self.in_packets.pop_front() {
|
||||
if data_packet.command == 0x01 && data_packet.len == 32 {
|
||||
let mut input_handle = self.state.input.lock();
|
||||
input_handle
|
||||
.ground
|
||||
.copy_from_slice(&data_packet.data[0..32]);
|
||||
input_handle.flip_all();
|
||||
work = true;
|
||||
}
|
||||
}
|
||||
|
||||
let mut send_lights = false;
|
||||
let mut lights_buf = [0; 94];
|
||||
{
|
||||
let mut lights_handle = self.state.lights.lock();
|
||||
// Send leds at least once a second to keep alive
|
||||
if lights_handle.dirty || self.last_lights.elapsed() > Duration::from_millis(1000) {
|
||||
send_lights = true;
|
||||
lights_buf[0] = self.brightness;
|
||||
for (buf_chunk, state_chunk) in lights_buf[1..94]
|
||||
.chunks_mut(3)
|
||||
.take(31)
|
||||
.zip(lights_handle.ground.chunks(3).rev())
|
||||
{
|
||||
buf_chunk[0] = state_chunk[2];
|
||||
buf_chunk[1] = state_chunk[0];
|
||||
buf_chunk[2] = state_chunk[1];
|
||||
}
|
||||
lights_handle.dirty = false;
|
||||
}
|
||||
}
|
||||
|
||||
if send_lights {
|
||||
self.last_lights = Instant::now();
|
||||
let lights_packet = DivaPacket::from_bytes(0x02, &lights_buf);
|
||||
self.out_packets.push_back(lights_packet);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// sleep(Duration::from_millis(3));
|
||||
while let Some(mut packet) = self.out_packets.pop_front() {
|
||||
work = true;
|
||||
let data = packet.serialize();
|
||||
let bytes_written = serial_port.write(data);
|
||||
if bytes_written == 0 {
|
||||
warn!("Serial write timeout");
|
||||
}
|
||||
serial_port.flush();
|
||||
// debug!("Serial write {}/{}", bytes_written, data.len());
|
||||
}
|
||||
|
||||
// sleep(Duration::from_millis(3));
|
||||
|
||||
// TODO: async worker?
|
||||
// sleep(Duration::from_millis(10));
|
||||
|
||||
work
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DivaSliderJob {
|
||||
fn drop(&mut self) {
|
||||
match self.bootstrap {
|
||||
DivaSliderBootstrap::ReadLoop => {
|
||||
let serial_port = self.serial_port.as_mut().unwrap();
|
||||
let mut stop_packet = DivaPacket::from_bytes(0x04, &[]);
|
||||
serial_port.write(stop_packet.serialize());
|
||||
}
|
||||
_ => {}
|
||||
};
|
||||
info!("Diva serial port closed");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,494 @@
|
||||
use log::{error, info};
|
||||
use rusb::{self, DeviceHandle, GlobalContext};
|
||||
use std::{
|
||||
error::Error,
|
||||
mem::swap,
|
||||
ops::{Deref, DerefMut},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
shared::{
|
||||
utils::{Buffer, ShimError},
|
||||
worker::ThreadJob,
|
||||
},
|
||||
state::{SliderInput, SliderLights, SliderState},
|
||||
};
|
||||
|
||||
use super::config::HardwareSpec;
|
||||
|
||||
type HidReadCallback = fn(&Buffer, &mut SliderInput) -> ();
|
||||
type HidLedCallback = fn(&mut Buffer, &mut Buffer, &SliderLights) -> ();
|
||||
|
||||
enum WriteType {
|
||||
Bulk,
|
||||
Interrupt,
|
||||
}
|
||||
|
||||
pub struct HidJob {
|
||||
state: SliderState,
|
||||
|
||||
vid: u16,
|
||||
pid: u16,
|
||||
read_endpoint: u8,
|
||||
led_endpoint: u8,
|
||||
disable_air: bool,
|
||||
|
||||
read_callback: HidReadCallback,
|
||||
read_buf: Buffer,
|
||||
last_read_buf: Buffer,
|
||||
|
||||
led_write_type: WriteType,
|
||||
led_callback: HidLedCallback,
|
||||
led_buf: Buffer,
|
||||
led_buf_two: Buffer,
|
||||
|
||||
handle: Option<DeviceHandle<GlobalContext>>,
|
||||
}
|
||||
|
||||
impl HidJob {
|
||||
fn new(
|
||||
state: SliderState,
|
||||
vid: u16,
|
||||
pid: u16,
|
||||
read_endpoint: u8,
|
||||
led_endpoint: u8,
|
||||
disable_air: bool,
|
||||
read_callback: HidReadCallback,
|
||||
led_type: WriteType,
|
||||
led_callback: HidLedCallback,
|
||||
) -> Self {
|
||||
Self {
|
||||
state,
|
||||
vid,
|
||||
pid,
|
||||
read_endpoint,
|
||||
led_endpoint,
|
||||
disable_air,
|
||||
read_callback,
|
||||
read_buf: Buffer::new(),
|
||||
last_read_buf: Buffer::new(),
|
||||
led_write_type: led_type,
|
||||
led_callback,
|
||||
led_buf: Buffer::new(),
|
||||
led_buf_two: Buffer::new(),
|
||||
handle: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_config(state: &SliderState, spec: &HardwareSpec, disable_air: &bool) -> Self {
|
||||
match spec {
|
||||
HardwareSpec::TasollerOne => Self::new(
|
||||
state.clone(),
|
||||
0x1ccf,
|
||||
0x2333,
|
||||
0x84,
|
||||
0x03,
|
||||
*disable_air,
|
||||
|buf, input| {
|
||||
if buf.len != 11 {
|
||||
return;
|
||||
}
|
||||
|
||||
let bits: Vec<u8> = buf
|
||||
.data
|
||||
.iter()
|
||||
.flat_map(|x| (0..8).map(move |i| ((x) >> i) & 1))
|
||||
.collect();
|
||||
for i in 0..32 {
|
||||
input.ground[i] = bits[34 + i] * 255;
|
||||
}
|
||||
input.flip_vert();
|
||||
|
||||
input.air.copy_from_slice(&bits[28..34]);
|
||||
input.extra[0..2].copy_from_slice(&bits[26..28]);
|
||||
},
|
||||
WriteType::Bulk,
|
||||
|buf, _, lights| {
|
||||
buf.len = 240;
|
||||
buf.data[0] = 'B' as u8;
|
||||
buf.data[1] = 'L' as u8;
|
||||
buf.data[2] = '\x00' as u8;
|
||||
for (buf_chunk, state_chunk) in buf.data[3..96]
|
||||
.chunks_mut(3)
|
||||
.take(31)
|
||||
.zip(lights.ground.chunks(3).rev())
|
||||
{
|
||||
buf_chunk[0] = state_chunk[1];
|
||||
buf_chunk[1] = state_chunk[0];
|
||||
buf_chunk[2] = state_chunk[2];
|
||||
}
|
||||
buf.data[96..240].fill(0);
|
||||
},
|
||||
),
|
||||
HardwareSpec::TasollerTwo => Self::new(
|
||||
state.clone(),
|
||||
0x1ccf,
|
||||
0x2333,
|
||||
0x84,
|
||||
0x03,
|
||||
*disable_air,
|
||||
|buf, input| {
|
||||
if buf.len != 36 {
|
||||
return;
|
||||
}
|
||||
|
||||
input.ground.copy_from_slice(&buf.data[4..36]);
|
||||
input.flip_vert();
|
||||
|
||||
let bits: Vec<u8> = (0..8).map(|x| (buf.data[3] >> x) & 1).collect();
|
||||
input.air.copy_from_slice(&bits[0..6]);
|
||||
input.extra[0..2].copy_from_slice(&bits[6..8]);
|
||||
},
|
||||
WriteType::Bulk,
|
||||
|buf, _, lights| {
|
||||
buf.len = 240;
|
||||
buf.data[0] = 'B' as u8;
|
||||
buf.data[1] = 'L' as u8;
|
||||
buf.data[2] = '\x00' as u8;
|
||||
for (buf_chunk, state_chunk) in buf.data[3..96]
|
||||
.chunks_mut(3)
|
||||
.take(31)
|
||||
.zip(lights.ground.chunks(3).rev())
|
||||
{
|
||||
buf_chunk[0] = state_chunk[1];
|
||||
buf_chunk[1] = state_chunk[0];
|
||||
buf_chunk[2] = state_chunk[2];
|
||||
}
|
||||
|
||||
for (buf_chunks, state_chunk) in buf.data[96..240].chunks_mut(24).zip(
|
||||
lights
|
||||
.air_left
|
||||
.chunks(3)
|
||||
.rev()
|
||||
.chain(lights.air_right.chunks(3)),
|
||||
) {
|
||||
for idx in 0..8 {
|
||||
buf_chunks[0 + idx * 3] = state_chunk[1];
|
||||
buf_chunks[1 + idx * 3] = state_chunk[0];
|
||||
buf_chunks[2 + idx * 3] = state_chunk[2];
|
||||
}
|
||||
}
|
||||
},
|
||||
),
|
||||
HardwareSpec::Yuancon => Self::new(
|
||||
state.clone(),
|
||||
0x1973,
|
||||
0x2001,
|
||||
0x81,
|
||||
0x02,
|
||||
*disable_air,
|
||||
|buf, input| {
|
||||
if buf.len != 34 && buf.len != 35 {
|
||||
return;
|
||||
}
|
||||
|
||||
input.ground.copy_from_slice(&buf.data[2..34]);
|
||||
for i in 0..6 {
|
||||
input.air[i ^ 1] = (buf.data[0] >> i) & 1;
|
||||
}
|
||||
for i in 0..3 {
|
||||
input.extra[2 - i] = (buf.data[1] >> i) & 1;
|
||||
}
|
||||
},
|
||||
WriteType::Interrupt,
|
||||
|buf, _, lights| {
|
||||
buf.len = 31 * 2;
|
||||
for (buf_chunk, state_chunk) in buf
|
||||
.data
|
||||
.chunks_mut(2)
|
||||
.take(31)
|
||||
.zip(lights.ground.chunks(3).rev())
|
||||
{
|
||||
buf_chunk[0] = (state_chunk[0] << 3 & 0xe0) | (state_chunk[2] >> 3);
|
||||
buf_chunk[1] = (state_chunk[1] & 0xf8) | (state_chunk[0] >> 5);
|
||||
}
|
||||
},
|
||||
),
|
||||
HardwareSpec::YuanconThree => Self::new(
|
||||
state.clone(),
|
||||
0x0518,
|
||||
0x2022,
|
||||
0x83,
|
||||
0x03,
|
||||
*disable_air,
|
||||
|buf, input| {
|
||||
if buf.len != 46 { // real length is 46 but last 12 bytes are unused
|
||||
return;
|
||||
}
|
||||
|
||||
input.ground.copy_from_slice(&buf.data[2..34]);
|
||||
input.flip_vert();
|
||||
|
||||
let bits: Vec<u8> = (0..8).map(|x| (buf.data[0] >> x) & 1).collect();
|
||||
for i in 0..6 {
|
||||
input.air[i ^ 1] = bits[i];
|
||||
}
|
||||
input.extra[0..2].copy_from_slice(&bits[6..8]);
|
||||
},
|
||||
WriteType::Interrupt,
|
||||
|buf, buf_two, lights| {
|
||||
buf.len = 61;
|
||||
buf.data[0] = 0;
|
||||
buf_two.len = 61;
|
||||
buf_two.data[0] = 1;
|
||||
|
||||
for (buf_chunk, state_chunk) in buf.data[1..61]
|
||||
.chunks_mut(3)
|
||||
.zip(lights.ground.chunks(3).skip(11).take(20).rev())
|
||||
{
|
||||
buf_chunk[0] = state_chunk[0];
|
||||
buf_chunk[1] = state_chunk[1];
|
||||
buf_chunk[2] = state_chunk[2];
|
||||
}
|
||||
|
||||
for (buf_chunk, state_chunk) in buf_two.data[1..34]
|
||||
.chunks_mut(3)
|
||||
.zip(lights.ground.chunks(3).take(11).rev())
|
||||
{
|
||||
buf_chunk[0] = state_chunk[0];
|
||||
buf_chunk[1] = state_chunk[1];
|
||||
buf_chunk[2] = state_chunk[2];
|
||||
}
|
||||
},
|
||||
),
|
||||
HardwareSpec::Yubideck => Self::new(
|
||||
state.clone(),
|
||||
0x1973,
|
||||
0x2001,
|
||||
0x81, // Need to confirm
|
||||
0x02, // Need to confirm
|
||||
*disable_air,
|
||||
|buf, input| {
|
||||
if buf.len != 45 && buf.len != 46 {
|
||||
return;
|
||||
}
|
||||
|
||||
input.ground.copy_from_slice(&buf.data[2..34]);
|
||||
input.flip_vert();
|
||||
for i in 0..6 {
|
||||
input.air[i ^ 1] = (buf.data[0] >> i) & 1;
|
||||
}
|
||||
for i in 0..3 {
|
||||
input.extra[2 - i] = (buf.data[1] >> i) & 1;
|
||||
}
|
||||
},
|
||||
WriteType::Interrupt,
|
||||
|buf, _, lights| {
|
||||
buf.len = 62;
|
||||
|
||||
let lights_nibbles: Vec<u8> = lights
|
||||
.ground
|
||||
.chunks(3)
|
||||
.rev()
|
||||
.flat_map(|x| x.iter().map(|y| *y >> 4))
|
||||
.chain([
|
||||
lights.air_left[3] >> 4,
|
||||
lights.air_left[4] >> 4,
|
||||
lights.air_left[5] >> 4,
|
||||
])
|
||||
.collect();
|
||||
|
||||
for (buf_chunk, state_chunk) in buf
|
||||
.data
|
||||
.chunks_mut(3)
|
||||
.take(16)
|
||||
.zip(lights_nibbles.chunks(6))
|
||||
{
|
||||
buf_chunk[0] = (state_chunk[0]) | (state_chunk[1] << 4);
|
||||
buf_chunk[1] = (state_chunk[2]) | (state_chunk[3] << 4);
|
||||
buf_chunk[2] = (state_chunk[4]) | (state_chunk[5] << 4);
|
||||
}
|
||||
},
|
||||
),
|
||||
HardwareSpec::YubideckThree => Self::new(
|
||||
state.clone(),
|
||||
0x1973,
|
||||
0x2001,
|
||||
0x81, // Need to confirm
|
||||
0x02, // Need to confirm
|
||||
*disable_air,
|
||||
|buf, input| {
|
||||
if buf.len != 45 && buf.len != 46 {
|
||||
return;
|
||||
}
|
||||
|
||||
input.ground.copy_from_slice(&buf.data[2..34]);
|
||||
input.flip_vert();
|
||||
for i in 0..6 {
|
||||
input.air[i ^ 1] = (buf.data[0] >> i) & 1;
|
||||
}
|
||||
for i in 0..3 {
|
||||
input.extra[2 - i] = (buf.data[1] >> i) & 1;
|
||||
}
|
||||
},
|
||||
WriteType::Interrupt,
|
||||
|buf, buf_two, lights| {
|
||||
buf.len = 61;
|
||||
buf.data[0] = 0;
|
||||
buf_two.len = 61;
|
||||
buf_two.data[0] = 1;
|
||||
|
||||
for (buf_chunk, state_chunk) in buf.data[1..61]
|
||||
.chunks_mut(3)
|
||||
.zip(lights.ground.chunks(3).skip(11).take(20).rev())
|
||||
{
|
||||
buf_chunk[0] = state_chunk[0];
|
||||
buf_chunk[1] = state_chunk[1];
|
||||
buf_chunk[2] = state_chunk[2];
|
||||
}
|
||||
|
||||
for (buf_chunk, state_chunk) in buf_two.data[1..34]
|
||||
.chunks_mut(3)
|
||||
.zip(lights.ground.chunks(3).take(11).rev())
|
||||
{
|
||||
buf_chunk[0] = state_chunk[0];
|
||||
buf_chunk[1] = state_chunk[1];
|
||||
buf_chunk[2] = state_chunk[2];
|
||||
}
|
||||
|
||||
buf_two.data[34..37].copy_from_slice(&lights.air_left[3..6]);
|
||||
buf_two.data[37..40].copy_from_slice(&lights.air_right[3..6]);
|
||||
},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn get_handle(&mut self) -> Result<(), Box<dyn Error>> {
|
||||
info!("Device finding vid {} pid {}", self.vid, self.pid);
|
||||
let handle = rusb::open_device_with_vid_pid(self.vid, self.pid);
|
||||
if handle.is_none() {
|
||||
error!("Device not found");
|
||||
return Err(Box::new(ShimError));
|
||||
}
|
||||
let mut handle = handle.unwrap();
|
||||
info!("Device found {:?}", handle);
|
||||
|
||||
if handle.kernel_driver_active(0).unwrap_or(false) {
|
||||
info!("Device detaching kernel driver");
|
||||
handle.detach_kernel_driver(0)?;
|
||||
}
|
||||
info!("Device setting configuration");
|
||||
handle.set_active_configuration(1)?;
|
||||
|
||||
// A bit janky but Laverita v3 seems to require interface 3
|
||||
info!("Device claiming interface");
|
||||
if self.vid == 0x0518 && self.pid == 0x2022 {
|
||||
handle.claim_interface(3)?;
|
||||
} else {
|
||||
handle.claim_interface(0)?;
|
||||
}
|
||||
|
||||
self.handle = Some(handle);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
const TIMEOUT: Duration = Duration::from_millis(20);
|
||||
|
||||
impl ThreadJob for HidJob {
|
||||
fn setup(&mut self) -> bool {
|
||||
match self.get_handle() {
|
||||
Ok(_) => {
|
||||
info!("Device OK");
|
||||
true
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Device setup failed: {}", e);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn tick(&mut self) -> bool {
|
||||
// Input loop
|
||||
let handle = self.handle.as_mut().unwrap();
|
||||
let mut work = false;
|
||||
|
||||
{
|
||||
let res = handle
|
||||
.read_interrupt(self.read_endpoint, &mut self.read_buf.data, TIMEOUT)
|
||||
.map_err(|e| {
|
||||
// debug!("Device read error {}", &e);
|
||||
e
|
||||
})
|
||||
.unwrap_or(0);
|
||||
self.read_buf.len = res;
|
||||
// debug!("{:?}", self.read_buf.slice());
|
||||
// if self.read_buf.len != 0 {
|
||||
if (self.read_buf.len != 0) && (self.read_buf.slice() != self.last_read_buf.slice()) {
|
||||
work = true;
|
||||
let mut input_handle = self.state.input.lock();
|
||||
(self.read_callback)(&self.read_buf, input_handle.deref_mut());
|
||||
|
||||
if self.disable_air {
|
||||
input_handle.air.fill(0);
|
||||
}
|
||||
swap(&mut self.read_buf, &mut self.last_read_buf);
|
||||
}
|
||||
}
|
||||
|
||||
// Led loop
|
||||
{
|
||||
{
|
||||
let mut lights_handle = self.state.lights.lock();
|
||||
if lights_handle.dirty {
|
||||
(self.led_callback)(
|
||||
&mut self.led_buf,
|
||||
&mut self.led_buf_two,
|
||||
lights_handle.deref(),
|
||||
);
|
||||
lights_handle.dirty = false;
|
||||
}
|
||||
}
|
||||
|
||||
if self.led_buf.len != 0 {
|
||||
let res = (match self.led_write_type {
|
||||
WriteType::Bulk => handle.write_bulk(self.led_endpoint, self.led_buf.slice(), TIMEOUT),
|
||||
WriteType::Interrupt => {
|
||||
handle.write_interrupt(self.led_endpoint, &self.led_buf.slice(), TIMEOUT)
|
||||
}
|
||||
})
|
||||
.map_err(|e| {
|
||||
// debug!("Device write error {}", e);
|
||||
e
|
||||
})
|
||||
.unwrap_or(0);
|
||||
if res == self.led_buf.len + 1 {
|
||||
// work = true;
|
||||
self.led_buf.len = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if self.led_buf_two.len != 0 {
|
||||
let res = (match self.led_write_type {
|
||||
WriteType::Bulk => {
|
||||
handle.write_bulk(self.led_endpoint, self.led_buf_two.slice(), TIMEOUT)
|
||||
}
|
||||
WriteType::Interrupt => {
|
||||
handle.write_interrupt(self.led_endpoint, &self.led_buf_two.slice(), TIMEOUT)
|
||||
}
|
||||
})
|
||||
.map_err(|e| {
|
||||
// debug!("Device write error {}", e);
|
||||
e
|
||||
})
|
||||
.unwrap_or(0);
|
||||
if res == self.led_buf_two.len + 1 {
|
||||
// work = true;
|
||||
self.led_buf_two.len = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
work
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for HidJob {
|
||||
fn drop(&mut self) {
|
||||
if let Some(handle) = self.handle.as_mut() {
|
||||
handle.release_interface(0).ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
pub mod config;
|
||||
|
||||
pub mod brokenithm;
|
||||
pub mod diva;
|
||||
pub mod hid;
|
||||
@@ -0,0 +1,23 @@
|
||||
#![cfg_attr(
|
||||
all(not(debug_assertions), target_os = "windows"),
|
||||
windows_subsystem = "windows"
|
||||
)]
|
||||
#![feature(div_duration)]
|
||||
#![feature(more_qualified_paths)]
|
||||
|
||||
pub mod config;
|
||||
pub mod shared;
|
||||
pub mod state;
|
||||
|
||||
pub mod device;
|
||||
pub mod lighting;
|
||||
pub mod output;
|
||||
|
||||
pub mod system;
|
||||
|
||||
pub mod context;
|
||||
pub mod manager;
|
||||
|
||||
pub use config::Config;
|
||||
pub use manager::Manager;
|
||||
pub use system::{get_brokenithm_qr_path, get_log_file_path, list_ips};
|
||||
@@ -0,0 +1,157 @@
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum ReactiveLayout {
|
||||
Even { splits: usize },
|
||||
Six,
|
||||
Voltex,
|
||||
Hori,
|
||||
Rainbow,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ColorScheme {
|
||||
pub active: [u8; 3],
|
||||
pub inactive: [u8; 3],
|
||||
pub air_active: [u8; 3],
|
||||
pub air_inactive: [u8; 3],
|
||||
}
|
||||
|
||||
impl ColorScheme {
|
||||
pub fn from_serde_value(v: &Value) -> Option<Self> {
|
||||
Some(Self {
|
||||
active: [
|
||||
u8::from_str_radix(&v["ledColorActive"].as_str()?[1..3], 16).ok()?,
|
||||
u8::from_str_radix(&v["ledColorActive"].as_str()?[3..5], 16).ok()?,
|
||||
u8::from_str_radix(&v["ledColorActive"].as_str()?[5..7], 16).ok()?,
|
||||
],
|
||||
inactive: [
|
||||
u8::from_str_radix(&v["ledColorInactive"].as_str()?[1..3], 16).ok()?,
|
||||
u8::from_str_radix(&v["ledColorInactive"].as_str()?[3..5], 16).ok()?,
|
||||
u8::from_str_radix(&v["ledColorInactive"].as_str()?[5..7], 16).ok()?,
|
||||
],
|
||||
air_active: [
|
||||
u8::from_str_radix(&v["ledColorAirActive"].as_str()?[1..3], 16).ok()?,
|
||||
u8::from_str_radix(&v["ledColorAirActive"].as_str()?[3..5], 16).ok()?,
|
||||
u8::from_str_radix(&v["ledColorAirActive"].as_str()?[5..7], 16).ok()?,
|
||||
],
|
||||
air_inactive: [
|
||||
u8::from_str_radix(&v["ledColorAirInactive"].as_str()?[1..3], 16).ok()?,
|
||||
u8::from_str_radix(&v["ledColorAirInactive"].as_str()?[3..5], 16).ok()?,
|
||||
u8::from_str_radix(&v["ledColorAirInactive"].as_str()?[5..7], 16).ok()?,
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
pub fn default() -> Self {
|
||||
Self {
|
||||
active: [255, 0, 255],
|
||||
inactive: [255, 255, 0],
|
||||
air_active: [0, 134, 237],
|
||||
air_inactive: [0, 0, 0],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_serde_value_or_default(v: &Value) -> Self {
|
||||
Self::from_serde_value(v)
|
||||
.or(Some(Self {
|
||||
active: [255, 0, 255],
|
||||
inactive: [255, 255, 0],
|
||||
air_active: [0, 134, 237],
|
||||
air_inactive: [0, 0, 0],
|
||||
}))
|
||||
.unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum LightsMode {
|
||||
None,
|
||||
Reactive {
|
||||
faster: bool,
|
||||
layout: ReactiveLayout,
|
||||
sensitivity: u8,
|
||||
color: ColorScheme,
|
||||
},
|
||||
Attract {
|
||||
faster: bool,
|
||||
},
|
||||
Websocket {
|
||||
faster: bool,
|
||||
url: String,
|
||||
},
|
||||
UmgrWebsocket {
|
||||
faster: bool,
|
||||
port: u16,
|
||||
},
|
||||
Serial {
|
||||
faster: bool,
|
||||
port: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl LightsMode {
|
||||
pub fn from_serde_value(v: &Value) -> Option<Self> {
|
||||
Some(match v["ledMode"].as_str()? {
|
||||
"none" => LightsMode::None,
|
||||
"reactive-16" => LightsMode::Reactive {
|
||||
faster: v["ledFaster"].as_bool()?,
|
||||
layout: ReactiveLayout::Even { splits: 16 },
|
||||
sensitivity: u8::try_from(v["ledSensitivity"].as_i64()?).ok()?,
|
||||
color: ColorScheme::from_serde_value_or_default(v),
|
||||
},
|
||||
"reactive-8" => LightsMode::Reactive {
|
||||
faster: v["ledFaster"].as_bool()?,
|
||||
layout: ReactiveLayout::Even { splits: 8 },
|
||||
sensitivity: u8::try_from(v["ledSensitivity"].as_i64()?).ok()?,
|
||||
color: ColorScheme::from_serde_value_or_default(v),
|
||||
},
|
||||
"reactive-6" => LightsMode::Reactive {
|
||||
faster: v["ledFaster"].as_bool()?,
|
||||
layout: ReactiveLayout::Six,
|
||||
sensitivity: u8::try_from(v["ledSensitivity"].as_i64()?).ok()?,
|
||||
color: ColorScheme::from_serde_value_or_default(v),
|
||||
},
|
||||
"reactive-4" => LightsMode::Reactive {
|
||||
faster: v["ledFaster"].as_bool()?,
|
||||
layout: ReactiveLayout::Even { splits: 4 },
|
||||
sensitivity: u8::try_from(v["ledSensitivity"].as_i64()?).ok()?,
|
||||
color: ColorScheme::from_serde_value_or_default(v),
|
||||
},
|
||||
"reactive-rainbow" => LightsMode::Reactive {
|
||||
faster: v["ledFaster"].as_bool()?,
|
||||
layout: ReactiveLayout::Rainbow,
|
||||
sensitivity: u8::try_from(v["ledSensitivity"].as_i64()?).ok()?,
|
||||
color: ColorScheme::default(),
|
||||
},
|
||||
"reactive-voltex" => LightsMode::Reactive {
|
||||
faster: v["ledFaster"].as_bool()?,
|
||||
layout: ReactiveLayout::Voltex,
|
||||
sensitivity: u8::try_from(v["ledSensitivity"].as_i64()?).ok()?,
|
||||
color: ColorScheme::default(),
|
||||
},
|
||||
"reactive-hori" => LightsMode::Reactive {
|
||||
faster: v["ledFaster"].as_bool()?,
|
||||
layout: ReactiveLayout::Hori,
|
||||
sensitivity: u8::try_from(v["ledSensitivity"].as_i64()?).ok()?,
|
||||
color: ColorScheme::default(),
|
||||
},
|
||||
"attract" => LightsMode::Attract {
|
||||
faster: v["ledFaster"].as_bool()?,
|
||||
},
|
||||
"websocket" => LightsMode::Websocket {
|
||||
faster: v["ledFaster"].as_bool()?,
|
||||
url: v["ledWebsocketUrl"].as_str()?.to_string(),
|
||||
},
|
||||
"umgr-websocket" => LightsMode::UmgrWebsocket {
|
||||
faster: v["ledFaster"].as_bool()?,
|
||||
port: u16::try_from(v["ledUmgrWebsocketPort"].as_i64()?).ok()?,
|
||||
},
|
||||
"serial" => LightsMode::Serial {
|
||||
faster: v["ledFaster"].as_bool()?,
|
||||
port: v["ledSerialPort"].as_str()?.to_string(),
|
||||
},
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,401 @@
|
||||
use async_trait::async_trait;
|
||||
use log::{error, info};
|
||||
use palette::{encoding::Srgb as SrgbEncoding, rgb::Rgb, FromColor, Hsv, Srgb};
|
||||
use serialport::{ClearBuffer, SerialPort};
|
||||
use std::{
|
||||
ops::DerefMut,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tokio::time::{interval, Interval};
|
||||
|
||||
use crate::{
|
||||
shared::{hori::HoriState, utils::Buffer, voltex::VoltexState, worker::AsyncJob},
|
||||
state::{SliderLights, SliderState},
|
||||
};
|
||||
|
||||
use super::config::{LightsMode, ReactiveLayout};
|
||||
|
||||
fn get_rainbow(phase: f64, desaturate: bool) -> Rgb<SrgbEncoding, u8> {
|
||||
let phase = ((phase % 1.0) + 1.0) % 1.0;
|
||||
let color = Srgb::from_color(Hsv::new(
|
||||
phase * 360.0,
|
||||
match desaturate {
|
||||
false => 1.0,
|
||||
true => 0.2,
|
||||
},
|
||||
1.0,
|
||||
))
|
||||
.into_format::<u8>();
|
||||
|
||||
return color;
|
||||
}
|
||||
|
||||
pub struct LightsJob {
|
||||
state: SliderState,
|
||||
mode: LightsMode,
|
||||
serial_port: Option<Box<dyn SerialPort>>,
|
||||
started: Instant,
|
||||
timer: Interval,
|
||||
}
|
||||
|
||||
impl LightsJob {
|
||||
pub fn new(state: &SliderState, mode: &LightsMode) -> Self {
|
||||
Self {
|
||||
state: state.clone(),
|
||||
mode: mode.clone(),
|
||||
serial_port: None,
|
||||
started: Instant::now(),
|
||||
timer: match match mode {
|
||||
LightsMode::Attract { faster, .. } => *faster,
|
||||
LightsMode::Websocket { faster, .. } => *faster,
|
||||
LightsMode::Serial { faster, .. } => *faster,
|
||||
_ => false,
|
||||
} {
|
||||
false => interval(Duration::from_micros(66666)),
|
||||
true => interval(Duration::from_micros(33333)),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn calc_lights(
|
||||
&self,
|
||||
flat_input: Option<&Vec<bool>>,
|
||||
serial_buffer: Option<&Buffer>,
|
||||
lights: &mut SliderLights,
|
||||
) {
|
||||
match &self.mode {
|
||||
LightsMode::Reactive { layout, color, .. } => {
|
||||
let flat_input = flat_input.unwrap();
|
||||
|
||||
match layout {
|
||||
ReactiveLayout::Even { splits } => {
|
||||
let buttons_per_split = 32 / splits;
|
||||
|
||||
let banks: Vec<bool> = flat_input
|
||||
.chunks(32 / splits)
|
||||
.take(*splits)
|
||||
.map(|x| x.contains(&true))
|
||||
.collect();
|
||||
|
||||
for idx in 0..31 {
|
||||
lights.paint(
|
||||
idx,
|
||||
match ((idx + 1) % buttons_per_split, (idx + 1) % 2) {
|
||||
(0, _) => &color.active,
|
||||
(_, 0) => &color.inactive,
|
||||
_ => match banks[idx / buttons_per_split] {
|
||||
true => &color.active,
|
||||
false => &color.inactive,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
for idx in 0..3 {
|
||||
lights.paint_air(
|
||||
idx,
|
||||
match flat_input[32 + idx * 2] || flat_input[33 + idx * 2] {
|
||||
true => &color.air_active,
|
||||
false => &color.air_inactive,
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
ReactiveLayout::Six => {
|
||||
let banks: Vec<bool> = [0..6, 6..10, 10..16, 16..22, 22..26, 26..32]
|
||||
.into_iter()
|
||||
.map(|x| flat_input[x].contains(&true))
|
||||
.collect();
|
||||
|
||||
for idx in (1..31).step_by(2) {
|
||||
lights.paint(
|
||||
idx,
|
||||
match idx {
|
||||
5 | 9 | 15 | 21 | 25 => &color.active,
|
||||
_ => &color.inactive,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
for (bank_idxs, bank_val) in [0..6, 6..10, 10..16, 16..22, 22..26, 26..32]
|
||||
.into_iter()
|
||||
.zip(banks)
|
||||
{
|
||||
for idx in bank_idxs.step_by(2) {
|
||||
lights.paint(
|
||||
idx,
|
||||
match bank_val {
|
||||
true => &color.active,
|
||||
false => &color.inactive,
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
for idx in 0..3 {
|
||||
lights.paint_air(
|
||||
idx,
|
||||
match flat_input[32 + idx * 2] || flat_input[33 + idx * 2] {
|
||||
true => &color.air_active,
|
||||
false => &color.air_inactive,
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
ReactiveLayout::Voltex => {
|
||||
lights.ground.fill(0);
|
||||
|
||||
// Fixed
|
||||
lights.paint(3, &[10, 100, 180]);
|
||||
for idx in 0..5 {
|
||||
lights.paint(7 + idx * 4, &[64, 64, 64]);
|
||||
}
|
||||
lights.paint(27, &[180, 10, 110]);
|
||||
|
||||
let voltex_input = VoltexState::from_flat(flat_input);
|
||||
|
||||
// Left laser
|
||||
for (idx, state) in voltex_input.laser[0..2].iter().enumerate() {
|
||||
if *state {
|
||||
lights.paint(0 + idx * 4, &[70, 230, 250]);
|
||||
lights.paint(1 + idx * 4, &[70, 230, 250]);
|
||||
lights.paint(2 + idx * 4, &[70, 230, 250]);
|
||||
}
|
||||
}
|
||||
|
||||
// Right laser
|
||||
for (idx, state) in voltex_input.laser[2..4].iter().enumerate() {
|
||||
if *state {
|
||||
lights.paint(24 + idx * 4, &[250, 60, 200]);
|
||||
lights.paint(25 + idx * 4, &[255, 60, 200]);
|
||||
lights.paint(26 + idx * 4, &[255, 60, 200]);
|
||||
}
|
||||
}
|
||||
|
||||
// Buttons
|
||||
for (idx, state) in voltex_input.bt.iter().enumerate() {
|
||||
if *state {
|
||||
lights.paint(8 + idx * 4, &[255, 255, 255]);
|
||||
lights.paint(10 + idx * 4, &[255, 255, 255]);
|
||||
}
|
||||
}
|
||||
|
||||
// Fx
|
||||
for (idx, state) in voltex_input.fx.iter().enumerate() {
|
||||
if *state {
|
||||
lights.paint(9 + idx * 8, &[250, 100, 30]);
|
||||
lights.paint(11 + idx * 8, &[250, 100, 30]);
|
||||
lights.paint(13 + idx * 8, &[250, 100, 30]);
|
||||
}
|
||||
}
|
||||
}
|
||||
ReactiveLayout::Hori => {
|
||||
lights.ground.fill(0);
|
||||
|
||||
// Fixed
|
||||
for idx in [7, 15, 23] {
|
||||
lights.paint(idx, &[64, 64, 64]);
|
||||
}
|
||||
|
||||
let hori_state = HoriState::from_flat(flat_input);
|
||||
|
||||
for (idx, (bt, color)) in hori_state
|
||||
.bt
|
||||
.iter()
|
||||
.zip([
|
||||
&[64, 226, 160],
|
||||
&[255, 105, 248],
|
||||
&[124, 178, 232],
|
||||
&[255, 102, 102],
|
||||
])
|
||||
.enumerate()
|
||||
{
|
||||
let color_f = match bt {
|
||||
true => 1,
|
||||
false => 4,
|
||||
};
|
||||
let adjcolor = [color[0] / color_f, color[1] / color_f, color[2] / color_f];
|
||||
for i in 0..4 {
|
||||
lights.paint(idx * 8 + i * 2, &adjcolor);
|
||||
}
|
||||
}
|
||||
|
||||
for (idx, (a, b)) in hori_state
|
||||
.slider
|
||||
.iter()
|
||||
.zip(hori_state.slider.iter().skip(1))
|
||||
.enumerate()
|
||||
{
|
||||
if *a || *b {
|
||||
lights.paint(1 + idx * 2, &[200, 200, 200]);
|
||||
}
|
||||
}
|
||||
}
|
||||
ReactiveLayout::Rainbow => {
|
||||
let banks: Vec<bool> = flat_input
|
||||
.chunks(2)
|
||||
.take(16)
|
||||
.map(|x| x.contains(&true))
|
||||
.collect();
|
||||
let theta = self
|
||||
.started
|
||||
.elapsed()
|
||||
.div_duration_f64(Duration::from_secs(4))
|
||||
% 1.0;
|
||||
|
||||
for idx in 0..31 {
|
||||
let slice_theta = theta + (idx as f64) / 32.0;
|
||||
let color = get_rainbow(slice_theta, ((idx % 2) == 0) && banks[idx / 2]);
|
||||
lights.paint(idx, &[color.red, color.green, color.blue]);
|
||||
}
|
||||
|
||||
// left
|
||||
for idx in 0..3 {
|
||||
let slice_theta = theta - ((idx + 1) as f64) / 32.0;
|
||||
let color = get_rainbow(
|
||||
slice_theta,
|
||||
flat_input[32 + idx * 2] || flat_input[33 + idx * 2],
|
||||
);
|
||||
lights.paint_air_left(idx, &[color.red, color.green, color.blue]);
|
||||
}
|
||||
|
||||
// right
|
||||
for idx in 0..3 {
|
||||
let slice_theta = theta + (idx as f64) / 32.0;
|
||||
let color = get_rainbow(
|
||||
slice_theta,
|
||||
flat_input[32 + idx * 2] || flat_input[33 + idx * 2],
|
||||
);
|
||||
lights.paint_air_right(idx, &[color.red, color.green, color.blue]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
LightsMode::Attract { .. } => {
|
||||
let theta = self
|
||||
.started
|
||||
.elapsed()
|
||||
.div_duration_f64(Duration::from_secs(4))
|
||||
% 1.0;
|
||||
|
||||
for idx in 0..31 {
|
||||
let slice_theta = theta + (idx as f64) / 32.0;
|
||||
let color = get_rainbow(slice_theta, false);
|
||||
lights.paint(idx, &[color.red, color.green, color.blue]);
|
||||
}
|
||||
|
||||
// left
|
||||
for idx in 0..3 {
|
||||
let slice_theta = theta - ((idx + 1) as f64) / 32.0;
|
||||
let color = get_rainbow(slice_theta, false);
|
||||
lights.paint_air_left(idx, &[color.red, color.green, color.blue]);
|
||||
}
|
||||
|
||||
// right
|
||||
for idx in 0..3 {
|
||||
let slice_theta = theta + (idx as f64) / 32.0;
|
||||
let color = get_rainbow(slice_theta, false);
|
||||
lights.paint_air_right(idx, &[color.red, color.green, color.blue]);
|
||||
}
|
||||
}
|
||||
LightsMode::Serial { .. } => {
|
||||
// https://github.com/jmontineri/OpeNITHM/blob/89e9a43f7484e8949cd31bbff79c32f21ea3ec1d/Firmware/OpeNITHM/SerialProcessor.h
|
||||
// https://github.com/jmontineri/OpeNITHM/blob/89e9a43f7484e8949cd31bbff79c32f21ea3ec1d/Firmware/OpeNITHM/SerialProcessor.cpp
|
||||
// https://github.com/jmontineri/OpeNITHM/blob/89e9a43f7484e8949cd31bbff79c32f21ea3ec1d/Firmware/OpeNITHM/SerialLeds.h
|
||||
// https://github.com/jmontineri/OpeNITHM/blob/89e9a43f7484e8949cd31bbff79c32f21ea3ec1d/Firmware/OpeNITHM/SerialLeds.cpp
|
||||
if let Some(serial_buffer) = serial_buffer {
|
||||
// println!("buffer {:?}", serial_buffer.data);
|
||||
if serial_buffer.data[0] == 0xaa && serial_buffer.data[1] == 0xaa {
|
||||
for (idx, buf_chunk) in serial_buffer.data[2..95]
|
||||
.chunks(3)
|
||||
.take(31)
|
||||
.rev()
|
||||
.enumerate()
|
||||
{
|
||||
lights.paint(idx, &[(*buf_chunk)[1], (*buf_chunk)[2], (*buf_chunk)[0]]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => panic!("Not implemented"),
|
||||
}
|
||||
|
||||
lights.dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl AsyncJob for LightsJob {
|
||||
async fn setup(&mut self) -> bool {
|
||||
match &self.mode {
|
||||
LightsMode::Serial { port, .. } => {
|
||||
info!(
|
||||
"Serial port for led opening at {} {:?}",
|
||||
port.as_str(),
|
||||
115200
|
||||
);
|
||||
self.serial_port = match serialport::new(port, 115200).open() {
|
||||
Ok(s) => {
|
||||
info!("Serial port opened");
|
||||
Some(s)
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Serial port could not open: {}", e);
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
self.serial_port.is_some()
|
||||
}
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
async fn tick(&mut self) -> bool {
|
||||
let mut flat_input: Option<Vec<bool>> = None;
|
||||
let mut serial_buffer: Option<Buffer> = None;
|
||||
|
||||
// Do the IO here
|
||||
match self.mode {
|
||||
LightsMode::Reactive { sensitivity, .. } => {
|
||||
let input_handle = self.state.input.lock();
|
||||
flat_input = Some(input_handle.to_flat(&sensitivity));
|
||||
}
|
||||
LightsMode::Serial { .. } => {
|
||||
if let Some(serial_port) = self.serial_port.as_mut() {
|
||||
let mut serial_data_avail = serial_port.bytes_to_read().unwrap_or(0);
|
||||
if serial_data_avail >= 100 {
|
||||
if serial_data_avail % 100 == 0 {
|
||||
let mut serial_buffer_working = Buffer::new();
|
||||
serial_port
|
||||
.as_mut()
|
||||
.read_exact(&mut serial_buffer_working.data[..100])
|
||||
.ok()
|
||||
.unwrap();
|
||||
serial_data_avail -= 100;
|
||||
serial_buffer = Some(serial_buffer_working);
|
||||
}
|
||||
|
||||
if serial_data_avail > 0 {
|
||||
serial_port.clear(ClearBuffer::All).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
// Then calculate and transfer
|
||||
{
|
||||
let mut lights_handle = self.state.lights.lock();
|
||||
self.calc_lights(
|
||||
flat_input.as_ref(),
|
||||
serial_buffer.as_ref(),
|
||||
lights_handle.deref_mut(),
|
||||
);
|
||||
}
|
||||
self.timer.tick().await;
|
||||
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
pub mod config;
|
||||
|
||||
pub mod lighting;
|
||||
pub mod umgr_websocket;
|
||||
@@ -0,0 +1,313 @@
|
||||
use async_trait::async_trait;
|
||||
use futures::{SinkExt, StreamExt};
|
||||
use hyper::{
|
||||
header,
|
||||
server::conn::AddrStream,
|
||||
service::{make_service_fn, service_fn},
|
||||
upgrade::{self, Upgraded},
|
||||
Body, Method, Request, Response, Server, StatusCode,
|
||||
};
|
||||
use log::{error, info};
|
||||
use std::{convert::Infallible, future::Future, net::SocketAddr};
|
||||
use tokio::{
|
||||
select,
|
||||
sync::mpsc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tokio_tungstenite::WebSocketStream;
|
||||
use tungstenite::{handshake, Message};
|
||||
|
||||
use crate::{shared::worker::AsyncHaltableJob, state::SliderState};
|
||||
|
||||
async fn error_response() -> Result<Response<Body>, Infallible> {
|
||||
Ok(
|
||||
Response::builder()
|
||||
.status(StatusCode::NOT_FOUND)
|
||||
.body(Body::from(format!("Not found")))
|
||||
.unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
async fn handle_umgr_leds(ws_stream: WebSocketStream<Upgraded>, state: SliderState, faster: bool) {
|
||||
let (mut ws_write, mut ws_read) = ws_stream.split();
|
||||
|
||||
let (msg_write, mut msg_read) = mpsc::unbounded_channel::<Message>();
|
||||
|
||||
let write_task = async move {
|
||||
// info!("UMGR LED write task started");
|
||||
loop {
|
||||
let message = msg_read.recv().await;
|
||||
// info!("UMGR LED Sending {:?}", message);
|
||||
match message {
|
||||
Some(msg) => match ws_write.send(msg).await.ok() {
|
||||
Some(_) => {}
|
||||
None => {
|
||||
break;
|
||||
}
|
||||
},
|
||||
None => {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// info!("Websocket write task done");
|
||||
};
|
||||
|
||||
let msg_write_handle = msg_write.clone();
|
||||
let state_handle = state.clone();
|
||||
let read_task = async move {
|
||||
// info!("UMGR LED read task started");
|
||||
let mut latest_lights = Instant::now();
|
||||
let delay = match faster {
|
||||
true => Duration::from_micros(33333),
|
||||
false => Duration::from_micros(66666),
|
||||
};
|
||||
|
||||
loop {
|
||||
match ws_read.next().await {
|
||||
Some(msg) => match msg {
|
||||
Ok(msg) => match msg {
|
||||
Message::Binary(msg) => {
|
||||
// Full protocol at
|
||||
// https://gist.github.com/inonote/00251fed881a82c9df1e505eef1722bc
|
||||
// https://gist.github.com/4yn/a6737a33fbce51a8c7d64a8045cb2bee
|
||||
|
||||
// info!("UMGR Packet {:?}", msg);
|
||||
|
||||
if msg.len() < 3 {
|
||||
error!("Unexpected length of UMGR led packet");
|
||||
break;
|
||||
}
|
||||
|
||||
let version = msg[0];
|
||||
let opcode = msg[1];
|
||||
let payload_len = msg[2];
|
||||
let payload = &msg[3..];
|
||||
|
||||
if payload_len as usize != payload.len() {
|
||||
error!("Unexpected length of UMGR led packet");
|
||||
break;
|
||||
}
|
||||
|
||||
match (version, opcode, payload_len) {
|
||||
(0x01, 0x10, 103) => {
|
||||
// SetLED
|
||||
let mut lights_handle = state_handle.lights.lock();
|
||||
|
||||
for i in 0..16 {
|
||||
// Copy lights
|
||||
let pos = 1 + i * 3;
|
||||
lights_handle.paint(i * 2, &[payload[pos], payload[pos + 1], payload[pos + 2]]);
|
||||
}
|
||||
|
||||
for i in 0..15 {
|
||||
let pos = 49 + i * 3;
|
||||
lights_handle.paint(
|
||||
1 + i * 2,
|
||||
&[payload[pos], payload[pos + 1], payload[pos + 2]],
|
||||
);
|
||||
}
|
||||
|
||||
for i in 0..3 {
|
||||
let pos = 94 + i * 3;
|
||||
lights_handle
|
||||
.paint_air(2 - i, &[payload[pos], payload[pos + 1], payload[pos + 2]]);
|
||||
}
|
||||
|
||||
if latest_lights.elapsed() > delay {
|
||||
lights_handle.dirty = true;
|
||||
latest_lights = Instant::now();
|
||||
}
|
||||
}
|
||||
(0x01, 0x11, 0) => {
|
||||
// Initialize
|
||||
info!("UMGR LED Initialize");
|
||||
// Reply with Ready
|
||||
msg_write_handle
|
||||
.send(Message::Binary(vec![0x01, 0x19, 0x00]))
|
||||
.ok();
|
||||
}
|
||||
(0x01, 0x12, 4) => {
|
||||
// Client Ping
|
||||
info!("UMGR LED Ping");
|
||||
// Reply with Pong and extra server magic
|
||||
msg_write_handle
|
||||
.send(Message::Binary(vec![
|
||||
0x01, 0x1a, 6, payload[0], payload[1], payload[2], payload[3], 0x51, 0xed,
|
||||
]))
|
||||
.ok();
|
||||
}
|
||||
(0x01, 0xD0, 0) => {
|
||||
// Client RequestServerInfo
|
||||
info!("UMGR LED Info");
|
||||
// Reply with ReportServerInfo
|
||||
let server_major: u16 = env!("CARGO_PKG_VERSION_MAJOR").parse().unwrap();
|
||||
let server_minor: u16 = env!("CARGO_PKG_VERSION_MINOR").parse().unwrap();
|
||||
let response = [
|
||||
// Command
|
||||
vec![0x01, 0xd8, 44],
|
||||
// Server name
|
||||
b"slider-io\x00\x00\x00\x00\x00\x00\x00".to_vec(),
|
||||
// Server version
|
||||
vec![
|
||||
(server_major >> 8) as u8,
|
||||
(server_major & 0xff) as u8,
|
||||
(server_minor >> 8) as u8,
|
||||
(server_minor & 0xff) as u8,
|
||||
],
|
||||
// Reserved
|
||||
vec![0x00, 0x00],
|
||||
// Hardware name
|
||||
b"generic-slider\x00\x00".to_vec(),
|
||||
// Hardware version
|
||||
vec![0x00, 0x01, 0x00, 0x01],
|
||||
// Reserved
|
||||
vec![0x00, 0x00],
|
||||
]
|
||||
.concat();
|
||||
|
||||
msg_write_handle.send(Message::Binary(response)).ok();
|
||||
}
|
||||
_ => {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Message::Close(_) => {
|
||||
info!("Websocket connection closed");
|
||||
let mut lights_handle = state_handle.lights.lock();
|
||||
lights_handle.reset();
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Err(e) => {
|
||||
error!("Websocket connection error: {}", e);
|
||||
let mut lights_handle = state_handle.lights.lock();
|
||||
lights_handle.reset();
|
||||
break;
|
||||
}
|
||||
},
|
||||
None => {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// info!("Websocket read task done");
|
||||
};
|
||||
|
||||
select! {
|
||||
_ = read_task => {}
|
||||
_ = write_task => {}
|
||||
};
|
||||
}
|
||||
|
||||
async fn handle_websocket(
|
||||
mut request: Request<Body>,
|
||||
state: SliderState,
|
||||
faster: bool,
|
||||
) -> Result<Response<Body>, Infallible> {
|
||||
let res = match handshake::server::create_response_with_body(&request, || Body::empty()) {
|
||||
Ok(res) => {
|
||||
tokio::spawn(async move {
|
||||
match upgrade::on(&mut request).await {
|
||||
Ok(upgraded) => {
|
||||
let ws_stream = WebSocketStream::from_raw_socket(
|
||||
upgraded,
|
||||
tokio_tungstenite::tungstenite::protocol::Role::Server,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
|
||||
handle_umgr_leds(ws_stream, state, faster).await;
|
||||
}
|
||||
|
||||
Err(e) => {
|
||||
error!("Websocket upgrade error: {}", e);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
res
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Websocket creation error: {}", e);
|
||||
Response::builder()
|
||||
.status(StatusCode::BAD_REQUEST)
|
||||
.body(Body::from(format!("Failed to create websocket: {}", e)))
|
||||
.unwrap()
|
||||
}
|
||||
};
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
async fn handle_request(
|
||||
request: Request<Body>,
|
||||
remote_addr: SocketAddr,
|
||||
state: SliderState,
|
||||
faster: bool,
|
||||
) -> Result<Response<Body>, Infallible> {
|
||||
let method = request.method();
|
||||
let path = request.uri().path();
|
||||
if method != Method::GET {
|
||||
error!(
|
||||
"Server unknown method {} -> {} {}",
|
||||
remote_addr, method, path
|
||||
);
|
||||
return error_response().await;
|
||||
}
|
||||
info!("Server {} -> {} {}", remote_addr, method, path);
|
||||
|
||||
match (
|
||||
request.uri().path(),
|
||||
request.headers().contains_key(header::UPGRADE),
|
||||
) {
|
||||
("/", true) => handle_websocket(request, state, faster).await,
|
||||
_ => error_response().await,
|
||||
}
|
||||
}
|
||||
|
||||
pub struct UmgrWebsocketJob {
|
||||
state: SliderState,
|
||||
faster: bool,
|
||||
port: u16,
|
||||
}
|
||||
|
||||
impl UmgrWebsocketJob {
|
||||
pub fn new(state: &SliderState, faster: &bool, port: &u16) -> Self {
|
||||
Self {
|
||||
state: state.clone(),
|
||||
faster: *faster,
|
||||
port: *port,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl AsyncHaltableJob for UmgrWebsocketJob {
|
||||
async fn run<F: Future<Output = ()> + Send>(self, stop_signal: F) {
|
||||
let state = self.state.clone();
|
||||
let faster = self.faster;
|
||||
let make_svc = make_service_fn(|conn: &AddrStream| {
|
||||
let remote_addr = conn.remote_addr();
|
||||
let make_svc_state = state.clone();
|
||||
async move {
|
||||
Ok::<_, Infallible>(service_fn(move |request: Request<Body>| {
|
||||
let svc_state = make_svc_state.clone();
|
||||
handle_request(request, remote_addr, svc_state, faster)
|
||||
}))
|
||||
}
|
||||
});
|
||||
|
||||
let addr = SocketAddr::from(([0, 0, 0, 0], self.port));
|
||||
info!("UMGR LED websocket server listening on {}", addr);
|
||||
|
||||
let server = Server::bind(&addr)
|
||||
.serve(make_svc)
|
||||
.with_graceful_shutdown(stop_signal);
|
||||
|
||||
if let Err(e) = server.await {
|
||||
info!("UMGR LED websocket server stopped: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,12 +9,10 @@ use tokio::{
|
||||
sync::{mpsc, oneshot},
|
||||
};
|
||||
|
||||
use crate::slider_io::{config::Config, context::Context};
|
||||
|
||||
use super::controller_state::FullState;
|
||||
use crate::{config::Config, context::Context, state::SliderState};
|
||||
|
||||
pub struct Manager {
|
||||
state: Arc<Mutex<Option<FullState>>>,
|
||||
state: Arc<Mutex<Option<SliderState>>>,
|
||||
context: Arc<Mutex<Option<Context>>>,
|
||||
join_handle: Option<JoinHandle<()>>,
|
||||
tx_config: mpsc::UnboundedSender<Config>,
|
||||
@@ -83,7 +81,7 @@ impl Manager {
|
||||
self.tx_config.send(config).unwrap();
|
||||
}
|
||||
|
||||
pub fn try_get_state(&self) -> Option<FullState> {
|
||||
pub fn try_get_state(&self) -> Option<SliderState> {
|
||||
let state_handle = self.state.lock();
|
||||
state_handle.as_ref().map(|x| x.clone())
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum PollingRate {
|
||||
Sixty,
|
||||
Hundred,
|
||||
TwoHundredFifty,
|
||||
FiveHundred,
|
||||
Thousand,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum KeyboardLayout {
|
||||
Tasoller,
|
||||
Yuancon,
|
||||
Umiguri,
|
||||
TasollerHalf,
|
||||
EightK,
|
||||
SixK,
|
||||
FourK,
|
||||
Voltex,
|
||||
Neardayo,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum GamepadLayout {
|
||||
Voltex,
|
||||
Neardayo,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum HoriLayout {
|
||||
Full,
|
||||
SliderOnly,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum OutputMode {
|
||||
None,
|
||||
Keyboard {
|
||||
layout: KeyboardLayout,
|
||||
polling: PollingRate,
|
||||
sensitivity: u8,
|
||||
direct_input: bool,
|
||||
},
|
||||
Gamepad {
|
||||
layout: GamepadLayout,
|
||||
polling: PollingRate,
|
||||
sensitivity: u8,
|
||||
},
|
||||
Hori {
|
||||
layout: HoriLayout,
|
||||
polling: PollingRate,
|
||||
sensitivity: u8,
|
||||
},
|
||||
Websocket {
|
||||
url: String,
|
||||
polling: PollingRate,
|
||||
},
|
||||
}
|
||||
|
||||
impl PollingRate {
|
||||
pub fn from_str(s: &str) -> Option<Self> {
|
||||
match s {
|
||||
"60" => Some(PollingRate::Sixty),
|
||||
"100" => Some(PollingRate::Hundred),
|
||||
"250" => Some(PollingRate::TwoHundredFifty),
|
||||
"500" => Some(PollingRate::FiveHundred),
|
||||
"1000" => Some(PollingRate::Thousand),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_t_u64(&self) -> u64 {
|
||||
match self {
|
||||
PollingRate::Sixty => 16666,
|
||||
PollingRate::Hundred => 10000,
|
||||
PollingRate::TwoHundredFifty => 4000,
|
||||
PollingRate::FiveHundred => 2000,
|
||||
PollingRate::Thousand => 1000,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl OutputMode {
|
||||
pub fn from_serde_value(v: &Value) -> Option<Self> {
|
||||
Some(match v["outputMode"].as_str().unwrap() {
|
||||
"none" => OutputMode::None,
|
||||
"kb-32-tasoller" => OutputMode::Keyboard {
|
||||
layout: KeyboardLayout::Tasoller,
|
||||
polling: PollingRate::from_str(v["outputPolling"].as_str()?)?,
|
||||
sensitivity: u8::try_from(v["keyboardSensitivity"].as_i64()?).ok()?,
|
||||
direct_input: v["keyboardDirectInput"].as_bool()?,
|
||||
},
|
||||
"kb-32-yuancon" => OutputMode::Keyboard {
|
||||
layout: KeyboardLayout::Yuancon,
|
||||
polling: PollingRate::from_str(v["outputPolling"].as_str()?)?,
|
||||
sensitivity: u8::try_from(v["keyboardSensitivity"].as_i64()?).ok()?,
|
||||
direct_input: v["keyboardDirectInput"].as_bool()?,
|
||||
},
|
||||
"kb-32-umiguri" => OutputMode::Keyboard {
|
||||
layout: KeyboardLayout::Umiguri,
|
||||
polling: PollingRate::from_str(v["outputPolling"].as_str()?)?,
|
||||
sensitivity: u8::try_from(v["keyboardSensitivity"].as_i64()?).ok()?,
|
||||
direct_input: v["keyboardDirectInput"].as_bool()?,
|
||||
},
|
||||
"kb-16" => OutputMode::Keyboard {
|
||||
layout: KeyboardLayout::TasollerHalf,
|
||||
polling: PollingRate::from_str(v["outputPolling"].as_str()?)?,
|
||||
sensitivity: u8::try_from(v["keyboardSensitivity"].as_i64()?).ok()?,
|
||||
direct_input: v["keyboardDirectInput"].as_bool()?,
|
||||
},
|
||||
"kb-8" => OutputMode::Keyboard {
|
||||
layout: KeyboardLayout::EightK,
|
||||
polling: PollingRate::from_str(v["outputPolling"].as_str()?)?,
|
||||
sensitivity: u8::try_from(v["keyboardSensitivity"].as_i64()?).ok()?,
|
||||
direct_input: v["keyboardDirectInput"].as_bool()?,
|
||||
},
|
||||
"kb-6" => OutputMode::Keyboard {
|
||||
layout: KeyboardLayout::SixK,
|
||||
polling: PollingRate::from_str(v["outputPolling"].as_str()?)?,
|
||||
sensitivity: u8::try_from(v["keyboardSensitivity"].as_i64()?).ok()?,
|
||||
direct_input: v["keyboardDirectInput"].as_bool()?,
|
||||
},
|
||||
"kb-4" => OutputMode::Keyboard {
|
||||
layout: KeyboardLayout::FourK,
|
||||
polling: PollingRate::from_str(v["outputPolling"].as_str()?)?,
|
||||
sensitivity: u8::try_from(v["keyboardSensitivity"].as_i64()?).ok()?,
|
||||
direct_input: v["keyboardDirectInput"].as_bool()?,
|
||||
},
|
||||
"kb-voltex" => OutputMode::Keyboard {
|
||||
layout: KeyboardLayout::Voltex,
|
||||
polling: PollingRate::from_str(v["outputPolling"].as_str()?)?,
|
||||
sensitivity: u8::try_from(v["keyboardSensitivity"].as_i64()?).ok()?,
|
||||
direct_input: v["keyboardDirectInput"].as_bool()?,
|
||||
},
|
||||
"kb-neardayo" => OutputMode::Keyboard {
|
||||
layout: KeyboardLayout::Neardayo,
|
||||
polling: PollingRate::from_str(v["outputPolling"].as_str()?)?,
|
||||
sensitivity: u8::try_from(v["keyboardSensitivity"].as_i64()?).ok()?,
|
||||
direct_input: v["keyboardDirectInput"].as_bool()?,
|
||||
},
|
||||
"gamepad-voltex" => OutputMode::Gamepad {
|
||||
layout: GamepadLayout::Voltex,
|
||||
polling: PollingRate::from_str(v["outputPolling"].as_str()?)?,
|
||||
sensitivity: u8::try_from(v["keyboardSensitivity"].as_i64()?).ok()?,
|
||||
},
|
||||
"gamepad-neardayo" => OutputMode::Gamepad {
|
||||
layout: GamepadLayout::Neardayo,
|
||||
polling: PollingRate::from_str(v["outputPolling"].as_str()?)?,
|
||||
sensitivity: u8::try_from(v["keyboardSensitivity"].as_i64()?).ok()?,
|
||||
},
|
||||
"gamepad-hori" => OutputMode::Hori {
|
||||
layout: HoriLayout::Full,
|
||||
polling: PollingRate::from_str(v["outputPolling"].as_str()?)?,
|
||||
sensitivity: u8::try_from(v["keyboardSensitivity"].as_i64()?).ok()?,
|
||||
},
|
||||
"gamepad-hori-wide" => OutputMode::Hori {
|
||||
layout: HoriLayout::SliderOnly,
|
||||
polling: PollingRate::from_str(v["outputPolling"].as_str()?)?,
|
||||
sensitivity: u8::try_from(v["keyboardSensitivity"].as_i64()?).ok()?,
|
||||
},
|
||||
"websocket" => OutputMode::Websocket {
|
||||
url: v["outputWebsocketUrl"].as_str()?.to_string(),
|
||||
polling: PollingRate::from_str(v["outputPolling"].as_str()?)?,
|
||||
},
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,9 @@ use log::error;
|
||||
use std::error::Error;
|
||||
use vigem_client::{Client, TargetId, XButtons, XGamepad, Xbox360Wired};
|
||||
|
||||
use crate::slider_io::{config::GamepadLayout, output::OutputHandler, voltex::VoltexState};
|
||||
use crate::shared::voltex::VoltexState;
|
||||
|
||||
use super::{config::GamepadLayout, output::OutputHandler};
|
||||
|
||||
struct LastWind {
|
||||
left: bool,
|
||||
@@ -93,8 +95,8 @@ impl GamepadOutput {
|
||||
}
|
||||
|
||||
impl OutputHandler for GamepadOutput {
|
||||
fn tick(&mut self, flat_controller_state: &Vec<bool>) -> bool {
|
||||
let voltex_state = VoltexState::from_flat(flat_controller_state);
|
||||
fn tick(&mut self, flat_input: &Vec<bool>) -> bool {
|
||||
let voltex_state = VoltexState::from_flat(flat_input);
|
||||
|
||||
let buttons = voltex_state
|
||||
.bt
|
||||
@@ -121,15 +123,13 @@ impl OutputHandler for GamepadOutput {
|
||||
});
|
||||
|
||||
let lx = self.left_wind.update(
|
||||
voltex_state.laser[0] || (self.use_air && flat_controller_state[32]),
|
||||
voltex_state.laser[1]
|
||||
|| (self.use_air && (flat_controller_state[33] || flat_controller_state[34])),
|
||||
voltex_state.laser[0] || (self.use_air && flat_input[32]),
|
||||
voltex_state.laser[1] || (self.use_air && (flat_input[33] || flat_input[34])),
|
||||
) * 20000;
|
||||
|
||||
let rx = self.right_wind.update(
|
||||
voltex_state.laser[2]
|
||||
|| (self.use_air && (flat_controller_state[35] || flat_controller_state[36])),
|
||||
voltex_state.laser[3] || (self.use_air && flat_controller_state[37]),
|
||||
voltex_state.laser[2] || (self.use_air && (flat_input[35] || flat_input[36])),
|
||||
voltex_state.laser[3] || (self.use_air && flat_input[37]),
|
||||
) * 20000;
|
||||
|
||||
let mut dirty = false;
|
||||
@@ -0,0 +1,146 @@
|
||||
use log::error;
|
||||
use std::error::Error;
|
||||
use vigem_client::{Client, DS4Report, DualShock4Wired, TargetId};
|
||||
|
||||
use crate::shared::hori::HoriState;
|
||||
|
||||
use super::{config::HoriLayout, output::OutputHandler};
|
||||
|
||||
pub struct HoriOutput {
|
||||
target: DualShock4Wired<Client>,
|
||||
slider_only: bool,
|
||||
gamepad: DS4Report,
|
||||
}
|
||||
|
||||
impl HoriOutput {
|
||||
pub fn new(layout: HoriLayout) -> Option<Self> {
|
||||
let target = Self::get_target();
|
||||
|
||||
let slider_only = match layout {
|
||||
HoriLayout::Full => false,
|
||||
HoriLayout::SliderOnly => true,
|
||||
};
|
||||
|
||||
match target {
|
||||
Ok(target) => Some(Self {
|
||||
target,
|
||||
slider_only,
|
||||
gamepad: DS4Report::default(),
|
||||
}),
|
||||
Err(e) => {
|
||||
error!("Gamepad connection error: {}", e);
|
||||
error!("Gamepad connection error: Is ViGEMBus missing?");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn get_target() -> Result<DualShock4Wired<Client>, Box<dyn Error>> {
|
||||
let client = Client::connect()?;
|
||||
|
||||
let mut target = DualShock4Wired::new(client, TargetId::DUALSHOCK4_WIRED);
|
||||
target.plugin()?;
|
||||
target.wait_ready()?;
|
||||
Ok(target)
|
||||
}
|
||||
|
||||
fn update(&mut self) -> bool {
|
||||
match self.target.update(&self.gamepad) {
|
||||
Ok(_) => true,
|
||||
Err(e) => {
|
||||
error!("Gamepad update error: {}", e);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl OutputHandler for HoriOutput {
|
||||
fn tick(&mut self, flat_input: &Vec<bool>) -> bool {
|
||||
let hori_state = match self.slider_only {
|
||||
false => HoriState::from_flat(flat_input),
|
||||
true => HoriState::from_flat_to_wide(flat_input),
|
||||
};
|
||||
|
||||
let buttons: u16 = hori_state
|
||||
.bt
|
||||
.iter()
|
||||
.zip([
|
||||
// https://github.com/ViGEm/ViGEmClient/blob/master/include/ViGEm/Common.h#L117
|
||||
1 << 7, // triangle
|
||||
1 << 4, // square
|
||||
1 << 5, // cross
|
||||
1 << 6, // circle
|
||||
])
|
||||
.fold(0x8, |buttons, (state, code)| {
|
||||
buttons
|
||||
| match state {
|
||||
true => code,
|
||||
false => 0,
|
||||
}
|
||||
})
|
||||
| match hori_state.extra[0] {
|
||||
true => 1 << 13, // options
|
||||
false => 0,
|
||||
};
|
||||
|
||||
let axis: u32 = hori_state
|
||||
.slider
|
||||
.iter()
|
||||
.enumerate()
|
||||
.fold(0, |axis, (idx, state)| {
|
||||
axis
|
||||
| match state {
|
||||
true => 0b11 << ((idx ^ 3) * 2),
|
||||
false => 0,
|
||||
}
|
||||
})
|
||||
^ 0x80808080;
|
||||
|
||||
let mut dirty = false;
|
||||
if self.gamepad.buttons != buttons {
|
||||
self.gamepad.buttons = buttons;
|
||||
dirty = true;
|
||||
}
|
||||
|
||||
for (idx, state) in [
|
||||
&mut self.gamepad.thumb_lx,
|
||||
&mut self.gamepad.thumb_ly,
|
||||
&mut self.gamepad.thumb_rx,
|
||||
&mut self.gamepad.thumb_ry,
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let slice: u8 = ((axis >> ((3 - idx) * 8)) & 0xff) as u8;
|
||||
if *state != slice {
|
||||
*state = slice;
|
||||
dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
match dirty {
|
||||
true => self.update(),
|
||||
false => true,
|
||||
}
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.gamepad = DS4Report::default();
|
||||
self.update();
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for HoriOutput {
|
||||
fn drop(&mut self) {
|
||||
match self.target.unplug() {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
error!("Gamepad unplug error: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// dammit vigem_client::Event
|
||||
unsafe impl Send for HoriOutput {}
|
||||
@@ -0,0 +1,336 @@
|
||||
use interception::{Interception, KeyState, ScanCode, Stroke};
|
||||
use log::{error, info};
|
||||
use std::mem;
|
||||
use winapi::{
|
||||
ctypes::c_int,
|
||||
um::winuser::{
|
||||
MapVirtualKeyA, SendInput, INPUT, INPUT_KEYBOARD, KEYBDINPUT, KEYEVENTF_KEYUP, MAPVK_VK_TO_VSC,
|
||||
},
|
||||
};
|
||||
|
||||
use super::{config::KeyboardLayout, output::OutputHandler};
|
||||
|
||||
#[rustfmt::skip]
|
||||
const TASOLLER_KB_MAP: [usize; 41] = [
|
||||
0x41 /* A */, 0x31 /* 1 */, 0x5a /* Z */, 0x51 /* Q */, 0x53 /* S */, 0x32 /* 2 */, 0x58 /* X */, 0x57 /* W */,
|
||||
0x44 /* D */, 0x33 /* 3 */, 0x43 /* C */, 0x45 /* E */, 0x46 /* F */, 0x34 /* 4 */, 0x56 /* V */, 0x52 /* R */,
|
||||
0x47 /* G */, 0x35 /* 5 */, 0x42 /* B */, 0x54 /* T */, 0x48 /* H */, 0x36 /* 6 */, 0x4e /* N */, 0x59 /* Y */,
|
||||
0x4a /* J */, 0x37 /* 7 */, 0x4d /* M */, 0x55 /* U */, 0x4b /* K */, 0x38 /* 8 */, 0xbc /* VK_OEM_COMMA */, 0x49 /* I */,
|
||||
0xbf, 0xde, 0xbe, // VK_OEM_2, VK_OEM_7, VK_OEM_PERIOD,
|
||||
0xba, 0xdd, 0xdb, // VK_OEM_1, VK_OEM_6, VK_OEM_4
|
||||
0x0d, 0x20, 0x1b // VK_RETURN, VK_SPACE, VK_ESCAPE
|
||||
];
|
||||
|
||||
#[rustfmt::skip]
|
||||
const YUANCON_KB_MAP: [usize; 41] = [
|
||||
0x36 /* 6 */, 0x35 /* 5 */, 0x34 /* 4 */, 0x33 /* 3 */, 0x32 /* 2 */, 0x31 /* 1 */, 0x5a /* Z */, 0x59 /* Y */,
|
||||
0x58 /* X */, 0x57 /* W */, 0x56 /* V */, 0x55 /* U */, 0x54 /* T */, 0x53 /* S */, 0x52 /* R */, 0x51 /* Q */,
|
||||
0x50 /* P */, 0x4f /* O */, 0x4e /* N */, 0x4d /* M */, 0x4c /* L */, 0x4b /* K */, 0x4a /* J */, 0x49 /* I */,
|
||||
0x48 /* H */, 0x47 /* G */, 0x46 /* F */, 0x45 /* E */, 0x44 /* D */, 0x43 /* C */, 0x42 /* B */, 0x41 /* A */,
|
||||
0xbd, 0xbb, 0xdb, // VK_OEM_MINUS, VK_OEM_PLUS, VK_OEM_4,
|
||||
0xdd, 0xdc, 0xba, // VK_OEM_6, VK_OEM_5, VK_OEM_1,
|
||||
0x0d, 0x20, 0x1b, // VK_RETURN, VK_SPACE, VK_ESCAPE
|
||||
];
|
||||
|
||||
#[rustfmt::skip]
|
||||
const UMIGURI_KB_MAP: [usize; 41] = [
|
||||
0x41 /* A */, 0x31 /* 1 */, 0x5a /* Z */, 0x51 /* Q */, 0x53 /* S */, 0x32 /* 2 */, 0x58 /* X */, 0x57 /* W */,
|
||||
0x44 /* D */, 0x33 /* 3 */, 0x43 /* C */, 0x45 /* E */, 0x46 /* F */, 0x34 /* 4 */, 0x56 /* V */, 0x52 /* R */,
|
||||
0x47 /* G */, 0x35 /* 5 */, 0x42 /* B */, 0x54 /* T */, 0x48 /* H */, 0x36 /* 6 */, 0x4e /* N */, 0x59 /* Y */,
|
||||
0x4a /* J */, 0x37 /* 7 */, 0x4d /* M */, 0x55 /* U */, 0x4b /* K */, 0x38 /* 8 */, 0x39 /* 9 */, 0x49 /* I */,
|
||||
0x30, 0x4f, 0x4c, // 0, O, L
|
||||
0x50, 0xbc, 0xbe, // P, VK_OEM_COMMA, VK_OEM_PERIOD,
|
||||
0x0d, 0x20, 0x1b // VK_RETURN, VK_SPACE, VK_ESCAPE
|
||||
];
|
||||
|
||||
#[rustfmt::skip]
|
||||
const TASOLLER_HALF_KB_MAP: [usize; 41] = [
|
||||
0x41, 0x41 /* A */, 0x5a, 0x5a /* Z */, 0x53, 0x53 /* S */, 0x58, 0x58 /* X */,
|
||||
0x44, 0x44 /* D */, 0x43, 0x43 /* C */, 0x46, 0x46 /* F */, 0x56, 0x56 /* V */,
|
||||
0x47, 0x47 /* G */, 0x42, 0x42 /* B */, 0x48, 0x48 /* H */, 0x4e, 0x4e /* N */,
|
||||
0x4a, 0x4a /* J */, 0x4d, 0x4d /* M */, 0x4b, 0x4b /* K */, 0xbc, 0xbc /* VK_OEM_COMMA */,
|
||||
0xbf, 0xde, 0xbe, // VK_OEM_2, VK_OEM_7, VK_OEM_PERIOD,
|
||||
0xba, 0xdd, 0xdb, // VK_OEM_1, VK_OEM_6, VK_OEM_4
|
||||
0x0d, 0x20, 0x1b // VK_RETURN, VK_SPACE, VK_ESCAPE
|
||||
];
|
||||
|
||||
#[rustfmt::skip]
|
||||
const EIGHT_K_MAP: [usize; 41] = [
|
||||
0x41, 0x41, 0x41, 0x41, // A
|
||||
0x53, 0x53, 0x53, 0x53, // S
|
||||
0x44, 0x44, 0x44, 0x44, // D
|
||||
0x46, 0x46, 0x46, 0x46, // F
|
||||
0x4a, 0x4a, 0x4a, 0x4a, // J
|
||||
0x4b, 0x4b, 0x4b, 0x4b, // K
|
||||
0x4c, 0x4c, 0x4c, 0x4c, // L
|
||||
0xba, 0xba, 0xba, 0xba, // VK_OEM_1
|
||||
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // VK_SPACE
|
||||
0x00, 0x00, 0x00, // Disabled
|
||||
];
|
||||
|
||||
#[rustfmt::skip]
|
||||
const SIX_K_MAP: [usize; 41] = [
|
||||
0x53, 0x53, 0x53, 0x53, 0x53, 0x53, // S
|
||||
0x44, 0x44, 0x44, 0x44, // D
|
||||
0x46, 0x46, 0x46, 0x46, 0x46, 0x46, // F
|
||||
0x4a, 0x4a, 0x4a, 0x4a, 0x4a, 0x4a, // J
|
||||
0x4b, 0x4b, 0x4b, 0x4b, // K
|
||||
0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, // L
|
||||
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // VK_SPACE
|
||||
0x00, 0x00, 0x00, // Disabled
|
||||
];
|
||||
|
||||
#[rustfmt::skip]
|
||||
const FOUR_K_MAP: [usize; 41] = [
|
||||
0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, // D
|
||||
0x46, 0x46, 0x46, 0x46, 0x46, 0x46, 0x46, 0x46, // F
|
||||
0x4a, 0x4a, 0x4a, 0x4a, 0x4a, 0x4a, 0x4a, 0x4a, // J
|
||||
0x4b, 0x4b, 0x4b, 0x4b, 0x4b, 0x4b, 0x4b, 0x4b, // K
|
||||
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // VK_SPACE
|
||||
0x00, 0x00, 0x00, // Disabled
|
||||
];
|
||||
|
||||
#[rustfmt::skip]
|
||||
const VOLTEX_KB_MAP: [usize; 41] = [
|
||||
0x57, 0x57, 0x57, 0x57, // W
|
||||
0x45, 0x45, 0x45, 0x45, // E
|
||||
0x43, 0x44,
|
||||
0x43, 0x44,
|
||||
0x43, 0x46, // D
|
||||
0x43, 0x46, // C // F
|
||||
0x4d, 0x4a, // M // J
|
||||
0x4d, 0x4a, // K
|
||||
0x4d, 0x4b,
|
||||
0x4d, 0x4b,
|
||||
0x4f, 0x4f, 0x4f, 0x4f, // O
|
||||
0x50, 0x50, 0x50, 0x50, // P
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Disabled
|
||||
0x31, 0x0d, 0x1b, // 1, VK_RETURN, VK_ESCAPE
|
||||
];
|
||||
|
||||
#[rustfmt::skip]
|
||||
const VOLTEX_KB_MAP_NEARDAYO: [usize; 41] = [
|
||||
0x57, 0x57, 0x57, 0x57, // W
|
||||
0x45, 0x45, 0x45, 0x45, // E
|
||||
0x43, 0x44,
|
||||
0x43, 0x44,
|
||||
0x43, 0x46, // D
|
||||
0x43, 0x46, // C // F
|
||||
0x4d, 0x4a, // M // J
|
||||
0x4d, 0x4a, // K
|
||||
0x4d, 0x4b,
|
||||
0x4d, 0x4b,
|
||||
0x4f, 0x4f, 0x4f, 0x4f, // O
|
||||
0x50, 0x50, 0x50, 0x50, // P
|
||||
0x57, 0x45, 0x45, 0x4f, 0x4f, 0x50, // Disabled
|
||||
0x31, 0x0d, 0x1b, // 1, VK_RETURN, VK_ESCAPE
|
||||
];
|
||||
|
||||
pub struct KeyboardOutput {
|
||||
input_to_idx: [usize; 41],
|
||||
key_idx_to_keycode: [u16; 41],
|
||||
key_idx_to_scancode: [Option<ScanCode>; 41],
|
||||
next_keys: [bool; 41],
|
||||
last_keys: [bool; 41],
|
||||
|
||||
direct_input: bool,
|
||||
interception_handle: Option<Interception>,
|
||||
|
||||
kb_buf: [INPUT; 41],
|
||||
kb_direct_buf: [Stroke; 41],
|
||||
n_kb_buf: u32,
|
||||
}
|
||||
|
||||
// interception isn't send, but lazy to wrap
|
||||
unsafe impl Send for KeyboardOutput {}
|
||||
|
||||
impl KeyboardOutput {
|
||||
pub fn new(layout: KeyboardLayout, direct_input: bool) -> Self {
|
||||
let kb_map = match layout {
|
||||
KeyboardLayout::Tasoller => &TASOLLER_KB_MAP,
|
||||
KeyboardLayout::Yuancon => &YUANCON_KB_MAP,
|
||||
KeyboardLayout::Umiguri => &UMIGURI_KB_MAP,
|
||||
KeyboardLayout::TasollerHalf => &TASOLLER_HALF_KB_MAP,
|
||||
KeyboardLayout::EightK => &EIGHT_K_MAP,
|
||||
KeyboardLayout::SixK => &SIX_K_MAP,
|
||||
KeyboardLayout::FourK => &FOUR_K_MAP,
|
||||
KeyboardLayout::Voltex => &VOLTEX_KB_MAP,
|
||||
KeyboardLayout::Neardayo => &VOLTEX_KB_MAP_NEARDAYO,
|
||||
};
|
||||
|
||||
let mut input_to_key_idx = [0 as usize; 41];
|
||||
let mut key_idx_to_keycode = [0 as u16; 41];
|
||||
let mut key_idx_to_scancode = [None as Option<ScanCode>; 41];
|
||||
let mut keycode_to_idx = [0xffff as usize; 256];
|
||||
let mut keycode_count: usize = 0;
|
||||
|
||||
for (ground, keycode) in kb_map.iter().enumerate() {
|
||||
if keycode_to_idx[*keycode] == 0xffff {
|
||||
keycode_to_idx[*keycode] = keycode_count;
|
||||
key_idx_to_keycode[keycode_count] = *keycode as u16;
|
||||
key_idx_to_scancode[keycode_count] =
|
||||
ScanCode::try_from(unsafe { MapVirtualKeyA((*keycode) as u32, MAPVK_VK_TO_VSC) as u16 })
|
||||
.ok();
|
||||
// info!(
|
||||
// "mapped {:?} to {:?}",
|
||||
// key_idx_to_keycode[keycode_count], key_idx_to_scancode[keycode_count]
|
||||
// );
|
||||
keycode_count += 1;
|
||||
}
|
||||
input_to_key_idx[ground] = keycode_to_idx[*keycode]
|
||||
}
|
||||
|
||||
let interception_handle = match direct_input {
|
||||
true => {
|
||||
let inner_handle = Interception::new();
|
||||
|
||||
if inner_handle.is_some() {
|
||||
info!("Keyboard emulation with interception loaded");
|
||||
} else {
|
||||
error!("Keyboard emulation cannot load interception, falling back to SendKeys()");
|
||||
}
|
||||
inner_handle
|
||||
}
|
||||
false => None,
|
||||
};
|
||||
let direct_input = interception_handle.is_some();
|
||||
|
||||
let mut kb_buf = [INPUT {
|
||||
type_: INPUT_KEYBOARD,
|
||||
u: unsafe { mem::zeroed() },
|
||||
}; 41];
|
||||
|
||||
for i in kb_buf.iter_mut() {
|
||||
let mut inner = unsafe { i.u.ki_mut() };
|
||||
inner.wVk = 0;
|
||||
inner.wScan = 0;
|
||||
inner.dwFlags = 0;
|
||||
inner.time = 0;
|
||||
inner.dwExtraInfo = 0;
|
||||
}
|
||||
|
||||
let kb_direct_buf = [Stroke::Keyboard {
|
||||
code: ScanCode::Esc,
|
||||
state: KeyState::UP,
|
||||
information: 0,
|
||||
}; 41];
|
||||
|
||||
Self {
|
||||
input_to_idx: input_to_key_idx,
|
||||
key_idx_to_keycode,
|
||||
key_idx_to_scancode,
|
||||
next_keys: [false; 41],
|
||||
last_keys: [false; 41],
|
||||
|
||||
direct_input,
|
||||
interception_handle,
|
||||
|
||||
kb_buf,
|
||||
kb_direct_buf,
|
||||
n_kb_buf: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn send(&mut self) {
|
||||
self.n_kb_buf = 0;
|
||||
|
||||
for (i, (n, l)) in self
|
||||
.next_keys
|
||||
.iter_mut()
|
||||
.zip(self.last_keys.iter_mut())
|
||||
.enumerate()
|
||||
{
|
||||
let keycode = self.key_idx_to_keycode[i];
|
||||
let scancode = self.key_idx_to_scancode[i];
|
||||
|
||||
if (!self.direct_input && keycode == 0) || (self.direct_input && scancode.is_none()) {
|
||||
continue;
|
||||
}
|
||||
match (self.direct_input, *n, *l) {
|
||||
(false, true, false) => {
|
||||
let inner: &mut KEYBDINPUT = unsafe { self.kb_buf[self.n_kb_buf as usize].u.ki_mut() };
|
||||
inner.wVk = keycode;
|
||||
inner.dwFlags = 0;
|
||||
self.n_kb_buf += 1;
|
||||
}
|
||||
(false, false, true) => {
|
||||
let inner: &mut KEYBDINPUT = unsafe { self.kb_buf[self.n_kb_buf as usize].u.ki_mut() };
|
||||
inner.wVk = keycode;
|
||||
inner.dwFlags = KEYEVENTF_KEYUP;
|
||||
self.n_kb_buf += 1;
|
||||
}
|
||||
(true, true, false) => {
|
||||
// info!("keydown {:?}", scancode);
|
||||
let inner: &mut Stroke = &mut self.kb_direct_buf[self.n_kb_buf as usize];
|
||||
if let Stroke::Keyboard {
|
||||
code,
|
||||
state,
|
||||
information: _,
|
||||
} = inner
|
||||
{
|
||||
*code = scancode.unwrap();
|
||||
*state = KeyState::DOWN;
|
||||
self.n_kb_buf += 1;
|
||||
}
|
||||
}
|
||||
(true, false, true) => {
|
||||
// info!("keyup {:?}", scancode);
|
||||
let inner: &mut Stroke = &mut self.kb_direct_buf[self.n_kb_buf as usize];
|
||||
if let Stroke::Keyboard {
|
||||
code,
|
||||
state,
|
||||
information: _,
|
||||
} = inner
|
||||
{
|
||||
*code = scancode.unwrap();
|
||||
*state = KeyState::UP;
|
||||
self.n_kb_buf += 1;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
*l = *n;
|
||||
}
|
||||
|
||||
if self.n_kb_buf != 0 {
|
||||
match self.direct_input {
|
||||
false => unsafe {
|
||||
SendInput(
|
||||
self.n_kb_buf,
|
||||
self.kb_buf.as_mut_ptr(),
|
||||
mem::size_of::<INPUT>() as c_int,
|
||||
);
|
||||
},
|
||||
true => {
|
||||
if let Some(handle) = self.interception_handle.as_mut() {
|
||||
handle.send(1, &self.kb_direct_buf[0..self.n_kb_buf as usize]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl OutputHandler for KeyboardOutput {
|
||||
fn tick(&mut self, flat_input: &Vec<bool>) -> bool {
|
||||
self.next_keys.fill(false);
|
||||
for (idx, x) in flat_input.iter().enumerate() {
|
||||
if *x {
|
||||
self.next_keys[self.input_to_idx[idx]] = true;
|
||||
}
|
||||
}
|
||||
self.send();
|
||||
true
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.next_keys.fill(false);
|
||||
self.send();
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for KeyboardOutput {
|
||||
fn drop(&mut self) {
|
||||
self.reset();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
pub mod config;
|
||||
|
||||
mod gamepad;
|
||||
mod hori;
|
||||
mod keyboard;
|
||||
|
||||
pub mod output;
|
||||
@@ -3,18 +3,19 @@ use log::error;
|
||||
use std::time::Duration;
|
||||
use tokio::time::{interval, Interval};
|
||||
|
||||
use crate::slider_io::{
|
||||
config::OutputMode, controller_state::FullState, gamepad::GamepadOutput,
|
||||
keyboard::KeyboardOutput, worker::AsyncJob,
|
||||
use crate::{shared::worker::AsyncJob, state::SliderState};
|
||||
|
||||
use super::{
|
||||
config::OutputMode, gamepad::GamepadOutput, hori::HoriOutput, keyboard::KeyboardOutput,
|
||||
};
|
||||
|
||||
pub trait OutputHandler: Send {
|
||||
fn tick(&mut self, flat_controller_state: &Vec<bool>) -> bool;
|
||||
fn tick(&mut self, flat_input: &Vec<bool>) -> bool;
|
||||
fn reset(&mut self);
|
||||
}
|
||||
|
||||
pub struct OutputJob {
|
||||
state: FullState,
|
||||
state: SliderState,
|
||||
mode: OutputMode,
|
||||
sensitivity: u8,
|
||||
handler: Option<Box<dyn OutputHandler>>,
|
||||
@@ -22,7 +23,7 @@ pub struct OutputJob {
|
||||
}
|
||||
|
||||
impl OutputJob {
|
||||
pub fn new(state: &FullState, mode: &OutputMode) -> Self {
|
||||
pub fn new(state: &SliderState, mode: &OutputMode) -> Self {
|
||||
Self {
|
||||
state: state.clone(),
|
||||
mode: mode.clone(),
|
||||
@@ -41,9 +42,10 @@ impl AsyncJob for OutputJob {
|
||||
layout,
|
||||
polling,
|
||||
sensitivity,
|
||||
direct_input,
|
||||
} => {
|
||||
self.sensitivity = sensitivity;
|
||||
self.handler = Some(Box::new(KeyboardOutput::new(layout.clone())));
|
||||
self.handler = Some(Box::new(KeyboardOutput::new(layout.clone(), direct_input)));
|
||||
self.timer = interval(Duration::from_micros(polling.to_t_u64()));
|
||||
|
||||
true
|
||||
@@ -65,6 +67,23 @@ impl AsyncJob for OutputJob {
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
OutputMode::Hori {
|
||||
layout,
|
||||
polling,
|
||||
sensitivity,
|
||||
} => {
|
||||
self.sensitivity = sensitivity;
|
||||
let handler = HoriOutput::new(layout.clone());
|
||||
self.timer = interval(Duration::from_micros(polling.to_t_u64()));
|
||||
|
||||
match handler {
|
||||
Some(handler) => {
|
||||
self.handler = Some(Box::new(handler));
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
error!("Not implemented");
|
||||
false
|
||||
@@ -73,14 +92,13 @@ impl AsyncJob for OutputJob {
|
||||
}
|
||||
|
||||
async fn tick(&mut self) -> bool {
|
||||
let flat_controller_state: Vec<bool>;
|
||||
{
|
||||
let controller_state_handle = self.state.controller_state.lock();
|
||||
flat_controller_state = controller_state_handle.flat(&self.sensitivity);
|
||||
}
|
||||
let flat_input = {
|
||||
let input_handle = self.state.input.lock();
|
||||
input_handle.to_flat(&self.sensitivity)
|
||||
};
|
||||
|
||||
if let Some(handler) = self.handler.as_mut() {
|
||||
handler.tick(&flat_controller_state);
|
||||
handler.tick(&flat_input);
|
||||
}
|
||||
self.timer.tick().await;
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
pub struct HoriState {
|
||||
pub slider: [bool; 16],
|
||||
pub bt: [bool; 4],
|
||||
pub extra: [bool; 1],
|
||||
}
|
||||
|
||||
impl HoriState {
|
||||
pub fn from_flat(flat_input: &Vec<bool>) -> Self {
|
||||
let mut hori_state = Self {
|
||||
slider: [false; 16],
|
||||
bt: [false; 4],
|
||||
extra: [false; 1],
|
||||
};
|
||||
|
||||
for (idx, i) in flat_input[0..32].iter().enumerate() {
|
||||
match idx % 2 {
|
||||
0 => {
|
||||
hori_state.bt[idx / 8] |= *i;
|
||||
}
|
||||
1 => {
|
||||
hori_state.slider[idx / 2] |= *i;
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
hori_state.extra[0] = flat_input[38];
|
||||
|
||||
hori_state
|
||||
}
|
||||
|
||||
pub fn from_flat_to_wide(flat_input: &Vec<bool>) -> Self {
|
||||
let mut hori_state = Self {
|
||||
slider: [false; 16],
|
||||
bt: [false; 4],
|
||||
extra: [false; 1],
|
||||
};
|
||||
|
||||
for (idx, i) in flat_input[0..32].iter().enumerate() {
|
||||
hori_state.slider[idx / 2] |= *i;
|
||||
}
|
||||
|
||||
hori_state.extra[0] = flat_input[38];
|
||||
|
||||
hori_state
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
pub mod hori;
|
||||
pub mod serial;
|
||||
pub mod utils;
|
||||
pub mod voltex;
|
||||
pub mod worker;
|
||||
@@ -0,0 +1,31 @@
|
||||
use serialport::COMPort;
|
||||
use std::{os::windows::prelude::AsRawHandle, time::Duration};
|
||||
|
||||
use winapi::{
|
||||
shared::minwindef::DWORD,
|
||||
um::{commapi::SetCommTimeouts, winbase::COMMTIMEOUTS},
|
||||
};
|
||||
|
||||
pub trait ReadWriteTimeout {
|
||||
fn set_read_write_timeout(&self, timeout: Duration) -> Result<(), ()>;
|
||||
}
|
||||
|
||||
impl ReadWriteTimeout for COMPort {
|
||||
fn set_read_write_timeout(&self, timeout: Duration) -> Result<(), ()> {
|
||||
let milliseconds = timeout.as_secs() * 1000 + timeout.subsec_nanos() as u64 / 1_000_000;
|
||||
|
||||
let mut timeouts = COMMTIMEOUTS {
|
||||
ReadIntervalTimeout: 0,
|
||||
ReadTotalTimeoutMultiplier: 0,
|
||||
ReadTotalTimeoutConstant: milliseconds as DWORD,
|
||||
WriteTotalTimeoutMultiplier: 0,
|
||||
WriteTotalTimeoutConstant: milliseconds as DWORD,
|
||||
};
|
||||
|
||||
if unsafe { SetCommTimeouts(self.as_raw_handle(), &mut timeouts) } == 0 {
|
||||
return Err(());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -40,20 +40,10 @@ impl Error for ShimError {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_ips() -> Result<Vec<String>, Box<dyn Error>> {
|
||||
let mut ips = vec![];
|
||||
for adapter in ipconfig::get_adapters()? {
|
||||
for ip_address in adapter.ip_addresses() {
|
||||
ips.push(format!("{}", ip_address));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(ips)
|
||||
}
|
||||
|
||||
pub struct LoopTimer {
|
||||
cap: usize,
|
||||
cur: usize,
|
||||
init: usize,
|
||||
buf: Vec<Instant>,
|
||||
freq: Arc<AtomicF64>,
|
||||
}
|
||||
@@ -63,16 +53,22 @@ impl LoopTimer {
|
||||
Self {
|
||||
cap: 100,
|
||||
cur: 0,
|
||||
buf: vec![Instant::now() - Duration::from_secs(10); 100],
|
||||
init: 0,
|
||||
buf: vec![Instant::now(); 100],
|
||||
freq: Arc::new(AtomicF64::new(0.0)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn tick(&mut self) {
|
||||
let last = self.buf[self.cur];
|
||||
let now = Instant::now();
|
||||
if self.init < 100 {
|
||||
self.init += 1;
|
||||
}
|
||||
|
||||
self.buf[self.cur] = now;
|
||||
|
||||
let delta = (now - last) / 100 + Duration::from_micros(1);
|
||||
let delta = (now - last) / (self.init as u32) + Duration::from_micros(1);
|
||||
let freq = Duration::from_millis(1000)
|
||||
.div_duration_f64(delta)
|
||||
.clamp(0.0, 9999.0);
|
||||
@@ -86,7 +82,8 @@ impl LoopTimer {
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn reset(&mut self) {
|
||||
self.buf = vec![Instant::now() - Duration::from_secs(10); 100];
|
||||
self.init = 0;
|
||||
self.buf = vec![Instant::now(); 100];
|
||||
self.cur = 0;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
pub struct VoltexState {
|
||||
pub laser: [bool; 4],
|
||||
pub bt: [bool; 4],
|
||||
pub fx: [bool; 2],
|
||||
pub extra: [bool; 3],
|
||||
}
|
||||
|
||||
impl VoltexState {
|
||||
pub fn from_flat(flat_input: &Vec<bool>) -> Self {
|
||||
let mut voltex_state = Self {
|
||||
laser: [false; 4],
|
||||
bt: [false; 4],
|
||||
fx: [false; 2],
|
||||
extra: [false; 3],
|
||||
};
|
||||
|
||||
voltex_state.laser[0] = flat_input[0..4].contains(&true);
|
||||
voltex_state.laser[1] = flat_input[4..8].contains(&true);
|
||||
voltex_state.laser[2] = flat_input[24..28].contains(&true);
|
||||
voltex_state.laser[3] = flat_input[28..32].contains(&true);
|
||||
|
||||
for i in 0..4 {
|
||||
voltex_state.bt[i] = flat_input[9 + i * 4] || flat_input[11 + i * 4];
|
||||
}
|
||||
|
||||
for i in 0..2 {
|
||||
voltex_state.fx[i] = flat_input[8 + i * 8]
|
||||
|| flat_input[10 + i * 8]
|
||||
|| flat_input[12 + i * 8]
|
||||
|| flat_input[14 + i * 8];
|
||||
}
|
||||
|
||||
for i in 0..3 {
|
||||
voltex_state.extra[i] = flat_input[38 + i];
|
||||
}
|
||||
|
||||
voltex_state
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ use std::{
|
||||
|
||||
use tokio::{sync::oneshot, task};
|
||||
|
||||
use crate::slider_io::utils::LoopTimer;
|
||||
use super::utils::LoopTimer;
|
||||
|
||||
pub trait ThreadJob: Send {
|
||||
fn setup(&mut self) -> bool;
|
||||
@@ -82,6 +82,8 @@ impl AsyncWorker {
|
||||
where
|
||||
T: AsyncJob,
|
||||
{
|
||||
info!("Async worker starting {}", name);
|
||||
|
||||
let stop_signal = Arc::new(AtomicBool::new(false));
|
||||
|
||||
let stop_signal_clone = Arc::clone(&stop_signal);
|
||||
@@ -0,0 +1,169 @@
|
||||
use parking_lot::Mutex;
|
||||
use std::{sync::Arc, time::Instant};
|
||||
|
||||
/// Stores the input state of a slider controller, including ground touch pads,
|
||||
/// air strings and extra buttons.
|
||||
pub struct SliderInput {
|
||||
/// Represents touch pressure in 32 touch pads in a 2 tall and 16 wide grid.
|
||||
/// Each pressur is in a `u8` from 0 to 255. Pads are represented in order of
|
||||
/// bottom left, then top left, then flows from left to right.
|
||||
pub ground: [u8; 32],
|
||||
|
||||
/// Represents air string state in 6 pads starting from bottom to top. 0 means
|
||||
/// uninterrupted, 1 means interrupted.
|
||||
pub air: [u8; 6],
|
||||
|
||||
/// Represents extra button state, usually used for coin/test/card entry
|
||||
/// functions.
|
||||
pub extra: [u8; 3],
|
||||
}
|
||||
|
||||
impl SliderInput {
|
||||
/// Make a blank input state.
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
ground: [0; 32],
|
||||
air: [0; 6],
|
||||
extra: [0; 3],
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts an input state to a `Vec<bool>`, used for output simulation and
|
||||
/// visualisation.
|
||||
pub fn to_flat(&self, sensitivity: &u8) -> Vec<bool> {
|
||||
self
|
||||
.ground
|
||||
.iter()
|
||||
.map(|x| x >= sensitivity)
|
||||
.chain(self.air.iter().chain(self.extra.iter()).map(|x| x > &0))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Flips the ground slider state vertically. Used when taking input for
|
||||
/// tasoller controllers as they report starting from top left (instead of
|
||||
/// botton left that is used internally).
|
||||
pub fn flip_vert(&mut self) {
|
||||
for i in 0..16 {
|
||||
self.ground.swap(i * 2, i * 2 + 1);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn flip_all(&mut self) {
|
||||
for i in 0..16 {
|
||||
self.ground.swap(i, 31 - i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Stores the lighting state of a slider controller.
|
||||
pub struct SliderLights {
|
||||
/// Represents the RGB pixel values of the slider controller from left to
|
||||
/// right. Alternates between 16 touch pad pixels and 15 divider pixels.
|
||||
pub ground: [u8; 3 * 31],
|
||||
|
||||
// RGB light values for left and right air sensors, bottom to top
|
||||
pub air_left: [u8; 3 * 3],
|
||||
pub air_right: [u8; 3 * 3],
|
||||
|
||||
/// Internal dirty flag used to indicate that new lighting data is available.
|
||||
pub dirty: bool,
|
||||
|
||||
/// To deprecate
|
||||
pub start: Instant,
|
||||
}
|
||||
|
||||
impl SliderLights {
|
||||
/// Make a blank lighting state.
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
ground: [0; 3 * 31],
|
||||
air_left: [0; 3 * 3],
|
||||
air_right: [0; 3 * 3],
|
||||
dirty: false,
|
||||
start: Instant::now(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply a RGB color to some pixel in the lighting state.
|
||||
pub fn paint(&mut self, idx: usize, color: &[u8; 3]) {
|
||||
self.ground[3 * idx..3 * (idx + 1)].copy_from_slice(color);
|
||||
}
|
||||
|
||||
pub fn paint_air(&mut self, idx: usize, color: &[u8; 3]) {
|
||||
self.air_left[3 * idx..3 * (idx + 1)].copy_from_slice(color);
|
||||
self.air_right[3 * idx..3 * (idx + 1)].copy_from_slice(color);
|
||||
}
|
||||
|
||||
pub fn paint_air_left(&mut self, idx: usize, color: &[u8; 3]) {
|
||||
self.air_left[3 * idx..3 * (idx + 1)].copy_from_slice(color);
|
||||
}
|
||||
|
||||
pub fn paint_air_right(&mut self, idx: usize, color: &[u8; 3]) {
|
||||
self.air_right[3 * idx..3 * (idx + 1)].copy_from_slice(color);
|
||||
}
|
||||
|
||||
pub fn get_air_middle(&self) -> [u8; 3] {
|
||||
return [
|
||||
((self.air_left[3] as u16 + self.air_right[3] as u16) / 2) as u8,
|
||||
((self.air_left[4] as u16 + self.air_right[4] as u16) / 2) as u8,
|
||||
((self.air_left[5] as u16 + self.air_right[5] as u16) / 2) as u8,
|
||||
];
|
||||
}
|
||||
|
||||
pub fn reset(&mut self) {
|
||||
self.ground.fill(0);
|
||||
self.air_left.fill(0);
|
||||
self.air_right.fill(0);
|
||||
self.dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Stores data required for a single slider controller. Data and lighting
|
||||
/// states are stored seperately in their own `Arc<Mutex<T>>` so that they can
|
||||
/// be locked independently.
|
||||
pub struct SliderState {
|
||||
/// Input data for the slider controller.
|
||||
pub input: Arc<Mutex<SliderInput>>,
|
||||
|
||||
/// Lighting data for the slider controller.
|
||||
pub lights: Arc<Mutex<SliderLights>>,
|
||||
}
|
||||
|
||||
impl SliderState {
|
||||
/// Creates a blank slider controller state
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
input: Arc::new(Mutex::new(SliderInput::new())),
|
||||
lights: Arc::new(Mutex::new(SliderLights::new())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes an instantaneous slider controller state (input + lighting) as a
|
||||
/// `Vec<u8>` that can be used for visualisation.
|
||||
pub fn snapshot(&self) -> Vec<u8> {
|
||||
let mut buf: Vec<u8> = vec![];
|
||||
{
|
||||
let input_handle = self.input.lock();
|
||||
buf.extend(input_handle.ground);
|
||||
buf.extend(input_handle.air);
|
||||
buf.extend(input_handle.extra);
|
||||
};
|
||||
{
|
||||
let lights_handle = self.lights.lock();
|
||||
buf.extend(lights_handle.ground);
|
||||
buf.extend(lights_handle.air_left);
|
||||
buf.extend(lights_handle.air_right);
|
||||
};
|
||||
|
||||
buf
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for SliderState {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
input: Arc::clone(&self.input),
|
||||
lights: Arc::clone(&self.lights),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
use directories::ProjectDirs;
|
||||
use image::Luma;
|
||||
use log::info;
|
||||
use qrcode::QrCode;
|
||||
use std::{error::Error, fs, path::PathBuf};
|
||||
|
||||
pub fn list_ips() -> Result<Vec<String>, Box<dyn Error>> {
|
||||
let mut ips = vec![];
|
||||
for adapter in ipconfig::get_adapters()? {
|
||||
for ip_address in adapter.ip_addresses() {
|
||||
ips.push(format!("{}", ip_address));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(ips)
|
||||
}
|
||||
|
||||
/// Get the %APPDATA% path for config files (and create if it does not already
|
||||
/// exist).
|
||||
fn get_config_dir() -> Option<Box<PathBuf>> {
|
||||
let project_dir = ProjectDirs::from("me", "impress labs", "slidershim").unwrap();
|
||||
let config_dir = project_dir.config_dir();
|
||||
fs::create_dir_all(config_dir).ok()?;
|
||||
|
||||
Some(Box::new(config_dir.to_path_buf()))
|
||||
}
|
||||
|
||||
/// Generates a helper QR for connecting with brokenithm
|
||||
pub fn get_brokenithm_qr_path(port: Option<u16>) -> Option<Box<PathBuf>> {
|
||||
let config_dir = get_config_dir()?;
|
||||
let brokenithm_qr_path = config_dir.join("brokenithm.png");
|
||||
|
||||
let ips = list_ips().ok()?;
|
||||
let link = "http://imp.ress.me/t/sshelper?d=".to_string()
|
||||
+ &ips
|
||||
.into_iter()
|
||||
.filter(|s| s.as_str().chars().filter(|x| *x == '.').count() == 3)
|
||||
.map(|s| base64::encode_config(s, base64::URL_SAFE_NO_PAD))
|
||||
.collect::<Vec<String>>()
|
||||
.join(";")
|
||||
+ "&p="
|
||||
+ port.or(Some(1606)).unwrap().to_string().as_str();
|
||||
info!("Url generated {}", link);
|
||||
let qr = QrCode::new(link).ok()?;
|
||||
let image = qr.render::<Luma<u8>>().build();
|
||||
image.save(brokenithm_qr_path.as_path()).ok()?;
|
||||
|
||||
return Some(Box::new(brokenithm_qr_path));
|
||||
}
|
||||
|
||||
pub fn get_log_file_path() -> Option<Box<PathBuf>> {
|
||||
let config_dir = get_config_dir()?;
|
||||
let log_path = config_dir.join("log.txt");
|
||||
|
||||
return Some(Box::new(log_path));
|
||||
}
|
||||
|
||||
pub fn get_config_path() -> Option<Box<PathBuf>> {
|
||||
let config_dir = get_config_dir()?;
|
||||
let config_path = config_dir.join("config.json");
|
||||
|
||||
return Some(Box::new(config_path));
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "slidershim"
|
||||
version = "0.1.4"
|
||||
version = "0.6.0"
|
||||
description = "slidershim"
|
||||
authors = ["4yn"]
|
||||
license = ""
|
||||
@@ -10,52 +10,19 @@ edition = "2018"
|
||||
build = "src/build.rs"
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "1.0.0-beta.4" }
|
||||
tauri-build = { version = "1.0.4", features = [] }
|
||||
|
||||
[dependencies]
|
||||
|
||||
# logging
|
||||
log = "0.4.14"
|
||||
env_logger = "0.9.0"
|
||||
simple-logging = "2.0.2"
|
||||
env_logger = "0.9.0"
|
||||
|
||||
# threads
|
||||
parking_lot = "0.12.0"
|
||||
atomic_float = "0.1.0"
|
||||
spin_sleep = "1.0.0"
|
||||
|
||||
# async
|
||||
futures = "0.3.19"
|
||||
futures-util = "0.3.19"
|
||||
async-trait = "0.1.52"
|
||||
tokio = { version="1.16.1", features= ["rt-multi-thread","macros"] }
|
||||
tokio-util = "0.6.9"
|
||||
|
||||
# UI
|
||||
tauri = { version = "1.0.0-beta.8", features = ["shell-open", "system-tray"] }
|
||||
serde_json = "1.0"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
tauri = { version = "1.0.4", features = ["shell-open", "system-tray", "window-start-dragging"] }
|
||||
open = "2.0.2"
|
||||
directories = "4.0.1"
|
||||
image = "0.23.14"
|
||||
|
||||
# device and system
|
||||
rusb = "0.9.0"
|
||||
serialport = "4.0.1"
|
||||
vigem-client = "0.1.1"
|
||||
winapi = "0.3.9"
|
||||
ipconfig = "0.3.0"
|
||||
|
||||
# webserver
|
||||
hyper = { version="0.14.16", features= ["server", "http1", "http2", "tcp", "stream", "runtime"] }
|
||||
phf = { version = "0.10.1", features = ["macros"] }
|
||||
tungstenite = { version="0.16.0", default-features=false }
|
||||
tokio-tungstenite = "0.16.1"
|
||||
|
||||
# webserver utils
|
||||
base64 = "0.13.0"
|
||||
palette = "0.6.0"
|
||||
qrcode = { version="0.12.0", features= ["image"] }
|
||||
slider_io = {path = "../src-slider_io" }
|
||||
|
||||
[features]
|
||||
default = [ "custom-protocol" ]
|
||||
|
||||
@@ -1,6 +1,63 @@
|
||||
_ _ _ _ _
|
||||
___| (_) __| | ___ _ __| |__ ___(_)_ __ ___
|
||||
/ __| | |/ _` |/ _ \ '__| '_ \/ __| | '_ ` _ \
|
||||
\__ \ | | (_| | __/ | | | | \__ \ | | | | | |
|
||||
|___/_|_|\__,_|\___|_| |_| |_|___/_|_| |_| |_|
|
||||
===============================================
|
||||
_ _ _ _ _
|
||||
___| (_) __| | ___ _ __ ___| |__ (_)_ __ ___
|
||||
/ __| | |/ _` |/ _ \ '__/ __| '_ \| | '_ ` _ \
|
||||
\__ \ | | (_| | __/ | \__ \ | | | | | | | | |
|
||||
|___/_|_|\__,_|\___|_| |___/_| |_|_|_| |_| |_| v0.6.1
|
||||
===============================================
|
||||
|
||||
https://github.com/4yn/slidershim
|
||||
|
||||
# Changelog
|
||||
|
||||
- v0.6.0
|
||||
- Support Laverita v3. Thanks @sr1canskhsia
|
||||
- v0.5.1
|
||||
- Support SSL/wss if brokenithm used with tunnelling. Thanks @kokarare1212
|
||||
- v0.5.0
|
||||
- Support for Yubideck 3.0 firmware
|
||||
- v0.4.3
|
||||
- Make Yubideck USB reports more flexible when reading data
|
||||
- v0.4.2
|
||||
- Fix HORI Project Diva gamepad slider output order
|
||||
- v0.4.1
|
||||
- Fix misplaced checkbox label (clicking on "use DirectInput" would check "disable air" instead)
|
||||
- Make Yuancon USB reports more flexible when reading data
|
||||
- v0.4.0
|
||||
- Add DirectInput keyboard emulation using oblitum/Interception
|
||||
- Add slide LED support for some controllers
|
||||
- v0.3.1
|
||||
- Fix wrong key in UMIGURI keyboard layout
|
||||
- v0.3.0
|
||||
- Add UMIGURI LED controller server support
|
||||
- Add UMIGURI default keyboard layout
|
||||
- v0.2.8
|
||||
- Add slider only layout (no buttons) for Project Diva gamepad output
|
||||
- Add options button to Project Diva gamepad output
|
||||
- v0.2.7
|
||||
- Add HORI Project Diva gamepad output and lighting mode
|
||||
- v0.2.6
|
||||
- Add Yubideck controller support
|
||||
- Add option to change Brokenithm sever port
|
||||
- v0.2.5
|
||||
- Add 6k and 4k keyboard output options
|
||||
- Add settings for reactive LED colors
|
||||
- v0.2.4
|
||||
- Restore support for older tablet devices for brokenithm by compiling brokenithm JS with older babel preset
|
||||
- Fix keys staying pressed even after brokenithm controller is closed
|
||||
- New Brokestalgia 28k web touch controller option
|
||||
- v0.2.3
|
||||
- Fix first and last buttons not working with brokenithm
|
||||
- Add option to disable air strings for controllers
|
||||
- Add option to slow down lighting updates
|
||||
- v0.2.2
|
||||
- Retcon serial slider name
|
||||
- Fix crash on some systems due to time math
|
||||
- Add link to repo
|
||||
- v0.2.1
|
||||
- Reactive + Rainbow mode
|
||||
- Fixed byte order for serial slider lights
|
||||
- v0.2.0
|
||||
- Added support for serial slider protocol
|
||||
- Added 16 key keyboard layout
|
||||
- v0.1.4
|
||||
- Initial public release
|
||||
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 2.0 KiB |
|
Before Width: | Height: | Size: 2.9 KiB After Width: | Height: | Size: 3.8 KiB |
|
Before Width: | Height: | Size: 582 B After Width: | Height: | Size: 560 B |
|
Before Width: | Height: | Size: 1.2 KiB After Width: | Height: | Size: 1.3 KiB |
|
Before Width: | Height: | Size: 1.7 KiB After Width: | Height: | Size: 2.1 KiB |
|
Before Width: | Height: | Size: 1.6 KiB After Width: | Height: | Size: 2.1 KiB |
|
Before Width: | Height: | Size: 640 B After Width: | Height: | Size: 620 B |
|
Before Width: | Height: | Size: 1.0 KiB After Width: | Height: | Size: 918 B |
|
Before Width: | Height: | Size: 1.3 KiB After Width: | Height: | Size: 1.2 KiB |
|
Before Width: | Height: | Size: 1.1 KiB After Width: | Height: | Size: 1.1 KiB |
|
Before Width: | Height: | Size: 1.1 KiB After Width: | Height: | Size: 1023 B |
|
Before Width: | Height: | Size: 5.7 KiB After Width: | Height: | Size: 4.2 KiB |
|
Before Width: | Height: | Size: 2.5 KiB After Width: | Height: | Size: 3.8 KiB |
@@ -5,7 +5,7 @@
|
||||
#![feature(div_duration)]
|
||||
#![feature(more_qualified_paths)]
|
||||
|
||||
mod slider_io;
|
||||
use slider_io;
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use std::sync::Arc;
|
||||
@@ -13,7 +13,8 @@ use std::sync::Arc;
|
||||
use log::info;
|
||||
|
||||
use tauri::{
|
||||
AppHandle, CustomMenuItem, Event, Manager, Runtime, SystemTray, SystemTrayEvent, SystemTrayMenu,
|
||||
AppHandle, CustomMenuItem, Manager, RunEvent, Runtime, SystemTray, SystemTrayEvent,
|
||||
SystemTrayMenu,
|
||||
};
|
||||
|
||||
fn show_window<R: Runtime>(handle: &AppHandle<R>) {
|
||||
@@ -37,14 +38,17 @@ fn main() {
|
||||
env_logger::Builder::new()
|
||||
.filter_level(log::LevelFilter::Debug)
|
||||
.init();
|
||||
info!("Starting slidershim");
|
||||
|
||||
#[cfg(not(debug_assertions))]
|
||||
{
|
||||
let log_file_path = slider_io::Config::get_log_file_path().unwrap();
|
||||
let log_file_path = slider_io::system::get_log_file_path().unwrap();
|
||||
simple_logging::log_to_file(log_file_path.as_path(), log::LevelFilter::Debug).unwrap();
|
||||
}
|
||||
|
||||
info!("Loading config");
|
||||
let config = Arc::new(Mutex::new(Some(slider_io::Config::load())));
|
||||
info!("Loading manager");
|
||||
let manager = Arc::new(Mutex::new(slider_io::Manager::new()));
|
||||
{
|
||||
let config_handle = config.lock();
|
||||
@@ -54,6 +58,7 @@ fn main() {
|
||||
manager_handle.update_config(config_handle_ref.clone());
|
||||
}
|
||||
|
||||
info!("Running tauri");
|
||||
tauri::Builder::default()
|
||||
.system_tray(
|
||||
// System tray content
|
||||
@@ -102,20 +107,32 @@ fn main() {
|
||||
|
||||
// Show logs
|
||||
app.listen_global("openLogfile", |_| {
|
||||
let log_file_path = slider_io::Config::get_log_file_path();
|
||||
let log_file_path = slider_io::get_log_file_path();
|
||||
if let Some(log_file_path) = log_file_path {
|
||||
open::that(log_file_path.as_path()).ok();
|
||||
}
|
||||
});
|
||||
|
||||
// Show brokenithm qr
|
||||
app.listen_global("openBrokenithmQr", |_| {
|
||||
let brokenithm_qr_path = slider_io::Config::get_brokenithm_qr_path();
|
||||
let config_clone = Arc::clone(&config);
|
||||
app.listen_global("openBrokenithmQr", move |_| {
|
||||
let config_handle = config_clone.lock();
|
||||
let brokenithm_qr_path = slider_io::get_brokenithm_qr_path(
|
||||
config_handle
|
||||
.as_ref()
|
||||
.map(|c| c.device_mode.get_port())
|
||||
.unwrap_or(None),
|
||||
);
|
||||
if let Some(brokenithm_qr_path) = brokenithm_qr_path {
|
||||
open::that(brokenithm_qr_path.as_path()).ok();
|
||||
}
|
||||
});
|
||||
|
||||
// Show repo
|
||||
app.listen_global("openRepo", |_| {
|
||||
open::that("https://github.com/4yn/slidershim").ok();
|
||||
});
|
||||
|
||||
// UI ready event
|
||||
let app_handle = app.handle();
|
||||
let config_clone = Arc::clone(&config);
|
||||
@@ -180,8 +197,8 @@ fn main() {
|
||||
.expect("error while running tauri application")
|
||||
.run(|app_handle, event| match event {
|
||||
// After app starts
|
||||
Event::CloseRequested { label, api, .. } if label.as_str() == "main" => {
|
||||
api.prevent_close();
|
||||
RunEvent::ExitRequested { api, .. } => {
|
||||
api.prevent_exit();
|
||||
hide_window(app_handle);
|
||||
}
|
||||
_ => {}
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
extern crate slidershim;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use std::{future::Future, io, time::Duration};
|
||||
|
||||
use tokio::{select, time::sleep};
|
||||
|
||||
// use slidershim::slider_io::worker::{AsyncJob, AsyncWorker};
|
||||
|
||||
// struct CounterJob;
|
||||
|
||||
// #[async_trait]
|
||||
// impl AsyncJob for CounterJob {
|
||||
// async fn run<F: Future<Output = ()> + Send>(self, stop_signal: F) {
|
||||
// let job_a = async {
|
||||
// println!("Start job A");
|
||||
// let mut x = 0;
|
||||
// loop {
|
||||
// x += 1;
|
||||
// println!("{}", x);
|
||||
// sleep(Duration::from_millis(100)).await;
|
||||
// }
|
||||
// };
|
||||
// let job_b = async move {
|
||||
// println!("Start job B");
|
||||
// stop_signal.await;
|
||||
// println!("Stop signal hit at job B");
|
||||
// };
|
||||
|
||||
// select! {
|
||||
// _ = job_a => {},
|
||||
// _ = job_b => {},
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
fn main() {
|
||||
env_logger::Builder::new()
|
||||
.filter_level(log::LevelFilter::Debug)
|
||||
.init();
|
||||
|
||||
// let worker = AsyncWorker::new("counter", CounterJob);
|
||||
let mut input = String::new();
|
||||
let string = io::stdin().read_line(&mut input).unwrap();
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
extern crate slidershim;
|
||||
|
||||
use std::{io, time::Duration};
|
||||
|
||||
use tokio::time::sleep;
|
||||
|
||||
// use slidershim::slider_io::{
|
||||
// brokenithm::BrokenithmJob, controller_state::FullState, worker::AsyncWorker,
|
||||
// };
|
||||
|
||||
fn main() {
|
||||
env_logger::Builder::new()
|
||||
.filter_level(log::LevelFilter::Debug)
|
||||
.init();
|
||||
|
||||
// let worker = AsyncWorker::new("brokenithm", BrokenithmJob::new(FullState::new()));
|
||||
let mut input = String::new();
|
||||
let string = io::stdin().read_line(&mut input).unwrap();
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
extern crate slidershim;
|
||||
|
||||
use std::io;
|
||||
|
||||
// use slidershim::slider_io::{Config, Context};
|
||||
|
||||
fn main() {
|
||||
env_logger::Builder::new()
|
||||
.filter_level(log::LevelFilter::Debug)
|
||||
.init();
|
||||
|
||||
// voltex?
|
||||
// let config = Config::from_str(
|
||||
// r#"{
|
||||
// "deviceMode": "yuancon",
|
||||
// "outputMode": "gamepad-voltex",
|
||||
// "keyboardSensitivity": 50,
|
||||
// "ledMode": "reactive-voltex",
|
||||
// "ledSensitivity": 50
|
||||
// }"#,
|
||||
// )
|
||||
// .unwrap();
|
||||
|
||||
// serial?
|
||||
// let config = Config::from_str(
|
||||
// r#"{
|
||||
// "deviceMode": "yuancon",
|
||||
// "outputMode": "kb-32-tasoller",
|
||||
// "keyboardSensitivity": 50,
|
||||
// "ledMode": "serial",
|
||||
// "ledSerialPort": "COM5"
|
||||
// }"#,
|
||||
// )
|
||||
// .unwrap();
|
||||
|
||||
// basic
|
||||
// let config = Config::from_str(
|
||||
// r#"{
|
||||
// "deviceMode": "yuancon",
|
||||
// "outputMode": "kb-32-tasoller",
|
||||
// "keyboardSensitivity": 50,fdwdfp1
|
||||
// "ledMode": "reactive-8",
|
||||
// "ledSensitivity": 50
|
||||
// }"#,
|
||||
// )
|
||||
// .unwrap();
|
||||
|
||||
// tasoller/
|
||||
// let config = Config::from_str(
|
||||
// r#"{
|
||||
// "deviceMode": "tasoller-two",
|
||||
// "outputMode": "kb-32-tasoller",
|
||||
// "keyboardSensitivity": 50,
|
||||
// "ledMode": "reactive-8",
|
||||
// "ledSensitivity": 50
|
||||
// }"#,
|
||||
// )
|
||||
// .unwrap();
|
||||
|
||||
// let manager = Context::new(config);
|
||||
|
||||
let mut input = String::new();
|
||||
let string = io::stdin().read_line(&mut input).unwrap();
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
extern crate slidershim;
|
||||
|
||||
use std::io;
|
||||
|
||||
// use slidershim::slider_io::worker::{Job, Worker};
|
||||
|
||||
// struct TestJob {
|
||||
// data: i64,
|
||||
// }
|
||||
|
||||
// impl Job for TestJob {
|
||||
// fn setup(&mut self) {
|
||||
// self.data = 10;
|
||||
// println!("setup {}", self.data);
|
||||
// }
|
||||
// fn tick(&mut self) {
|
||||
// self.data -= 1;
|
||||
// println!("tick {}", self.data);
|
||||
// }
|
||||
// fn teardown(&mut self) {
|
||||
// self.data = 11;
|
||||
// println!("teardown {}", self.data);
|
||||
// }
|
||||
// }
|
||||
|
||||
fn main() {
|
||||
// let worker = Worker::new(TestJob { data: 1 });
|
||||
|
||||
let mut input = String::new();
|
||||
let string = io::stdin().read_line(&mut input).unwrap();
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
#![cfg_attr(
|
||||
all(not(debug_assertions), target_os = "windows"),
|
||||
windows_subsystem = "windows"
|
||||
)]
|
||||
#![feature(div_duration)]
|
||||
#![feature(more_qualified_paths)]
|
||||
|
||||
pub mod slider_io;
|
||||
@@ -1,52 +0,0 @@
|
||||
// use serialport::SerialPort;
|
||||
// use std::io::{BufRead, BufReader};
|
||||
|
||||
// struct ArcadeSlider {
|
||||
// serial_port: BufReader<Box<dyn SerialPort>>,
|
||||
// }
|
||||
|
||||
// impl ArcadeSlider {
|
||||
// fn new() -> Self {
|
||||
// let serial_port = serialport::new("COM1", 152000).open().unwrap();
|
||||
// let serial_port_buf = BufReader::new(serial_port);
|
||||
// Self {
|
||||
// serial_port: serial_port_buf,
|
||||
// }
|
||||
// }
|
||||
|
||||
// fn recv(&mut self) {
|
||||
// let mut consumed = 0;
|
||||
// {
|
||||
// let d = self.serial_port.fill_buf().unwrap();
|
||||
|
||||
// let mut packets = vec![];
|
||||
// let mut packet = vec![];
|
||||
|
||||
// let mut bytes_taken = 0;
|
||||
// let mut in_escape = 0;
|
||||
// let mut checksum = 0;
|
||||
// for b in d.iter() {
|
||||
// bytes_taken += 1;
|
||||
|
||||
// match b {
|
||||
// 0xff => {
|
||||
// consumed += bytes_taken;
|
||||
// bytes_taken = 0;
|
||||
// in_escape = 0;
|
||||
// }
|
||||
// 0xfd => {
|
||||
// in_escape = 1;
|
||||
// }
|
||||
// _ => {
|
||||
// let b = b + in_escape;
|
||||
// in_escape = 0;
|
||||
// packet.push(b);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// self.serial_port.consume(consumed);
|
||||
// }
|
||||
|
||||
// fn send(&mut self) {}
|
||||
// }
|
||||
@@ -1,323 +0,0 @@
|
||||
use directories::ProjectDirs;
|
||||
use image::Luma;
|
||||
use log::{info, warn};
|
||||
use qrcode::QrCode;
|
||||
use serde_json::Value;
|
||||
use std::{convert::TryFrom, fs, path::PathBuf};
|
||||
|
||||
use crate::slider_io::utils::list_ips;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum HardwareSpec {
|
||||
TasollerOne,
|
||||
TasollerTwo,
|
||||
Yuancon,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum DeviceMode {
|
||||
None,
|
||||
Hardware {
|
||||
spec: HardwareSpec,
|
||||
},
|
||||
Brokenithm {
|
||||
ground_only: bool,
|
||||
led_enabled: bool,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum PollingRate {
|
||||
Sixty,
|
||||
Hundred,
|
||||
TwoHundredFifty,
|
||||
FiveHundred,
|
||||
Thousand,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum KeyboardLayout {
|
||||
Tasoller,
|
||||
Yuancon,
|
||||
Deemo,
|
||||
Voltex,
|
||||
Neardayo,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum GamepadLayout {
|
||||
Voltex,
|
||||
Neardayo,
|
||||
}
|
||||
|
||||
impl PollingRate {
|
||||
pub fn from_str(s: &str) -> Option<Self> {
|
||||
match s {
|
||||
"60" => Some(PollingRate::Sixty),
|
||||
"100" => Some(PollingRate::Hundred),
|
||||
"250" => Some(PollingRate::TwoHundredFifty),
|
||||
"500" => Some(PollingRate::FiveHundred),
|
||||
"1000" => Some(PollingRate::Thousand),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_t_u64(&self) -> u64 {
|
||||
match self {
|
||||
PollingRate::Sixty => 16666,
|
||||
PollingRate::Hundred => 10000,
|
||||
PollingRate::TwoHundredFifty => 4000,
|
||||
PollingRate::FiveHundred => 2000,
|
||||
PollingRate::Thousand => 1000,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum OutputMode {
|
||||
None,
|
||||
Keyboard {
|
||||
layout: KeyboardLayout,
|
||||
polling: PollingRate,
|
||||
sensitivity: u8,
|
||||
},
|
||||
Gamepad {
|
||||
layout: GamepadLayout,
|
||||
polling: PollingRate,
|
||||
sensitivity: u8,
|
||||
},
|
||||
Websocket {
|
||||
url: String,
|
||||
polling: PollingRate,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum ReactiveLayout {
|
||||
Even { splits: usize },
|
||||
Voltex,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum LedMode {
|
||||
None,
|
||||
Reactive {
|
||||
layout: ReactiveLayout,
|
||||
sensitivity: u8,
|
||||
},
|
||||
Attract,
|
||||
Test,
|
||||
Websocket {
|
||||
url: String,
|
||||
},
|
||||
Serial {
|
||||
port: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Config {
|
||||
pub raw: String,
|
||||
pub device_mode: DeviceMode,
|
||||
pub output_mode: OutputMode,
|
||||
pub led_mode: LedMode,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn from_str(s: &str) -> Option<Config> {
|
||||
let v: Value = serde_json::from_str(s).ok()?;
|
||||
|
||||
Some(Config {
|
||||
raw: s.to_string(),
|
||||
device_mode: match v["deviceMode"].as_str()? {
|
||||
"none" => DeviceMode::None,
|
||||
"tasoller-one" => DeviceMode::Hardware {
|
||||
spec: HardwareSpec::TasollerOne,
|
||||
},
|
||||
"tasoller-two" => DeviceMode::Hardware {
|
||||
spec: HardwareSpec::TasollerTwo,
|
||||
},
|
||||
"yuancon" => DeviceMode::Hardware {
|
||||
spec: HardwareSpec::Yuancon,
|
||||
},
|
||||
"brokenithm" => DeviceMode::Brokenithm {
|
||||
ground_only: false,
|
||||
led_enabled: false,
|
||||
},
|
||||
"brokenithm-led" => DeviceMode::Brokenithm {
|
||||
ground_only: false,
|
||||
led_enabled: true,
|
||||
},
|
||||
"brokenithm-ground" => DeviceMode::Brokenithm {
|
||||
ground_only: true,
|
||||
led_enabled: false,
|
||||
},
|
||||
"brokenithm-ground-led" => DeviceMode::Brokenithm {
|
||||
ground_only: true,
|
||||
led_enabled: true,
|
||||
},
|
||||
_ => panic!("Invalid device mode"),
|
||||
},
|
||||
output_mode: match v["outputMode"].as_str().unwrap() {
|
||||
"none" => OutputMode::None,
|
||||
"kb-32-tasoller" => OutputMode::Keyboard {
|
||||
layout: KeyboardLayout::Tasoller,
|
||||
polling: PollingRate::from_str(v["outputPolling"].as_str()?)?,
|
||||
sensitivity: u8::try_from(v["keyboardSensitivity"].as_i64()?).ok()?,
|
||||
},
|
||||
"kb-32-yuancon" => OutputMode::Keyboard {
|
||||
layout: KeyboardLayout::Yuancon,
|
||||
polling: PollingRate::from_str(v["outputPolling"].as_str()?)?,
|
||||
sensitivity: u8::try_from(v["keyboardSensitivity"].as_i64()?).ok()?,
|
||||
},
|
||||
"kb-8-deemo" => OutputMode::Keyboard {
|
||||
layout: KeyboardLayout::Deemo,
|
||||
polling: PollingRate::from_str(v["outputPolling"].as_str()?)?,
|
||||
sensitivity: u8::try_from(v["keyboardSensitivity"].as_i64()?).ok()?,
|
||||
},
|
||||
"kb-voltex" => OutputMode::Keyboard {
|
||||
layout: KeyboardLayout::Voltex,
|
||||
polling: PollingRate::from_str(v["outputPolling"].as_str()?)?,
|
||||
sensitivity: u8::try_from(v["keyboardSensitivity"].as_i64()?).ok()?,
|
||||
},
|
||||
"kb-neardayo" => OutputMode::Keyboard {
|
||||
layout: KeyboardLayout::Neardayo,
|
||||
polling: PollingRate::from_str(v["outputPolling"].as_str()?)?,
|
||||
sensitivity: u8::try_from(v["keyboardSensitivity"].as_i64()?).ok()?,
|
||||
},
|
||||
"gamepad-voltex" => OutputMode::Gamepad {
|
||||
layout: GamepadLayout::Voltex,
|
||||
polling: PollingRate::from_str(v["outputPolling"].as_str()?)?,
|
||||
sensitivity: u8::try_from(v["keyboardSensitivity"].as_i64()?).ok()?,
|
||||
},
|
||||
"gamepad-neardayo" => OutputMode::Gamepad {
|
||||
layout: GamepadLayout::Neardayo,
|
||||
polling: PollingRate::from_str(v["outputPolling"].as_str()?)?,
|
||||
sensitivity: u8::try_from(v["keyboardSensitivity"].as_i64()?).ok()?,
|
||||
},
|
||||
"websocket" => OutputMode::Websocket {
|
||||
url: v["outputWebsocketUrl"].as_str()?.to_string(),
|
||||
polling: PollingRate::from_str(v["outputPolling"].as_str()?)?,
|
||||
},
|
||||
_ => panic!("Invalid output mode"),
|
||||
},
|
||||
led_mode: match v["ledMode"].as_str()? {
|
||||
"none" => LedMode::None,
|
||||
"reactive-4" => LedMode::Reactive {
|
||||
layout: ReactiveLayout::Even { splits: 4 },
|
||||
sensitivity: u8::try_from(v["ledSensitivity"].as_i64()?).ok()?,
|
||||
},
|
||||
"reactive-8" => LedMode::Reactive {
|
||||
layout: ReactiveLayout::Even { splits: 8 },
|
||||
sensitivity: u8::try_from(v["ledSensitivity"].as_i64()?).ok()?,
|
||||
},
|
||||
"reactive-16" => LedMode::Reactive {
|
||||
layout: ReactiveLayout::Even { splits: 16 },
|
||||
sensitivity: u8::try_from(v["ledSensitivity"].as_i64()?).ok()?,
|
||||
},
|
||||
"reactive-voltex" => LedMode::Reactive {
|
||||
layout: ReactiveLayout::Voltex,
|
||||
sensitivity: u8::try_from(v["ledSensitivity"].as_i64()?).ok()?,
|
||||
},
|
||||
"attract" => LedMode::Attract,
|
||||
"test" => LedMode::Test,
|
||||
"websocket" => LedMode::Websocket {
|
||||
url: v["ledWebsocketUrl"].as_str()?.to_string(),
|
||||
},
|
||||
"serial" => LedMode::Serial {
|
||||
port: v["ledSerialPort"].as_str()?.to_string(),
|
||||
},
|
||||
_ => panic!("Invalid led mode"),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
pub fn get_log_file_path() -> Option<Box<PathBuf>> {
|
||||
let project_dir = ProjectDirs::from("me", "impress labs", "slidershim").unwrap();
|
||||
let config_dir = project_dir.config_dir();
|
||||
fs::create_dir_all(config_dir).ok()?;
|
||||
|
||||
let log_path = config_dir.join("log.txt");
|
||||
|
||||
return Some(Box::new(log_path));
|
||||
}
|
||||
|
||||
pub fn get_brokenithm_qr_path() -> Option<Box<PathBuf>> {
|
||||
let project_dir = ProjectDirs::from("me", "impress labs", "slidershim").unwrap();
|
||||
let config_dir = project_dir.config_dir();
|
||||
fs::create_dir_all(config_dir).ok()?;
|
||||
|
||||
let brokenithm_qr_path = config_dir.join("brokenithm.png");
|
||||
|
||||
let ips = list_ips().ok()?;
|
||||
let link = "http://imp.ress.me/t/sshelper?d=".to_string()
|
||||
+ &ips
|
||||
.into_iter()
|
||||
.filter(|s| s.as_str().chars().filter(|x| *x == '.').count() == 3)
|
||||
.map(|s| base64::encode_config(s, base64::URL_SAFE_NO_PAD))
|
||||
.collect::<Vec<String>>()
|
||||
.join(";");
|
||||
let qr = QrCode::new(link).ok()?;
|
||||
let image = qr.render::<Luma<u8>>().build();
|
||||
image.save(brokenithm_qr_path.as_path()).ok()?;
|
||||
|
||||
return Some(Box::new(brokenithm_qr_path));
|
||||
}
|
||||
|
||||
fn get_config_path() -> Option<Box<PathBuf>> {
|
||||
let project_dir = ProjectDirs::from("me", "impress labs", "slidershim").unwrap();
|
||||
let config_dir = project_dir.config_dir();
|
||||
fs::create_dir_all(config_dir).ok()?;
|
||||
|
||||
let config_path = config_dir.join("config.json");
|
||||
|
||||
return Some(Box::new(config_path));
|
||||
}
|
||||
|
||||
fn default() -> Self {
|
||||
Self::from_str(
|
||||
r#"{
|
||||
"deviceMode": "none",
|
||||
"devicePolling": "100",
|
||||
"outputMode": "none",
|
||||
"ledMode": "none",
|
||||
"keyboardSensitivity": 20,
|
||||
"outputWebsocketUrl": "localhost:3000",
|
||||
"outputPolling": "100",
|
||||
"ledSensitivity": 20,
|
||||
"ledWebsocketUrl": "localhost:3001",
|
||||
"ledSerialPort": "COM5"
|
||||
}"#,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn load_saved() -> Option<Self> {
|
||||
let config_path = Self::get_config_path()?;
|
||||
if !config_path.exists() {
|
||||
return None;
|
||||
}
|
||||
info!("Config file found at {:?}", config_path);
|
||||
let saved_data = fs::read_to_string(config_path.as_path()).ok()?;
|
||||
return Self::from_str(saved_data.as_str());
|
||||
}
|
||||
|
||||
pub fn load() -> Self {
|
||||
Self::load_saved()
|
||||
.or_else(|| {
|
||||
warn!("Config loading from file failed, using default");
|
||||
Some(Self::default())
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
pub fn save(&self) -> Option<()> {
|
||||
info!("Config saving...");
|
||||
let config_path = Self::get_config_path()?;
|
||||
info!("Config saving to {:?}", config_path);
|
||||
fs::write(config_path.as_path(), self.raw.as_str()).unwrap();
|
||||
info!("Config saved");
|
||||
|
||||
Some(())
|
||||
}
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
use atomic_float::AtomicF64;
|
||||
use log::info;
|
||||
use std::sync::{atomic::Ordering, Arc};
|
||||
|
||||
use crate::slider_io::{
|
||||
brokenithm::BrokenithmJob,
|
||||
config::{Config, DeviceMode, LedMode, OutputMode},
|
||||
controller_state::FullState,
|
||||
device::HidDeviceJob,
|
||||
led::LedJob,
|
||||
output::OutputJob,
|
||||
utils::LoopTimer,
|
||||
worker::{AsyncHaltableWorker, AsyncWorker, ThreadWorker},
|
||||
};
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub struct Context {
|
||||
state: FullState,
|
||||
config: Config,
|
||||
device_worker: Option<ThreadWorker>,
|
||||
brokenithm_worker: Option<AsyncHaltableWorker>,
|
||||
output_worker: Option<AsyncWorker>,
|
||||
led_worker: Option<AsyncWorker>,
|
||||
timers: Vec<(&'static str, Arc<AtomicF64>)>,
|
||||
}
|
||||
|
||||
impl Context {
|
||||
pub fn new(config: Config) -> Self {
|
||||
info!("Context creating");
|
||||
info!("Device config {:?}", config.device_mode);
|
||||
info!("Output config {:?}", config.output_mode);
|
||||
info!("LED config {:?}", config.led_mode);
|
||||
|
||||
let state = FullState::new();
|
||||
let mut timers = vec![];
|
||||
|
||||
let (device_worker, brokenithm_worker) = match &config.device_mode {
|
||||
DeviceMode::None => (None, None),
|
||||
DeviceMode::Brokenithm {
|
||||
ground_only,
|
||||
led_enabled,
|
||||
} => (
|
||||
None,
|
||||
Some(AsyncHaltableWorker::new(
|
||||
"brokenithm",
|
||||
BrokenithmJob::new(&state, ground_only, led_enabled),
|
||||
)),
|
||||
),
|
||||
DeviceMode::Hardware { spec } => (
|
||||
{
|
||||
let timer = LoopTimer::new();
|
||||
timers.push(("d", timer.fork()));
|
||||
Some(ThreadWorker::new(
|
||||
"device",
|
||||
HidDeviceJob::from_config(&state, spec),
|
||||
timer,
|
||||
))
|
||||
},
|
||||
None,
|
||||
),
|
||||
};
|
||||
let output_worker = match &config.output_mode {
|
||||
OutputMode::None => None,
|
||||
_ => {
|
||||
let timer = LoopTimer::new();
|
||||
timers.push(("o", timer.fork()));
|
||||
Some(AsyncWorker::new(
|
||||
"output",
|
||||
OutputJob::new(&state, &config.output_mode),
|
||||
timer,
|
||||
))
|
||||
}
|
||||
};
|
||||
let led_worker = match &config.led_mode {
|
||||
LedMode::None => None,
|
||||
_ => {
|
||||
let timer = LoopTimer::new();
|
||||
timers.push(("l", timer.fork()));
|
||||
Some(AsyncWorker::new(
|
||||
"led",
|
||||
LedJob::new(&state, &config.led_mode),
|
||||
timer,
|
||||
))
|
||||
}
|
||||
};
|
||||
|
||||
Self {
|
||||
state,
|
||||
config,
|
||||
device_worker,
|
||||
brokenithm_worker,
|
||||
output_worker,
|
||||
led_worker,
|
||||
timers,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clone_state(&self) -> FullState {
|
||||
self.state.clone()
|
||||
}
|
||||
|
||||
pub fn timer_state(&self) -> String {
|
||||
self
|
||||
.timers
|
||||
.iter()
|
||||
.map(|(s, f)| format!("{}:{:.1}/s", s, f.load(Ordering::SeqCst)))
|
||||
.collect::<Vec<String>>()
|
||||
.join(" ")
|
||||
}
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
use parking_lot::Mutex;
|
||||
use std::{sync::Arc, time::Instant};
|
||||
|
||||
pub struct ControllerState {
|
||||
pub ground_state: [u8; 32],
|
||||
pub air_state: [u8; 6],
|
||||
pub extra_state: [u8; 3],
|
||||
}
|
||||
|
||||
impl ControllerState {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
ground_state: [0; 32],
|
||||
air_state: [0; 6],
|
||||
extra_state: [0; 3],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn flat(&self, sensitivity: &u8) -> Vec<bool> {
|
||||
self
|
||||
.ground_state
|
||||
.iter()
|
||||
.map(|x| x > sensitivity)
|
||||
.chain(
|
||||
self
|
||||
.air_state
|
||||
.iter()
|
||||
.chain(self.extra_state.iter())
|
||||
.map(|x| x > &0),
|
||||
)
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn flip_vert(&mut self) {
|
||||
for i in 0..16 {
|
||||
self.ground_state.swap(i * 2, i * 2 + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct LedState {
|
||||
pub led_state: [u8; 3 * 31],
|
||||
pub dirty: bool,
|
||||
pub start: Instant,
|
||||
}
|
||||
|
||||
impl LedState {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
led_state: [0; 3 * 31],
|
||||
dirty: false,
|
||||
start: Instant::now(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn paint(&mut self, idx: usize, color: &[u8; 3]) {
|
||||
self.led_state[3 * idx..3 * (idx + 1)].copy_from_slice(color);
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FullState {
|
||||
pub controller_state: Arc<Mutex<ControllerState>>,
|
||||
pub led_state: Arc<Mutex<LedState>>,
|
||||
}
|
||||
|
||||
impl FullState {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
controller_state: Arc::new(Mutex::new(ControllerState::new())),
|
||||
led_state: Arc::new(Mutex::new(LedState::new())),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clone_controller(&self) -> Arc<Mutex<ControllerState>> {
|
||||
Arc::clone(&self.controller_state)
|
||||
}
|
||||
|
||||
pub fn clone_led(&self) -> Arc<Mutex<LedState>> {
|
||||
Arc::clone(&self.led_state)
|
||||
}
|
||||
|
||||
pub fn snapshot(&self) -> Vec<u8> {
|
||||
let mut buf: Vec<u8> = vec![];
|
||||
{
|
||||
let controller_state_handle = self.controller_state.lock();
|
||||
buf.extend(controller_state_handle.ground_state);
|
||||
buf.extend(controller_state_handle.air_state);
|
||||
buf.extend(controller_state_handle.extra_state);
|
||||
};
|
||||
{
|
||||
let led_state_handle = self.led_state.lock();
|
||||
buf.extend(led_state_handle.led_state);
|
||||
};
|
||||
|
||||
buf
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for FullState {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
controller_state: self.clone_controller(),
|
||||
led_state: self.clone_led(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,293 +0,0 @@
|
||||
use log::{error, info};
|
||||
use rusb::{self, DeviceHandle, GlobalContext};
|
||||
use std::{
|
||||
error::Error,
|
||||
mem::swap,
|
||||
ops::{Deref, DerefMut},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use crate::slider_io::{
|
||||
config::HardwareSpec,
|
||||
controller_state::{ControllerState, FullState, LedState},
|
||||
utils::{Buffer, ShimError},
|
||||
worker::ThreadJob,
|
||||
};
|
||||
|
||||
type HidReadCallback = fn(&Buffer, &mut ControllerState) -> ();
|
||||
type HidLedCallback = fn(&mut Buffer, &LedState) -> ();
|
||||
|
||||
enum WriteType {
|
||||
Bulk,
|
||||
Interrupt,
|
||||
}
|
||||
|
||||
pub struct HidDeviceJob {
|
||||
state: FullState,
|
||||
|
||||
vid: u16,
|
||||
pid: u16,
|
||||
read_endpoint: u8,
|
||||
led_endpoint: u8,
|
||||
|
||||
read_callback: HidReadCallback,
|
||||
read_buf: Buffer,
|
||||
last_read_buf: Buffer,
|
||||
|
||||
led_write_type: WriteType,
|
||||
led_callback: HidLedCallback,
|
||||
led_buf: Buffer,
|
||||
|
||||
handle: Option<DeviceHandle<GlobalContext>>,
|
||||
}
|
||||
|
||||
impl HidDeviceJob {
|
||||
fn new(
|
||||
state: FullState,
|
||||
vid: u16,
|
||||
pid: u16,
|
||||
read_endpoint: u8,
|
||||
led_endpoint: u8,
|
||||
read_callback: HidReadCallback,
|
||||
led_type: WriteType,
|
||||
led_callback: HidLedCallback,
|
||||
) -> Self {
|
||||
Self {
|
||||
state,
|
||||
vid,
|
||||
pid,
|
||||
read_endpoint,
|
||||
led_endpoint,
|
||||
read_callback,
|
||||
read_buf: Buffer::new(),
|
||||
last_read_buf: Buffer::new(),
|
||||
led_write_type: led_type,
|
||||
led_callback,
|
||||
led_buf: Buffer::new(),
|
||||
handle: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_config(state: &FullState, spec: &HardwareSpec) -> Self {
|
||||
match spec {
|
||||
HardwareSpec::TasollerOne => Self::new(
|
||||
state.clone(),
|
||||
0x1ccf,
|
||||
0x2333,
|
||||
0x84,
|
||||
0x03,
|
||||
|buf, controller_state| {
|
||||
if buf.len != 11 {
|
||||
return;
|
||||
}
|
||||
|
||||
let bits: Vec<u8> = buf
|
||||
.data
|
||||
.iter()
|
||||
.flat_map(|x| (0..8).map(move |i| ((x) >> i) & 1))
|
||||
.collect();
|
||||
for i in 0..32 {
|
||||
controller_state.ground_state[i] = bits[34 + i] * 255;
|
||||
}
|
||||
controller_state.flip_vert();
|
||||
|
||||
controller_state.air_state.copy_from_slice(&bits[28..34]);
|
||||
controller_state.extra_state[0..2].copy_from_slice(&bits[26..28]);
|
||||
},
|
||||
WriteType::Bulk,
|
||||
|buf, led_state| {
|
||||
buf.len = 240;
|
||||
buf.data[0] = 'B' as u8;
|
||||
buf.data[1] = 'L' as u8;
|
||||
buf.data[2] = '\x00' as u8;
|
||||
for (buf_chunk, state_chunk) in buf.data[3..96]
|
||||
.chunks_mut(3)
|
||||
.take(31)
|
||||
.zip(led_state.led_state.chunks(3).rev())
|
||||
{
|
||||
buf_chunk[0] = state_chunk[1];
|
||||
buf_chunk[1] = state_chunk[0];
|
||||
buf_chunk[2] = state_chunk[2];
|
||||
}
|
||||
buf.data[96..240].fill(0);
|
||||
},
|
||||
),
|
||||
HardwareSpec::TasollerTwo => Self::new(
|
||||
state.clone(),
|
||||
0x1ccf,
|
||||
0x2333,
|
||||
0x84,
|
||||
0x03,
|
||||
|buf, controller_state| {
|
||||
if buf.len != 36 {
|
||||
return;
|
||||
}
|
||||
|
||||
controller_state
|
||||
.ground_state
|
||||
.copy_from_slice(&buf.data[4..36]);
|
||||
controller_state.flip_vert();
|
||||
|
||||
let bits: Vec<u8> = (0..8).map(|x| (buf.data[3] >> x) & 1).collect();
|
||||
controller_state.air_state.copy_from_slice(&bits[0..6]);
|
||||
controller_state.extra_state[0..2].copy_from_slice(&bits[6..8]);
|
||||
},
|
||||
WriteType::Bulk,
|
||||
|buf, led_state| {
|
||||
buf.len = 240;
|
||||
buf.data[0] = 'B' as u8;
|
||||
buf.data[1] = 'L' as u8;
|
||||
buf.data[2] = '\x00' as u8;
|
||||
for (buf_chunk, state_chunk) in buf.data[3..96]
|
||||
.chunks_mut(3)
|
||||
.take(31)
|
||||
.zip(led_state.led_state.chunks(3).rev())
|
||||
{
|
||||
buf_chunk[0] = state_chunk[1];
|
||||
buf_chunk[1] = state_chunk[0];
|
||||
buf_chunk[2] = state_chunk[2];
|
||||
}
|
||||
buf.data[96..240].fill(0);
|
||||
},
|
||||
),
|
||||
HardwareSpec::Yuancon => Self::new(
|
||||
state.clone(),
|
||||
0x1973,
|
||||
0x2001,
|
||||
0x81,
|
||||
0x02,
|
||||
|buf, controller_state| {
|
||||
if buf.len != 34 {
|
||||
return;
|
||||
}
|
||||
|
||||
controller_state
|
||||
.ground_state
|
||||
.copy_from_slice(&buf.data[2..34]);
|
||||
for i in 0..6 {
|
||||
controller_state.air_state[i ^ 1] = (buf.data[0] >> i) & 1;
|
||||
}
|
||||
for i in 0..3 {
|
||||
controller_state.extra_state[2 - i] = (buf.data[1] >> i) & 1;
|
||||
}
|
||||
},
|
||||
WriteType::Interrupt,
|
||||
|buf, led_state| {
|
||||
buf.len = 31 * 2;
|
||||
for (buf_chunk, state_chunk) in buf
|
||||
.data
|
||||
.chunks_mut(2)
|
||||
.take(31)
|
||||
.zip(led_state.led_state.chunks(3).rev())
|
||||
{
|
||||
buf_chunk[0] = (state_chunk[0] << 3 & 0xe0) | (state_chunk[2] >> 3);
|
||||
buf_chunk[1] = (state_chunk[1] & 0xf8) | (state_chunk[0] >> 5);
|
||||
}
|
||||
},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn get_handle(&mut self) -> Result<(), Box<dyn Error>> {
|
||||
info!("Device finding vid {} pid {}", self.vid, self.pid);
|
||||
let handle = rusb::open_device_with_vid_pid(self.vid, self.pid);
|
||||
if handle.is_none() {
|
||||
error!("Device not found");
|
||||
return Err(Box::new(ShimError));
|
||||
}
|
||||
let mut handle = handle.unwrap();
|
||||
info!("Device found {:?}", handle);
|
||||
|
||||
if handle.kernel_driver_active(0).unwrap_or(false) {
|
||||
info!("Device detaching kernel driver");
|
||||
handle.detach_kernel_driver(0)?;
|
||||
}
|
||||
info!("Device setting configuration");
|
||||
handle.set_active_configuration(1)?;
|
||||
info!("Device claiming interface");
|
||||
handle.claim_interface(0)?;
|
||||
self.handle = Some(handle);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
const TIMEOUT: Duration = Duration::from_millis(20);
|
||||
|
||||
impl ThreadJob for HidDeviceJob {
|
||||
fn setup(&mut self) -> bool {
|
||||
match self.get_handle() {
|
||||
Ok(_) => {
|
||||
info!("Device OK");
|
||||
true
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Device setup failed: {}", e);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn tick(&mut self) -> bool {
|
||||
// Input loop
|
||||
let handle = self.handle.as_mut().unwrap();
|
||||
let mut work = false;
|
||||
|
||||
{
|
||||
let res = handle
|
||||
.read_interrupt(self.read_endpoint, &mut self.read_buf.data, TIMEOUT)
|
||||
.map_err(|e| {
|
||||
// debug!("Device read error {}", &e);
|
||||
e
|
||||
})
|
||||
.unwrap_or(0);
|
||||
self.read_buf.len = res;
|
||||
// debug!("{:?}", self.read_buf.slice());
|
||||
// if self.read_buf.len != 0 {
|
||||
if (self.read_buf.len != 0) && (self.read_buf.slice() != self.last_read_buf.slice()) {
|
||||
work = true;
|
||||
let mut controller_state_handle = self.state.controller_state.lock();
|
||||
(self.read_callback)(&self.read_buf, controller_state_handle.deref_mut());
|
||||
swap(&mut self.read_buf, &mut self.last_read_buf);
|
||||
}
|
||||
}
|
||||
|
||||
// Led loop
|
||||
{
|
||||
{
|
||||
let mut led_state_handle = self.state.led_state.lock();
|
||||
if led_state_handle.dirty {
|
||||
(self.led_callback)(&mut self.led_buf, led_state_handle.deref());
|
||||
led_state_handle.dirty = false;
|
||||
}
|
||||
}
|
||||
|
||||
if self.led_buf.len != 0 {
|
||||
let res = (match self.led_write_type {
|
||||
WriteType::Bulk => handle.write_bulk(self.led_endpoint, self.led_buf.slice(), TIMEOUT),
|
||||
WriteType::Interrupt => {
|
||||
handle.write_interrupt(self.led_endpoint, &self.led_buf.slice(), TIMEOUT)
|
||||
}
|
||||
})
|
||||
.map_err(|e| {
|
||||
// debug!("Device write error {}", e);
|
||||
e
|
||||
})
|
||||
.unwrap_or(0);
|
||||
if res == self.led_buf.len + 1 {
|
||||
// work = true;
|
||||
self.led_buf.len = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
work
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for HidDeviceJob {
|
||||
fn drop(&mut self) {
|
||||
if let Some(handle) = self.handle.as_mut() {
|
||||
handle.release_interface(0).ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,208 +0,0 @@
|
||||
use std::mem;
|
||||
use winapi::{
|
||||
ctypes::c_int,
|
||||
um::winuser::{SendInput, INPUT, INPUT_KEYBOARD, KEYBDINPUT, KEYEVENTF_KEYUP},
|
||||
};
|
||||
|
||||
use crate::slider_io::{config::KeyboardLayout, output::OutputHandler};
|
||||
|
||||
#[rustfmt::skip]
|
||||
const TASOLLER_KB_MAP: [usize; 41] = [
|
||||
0x41 /* A */, 0x31 /* 1 */, 0x5a /* Z */, 0x51 /* Q */, 0x53 /* S */, 0x32 /* 2 */, 0x58 /* X */, 0x57 /* W */,
|
||||
0x44 /* D */, 0x33 /* 3 */, 0x43 /* C */, 0x45 /* E */, 0x46 /* F */, 0x34 /* 4 */, 0x56 /* V */, 0x52 /* R */,
|
||||
0x47 /* G */, 0x35 /* 5 */, 0x42 /* B */, 0x54 /* T */, 0x48 /* H */, 0x36 /* 6 */, 0x4e /* N */, 0x59 /* Y */,
|
||||
0x4a /* J */, 0x37 /* 7 */, 0x4d /* M */, 0x55 /* U */, 0x4b /* K */, 0x38 /* 8 */, 0xbc /* VK_OEM_COMMA */, 0x49 /* I */,
|
||||
0xbf, 0xde, 0xbe, // VK_OEM_2, VK_OEM_7, VK_OEM_PERIOD,
|
||||
0xba, 0xdd, 0xdb, // VK_OEM_1, VK_OEM_6, VK_OEM_4
|
||||
0x0d, 0x20, 0x1b // VK_RETURN, VK_SPACE, VK_ESCAPE
|
||||
];
|
||||
|
||||
#[rustfmt::skip]
|
||||
const YUANCON_KB_MAP: [usize; 41] = [
|
||||
0x36 /* 6 */, 0x35 /* 5 */, 0x34 /* 4 */, 0x33 /* 3 */, 0x32 /* 2 */, 0x31 /* 1 */, 0x5a /* Z */, 0x59 /* Y */,
|
||||
0x58 /* X */, 0x57 /* W */, 0x56 /* V */, 0x55 /* U */, 0x54 /* T */, 0x53 /* S */, 0x52 /* R */, 0x51 /* Q */,
|
||||
0x50 /* P */, 0x4f /* O */, 0x4e /* N */, 0x4d /* M */, 0x4c /* L */, 0x4b /* K */, 0x4a /* J */, 0x49 /* I */,
|
||||
0x48 /* H */, 0x47 /* G */, 0x46 /* F */, 0x45 /* E */, 0x44 /* D */, 0x43 /* C */, 0x42 /* B */, 0x41 /* A */,
|
||||
0xbd, 0xbb, 0xdb, // VK_OEM_MINUS, VK_OEM_PLUS, VK_OEM_4,
|
||||
0xdd, 0xdc, 0xba, // VK_OEM_6, VK_OEM_5, VK_OEM_1,
|
||||
0x0d, 0x20, 0x1b, // VK_RETURN, VK_SPACE, VK_ESCAPE
|
||||
];
|
||||
|
||||
#[rustfmt::skip]
|
||||
const DEEMO_KB_MAP: [usize; 41] = [
|
||||
0x41, 0x41, 0x41, 0x41, // A
|
||||
0x53, 0x53, 0x53, 0x53, // S
|
||||
0x44, 0x44, 0x44, 0x44, // D
|
||||
0x46, 0x46, 0x46, 0x46, // F
|
||||
0x4a, 0x4a, 0x4a, 0x4a, // J
|
||||
0x4b, 0x4b, 0x4b, 0x4b, // K
|
||||
0x4c, 0x4c, 0x4c, 0x4c, // L
|
||||
0xba, 0xba, 0xba, 0xba, // VK_OEM_1
|
||||
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // VK_SPACE
|
||||
0x00, 0x00, 0x00, // Disabled
|
||||
];
|
||||
|
||||
#[rustfmt::skip]
|
||||
const VOLTEX_KB_MAP: [usize; 41] = [
|
||||
0x57, 0x57, 0x57, 0x57, // W
|
||||
0x45, 0x45, 0x45, 0x45, // E
|
||||
0x43, 0x44,
|
||||
0x43, 0x44,
|
||||
0x43, 0x46, // D
|
||||
0x43, 0x46, // C // F
|
||||
0x4d, 0x4a, // M // J
|
||||
0x4d, 0x4a, // K
|
||||
0x4d, 0x4b,
|
||||
0x4d, 0x4b,
|
||||
0x4f, 0x4f, 0x4f, 0x4f, // O
|
||||
0x50, 0x50, 0x50, 0x50, // P
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Disabled
|
||||
0x31, 0x0d, 0x1b, // 1, VK_RETURN, VK_ESCAPE
|
||||
];
|
||||
|
||||
#[rustfmt::skip]
|
||||
const VOLTEX_KB_MAP_NEARDAYO: [usize; 41] = [
|
||||
0x57, 0x57, 0x57, 0x57, // W
|
||||
0x45, 0x45, 0x45, 0x45, // E
|
||||
0x43, 0x44,
|
||||
0x43, 0x44,
|
||||
0x43, 0x46, // D
|
||||
0x43, 0x46, // C // F
|
||||
0x4d, 0x4a, // M // J
|
||||
0x4d, 0x4a, // K
|
||||
0x4d, 0x4b,
|
||||
0x4d, 0x4b,
|
||||
0x4f, 0x4f, 0x4f, 0x4f, // O
|
||||
0x50, 0x50, 0x50, 0x50, // P
|
||||
0x57, 0x45, 0x45, 0x4f, 0x4f, 0x50, // Disabled
|
||||
0x31, 0x0d, 0x1b, // 1, VK_RETURN, VK_ESCAPE
|
||||
];
|
||||
|
||||
pub struct KeyboardOutput {
|
||||
ground_to_idx: [usize; 41],
|
||||
idx_to_keycode: [u16; 41],
|
||||
// keycode_to_idx: [usize; 256],
|
||||
next_keys: [bool; 41],
|
||||
last_keys: [bool; 41],
|
||||
|
||||
kb_buf: [INPUT; 41],
|
||||
n_kb_buf: u32,
|
||||
}
|
||||
|
||||
impl KeyboardOutput {
|
||||
pub fn new(layout: KeyboardLayout) -> Self {
|
||||
let kb_map = match layout {
|
||||
KeyboardLayout::Tasoller => &TASOLLER_KB_MAP,
|
||||
KeyboardLayout::Yuancon => &YUANCON_KB_MAP,
|
||||
KeyboardLayout::Deemo => &DEEMO_KB_MAP,
|
||||
KeyboardLayout::Voltex => &VOLTEX_KB_MAP,
|
||||
KeyboardLayout::Neardayo => &VOLTEX_KB_MAP_NEARDAYO,
|
||||
};
|
||||
|
||||
let mut ground_to_idx = [0 as usize; 41];
|
||||
let mut idx_to_keycode = [0 as u16; 41];
|
||||
let mut keycode_to_idx = [0xffff as usize; 256];
|
||||
let mut keycode_count: usize = 0;
|
||||
|
||||
for (ground, keycode) in kb_map.iter().enumerate() {
|
||||
if keycode_to_idx[*keycode] == 0xffff {
|
||||
keycode_to_idx[*keycode] = keycode_count;
|
||||
idx_to_keycode[keycode_count] = *keycode as u16;
|
||||
keycode_count += 1;
|
||||
}
|
||||
ground_to_idx[ground] = keycode_to_idx[*keycode]
|
||||
}
|
||||
|
||||
let mut kb_buf = [INPUT {
|
||||
type_: INPUT_KEYBOARD,
|
||||
u: unsafe { mem::zeroed() },
|
||||
}; 41];
|
||||
|
||||
for i in kb_buf.iter_mut() {
|
||||
let mut inner = unsafe { i.u.ki_mut() };
|
||||
inner.wVk = 0;
|
||||
inner.wScan = 0;
|
||||
inner.dwFlags = 0;
|
||||
inner.time = 0;
|
||||
inner.dwExtraInfo = 0;
|
||||
}
|
||||
|
||||
Self {
|
||||
ground_to_idx,
|
||||
idx_to_keycode,
|
||||
// keycode_to_idx,
|
||||
next_keys: [false; 41],
|
||||
last_keys: [false; 41],
|
||||
kb_buf,
|
||||
n_kb_buf: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn send(&mut self) {
|
||||
self.n_kb_buf = 0;
|
||||
|
||||
for (i, (n, l)) in self
|
||||
.next_keys
|
||||
.iter_mut()
|
||||
.zip(self.last_keys.iter_mut())
|
||||
.enumerate()
|
||||
{
|
||||
let keycode = self.idx_to_keycode[i];
|
||||
if keycode == 0 {
|
||||
continue;
|
||||
}
|
||||
match (*n, *l) {
|
||||
(true, false) => {
|
||||
let inner: &mut KEYBDINPUT = unsafe { self.kb_buf[self.n_kb_buf as usize].u.ki_mut() };
|
||||
inner.wVk = keycode;
|
||||
inner.dwFlags = 0;
|
||||
self.n_kb_buf += 1;
|
||||
// println!("{} down", keycode);
|
||||
}
|
||||
(false, true) => {
|
||||
let inner: &mut KEYBDINPUT = unsafe { self.kb_buf[self.n_kb_buf as usize].u.ki_mut() };
|
||||
inner.wVk = keycode;
|
||||
inner.dwFlags = KEYEVENTF_KEYUP;
|
||||
self.n_kb_buf += 1;
|
||||
// println!("{} up", keycode);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
*l = *n;
|
||||
}
|
||||
|
||||
if self.n_kb_buf != 0 {
|
||||
unsafe {
|
||||
SendInput(
|
||||
self.n_kb_buf,
|
||||
self.kb_buf.as_mut_ptr(),
|
||||
mem::size_of::<INPUT>() as c_int,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl OutputHandler for KeyboardOutput {
|
||||
fn tick(&mut self, flat_controller_state: &Vec<bool>) -> bool {
|
||||
self.next_keys.fill(false);
|
||||
for (idx, x) in flat_controller_state.iter().enumerate() {
|
||||
if *x {
|
||||
self.next_keys[self.ground_to_idx[idx]] = true;
|
||||
}
|
||||
}
|
||||
self.send();
|
||||
true
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.next_keys.fill(false);
|
||||
self.send();
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for KeyboardOutput {
|
||||
fn drop(&mut self) {
|
||||
self.reset();
|
||||
}
|
||||
}
|
||||
@@ -1,235 +0,0 @@
|
||||
use async_trait::async_trait;
|
||||
use log::{error, info};
|
||||
use palette::{FromColor, Hsv, Srgb};
|
||||
use serialport::{ClearBuffer, SerialPort};
|
||||
use std::{
|
||||
ops::DerefMut,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tokio::time::{interval, Interval};
|
||||
|
||||
use crate::slider_io::{
|
||||
config::{LedMode, ReactiveLayout},
|
||||
controller_state::{FullState, LedState},
|
||||
utils::Buffer,
|
||||
voltex::VoltexState,
|
||||
worker::AsyncJob,
|
||||
};
|
||||
|
||||
pub struct LedJob {
|
||||
state: FullState,
|
||||
mode: LedMode,
|
||||
serial_port: Option<Box<dyn SerialPort>>,
|
||||
started: Instant,
|
||||
timer: Interval,
|
||||
}
|
||||
|
||||
impl LedJob {
|
||||
pub fn new(state: &FullState, mode: &LedMode) -> Self {
|
||||
Self {
|
||||
state: state.clone(),
|
||||
mode: mode.clone(),
|
||||
serial_port: None,
|
||||
started: Instant::now(),
|
||||
timer: interval(Duration::from_micros(33333)),
|
||||
}
|
||||
}
|
||||
|
||||
fn calc_lights(
|
||||
&self,
|
||||
flat_controller_state: Option<&Vec<bool>>,
|
||||
serial_buffer: Option<&Buffer>,
|
||||
led_state: &mut LedState,
|
||||
) {
|
||||
match self.mode {
|
||||
LedMode::Reactive { layout, .. } => {
|
||||
let flat_controller_state = flat_controller_state.unwrap();
|
||||
|
||||
match layout {
|
||||
ReactiveLayout::Even { splits } => {
|
||||
let buttons_per_split = 32 / splits;
|
||||
|
||||
let banks: Vec<bool> = flat_controller_state
|
||||
.chunks(32 / splits)
|
||||
.take(splits)
|
||||
.map(|x| x.contains(&true))
|
||||
.collect();
|
||||
|
||||
for idx in 0..31 {
|
||||
led_state.paint(
|
||||
idx,
|
||||
match (idx + 1) % buttons_per_split {
|
||||
0 => &[255, 0, 255],
|
||||
_ => match banks[idx / buttons_per_split] {
|
||||
true => &[255, 0, 255],
|
||||
false => &[255, 255, 0],
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
ReactiveLayout::Voltex => {
|
||||
led_state.led_state.fill(0);
|
||||
|
||||
// Fixed
|
||||
led_state.paint(3, &[10, 100, 180]);
|
||||
for idx in 0..5 {
|
||||
led_state.paint(7 + idx * 4, &[64, 64, 64]);
|
||||
}
|
||||
led_state.paint(27, &[180, 10, 110]);
|
||||
|
||||
let voltex_state = VoltexState::from_flat(flat_controller_state);
|
||||
|
||||
// Left laser
|
||||
for (idx, state) in voltex_state.laser[0..2].iter().enumerate() {
|
||||
if *state {
|
||||
led_state.paint(0 + idx * 4, &[70, 230, 250]);
|
||||
led_state.paint(1 + idx * 4, &[70, 230, 250]);
|
||||
led_state.paint(2 + idx * 4, &[70, 230, 250]);
|
||||
}
|
||||
}
|
||||
|
||||
// Right laser
|
||||
for (idx, state) in voltex_state.laser[2..4].iter().enumerate() {
|
||||
if *state {
|
||||
led_state.paint(24 + idx * 4, &[250, 60, 200]);
|
||||
led_state.paint(25 + idx * 4, &[255, 60, 200]);
|
||||
led_state.paint(26 + idx * 4, &[255, 60, 200]);
|
||||
}
|
||||
}
|
||||
|
||||
// Buttons
|
||||
for (idx, state) in voltex_state.bt.iter().enumerate() {
|
||||
if *state {
|
||||
led_state.paint(8 + idx * 4, &[255, 255, 255]);
|
||||
led_state.paint(10 + idx * 4, &[255, 255, 255]);
|
||||
}
|
||||
}
|
||||
|
||||
// Fx
|
||||
for (idx, state) in voltex_state.fx.iter().enumerate() {
|
||||
if *state {
|
||||
led_state.paint(9 + idx * 8, &[250, 100, 30]);
|
||||
led_state.paint(11 + idx * 8, &[250, 100, 30]);
|
||||
led_state.paint(13 + idx * 8, &[250, 100, 30]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
LedMode::Attract => {
|
||||
let theta = self
|
||||
.started
|
||||
.elapsed()
|
||||
.div_duration_f64(Duration::from_secs(4))
|
||||
% 1.0;
|
||||
for idx in 0..31 {
|
||||
let slice_theta = (&theta + (idx as f64) / 32.0) % 1.0;
|
||||
let color = Srgb::from_color(Hsv::new(slice_theta * 360.0, 1.0, 1.0)).into_format::<u8>();
|
||||
led_state.paint(idx, &[color.red, color.green, color.blue]);
|
||||
}
|
||||
}
|
||||
LedMode::Serial { .. } => {
|
||||
// https://github.com/jmontineri/OpeNITHM/blob/89e9a43f7484e8949cd31bbff79c32f21ea3ec1d/Firmware/OpeNITHM/SerialProcessor.h
|
||||
// https://github.com/jmontineri/OpeNITHM/blob/89e9a43f7484e8949cd31bbff79c32f21ea3ec1d/Firmware/OpeNITHM/SerialProcessor.cpp
|
||||
// https://github.com/jmontineri/OpeNITHM/blob/89e9a43f7484e8949cd31bbff79c32f21ea3ec1d/Firmware/OpeNITHM/SerialLeds.h
|
||||
// https://github.com/jmontineri/OpeNITHM/blob/89e9a43f7484e8949cd31bbff79c32f21ea3ec1d/Firmware/OpeNITHM/SerialLeds.cpp
|
||||
if let Some(serial_buffer) = serial_buffer {
|
||||
// println!("buffer {:?}", serial_buffer.data);
|
||||
if serial_buffer.data[0] == 0xaa && serial_buffer.data[1] == 0xaa {
|
||||
for (idx, buf_chunk) in serial_buffer.data[2..95]
|
||||
.chunks(3)
|
||||
.take(31)
|
||||
.rev()
|
||||
.enumerate()
|
||||
{
|
||||
led_state.paint(idx, &[(*buf_chunk)[1], (*buf_chunk)[2], (*buf_chunk)[0]]);
|
||||
}
|
||||
// println!("leds {:?}", led_state.led_state);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => panic!("Not implemented"),
|
||||
}
|
||||
|
||||
led_state.dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl AsyncJob for LedJob {
|
||||
async fn setup(&mut self) -> bool {
|
||||
match &self.mode {
|
||||
LedMode::Serial { port } => {
|
||||
info!(
|
||||
"Serial port for led opening at {} {:?}",
|
||||
port.as_str(),
|
||||
115200
|
||||
);
|
||||
self.serial_port = match serialport::new(port, 115200).open() {
|
||||
Ok(s) => {
|
||||
info!("Serial port opened");
|
||||
Some(s)
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Serial port could not open: {}", e);
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
self.serial_port.is_some()
|
||||
}
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
async fn tick(&mut self) -> bool {
|
||||
let mut flat_controller_state: Option<Vec<bool>> = None;
|
||||
let mut serial_buffer: Option<Buffer> = None;
|
||||
|
||||
// Do the IO here
|
||||
match self.mode {
|
||||
LedMode::Reactive { sensitivity, .. } => {
|
||||
let controller_state_handle = self.state.controller_state.lock();
|
||||
flat_controller_state = Some(controller_state_handle.flat(&sensitivity));
|
||||
}
|
||||
LedMode::Serial { .. } => {
|
||||
if let Some(serial_port) = self.serial_port.as_mut() {
|
||||
let mut serial_data_avail = serial_port.bytes_to_read().unwrap_or(0);
|
||||
if serial_data_avail >= 100 {
|
||||
if serial_data_avail % 100 == 0 {
|
||||
let mut serial_buffer_working = Buffer::new();
|
||||
serial_port
|
||||
.as_mut()
|
||||
.read_exact(&mut serial_buffer_working.data[..100])
|
||||
.ok()
|
||||
.unwrap();
|
||||
serial_data_avail -= 100;
|
||||
serial_buffer = Some(serial_buffer_working);
|
||||
}
|
||||
|
||||
if serial_data_avail > 0 {
|
||||
serial_port.clear(ClearBuffer::All).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
// Then calculate and transfer
|
||||
{
|
||||
let mut led_state_handle = self.state.led_state.lock();
|
||||
self.calc_lights(
|
||||
flat_controller_state.as_ref(),
|
||||
serial_buffer.as_ref(),
|
||||
led_state_handle.deref_mut(),
|
||||
);
|
||||
}
|
||||
// thread::sleep(Duration::from_millis(30));
|
||||
// spin_sleep::sleep(Duration::from_micros(33333));
|
||||
self.timer.tick().await;
|
||||
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
mod config;
|
||||
mod utils;
|
||||
mod worker;
|
||||
|
||||
mod controller_state;
|
||||
mod voltex;
|
||||
|
||||
mod acio;
|
||||
mod brokenithm;
|
||||
mod gamepad;
|
||||
mod keyboard;
|
||||
|
||||
mod device;
|
||||
mod led;
|
||||
mod output;
|
||||
|
||||
mod context;
|
||||
mod manager;
|
||||
|
||||
pub use config::Config;
|
||||
pub use manager::Manager;
|
||||
pub use utils::list_ips;
|
||||