Compare commits

..
Author SHA1 Message Date
Uriel d102cb3778 add university of maryland mirror for Eclipse formatter (#1289) 2025-01-26 19:33:52 +03:00
CollinandButterscotch! bfb30c472b Skeleton Constraints (#1222)
Co-authored-by: Butterscotch! <[email protected]>
2025-01-26 12:36:10 -03:00
Butterscotch!andUriel 4ad9d5cfca Expand skeleton height config (#1156)
Co-authored-by: Uriel <[email protected]>
2025-01-23 17:21:38 +01:00
Uriel 2c49d1dc65 Update apt cache action to fix CI error (#1287) 2025-01-23 17:06:44 +01:00
rcelyte fcd82324a9 SolarXR IPC Socket (#1247) 2025-01-22 18:53:48 +01:00
Butterscotch! b4df1d1444 Improve log file behaviour (#1262) 2025-01-22 19:30:28 +02:00
Erimel 181ba089c2 Attempt to fix moving average quaternions not resetting properly (#1278) 2025-01-13 23:24:22 +01:00
Yao Wei 394c1dd438 i18n: improve SlimeVR tracker flashing instruction (#1276) 2025-01-07 18:12:34 +01:00
2ff6e99385 Fix "trackers still on" when closing via tray (#1265)
Co-authored-by: Eiren Rain <[email protected]>
Co-authored-by: lucas lelievre <[email protected]>
2025-01-06 15:16:26 +01:00
Uriel 3614612ac2 Fix CI bugs that appeared recently (#1272) 2025-01-03 01:29:21 +03:00
Butterscotch! dfeb4e79a4 AutoBone bone contribution fix & cleanup (#1249) 2025-01-03 01:28:31 +03:00
Erimel a606c5a375 Fix over 180 degrees rotations in HumanSkeleton (#1277) 2025-01-02 22:24:56 +01:00
Butterscotch! 4e698b693c Don't filter non-temporal trackers (#1255) 2025-01-03 00:19:10 +03:00
Uriel 0eb81eec04 Disable update notifications for pnpm 2024-12-20 23:54:26 +01:00
Butterscotch! 35f5d132c8 Use jSerialComm 2.11.1-SNAPSHOT (#1269) 2024-12-20 17:06:37 +01:00
Uriel 02cc2496f0 Fix eslint error 2024-12-20 15:34:53 +01:00
loucass003 d84eaa203a Add more feedback 2024-12-20 00:48:23 +01:00
Uriel e0d372e9bb fix translation files key naming 2024-12-20 00:00:32 +01:00
Uriel b7a54f6aef fix bugs and stuff 2024-12-19 21:54:42 +01:00
9d65477af7 Automatic firmware update for official trackers (#1241)
Co-authored-by: ImUrX <[email protected]>
Co-authored-by: Uriel <[email protected]>
Co-authored-by: Butterscotch! <[email protected]>
Co-authored-by: Eiren Rain <[email protected]>
2024-12-19 20:03:43 +02:00
73cdc890f2 Firmware tool (#880)
Co-authored-by: ImUrX <[email protected]>
Co-authored-by: Uriel <[email protected]>
2024-12-19 19:35:54 +02:00
Vocaloid Fan e8afb49685 Refactor + Check for env variables (#1261) 2024-12-12 17:05:54 -03:00
Uriel bc487f8655 Fix Appimage crashing for people (#1253) 2024-12-11 17:09:17 +02:00
Uriel 2708b5a15b Small improvements on packaging for Tauri (#1254) 2024-12-11 17:08:17 +02:00
Vocaloid Fan b52e705dc4 Fix Rust logging by disabling ANSI for file output. (#1256) 2024-12-08 12:33:54 -03:00
Eiren Rain 1a5584bcfc Fix SolarXR on main 2024-12-07 12:22:22 +01:00
Erimel 8238f569c6 Flex resistance and angle support (#1242) 2024-11-27 01:11:19 +03:00
abb128 1051d0c5e5 Improve VRM model file input (#1246) 2024-11-21 21:48:17 +02:00
Collin 8fe2540f91 Potentially fix weird hip issues (#1244) 2024-11-21 21:46:53 +02:00
sctanf 6232903691 make HID Device a slime (#1235) 2024-11-21 21:46:34 +02:00
Uriel 819d2fc3b8 Fix error on labeler 2024-11-20 21:14:10 +01:00
Uriel 565a64b0e3 Make GUI check well against translation changes (#1227) 2024-11-19 22:15:48 +01:00
Erimel 18f291345d Finger tracking skeleton and VMC support (#1091) 2024-11-15 19:10:17 +02:00
158 changed files with 12236 additions and 1685 deletions

No files matched your search

+1 -2
View File
@@ -13,8 +13,7 @@
"Area: GUI":
- all:
- changed-files:
- any-glob-to-any-file: "gui/**/*"
- all-globs-to-all-files: "!gui/public/i18n/**"
- all-globs-to-any-file: ["gui/**/*", "!gui/public/i18n/**/*"]
"Area: Hardware Protocol":
- changed-files:
- any-glob-to-any-file: "server/core/src/main/java/dev/slimevr/tracking/trackers/udp/**"
+1 -1
View File
@@ -57,7 +57,7 @@ jobs:
- if: matrix.os == 'ubuntu-22.04'
name: Set up Linux dependencies
uses: awalsh128/cache-apt-pkgs-action@latest
uses: awalsh128/cache-apt-pkgs-action@v1.4.3
with:
packages: libgtk-3-dev webkit2gtk-4.1 libappindicator3-dev librsvg2-dev patchelf
# Increment to invalidate the cache
+16 -5
View File
@@ -144,7 +144,7 @@ jobs:
bundle-linux:
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
needs: [build, test]
if: contains(fromJSON('["workflow_dispatch", "create"]'), github.event_name)
steps:
@@ -158,16 +158,27 @@ jobs:
path: server/desktop/build/libs/
- name: Set up Linux dependencies
uses: awalsh128/cache-apt-pkgs-action@latest
uses: awalsh128/cache-apt-pkgs-action@v1.4.3
with:
packages: libgtk-3-dev webkit2gtk-4.1 libappindicator3-dev librsvg2-dev patchelf libfuse2
packages: |
build-essential curl wget file libssl-dev libgtk-3-dev libappindicator3-dev librsvg2-dev
# Increment to invalidate the cache
version: 1.0
version: 2.0
# Enables a workaround to attempt to run pre and post install scripts
execute_install_scripts: true
# Disables uploading logs as a build artifact
debug: false
- name: Set up specific Linux versioned dependencies
run: |
sudo apt-get update && sudo apt-get install -y \
libwebkit2gtk-4.1-0=2.44.0-2 \
libwebkit2gtk-4.1-dev=2.44.0-2 \
libjavascriptcoregtk-4.1-0=2.44.0-2 \
libjavascriptcoregtk-4.1-dev=2.44.0-2 \
gir1.2-javascriptcoregtk-4.1=2.44.0-2 \
gir1.2-webkit2-4.1=2.44.0-2;
- name: Cache cargo dependencies
uses: Swatinem/rust-cache@v2
with:
@@ -274,7 +285,7 @@ jobs:
./bundle_dmg.sh --volname SlimeVR --icon slimevr 180 170 --app-drop-link 480 170 \
--window-size 660 400 --hide-extension ../macos/SlimeVR.app \
--volicon ../macos/SlimeVR.app/Contents/Resources/icon.icns --skip-jenkins \
--eula ../../../../LICENSE-MIT slimevr.dmg ../macos/SlimeVR.app
--eula ../../../../../LICENSE-MIT slimevr.dmg ../macos/SlimeVR.app
- uses: actions/upload-artifact@v4
with:
+1
View File
@@ -0,0 +1 @@
update-notifier=false
Generated
+189
View File
@@ -1837,6 +1837,24 @@ dependencies = [
"want",
]
[[package]]
name = "hyper-rustls"
version = "0.27.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08afdbb5c31130e3034af566421053ab03787c640246a446327f550d11bcb333"
dependencies = [
"futures-util",
"http",
"hyper",
"hyper-util",
"rustls",
"rustls-pki-types",
"tokio",
"tokio-rustls",
"tower-service",
"webpki-roots",
]
[[package]]
name = "hyper-util"
version = "0.1.9"
@@ -2000,6 +2018,15 @@ version = "1.70.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf"
[[package]]
name = "itertools"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
dependencies = [
"either",
]
[[package]]
name = "itoa"
version = "0.4.8"
@@ -3124,6 +3151,55 @@ dependencies = [
"memchr",
]
[[package]]
name = "quinn"
version = "0.11.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c7c5fdde3cdae7203427dc4f0a68fe0ed09833edc525a03456b153b79828684"
dependencies = [
"bytes",
"pin-project-lite",
"quinn-proto",
"quinn-udp",
"rustc-hash",
"rustls",
"socket2",
"thiserror",
"tokio",
"tracing",
]
[[package]]
name = "quinn-proto"
version = "0.11.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fadfaed2cd7f389d0161bb73eeb07b7b78f8691047a6f3e73caaeae55310a4a6"
dependencies = [
"bytes",
"rand 0.8.5",
"ring",
"rustc-hash",
"rustls",
"slab",
"thiserror",
"tinyvec",
"tracing",
]
[[package]]
name = "quinn-udp"
version = "0.5.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d5a626c6807713b15cac82a6acaccd6043c9a5408c24baae07611fec3f243da"
dependencies = [
"cfg_aliases",
"libc",
"once_cell",
"socket2",
"tracing",
"windows-sys 0.59.0",
]
[[package]]
name = "quote"
version = "1.0.37"
@@ -3283,6 +3359,7 @@ dependencies = [
"http-body",
"http-body-util",
"hyper",
"hyper-rustls",
"hyper-util",
"ipnet",
"js-sys",
@@ -3291,11 +3368,16 @@ dependencies = [
"once_cell",
"percent-encoding",
"pin-project-lite",
"quinn",
"rustls",
"rustls-pemfile",
"rustls-pki-types",
"serde",
"serde_json",
"serde_urlencoded",
"sync_wrapper",
"tokio",
"tokio-rustls",
"tokio-util",
"tower-service",
"url",
@@ -3303,6 +3385,7 @@ dependencies = [
"wasm-bindgen-futures",
"wasm-streams",
"web-sys",
"webpki-roots",
"windows-registry",
]
@@ -3329,12 +3412,33 @@ dependencies = [
"windows-sys 0.48.0",
]
[[package]]
name = "ring"
version = "0.17.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c17fa4cb658e3583423e915b9f3acc01cceaee1860e33d59ebae66adc3a2dc0d"
dependencies = [
"cc",
"cfg-if",
"getrandom 0.2.15",
"libc",
"spin",
"untrusted",
"windows-sys 0.52.0",
]
[[package]]
name = "rustc-demangle"
version = "0.1.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f"
[[package]]
name = "rustc-hash"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c7fb8039b3032c191086b10f11f319a6e99e1e82889c5cc6046f515c9db1d497"
[[package]]
name = "rustc_version"
version = "0.4.1"
@@ -3357,6 +3461,46 @@ dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "rustls"
version = "0.23.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "934b404430bb06b3fae2cba809eb45a1ab1aecd64491213d7c3301b88393f8d1"
dependencies = [
"once_cell",
"ring",
"rustls-pki-types",
"rustls-webpki",
"subtle",
"zeroize",
]
[[package]]
name = "rustls-pemfile"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50"
dependencies = [
"rustls-pki-types",
]
[[package]]
name = "rustls-pki-types"
version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "16f1201b3c9a7ee8039bcadc17b7e605e2945b27eee7631788c1bd2b0643674b"
[[package]]
name = "rustls-webpki"
version = "0.102.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64ca1bc8749bd4cf37b5ce386cc146580777b4e8572c7b97baf22c83f444bee9"
dependencies = [
"ring",
"rustls-pki-types",
"untrusted",
]
[[package]]
name = "ryu"
version = "1.0.18"
@@ -3692,6 +3836,7 @@ dependencies = [
"discord-sdk",
"flexi_logger",
"glob",
"itertools",
"libloading 0.8.5",
"log",
"log-panics",
@@ -3780,6 +3925,12 @@ dependencies = [
"system-deps",
]
[[package]]
name = "spin"
version = "0.9.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"
[[package]]
name = "stable_deref_trait"
version = "1.2.0"
@@ -3824,6 +3975,12 @@ version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "swift-rs"
version = "1.0.7"
@@ -4397,6 +4554,17 @@ dependencies = [
"syn 2.0.79",
]
[[package]]
name = "tokio-rustls"
version = "0.26.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c7bc40d0e5a97695bb96e27995cd3a08538541b0a846f65bba7a359f36700d4"
dependencies = [
"rustls",
"rustls-pki-types",
"tokio",
]
[[package]]
name = "tokio-util"
version = "0.7.12"
@@ -4681,6 +4849,12 @@ version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
[[package]]
name = "untrusted"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "url"
version = "2.5.2"
@@ -4996,6 +5170,15 @@ dependencies = [
"system-deps",
]
[[package]]
name = "webpki-roots"
version = "0.26.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d642ff16b7e79272ae451b7322067cdc17cadf68c23264be9d94a32319efe7e"
dependencies = [
"rustls-pki-types",
]
[[package]]
name = "webview2-com"
version = "0.33.0"
@@ -5589,6 +5772,12 @@ dependencies = [
"syn 2.0.79",
]
[[package]]
name = "zeroize"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde"
[[package]]
name = "zvariant"
version = "4.0.0"
+1
View File
@@ -65,6 +65,7 @@ work. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
</provides>
<releases>
<release version="0.13.2" date="2024-11-06"><url>https://github.com/SlimeVR/SlimeVR-Server/releases/tag/v0.13.2</url></release>
<release version="0.13.1" date="2024-11-05"><url>https://github.com/SlimeVR/SlimeVR-Server/releases/tag/v0.13.1</url></release>
<release version="0.13.1~rc.3" type="development" date="2024-10-31"><url>https://github.com/SlimeVR/SlimeVR-Server/releases/tag/v0.13.1-rc.3</url></release>
<release version="0.13.1~rc.2" type="development" date="2024-10-26"><url>https://github.com/SlimeVR/SlimeVR-Server/releases/tag/v0.13.1-rc.2</url></release>
+1 -1
View File
@@ -92,7 +92,7 @@
harfbuzz
libffi
libsoup_3
openssl
openssl.dev
pango
pkg-config
treefmt
+1 -1
View File
@@ -14,7 +14,7 @@ android.nonTransitiveRClass=true
org.gradle.unsafe.configuration-cache=false
kotlinVersion=2.0.20
spotlessVersion=6.25.0
spotlessVersion=7.0.2
shadowJarVersion=8.3.2
buildconfigVersion=5.5.0
grgitVersion=5.2.2
+8
View File
@@ -0,0 +1,8 @@
VITE_FIRMWARE_TOOL_URL=https://fw-tool-api.slimevr.io
VITE_FIRMWARE_TOOL_S3_URL=https://fw-tool-bucket.slimevr.io
FIRMWARE_TOOL_SCHEMA_URL=https://fw-tool-api.slimevr.io/api-json
# VITE_FIRMWARE_TOOL_URL=http://localhost:3000
# VITE_FIRMWARE_TOOL_S3_URL=http://localhost:9000
# FIRMWARE_TOOL_SCHEMA_URL=http://localhost:3000/api-json
-51
View File
@@ -1,51 +0,0 @@
{
"env": {
"browser": true,
"es2021": true,
"jest": true
},
"extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended", "plugin:@dword-design/import-alias/recommended"],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": "latest",
"sourceType": "module"
},
"plugins": ["react-hooks", "@typescript-eslint"],
"rules": {
"react/react-in-jsx-scope": "off",
"react/prop-types": "off",
"spaced-comment": "error",
"quotes": ["error", "single"],
"no-duplicate-imports": "error",
"no-inline-styles": "off",
"@typescript-eslint/no-explicit-any": "off",
"react/no-unescaped-entities": "off",
"camelcase": "error",
"@typescript-eslint/no-unused-vars": [
"warn",
{
"argsIgnorePattern": "^_",
"varsIgnorePattern": "^_"
}
],
"@dword-design/import-alias/prefer-alias": [
"error",
{
"alias": {
"@": "./src/"
}
}
]
},
"settings": {
"import/resolver": {
"typescript": {}
},
"react": {
"version": "detect"
}
}
}
+1
View File
@@ -28,6 +28,7 @@ yarn-error.log*
# vite
/dist
/stats.html
vite.config.ts.timestamp*
# eslint
.eslintcache
+1 -1
View File
@@ -1,5 +1,5 @@
export default {
'**/*.{ts,tsx}': () => 'tsc -p tsconfig.json --noEmit',
'**/*.{js,jsx,ts,tsx}': 'eslint --max-warnings=0 --cache --fix',
'src/**/*.{js,jsx,ts,tsx}': 'eslint --max-warnings=0 --no-warn-ignored --cache --fix',
'**/*.{js,jsx,ts,tsx,css,md,json}': 'prettier --write',
};
+79
View File
@@ -0,0 +1,79 @@
import { FlatCompat } from '@eslint/eslintrc';
import eslint from '@eslint/js';
import globals from 'globals';
import tseslint from 'typescript-eslint';
const compat = new FlatCompat();
export const gui = [
eslint.configs.recommended,
...tseslint.configs.recommended,
...compat.extends('plugin:@dword-design/import-alias/recommended'),
...compat.plugins('eslint-plugin-react-hooks'),
// Add import-alias rule inside compat because plugin doesn't like flat configs
...compat.config({
rules: {
'@dword-design/import-alias/prefer-alias': [
'error',
{
alias: {
'@': './src/',
},
},
],
},
}),
{
languageOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
parser: tseslint.parser,
parserOptions: {
ecmaFeatures: {
jsx: true,
},
},
globals: {
...globals.browser,
...globals.jest,
},
},
files: ['src/**/*.{js,jsx,ts,tsx,json}'],
plugins: {
'@typescript-eslint': tseslint.plugin,
},
rules: {
'react/react-in-jsx-scope': 'off',
'react/prop-types': 'off',
'spaced-comment': 'error',
quotes: ['error', 'single'],
'no-duplicate-imports': 'error',
'no-inline-styles': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'react/no-unescaped-entities': 'off',
camelcase: 'error',
'@typescript-eslint/no-unused-vars': [
'warn',
{
argsIgnorePattern: '^_',
varsIgnorePattern: '^_',
ignoreRestSiblings: true,
},
],
},
settings: {
'import/resolver': {
typescript: {},
},
react: {
version: 'detect',
},
},
},
// Global ignore
{
ignores: ['**/firmware-tool-api/'],
},
];
export default gui;
+28
View File
@@ -0,0 +1,28 @@
import {
generateSchemaTypes,
generateReactQueryComponents,
} from '@openapi-codegen/typescript';
import { defineConfig } from '@openapi-codegen/cli';
import dotenv from 'dotenv';
dotenv.config()
export default defineConfig({
firmwareTool: {
from: {
source: 'url',
url: process.env.FIRMWARE_TOOL_SCHEMA_URL ?? 'http://localhost:3000/api-json',
},
outputDir: 'src/firmware-tool-api',
to: async (context) => {
const filenamePrefix = 'firmwareTool';
const { schemasFiles } = await generateSchemaTypes(context, {
filenamePrefix,
});
await generateReactQueryComponents(context, {
filenamePrefix,
schemasFiles,
});
},
},
});
+18 -4
View File
@@ -2,13 +2,17 @@
"name": "slimevr-ui",
"version": "0.5.1",
"private": true,
"type": "module",
"dependencies": {
"@fluent/bundle": "^0.18.0",
"@fluent/react": "^0.15.2",
"@fontsource/poppins": "^5.1.0",
"@formatjs/intl-localematcher": "^0.2.32",
"@hookform/resolvers": "^3.6.0",
"@react-three/drei": "^9.114.3",
"@react-three/fiber": "^8.17.10",
"@tailwindcss/typography": "^0.5.15",
"@tanstack/react-query": "^5.48.0",
"@tauri-apps/api": "^2.0.2",
"@tauri-apps/plugin-dialog": "^2.0.0",
"@tauri-apps/plugin-fs": "^2.0.0",
@@ -26,15 +30,18 @@
"react-error-boundary": "^4.0.13",
"react-helmet": "^6.1.0",
"react-hook-form": "^7.53.0",
"react-markdown": "^9.0.1",
"react-modal": "^3.16.1",
"react-responsive": "^10.0.0",
"react-router-dom": "^6.26.2",
"remark-gfm": "^4.0.0",
"semver": "^7.6.3",
"solarxr-protocol": "file:../solarxr-protocol",
"three": "^0.163.0",
"ts-pattern": "^5.4.0",
"typescript": "^5.6.3",
"use-double-tap": "^1.3.6"
"use-double-tap": "^1.3.6",
"yup": "^1.4.0"
},
"scripts": {
"start": "vite --force",
@@ -46,10 +53,14 @@
"lint:fix": "tsc --noEmit && eslint --fix --max-warnings=0 \"src/**/*.{js,jsx,ts,tsx,json}\" && pnpm run format",
"format": "prettier --write \"src/**/*.{js,jsx,ts,tsx,css,scss,md,json}\"",
"preview-vite": "vite preview",
"javaversion-build": "cd src-tauri/src/ && javac JavaVersion.java && jar cvfe JavaVersion.jar JavaVersion JavaVersion.class"
"javaversion-build": "cd src-tauri/src/ && javac JavaVersion.java && jar cvfe JavaVersion.jar JavaVersion JavaVersion.class",
"gen:javaversion": "cd src-tauri/src/ && javac JavaVersion.java && jar cvfe JavaVersion.jar JavaVersion JavaVersion.class",
"gen:firmware-tool": "openapi-codegen gen firmwareTool"
},
"devDependencies": {
"@dword-design/eslint-plugin-import-alias": "^4.0.9",
"@openapi-codegen/cli": "^2.0.2",
"@openapi-codegen/typescript": "^8.0.2",
"@tailwindcss/forms": "^0.5.9",
"@tauri-apps/cli": "^2.0.2",
"@types/file-saver": "^2.0.7",
@@ -64,6 +75,7 @@
"@vitejs/plugin-react": "^4.3.2",
"autoprefixer": "^10.4.20",
"cross-env": "^7.0.3",
"dotenv": "^16.4.5",
"eslint": "^8.57.1",
"eslint-config-airbnb": "^19.0.4",
"eslint-import-resolver-typescript": "^3.6.3",
@@ -71,12 +83,14 @@
"eslint-plugin-jsx-a11y": "^6.10.0",
"eslint-plugin-react": "^7.37.1",
"eslint-plugin-react-hooks": "^4.6.2",
"globals": "^15.10.0",
"prettier": "^3.3.3",
"rollup-plugin-visualizer": "^5.12.0",
"sass": "^1.79.4",
"spdx-satisfies": "^5.0.1",
"tailwind-gradient-mask-image": "^1.2.0",
"tailwindcss": "^3.4.13",
"vite": "^5.4.8"
"vite": "^5.4.8",
"typescript-eslint": "^8.8.0"
}
}
}
+247 -14
View File
@@ -44,8 +44,8 @@ body_part-LEFT_HAND = Left hand
body_part-LEFT_UPPER_LEG = Left thigh
body_part-LEFT_LOWER_LEG = Left ankle
body_part-LEFT_FOOT = Left foot
body_part-LEFT_THUMB_METACARPAL = Left thumb metacarpal
body_part-LEFT_THUMB_PROXIMAL = Left thumb proximal
body_part-LEFT_THUMB_INTERMEDIATE = Left thumb intermediate
body_part-LEFT_THUMB_DISTAL = Left thumb distal
body_part-LEFT_INDEX_PROXIMAL = Left index proximal
body_part-LEFT_INDEX_INTERMEDIATE = Left index intermediate
@@ -59,8 +59,8 @@ body_part-LEFT_RING_DISTAL = Left ring distal
body_part-LEFT_LITTLE_PROXIMAL = Left little proximal
body_part-LEFT_LITTLE_INTERMEDIATE = Left little intermediate
body_part-LEFT_LITTLE_DISTAL = Left little distal
body_part-RIGHT_THUMB_METACARPAL = Right thumb metacarpal
body_part-RIGHT_THUMB_PROXIMAL = Right thumb proximal
body_part-RIGHT_THUMB_INTERMEDIATE = Right thumb intermediate
body_part-RIGHT_THUMB_DISTAL = Right thumb distal
body_part-RIGHT_INDEX_PROXIMAL = Right index proximal
body_part-RIGHT_INDEX_INTERMEDIATE = Right index intermediate
@@ -75,6 +75,19 @@ body_part-RIGHT_LITTLE_PROXIMAL = Right little proximal
body_part-RIGHT_LITTLE_INTERMEDIATE = Right little intermediate
body_part-RIGHT_LITTLE_DISTAL = Right little distal
## BoardType
board_type-UNKNOWN = Unknown
board_type-NODEMCU = NodeMCU
board_type-CUSTOM = Custom Board
board_type-WROOM32 = WROOM32
board_type-WEMOSD1MINI = Wemos D1 Mini
board_type-TTGO_TBASE = TTGO T-Base
board_type-ESP01 = ESP-01
board_type-SLIMEVR = SlimeVR
board_type-LOLIN_C3_MINI = Lolin C3 Mini
board_type-BEETLE32C3 = Beetle ESP32-C3
board_type-ES32C3DEVKITM1 = Espressif ESP32-C3 DevKitM-1
## Proportions
skeleton_bone-NONE = None
skeleton_bone-HEAD = Head Shift
@@ -109,6 +122,10 @@ reset-reset_all_warning =
Are you sure you want to do this?
reset-reset_all_warning-reset = Reset proportions
reset-reset_all_warning-cancel = Cancel
reset-reset_all_warning_default =
<b>Warning:</b> You currently don't have your height defined, which
will make the proportions be based on a default height.
Are you sure you want to do this?
reset-full = Full Reset
reset-mounting = Reset Mounting
@@ -253,6 +270,11 @@ tracker-settings-name_section-label = Tracker name
tracker-settings-forget = Forget tracker
tracker-settings-forget-description = Removes the tracker from the SlimeVR Server and prevent it from connecting to it until the server is restarted. The configuration of the tracker won't be lost.
tracker-settings-forget-label = Forget tracker
tracker-settings-update-unavailable = Cannot be updated (DIY)
tracker-settings-update-up_to_date = Up to date
tracker-settings-update-available = { $versionName } is now available
tracker-settings-update = Update now
tracker-settings-update-title = Firmware version
## Tracker part card info
tracker-part_card-no_name = No name
@@ -325,6 +347,7 @@ settings-sidebar-utils = Utilities
settings-sidebar-serial = Serial console
settings-sidebar-appearance = Appearance
settings-sidebar-notifications = Notifications
settings-sidebar-firmware-tool = DIY Firmware Tool
settings-sidebar-advanced = Advanced
## SteamVR settings
@@ -427,6 +450,11 @@ settings-general-fk_settings-leg_tweak-foot_plant-description = Foot-plant rotat
settings-general-fk_settings-leg_fk = Leg tracking
settings-general-fk_settings-leg_fk-reset_mounting_feet-description = Enable feet Mounting Reset by tiptoeing.
settings-general-fk_settings-leg_fk-reset_mounting_feet = Feet Mounting Reset
settings-general-fk_settings-enforce_joint_constraints = Skeletal Limits
settings-general-fk_settings-enforce_joint_constraints-enforce_constraints = Enforce constraints
settings-general-fk_settings-enforce_joint_constraints-enforce_constraints-description = Prevents joints from rotating past their limit
settings-general-fk_settings-enforce_joint_constraints-correct_constraints = Correct with constraints
settings-general-fk_settings-enforce_joint_constraints-correct_constraints-description = Correct joint rotations when they push past their limit
settings-general-fk_settings-arm_fk = Arm tracking
settings-general-fk_settings-arm_fk-description = Force arms to be tracked from the headset (HMD) even if positional hand data is available.
settings-general-fk_settings-arm_fk-force_arms = Force arms from HMD
@@ -641,11 +669,7 @@ settings-osc-vmc-network-address-description = Choose which address to send out
settings-osc-vmc-network-address-placeholder = IPV4 address
settings-osc-vmc-vrm = VRM Model
settings-osc-vmc-vrm-description = Load a VRM model to allow head anchor and enable a higher compatibility with other applications.
settings-osc-vmc-vrm-model_unloaded = No model loaded
settings-osc-vmc-vrm-model_loaded = { $titled ->
*[false] Untitled model loaded
[true] Model loaded: { $name }
}
settings-osc-vmc-vrm-untitled_model = Untitled model
settings-osc-vmc-vrm-file_select = Drag & drop a model to use, or <u>browse</u>
settings-osc-vmc-anchor_hip = Anchor at hips
settings-osc-vmc-anchor_hip-description = Anchor the tracking at the hips, useful for seated VTubing. If disabling, load a VRM model.
@@ -703,6 +727,7 @@ onboarding-wifi_creds-submit = Submit!
onboarding-wifi_creds-ssid =
.label = Wi-Fi name
.placeholder = Enter Wi-Fi name
onboarding-wifi_creds-ssid-required = Wi-Fi name is required
onboarding-wifi_creds-password =
.label = Password
.placeholder = Enter password
@@ -752,6 +777,7 @@ onboarding-connect_tracker-issue-serial = I'm having trouble connecting!
onboarding-connect_tracker-usb = USB Tracker
onboarding-connect_tracker-connection_status-none = Looking for trackers
onboarding-connect_tracker-connection_status-serial_init = Connecting to serial device
onboarding-connect_tracker-connection_status-obtaining_mac_address = Obtaining the tracker mac address
onboarding-connect_tracker-connection_status-provisioning = Sending Wi-Fi credentials
onboarding-connect_tracker-connection_status-connecting = Trying to connect to Wi-Fi
onboarding-connect_tracker-connection_status-looking_for_server = Looking for server
@@ -945,6 +971,15 @@ onboarding-choose_proportions-manual_proportions = Manual proportions
# Italicized text
onboarding-choose_proportions-manual_proportions-subtitle = For small touches
onboarding-choose_proportions-manual_proportions-description = This will let you adjust your proportions manually by modifying them directly
onboarding-choose_proportions-scaled_proportions = Scaled proportions
# Italized text
onboarding-choose_proportions-scaled_proportions-subtitle = Recommended for new users
# Multiline string
onboarding-choose_proportions-scaled_proportions-description =
This will scale the proportions of an average human body based on your height, this will help for basic full-body tracking.
<b>This requires having your headset (HMD) connected to SlimeVR and on your head!</b>
onboarding-choose_proportions-scaled_proportions-button = Scaled proportions
onboarding-choose_proportions-export = Export proportions
onboarding-choose_proportions-import = Import proportions
onboarding-choose_proportions-import-success = Imported
@@ -964,9 +999,11 @@ onboarding-automatic_proportions-title = Measure your body
onboarding-automatic_proportions-description = For SlimeVR trackers to work, we need to know the length of your bones. This short calibration will measure it for you.
onboarding-automatic_proportions-manual = Manual proportions
onboarding-automatic_proportions-prev_step = Previous step
onboarding-automatic_proportions-put_trackers_on-title = Put on your trackers
onboarding-automatic_proportions-put_trackers_on-description = To calibrate your proportions, we're gonna use the trackers you just assigned. Put on all your trackers, you can see which are which in the figure to the right.
onboarding-automatic_proportions-put_trackers_on-next = I have all my trackers on
onboarding-automatic_proportions-requirements-title = Requirements
# Each line of text is a different list item
onboarding-automatic_proportions-requirements-descriptionv2 =
@@ -976,23 +1013,38 @@ onboarding-automatic_proportions-requirements-descriptionv2 =
Your headset is reporting positional data to the SlimeVR server (this generally means having SteamVR running and connected to SlimeVR using SlimeVR's SteamVR driver).
Your tracking is working and is accurately representing your movements (ex. you have performed a full reset and they move the right direction when kicking, bending over, sitting, etc).
onboarding-automatic_proportions-requirements-next = I have read the requirements
onboarding-automatic_proportions-check_height-title = Check your height
onboarding-automatic_proportions-check_height-description = We use your height as a basis of our measurements by using the headset's (HMD) height as an approximation of your actual height, but it's better to check if they are right yourself!
onboarding-automatic_proportions-check_height-title-v2 = Measure your height
onboarding-automatic_proportions-check_height-description-v2 = Your headset (HMD) height should be slightly less than your full height, as headsets measure your eye height. This measurement will be used as a baseline for your body proportions.
# All the text is in bold!
onboarding-automatic_proportions-check_height-calculation_warning = Please press the button while standing <u>upright</u> to calculate your height. You have 3 seconds after you press the button!
onboarding-automatic_proportions-check_height-calculation_warning-v2 = Start measuring while standing <u>upright</u> to calculate your height. Be careful to not raise your hands higher than your headset, as they may affect the measurement!
onboarding-automatic_proportions-check_height-guardian_tip = If you are using a standalone VR headset, make sure to have your guardian /
boundary turned on so that your height is correct!
onboarding-automatic_proportions-check_height-fetch_height = I'm standing!
# Context is that the height is unknown
onboarding-automatic_proportions-check_height-unknown = Unknown
# Shows an element below it
onboarding-automatic_proportions-check_height-hmd_height1 = Your HMD height is
onboarding-automatic_proportions-check_height-hmd_height2 = Your headset height is:
onboarding-automatic_proportions-check_height-measure-start = Start measuring
onboarding-automatic_proportions-check_height-measure-stop = Stop measuring
onboarding-automatic_proportions-check_height-measure-reset = Retry measuring
onboarding-automatic_proportions-check_height-next_step = Use headset height
onboarding-automatic_proportions-check_floor_height-title = Measure your floor height (optional)
onboarding-automatic_proportions-check_floor_height-description = In some cases, your floor height may not be set correctly by your headset, causing the headset height to be measured as higher than it should be. You can measure the "height" of your floor to correct your headset height.
# All the text is in bold!
onboarding-automatic_proportions-check_floor_height-calculation_warning = If you are sure that your floor height is correct, you can skip this step.
# Shows an element below it
onboarding-automatic_proportions-check_height-height1 = so your actual height is
onboarding-automatic_proportions-check_height-next_step = They are fine
onboarding-automatic_proportions-check_floor_height-floor_height = Your floor height is:
onboarding-automatic_proportions-check_floor_height-measure-start = Start measuring
onboarding-automatic_proportions-check_floor_height-measure-stop = Stop measuring
onboarding-automatic_proportions-check_floor_height-measure-reset = Retry measuring
onboarding-automatic_proportions-check_floor_height-skip_step = Skip step and save
onboarding-automatic_proportions-check_floor_height-next_step = Use floor height and save
onboarding-automatic_proportions-start_recording-title = Get ready to move
onboarding-automatic_proportions-start_recording-description = We're now going to record some specific poses and moves. These will be prompted in the next screen. Be ready to start when the button is pressed!
onboarding-automatic_proportions-start_recording-next = Start Recording
onboarding-automatic_proportions-recording-title = REC
onboarding-automatic_proportions-recording-description-p0 = Recording in progress...
onboarding-automatic_proportions-recording-description-p1 = Make the moves shown below:
@@ -1010,12 +1062,14 @@ onboarding-automatic_proportions-recording-timer = { $time ->
[one] 1 second left
*[other] { $time } seconds left
}
onboarding-automatic_proportions-verify_results-title = Verify results
onboarding-automatic_proportions-verify_results-description = Check the results below, do they look correct?
onboarding-automatic_proportions-verify_results-results = Recording results
onboarding-automatic_proportions-verify_results-processing = Processing the result
onboarding-automatic_proportions-verify_results-redo = Redo recording
onboarding-automatic_proportions-verify_results-confirm = They're correct
onboarding-automatic_proportions-done-title = Body measured and saved.
onboarding-automatic_proportions-done-description = Your body proportions' calibration is complete!
onboarding-automatic_proportions-error_modal-v2 =
@@ -1024,6 +1078,26 @@ onboarding-automatic_proportions-error_modal-v2 =
Please <docs>check the docs</docs> or join our <discord>Discord</discord> for help ^_^
onboarding-automatic_proportions-error_modal-confirm = Understood!
onboarding-automatic_proportions-smol_warning =
Your configured height of { $height } is smaller than the minimum accepted height of { $minHeight }.
<b>Please redo the measurements and ensure they are correct.</b>
onboarding-automatic_proportions-smol_warning-cancel = Go back
## Tracker scaled proportions setup
onboarding-scaled_proportions-title = Scaled proportions
onboarding-scaled_proportions-description = For SlimeVR trackers to work, we need to know the length of your bones. This will use an average proportion and scale it based on your height.
onboarding-scaled_proportions-manual_height-title = Configure your height
onboarding-scaled_proportions-manual_height-description = Your headset (HMD) height should be slightly less than your full height, as headsets measure your eye height. This height will be used as a baseline for your body proportions.
onboarding-scaled_proportions-manual_height-missing_steamvr = SteamVR is not currently connected to SlimeVR, so measurements can't be based on your headset. <b>Proceed at your own risk or check the docs!</b>
onboarding-scaled_proportions-manual_height-height = Your headset height is
onboarding-scaled_proportions-manual_height-next_step = Continue and save
## Tracker scaled proportions reset
onboarding-scaled_proportions-reset_proportion-title = Reset your body proportions
onboarding-scaled_proportions-reset_proportion-description = To set your body proportions based on your height, you need to now reset all of your proportions. This will clear any proportions you have configured and provide a baseline configuration.
onboarding-scaled_proportions-done-title = Body proportions set
onboarding-scaled_proportions-done-description = Your body proportions should now be configured based on your height.
## Home
home-no_trackers = No trackers detected or assigned
@@ -1044,6 +1118,165 @@ status_system-StatusSteamVRDisconnected = { $type ->
status_system-StatusTrackerError = The { $trackerName } tracker has an error.
status_system-StatusUnassignedHMD = The VR headset should be assigned as a head tracker.
## Firmware tool globals
firmware_tool-next_step = Next Step
firmware_tool-previous_step = Previous Step
firmware_tool-ok = Looks good
firmware_tool-retry = Retry
firmware_tool-loading = Loading...
## Firmware tool Steps
firmware_tool = DIY Firmware tool
firmware_tool-description =
Allows you to configure and flash your DIY trackers
firmware_tool-not_available = Oops, the firmware tool is not available at the moment. Come back later!
firmware_tool-not_compatible = The firmware tool is not compatible with this version of the server. Please update your server!
firmware_tool-board_step = Select your Board
firmware_tool-board_step-description = Select one of the boards listed below.
firmware_tool-board_pins_step = Check the pins
firmware_tool-board_pins_step-description =
Please verify that the selected pins are correct.
If you followed the SlimeVR documentation the defaults values should be correct
firmware_tool-board_pins_step-enable_led = Enable LED
firmware_tool-board_pins_step-led_pin =
.label = LED Pin
.placeholder = Enter the pin address of the LED
firmware_tool-board_pins_step-battery_type = Select the battery type
firmware_tool-board_pins_step-battery_type-BAT_EXTERNAL = External battery
firmware_tool-board_pins_step-battery_type-BAT_INTERNAL = Internal battery
firmware_tool-board_pins_step-battery_type-BAT_INTERNAL_MCP3021 = Internal MCP3021
firmware_tool-board_pins_step-battery_type-BAT_MCP3021 = MCP3021
firmware_tool-board_pins_step-battery_sensor_pin =
.label = Battery sensor Pin
.placeholder = Enter the pin address of battery sensor
firmware_tool-board_pins_step-battery_resistor =
.label = Battery Resistor (Ohms)
.placeholder = Enter the value of battery resistor
firmware_tool-board_pins_step-battery_shield_resistor-0 =
.label = Battery Shield R1 (Ohms)
.placeholder = Enter the value of Battery Shield R1
firmware_tool-board_pins_step-battery_shield_resistor-1 =
.label = Battery Shield R2 (Ohms)
.placeholder = Enter the value of Battery Shield R2
firmware_tool-add_imus_step = Declare your IMUs
firmware_tool-add_imus_step-description =
Please add the IMUs that your tracker has
If you followed the SlimeVR documentation the defaults values should be correct
firmware_tool-add_imus_step-imu_type-label = IMU type
firmware_tool-add_imus_step-imu_type-placeholder = Select the type of IMU
firmware_tool-add_imus_step-imu_rotation =
.label = IMU Rotation (deg)
.placeholder = Rotation angle of the IMU
firmware_tool-add_imus_step-scl_pin =
.label = SCL Pin
.placeholder = Pin address of SCL
firmware_tool-add_imus_step-sda_pin =
.label = SDA Pin
.placeholder = Pin address of SDA
firmware_tool-add_imus_step-int_pin =
.label = INT Pin
.placeholder = Pin address of INT
firmware_tool-add_imus_step-optional_tracker =
.label = Optional tracker
firmware_tool-add_imus_step-show_less = Show Less
firmware_tool-add_imus_step-show_more = Show More
firmware_tool-add_imus_step-add_more = Add more IMUs
firmware_tool-select_firmware_step = Select the firmware version
firmware_tool-select_firmware_step-description =
Please choose what version of the firmware you want to use
firmware_tool-select_firmware_step-show-third-party =
.label = Show third party firmwares
firmware_tool-flash_method_step = Flashing Method
firmware_tool-flash_method_step-description =
Please select the flashing method you want to use
firmware_tool-flash_method_step-ota =
.label = OTA
.description = Use the over the air method. Your tracker will use the Wi-Fi to update it's firmware. Works only on already setup trackers.
firmware_tool-flash_method_step-serial =
.label = Serial
.description = Use a USB cable to update your tracker.
firmware_tool-flashbtn_step = Press the boot btn
firmware_tool-flashbtn_step-description = Before going into the next step there is a few things you need to do
firmware_tool-flashbtn_step-board_SLIMEVR = Turn off the tracker, remove the case (if any), connect a USB cable to this computer, then do one of the following steps according to your SlimeVR board revision:
firmware_tool-flashbtn_step-board_SLIMEVR-r11 = Turn on the tracker while shorting the second rectangular FLASH pad from the edge on the top side of the board, and the metal shield of the microcontroller
firmware_tool-flashbtn_step-board_SLIMEVR-r12 = Turn on the tracker while shorting the circular FLASH pad on the top side of the board, and the metal shield of the microcontroller
firmware_tool-flashbtn_step-board_SLIMEVR-r14 = Turn on the tracker while pushing in the FLASH button on the top side of the board
firmware_tool-flashbtn_step-board_OTHER = Before flashing you will probably need to put the tracker into bootloader mode.
Most of the time it means pressing the boot button on the board before the flashing process starts.
If the flashing process timeout at the begining of the flashing it probably means that the tracker was not in bootloader mode
Please refer to the flashing instructions of your board to know how to turn on the boatloader mode
firmware_tool-flash_method_ota-devices = Detected OTA Devices:
firmware_tool-flash_method_ota-no_devices = There are no boards that can be updated using OTA, make sure you selected the correct board type
firmware_tool-flash_method_serial-wifi = Wi-Fi Credentials:
firmware_tool-flash_method_serial-devices-label = Detected Serial Devices:
firmware_tool-flash_method_serial-devices-placeholder = Select a serial device
firmware_tool-flash_method_serial-no_devices = There are no compatible serial devices detected, make sure the tracker is plugged in
firmware_tool-build_step = Building
firmware_tool-build_step-description =
The firmware is building, please wait
firmware_tool-flashing_step = Flashing
firmware_tool-flashing_step-description =
Your trackers are flashing, please follow the instructions on the screen
firmware_tool-flashing_step-warning = Do not unplug or restart the tracker during the upload process unless told to, it may make your board unusable
firmware_tool-flashing_step-flash_more = Flash more trackers
firmware_tool-flashing_step-exit = Exit
## firmware tool build status
firmware_tool-build-CREATING_BUILD_FOLDER = Creating the build folder
firmware_tool-build-DOWNLOADING_FIRMWARE = Downloading the firmware
firmware_tool-build-EXTRACTING_FIRMWARE = Extracting the firmware
firmware_tool-build-SETTING_UP_DEFINES = Configuring the defines
firmware_tool-build-BUILDING = Building the firmware
firmware_tool-build-SAVING = Saving the build
firmware_tool-build-DONE = Build Complete
firmware_tool-build-ERROR = Unable to build the firmware
## Firmware update status
firmware_update-status-DOWNLOADING = Downloading the firmware
firmware_update-status-NEED_MANUAL_REBOOT = Waiting for the user to reboot the tracker
firmware_update-status-AUTHENTICATING = Authenticating with the mcu
firmware_update-status-UPLOADING = Uploading the firmware
firmware_update-status-SYNCING_WITH_MCU = Syncing with the mcu
firmware_update-status-REBOOTING = Rebooting the tracker
firmware_update-status-PROVISIONING = Setting Wi-Fi credentials
firmware_update-status-DONE = Update complete!
firmware_update-status-ERROR_DEVICE_NOT_FOUND = Could not find the device
firmware_update-status-ERROR_TIMEOUT = The update process timed out
firmware_update-status-ERROR_DOWNLOAD_FAILED = Could not download the firmware
firmware_update-status-ERROR_AUTHENTICATION_FAILED = Could not authenticate with the mcu
firmware_update-status-ERROR_UPLOAD_FAILED = Could not upload the firmware
firmware_update-status-ERROR_PROVISIONING_FAILED = Could not set the Wi-Fi credentials
firmware_update-status-ERROR_UNSUPPORTED_METHOD = The update method is not supported
firmware_update-status-ERROR_UNKNOWN = Unknown error
## Dedicated Firmware Update Page
firmware_update-title = Firmware update
firmware_update-devices = Available Devices
firmware_update-devices-description = Please select the trackers you want to update to the latest version of SlimeVR firmware
firmware_update-no_devices = Plase make sure that the trackers you want to update are ON and connected to the Wi-Fi!
firmware_update-changelog-title = Updating to {$version}
firmware_update-looking_for_devices = Looking for devices to update...
firmware_update-retry = Retry
firmware_update-update = Update Selected Trackers
## Tray Menu
tray_menu-show = Show
tray_menu-hide = Hide
Binary file not shown.

After

Width:  |  Height:  |  Size: 450 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 578 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 428 KiB

+2 -1
View File
@@ -28,7 +28,7 @@ shadow-rs = "0.35"
[dependencies]
serde_json = "1"
serde = { version = "1", features = ["derive"] }
tauri = { version = "2.0", features = ["devtools", "tray-icon", "image-png"] }
tauri = { version = "2.0", features = ["devtools", "tray-icon", "image-png", "rustls-tls"] }
tauri-runtime = "2.0"
tauri-plugin-dialog = "2.0"
tauri-plugin-fs = "2.0"
@@ -53,6 +53,7 @@ rfd = { version = "0.15", features = ["gtk3"], default-features = false }
dirs-next = "2.0.0"
discord-sdk = "0.3.6"
tokio = { version = "1.37.0", features = ["time"] }
itertools = "0.13.0"
[target.'cfg(windows)'.dependencies]
win32job = "1"
+135 -78
View File
@@ -1,4 +1,5 @@
#![cfg_attr(all(not(debug_assertions), windows), windows_subsystem = "windows")]
use std::env;
use std::panic;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
@@ -68,84 +69,125 @@ fn main() -> Result<()> {
let tauri_context = tauri::generate_context!();
// Set up loggers and global handlers
let _logger = {
use flexi_logger::{
Age, Cleanup, Criterion, Duplicate, FileSpec, Logger, Naming, WriteMode,
};
use tauri::Error;
// Based on https://docs.rs/tauri/2.0.0-alpha.10/src/tauri/path/desktop.rs.html#238-256
#[cfg(target_os = "macos")]
let path = dirs_next::home_dir().ok_or(Error::UnknownPath).map(|dir| {
dir.join("Library/Logs")
.join(&tauri_context.config().identifier)
});
#[cfg(not(target_os = "macos"))]
let path = dirs_next::data_dir()
.ok_or(Error::UnknownPath)
.map(|dir| dir.join(&tauri_context.config().identifier).join("logs"));
Logger::try_with_env_or_str("info")?
.log_to_file(
FileSpec::default().directory(path.expect("We need a log dir")),
)
.format_for_files(util::logger_format)
.format_for_stderr(util::logger_format)
.rotate(
Criterion::Age(Age::Day),
Naming::Timestamps,
Cleanup::KeepLogFiles(2),
)
.duplicate_to_stderr(Duplicate::All)
.write_mode(WriteMode::BufferAndFlush)
.start()?
};
let _logger = setup_logger(&tauri_context);
// Ensure child processes die when spawned on windows
// and then check for WebView2's existence
#[cfg(windows)]
{
use crate::util::webview2_exists;
use win32job::{ExtendedLimitInfo, Job};
setup_webview2()?;
let mut info = ExtendedLimitInfo::new();
info.limit_kill_on_job_close();
let job = Job::create_with_limit_info(&mut info).expect("Failed to create Job");
job.assign_current_process()
.expect("Failed to assign current process to Job");
// We don't do anything with the job anymore, but we shouldn't drop it because that would
// terminate our process tree. So we intentionally leak it instead.
std::mem::forget(job);
if !webview2_exists() {
// This makes a dialog appear which let's you press Ok or Cancel
// If you press Ok it will open the SlimeVR installer documentation
use rfd::{
MessageButtons, MessageDialog, MessageDialogResult, MessageLevel,
};
let confirm = MessageDialog::new()
.set_title("SlimeVR")
.set_description("Couldn't find WebView2 installed. You can install it with the SlimeVR installer")
.set_buttons(MessageButtons::OkCancel)
.set_level(MessageLevel::Error)
.show();
if confirm == MessageDialogResult::Ok {
open::that("https://docs.slimevr.dev/server-setup/installing-and-connecting.html#install-the-latest-slimevr-installer").unwrap();
}
return Ok(());
}
}
// Check for environment variables that can affect the server, and if so, warn in log and GUI
check_environment_variables();
// Spawn server process
let exit_flag = Arc::new(AtomicBool::new(false));
let backend = Arc::new(Mutex::new(Option::<CommandChild>::None));
let backend_termination = backend.clone();
let run_path = get_launch_path(cli);
let server_info = if let Some(p) = run_path {
let server_info = execute_server(cli)?;
let build_result = setup_tauri(
tauri_context,
server_info,
exit_flag.clone(),
backend.clone(),
);
tauri_build_result(build_result, exit_flag, backend);
Ok(())
}
fn setup_logger(context: &tauri::Context) -> Result<flexi_logger::LoggerHandle> {
use flexi_logger::{
Age, Cleanup, Criterion, Duplicate, FileSpec, Logger, Naming, WriteMode,
};
use tauri::Error;
// Based on https://docs.rs/tauri/2.0.0-alpha.10/src/tauri/path/desktop.rs.html#238-256
#[cfg(target_os = "macos")]
let path = dirs_next::home_dir()
.ok_or(Error::UnknownPath)
.map(|dir| dir.join("Library/Logs").join(&context.config().identifier));
#[cfg(not(target_os = "macos"))]
let path = dirs_next::data_dir()
.ok_or(Error::UnknownPath)
.map(|dir| dir.join(&context.config().identifier).join("logs"));
Ok(Logger::try_with_env_or_str("info")?
.log_to_file(FileSpec::default().directory(path.expect("We need a log dir")))
.format_for_files(|w, now, record| util::logger_format(w, now, record, false))
.format_for_stderr(|w, now, record| util::logger_format(w, now, record, true))
.rotate(
Criterion::Age(Age::Day),
Naming::Timestamps,
Cleanup::KeepLogFiles(2),
)
.duplicate_to_stderr(Duplicate::All)
.write_mode(WriteMode::BufferAndFlush)
.start()?)
}
#[cfg(windows)]
fn setup_webview2() -> Result<()> {
use crate::util::webview2_exists;
use win32job::{ExtendedLimitInfo, Job};
let mut info = ExtendedLimitInfo::new();
info.limit_kill_on_job_close();
let job = Job::create_with_limit_info(&mut info).expect("Failed to create Job");
job.assign_current_process()
.expect("Failed to assign current process to Job");
// We don't do anything with the job anymore, but we shouldn't drop it because that would
// terminate our process tree. So we intentionally leak it instead.
std::mem::forget(job);
if !webview2_exists() {
// This makes a dialog appear which let's you press Ok or Cancel
// If you press Ok it will open the SlimeVR installer documentation
use rfd::{MessageButtons, MessageDialog, MessageDialogResult, MessageLevel};
let confirm = MessageDialog::new()
.set_title("SlimeVR")
.set_description("Couldn't find WebView2 installed. You can install it with the SlimeVR installer")
.set_buttons(MessageButtons::OkCancel)
.set_level(MessageLevel::Error)
.show();
if confirm == MessageDialogResult::Ok {
open::that("https://docs.slimevr.dev/server-setup/installing-and-connecting.html#install-the-latest-slimevr-installer").unwrap();
}
}
Ok(())
}
fn check_environment_variables() {
use itertools::Itertools;
const ENVS_TO_CHECK: &[&str] = &["_JAVA_OPTIONS", "JAVA_TOOL_OPTIONS"];
let checked_envs = ENVS_TO_CHECK
.into_iter()
.filter_map(|e| {
let Ok(data) = env::var(e) else {
return None;
};
log::warn!("{e} is set to: {data}");
Some(e)
})
.join(", ");
if !checked_envs.is_empty() {
rfd::MessageDialog::new()
.set_title("SlimeVR")
.set_description(format!("You have environment variables {} set, which may cause the SlimeVR Server to fail to launch properly.", checked_envs))
.set_level(rfd::MessageLevel::Warning)
.show();
}
}
fn execute_server(
cli: Cli,
) -> Result<Option<(std::ffi::OsString, std::path::PathBuf)>> {
use const_format::formatcp;
if let Some(p) = get_launch_path(cli) {
log::info!("Server found on path: {}", p.to_str().unwrap());
// Check if any Java already installed is compatible
@@ -155,19 +197,29 @@ fn main() -> Result<()> {
.then(|| jre.into_os_string())
.or_else(|| valid_java_paths().first().map(|x| x.0.to_owned()));
let Some(java_bin) = java_bin else {
show_error(&format!("Couldn't find a compatible Java version, please download Java {} or higher", MINIMUM_JAVA_VERSION));
return Ok(());
show_error(formatcp!(
"Couldn't find a compatible Java version, please download Java {} or higher",
MINIMUM_JAVA_VERSION
));
return Ok(None);
};
log::info!("Using Java binary: {:?}", java_bin);
Some((java_bin, p))
Ok(Some((java_bin, p)))
} else {
log::warn!("No server found. We will not start the server.");
None
};
Ok(None)
}
}
fn setup_tauri(
context: tauri::Context,
server_info: Option<(std::ffi::OsString, std::path::PathBuf)>,
exit_flag: Arc<AtomicBool>,
backend: Arc<Mutex<Option<CommandChild>>>,
) -> Result<tauri::App, tauri::Error> {
let exit_flag_terminated = exit_flag.clone();
let build_result = tauri::Builder::default()
tauri::Builder::default()
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_fs::init())
.plugin(tauri_plugin_os::init())
@@ -277,7 +329,14 @@ fn main() -> Result<()> {
// WindowEvent::Resized(_) => std::thread::sleep(std::time::Duration::from_nanos(1)),
_ => (),
})
.build(tauri_context);
.build(context)
}
fn tauri_build_result(
build_result: Result<tauri::App, tauri::Error>,
exit_flag: Arc<AtomicBool>,
backend: Arc<Mutex<Option<CommandChild>>>,
) {
match build_result {
Ok(app) => {
app.run(move |app_handle, event| match event {
@@ -291,7 +350,7 @@ fn main() -> Result<()> {
Err(e) => log::error!("failed to save window state: {}", e),
}
let mut lock = backend_termination.lock().unwrap();
let mut lock = backend.lock().unwrap();
let Some(ref mut child) = *lock else { return };
let write_result = child.write(b"exit\n");
match write_result {
@@ -335,6 +394,4 @@ fn main() -> Result<()> {
show_error(&error.to_string());
}
}
Ok(())
}
+4 -4
View File
@@ -1,7 +1,7 @@
use std::{collections::HashMap, sync::Mutex};
use tauri::{
image::Image,
include_image,
menu::{Menu, MenuBuilder, MenuItemBuilder, MenuItemKind},
tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent},
AppHandle, Emitter, Manager, Runtime, State,
@@ -107,10 +107,10 @@ pub fn create_tray<R: Runtime>(app: &tauri::AppHandle<R>) -> tauri::Result<()> {
.icon_as_template(true)
.menu_on_left_click(false)
.icon(if cfg!(target_os = "macos") {
Image::from_bytes(include_bytes!("../icons/appleTrayIcon.png"))
include_image!("icons/appleTrayIcon.png")
} else {
Image::from_bytes(include_bytes!("../icons/128x128.png"))
}?)
include_image!("icons/128x128.png")
})
.on_menu_event(move |app, event| match event.id.as_ref() {
"quit" => app.emit("try-close", "tray").unwrap(),
"toggle" => {
+16 -9
View File
@@ -107,7 +107,8 @@ pub fn show_error(text: &str) -> bool {
.set_description(text)
.set_buttons(MessageButtons::Ok)
.set_level(MessageLevel::Error)
.show() == MessageDialogResult::Ok
.show()
== MessageDialogResult::Ok
}
#[cfg(mobile)]
@@ -222,20 +223,26 @@ pub fn logger_format(
w: &mut dyn std::io::Write,
_now: &mut DeferredNow,
record: &Record,
ansi: bool,
) -> Result<(), std::io::Error> {
let level = record.level();
let module_path = record.module_path().unwrap_or("<unnamed>");
// optionally print target
// Optionally print target
let target = if module_path.starts_with(record.target()) {
"".to_string()
} else {
format!(", {}", record.target())
};
write!(
w,
"{} [{}{target}] {}",
style(level).paint(level.to_string()),
record.module_path().unwrap_or("<unnamed>"),
style(level).paint(record.args().to_string())
)
// A toggle for ansi formatting, mainly disabled for file logs, but enabled for terminal logs.
if ansi {
write!(
w,
"{} [{}{target}] {}",
style(level).paint(level.to_string()),
module_path,
style(level).paint(record.args().to_string())
)
} else {
write!(w, "{} [{}{target}] {}", level, module_path, record.args())
}
}
+27 -13
View File
@@ -51,11 +51,15 @@ import { useBreakpoint, useIsTauri } from './hooks/breakpoint';
import { VRModePage } from './components/vr-mode/VRModePage';
import { InterfaceSettings } from './components/settings/pages/InterfaceSettings';
import { error, log } from './utils/logging';
import { FirmwareToolSettings } from './components/firmware-tool/FirmwareTool';
import { AppLayout } from './AppLayout';
import { Preload } from './components/Preload';
import { UnknownDeviceModal } from './components/UnknownDeviceModal';
import { useDiscordPresence } from './hooks/discord-presence';
import { ScaledProportionsPage } from './components/onboarding/pages/body-proportions/ScaledProportions';
import { EmptyLayout } from './components/EmptyLayout';
import { AdvancedSettings } from './components/settings/pages/AdvancedSettings';
import { FirmwareUpdate } from './components/firmware-update/FirmwareUpdate';
export const GH_REPO = 'SlimeVR/SlimeVR-Server';
export const VersionContext = createContext('');
@@ -81,6 +85,14 @@ function Layout() {
</MainLayout>
}
/>
<Route
path="/firmware-update"
element={
<MainLayout isMobile={isMobile} widgets={false}>
<FirmwareUpdate />
</MainLayout>
}
/>
<Route
path="/vr-mode"
element={
@@ -105,6 +117,7 @@ function Layout() {
</SettingsLayout>
}
>
<Route path="firmware-tool" element={<FirmwareToolSettings />} />
<Route path="trackers" element={<GeneralSettings />} />
<Route path="serial" element={<Serial />} />
<Route path="osc/router" element={<OSCRouterSettings />} />
@@ -150,6 +163,10 @@ function Layout() {
path="body-proportions/manual"
element={<ManualProportionsPage />}
/>
<Route
path="body-proportions/scaled"
element={<ScaledProportionsPage />}
/>
<Route path="done" element={<DonePage />} />
</Route>
<Route path="*" element={<TopBar></TopBar>}></Route>
@@ -272,19 +289,16 @@ export default function App() {
<VersionContext.Provider value={updateFound}>
<div className="h-full w-full text-standard bg-background-80 text-background-10">
<Preload />
<div className="flex-col h-full">
{!websocketAPI.isConnected && (
<>
<TopBar></TopBar>
<div className="flex w-full h-full justify-center items-center p-2">
{websocketAPI.isFirstConnection
? l10n.getString('websocket-connecting')
: l10n.getString('websocket-connection_lost')}
</div>
</>
)}
{websocketAPI.isConnected && <Layout></Layout>}
</div>
{!websocketAPI.isConnected && (
<EmptyLayout>
<div className="flex w-full h-full justify-center items-center p-2">
{websocketAPI.isFirstConnection
? l10n.getString('websocket-connecting')
: l10n.getString('websocket-connection_lost')}
</div>
</EmptyLayout>
)}
{websocketAPI.isConnected && <Layout></Layout>}
</div>
</VersionContext.Provider>
</StatusProvider>
+7
View File
@@ -0,0 +1,7 @@
.empty-layout {
display: grid;
grid-template:
't' var(--topbar-h)
'c' calc(100% - var(--topbar-h))
/ 100%;
}
+16
View File
@@ -0,0 +1,16 @@
import { ReactNode } from 'react';
import { TopBar } from './TopBar';
import './EmptyLayout.scss';
export function EmptyLayout({ children }: { children: ReactNode }) {
return (
<div className="empty-layout h-full">
<div style={{ gridArea: 't' }}>
<TopBar></TopBar>
</div>
<div style={{ gridArea: 'c' }} className="mt-2 relative">
{children}
</div>
</div>
);
}
+5 -7
View File
@@ -39,12 +39,6 @@ export function SerialDetectionModal() {
const openWifi = () => {
setShowWifiForm(true);
// if (!hasWifiCreds) {
// setShowWifiForm(true);
// } else {
// closeModal();
// nav('/onboarding/connect-trackers', { state: { alonePage: true } });
// }
};
const modalWifiSubmit = (form: WifiFormData) => {
@@ -58,7 +52,11 @@ export function SerialDetectionModal() {
({ device }: NewSerialDeviceResponseT) => {
if (
config?.watchNewDevices &&
!['/settings/serial', '/onboarding/connect-trackers'].includes(pathname)
![
'/settings/serial',
'/onboarding/connect-trackers',
'/settings/firmware-tool',
].includes(pathname)
) {
setOpen(device);
}
+3 -1
View File
@@ -290,7 +290,9 @@ export function TopBar({
await invoke('update_tray_text');
} else if (
config?.connectedTrackersWarning &&
connectedIMUTrackers.length > 0
connectedIMUTrackers.filter(
(t) => t.tracker.status !== TrackerStatus.TIMED_OUT
).length > 0
) {
setConnectedTrackerWarning(true);
} else {
+3 -1
View File
@@ -25,7 +25,9 @@ export function UnknownDeviceModal() {
RpcMessage.UnknownDeviceHandshakeNotification,
({ macAddress }: UnknownDeviceHandshakeNotificationT) => {
if (
['/onboarding/connect-trackers'].includes(pathname) ||
['/onboarding/connect-trackers', '/settings/firmware-tool'].includes(
pathname
) ||
state.ignoredTrackers.has(macAddress as string) ||
(currentTracker !== null && currentTracker !== macAddress)
)
+4 -2
View File
@@ -1,11 +1,13 @@
import { open } from '@tauri-apps/plugin-shell';
import { ReactNode } from 'react';
export function A({ href, children }: { href: string; children?: ReactNode }) {
export function A({ href, children }: { href?: string; children?: ReactNode }) {
return (
<a
href="javascript:void(0)"
onClick={() => open(href).catch(() => window.open(href, '_blank'))}
onClick={() =>
href && open(href).catch(() => window.open(href, '_blank'))
}
className="underline"
>
{children}
+4 -4
View File
@@ -87,10 +87,10 @@ export const mapPart: Record<
<UpperLegIcon width={width} flipped></UpperLegIcon>
),
[BodyPart.WAIST]: ({ width }) => <WaistIcon width={width}></WaistIcon>,
[BodyPart.LEFT_THUMB_PROXIMAL]: ({ width }) => (
[BodyPart.LEFT_THUMB_METACARPAL]: ({ width }) => (
<FingersIcon width={width}></FingersIcon>
),
[BodyPart.LEFT_THUMB_INTERMEDIATE]: ({ width }) => (
[BodyPart.LEFT_THUMB_PROXIMAL]: ({ width }) => (
<FingersIcon width={width}></FingersIcon>
),
[BodyPart.LEFT_THUMB_DISTAL]: ({ width }) => (
@@ -132,10 +132,10 @@ export const mapPart: Record<
[BodyPart.LEFT_LITTLE_DISTAL]: ({ width }) => (
<FingersIcon width={width}></FingersIcon>
),
[BodyPart.RIGHT_THUMB_PROXIMAL]: ({ width }) => (
[BodyPart.RIGHT_THUMB_METACARPAL]: ({ width }) => (
<FingersIcon width={width}></FingersIcon>
),
[BodyPart.RIGHT_THUMB_INTERMEDIATE]: ({ width }) => (
[BodyPart.RIGHT_THUMB_PROXIMAL]: ({ width }) => (
<FingersIcon width={width}></FingersIcon>
),
[BodyPart.RIGHT_THUMB_DISTAL]: ({ width }) => (
+5 -3
View File
@@ -2,6 +2,10 @@ import classNames from 'classnames';
import { useMemo } from 'react';
import { Control, Controller } from 'react-hook-form';
export const CHECKBOX_CLASSES = classNames(
'bg-background-50 border-background-50 rounded-md w-5 h-5 text-accent-background-30 focus:border-accent-background-40 focus:ring-transparent focus:ring-offset-transparent focus:outline-transparent'
);
export function CheckBox({
label,
variant = 'checkbox',
@@ -25,9 +29,7 @@ export function CheckBox({
const classes = useMemo(() => {
const vriantsMap = {
checkbox: {
checkbox: classNames(
'bg-background-50 border-background-50 rounded-md w-5 h-5 text-accent-background-30 focus:border-accent-background-40 focus:ring-transparent focus:ring-offset-transparent focus:outline-transparent'
),
checkbox: CHECKBOX_CLASSES,
toggle: '',
pin: '',
},
+107 -40
View File
@@ -1,9 +1,17 @@
import { Localized } from '@fluent/react';
import classNames from 'classnames';
import { forwardRef, useMemo, useState } from 'react';
import {
forwardRef,
useImperativeHandle,
useMemo,
useRef,
useState,
} from 'react';
import { Control, Controller, UseControllerProps } from 'react-hook-form';
import { FileIcon } from './icon/FileIcon';
import { UploadFileIcon } from './icon/UploadFileIcon';
import { Typography } from './Typography';
import { CloseIcon } from './icon/CloseIcon';
interface InputProps {
variant?: 'primary' | 'secondary';
@@ -11,6 +19,80 @@ interface InputProps {
name: string;
}
const FileInputContentBlank = ({
isDragging,
label,
}: {
isDragging: boolean;
label: string;
}) => {
return (
<div
className={classNames(
'flex justify-center w-full h-32 px-4 transition border-2',
'border-background-20 rounded-md appearance-none cursor-pointer',
'hover:border-accent-background-20 focus:outline-none',
'border-dashed'
)}
>
<span className="flex items-center space-x-2 pointer-events-none">
<UploadFileIcon isDragging={isDragging} />
<div>
<Localized
id={label}
elems={{
u: <span className="underline text-background-20"></span>,
}}
>
<Typography>
Drop files to attach, or{' '}
<span className="underline text-background-20">browse</span>
</Typography>
</Localized>
</div>
</span>
</div>
);
};
const FileInputContentFile = ({
importedFileName,
onClearPicker,
}: {
importedFileName: string;
onClearPicker: () => any;
}) => {
return (
<div
className={classNames(
'flex flex-col w-full transition border-2',
'border-background-20 rounded-md appearance-none cursor-pointer',
'hover:border-accent-background-20 focus:outline-none'
)}
>
<div className="flex items-center space-x-2">
<div className="flex items-center space-x-2 px-4">
<FileIcon />
<span>{importedFileName}</span>
</div>
<span className="flex-grow"></span>
<a
href="#"
className="h-12 w-12 hover:bg-accent-background-20 cursor-pointer"
onClick={() => {
onClearPicker();
}}
>
<CloseIcon
className="stroke-background-20 hover:stroke-background-90"
size={48}
/>
</a>
</div>
</div>
);
};
export const FileInputInside = forwardRef<
HTMLInputElement,
{
@@ -22,44 +104,36 @@ export const FileInputInside = forwardRef<
value: FileList;
onChange: (...event: any[]) => void;
name: string;
importedFileName: string | null;
}
>(function AppInput(
{
label = 'tips-file_select',
name,
onChange,
variant = 'primary',
accept,
capture,
multiple = false,
importedFileName,
},
ref
) {
const classes = useMemo(() => {
const variantsMap = {
primary: classNames('bg-background-60 border-background-60'),
secondary: classNames('bg-background-50 border-background-50'),
};
const innerRef = useRef<HTMLInputElement>(null);
useImperativeHandle(ref, () => innerRef.current!);
return classNames(
variantsMap[variant],
'w-full focus:ring-transparent focus:ring-offset-transparent',
'focus:outline-transparent rounded-md bg-background-60 border-background-60',
'focus:border-accent-background-40 placeholder:text-background-30 text-standard',
'relative hidden'
);
}, [variant]);
const acceptList = useMemo(() => accept.split(/, ?/), [accept]);
const [isDragging, setDragging] = useState(false);
const isFileImported = importedFileName !== null && !isDragging;
const onClearPicker = () => {
onChange([]);
innerRef.current!.value = '';
};
return (
<label
className={classNames(
'flex justify-center w-full h-32 px-4 transition border-2',
'border-background-20 border-dashed rounded-md appearance-none cursor-pointer',
'hover:border-accent-background-20 focus:outline-none'
)}
onClick={() => typeof ref !== 'function' && ref?.current?.click()}
onDragOver={(ev) => ev.preventDefault()}
onDrop={(ev) => {
ev.preventDefault();
@@ -86,30 +160,20 @@ export const FileInputInside = forwardRef<
setDragging(false);
}}
>
<span className="flex items-center space-x-2 pointer-events-none">
<FileIcon isDragging={isDragging} />
<div>
<Localized
id={label}
elems={{
u: <span className="underline text-background-20"></span>,
}}
>
<Typography>
Drop files to attach, or{' '}
<span className="underline text-background-20">browse</span>
</Typography>
</Localized>
</div>
</span>
{isFileImported
? FileInputContentFile({ importedFileName, onClearPicker })
: FileInputContentBlank({ isDragging, label })}
<input
type="file"
className={classNames(classes)}
className="hidden"
onChange={(ev) => {
onChange(ev.target.files);
if (ev.target.files?.length) {
onChange(ev.target.files);
}
}}
name={name}
ref={ref}
ref={innerRef}
accept={accept}
multiple={multiple}
capture={capture}
@@ -127,6 +191,7 @@ export const FileInput = ({
accept,
multiple,
capture,
importedFileName,
}: {
rules: UseControllerProps<any>['rules'];
control: Control<any>;
@@ -137,6 +202,7 @@ export const FileInput = ({
* Use a translation key!
**/
label?: string;
importedFileName: string | null;
} & InputProps &
Partial<HTMLInputElement>) => {
return (
@@ -155,6 +221,7 @@ export const FileInput = ({
accept={accept}
capture={capture}
multiple={multiple}
importedFileName={importedFileName}
></FileInputInside>
)}
/>
+1 -1
View File
@@ -98,7 +98,7 @@ export const InputInside = forwardRef<
></input>
{type === 'password' && (
<div
className="fill-background-10 absolute inset-y-0 right-0 pr-6 z-10 my-auto w-[16px] h-[16px]"
className="fill-background-10 absolute inset-y-0 right-0 pr-6 z-10 my-auto w-[16px] h-[16px] cursor-pointer"
onClick={togglePassword}
>
<EyeIcon width={16} closed={forceText}></EyeIcon>
+52 -2
View File
@@ -1,6 +1,8 @@
import { Control, Controller } from 'react-hook-form';
import { Button } from './Button';
import { Typography } from './Typography';
import { useCallback, useMemo } from 'react';
import { useLocaleConfig } from '@/i18n/config';
export function NumberSelector({
label,
@@ -10,7 +12,9 @@ export function NumberSelector({
min,
max,
step,
doubleStep,
disabled = false,
showButtonWithNumber = false,
}: {
label?: string;
valueLabelFormat?: (value: number) => string;
@@ -19,14 +23,36 @@ export function NumberSelector({
min: number;
max: number;
step: number | ((value: number, add: boolean) => number);
doubleStep?: number;
disabled?: boolean;
showButtonWithNumber?: boolean;
}) {
const { currentLocales } = useLocaleConfig();
const stepFn =
typeof step === 'function'
? step
: (value: number, add: boolean) =>
+(add ? value + step : value - step).toFixed(2);
const doubleStepFn = useCallback(
(value: number, add: boolean) =>
doubleStep === undefined
? 0
: +(add ? value + doubleStep : value - doubleStep).toFixed(2),
[doubleStep]
);
const decimalFormat = useMemo(
() =>
new Intl.NumberFormat(currentLocales, {
style: 'decimal',
maximumFractionDigits: 2,
signDisplay: 'exceptZero',
}),
[currentLocales]
);
return (
<Controller
control={control}
@@ -35,7 +61,19 @@ export function NumberSelector({
<div className="flex flex-col gap-1 w-full">
<Typography bold>{label}</Typography>
<div className="flex gap-5 bg-background-60 p-2 rounded-lg">
<div className="flex">
<div className="flex gap-1">
{doubleStep !== undefined && (
<Button
variant="tertiary"
rounded
onClick={() => onChange(doubleStepFn(value, false))}
disabled={doubleStepFn(value, false) < min || disabled}
>
{showButtonWithNumber
? decimalFormat.format(-doubleStep)
: '--'}
</Button>
)}
<Button
variant="tertiary"
rounded
@@ -48,7 +86,7 @@ export function NumberSelector({
<div className="flex flex-grow justify-center items-center w-10 text-standard">
{valueLabelFormat ? valueLabelFormat(value) : value}
</div>
<div className="flex">
<div className="flex gap-1">
<Button
variant="tertiary"
rounded
@@ -57,6 +95,18 @@ export function NumberSelector({
>
+
</Button>
{doubleStep !== undefined && (
<Button
variant="tertiary"
rounded
onClick={() => onChange(doubleStepFn(value, true))}
disabled={doubleStepFn(value, true) > max || disabled}
>
{showButtonWithNumber
? decimalFormat.format(doubleStep)
: '++'}
</Button>
)}
</div>
</div>
</div>
+11 -2
View File
@@ -7,12 +7,14 @@ export function ProgressBar({
height = 10,
colorClass = 'bg-accent-background-20',
animated = false,
bottom = false,
}: {
progress: number;
parts?: number;
height?: number;
colorClass?: string;
animated?: boolean;
bottom?: boolean;
}) {
return (
<div className="flex w-full flex-row gap-2">
@@ -25,6 +27,7 @@ export function ProgressBar({
colorClass={colorClass}
animated={animated}
parts={parts}
bottom={bottom}
></Bar>
))}
</div>
@@ -38,6 +41,7 @@ export function Bar({
height,
animated,
colorClass,
bottom,
}: {
index: number;
progress: number;
@@ -45,6 +49,7 @@ export function Bar({
height: number;
colorClass: string;
animated: boolean;
bottom: boolean;
}) {
const value = useMemo(
() => Math.min(Math.max((progress * parts) / 1 - index, 0), 1),
@@ -52,12 +57,16 @@ export function Bar({
);
return (
<div
className="flex relative flex-grow bg-background-50 rounded-lg overflow-hidden"
className={classNames(
'flex relative flex-grow bg-background-50 rounded-lg overflow-hidden',
bottom && 'rounded-t-none'
)}
style={{ height: `${height}px` }}
>
<div
className={classNames(
'rounded-lg overflow-hidden absolute top-0',
'overflow-hidden absolute top-0',
bottom ? 'rounded-none' : 'rounded-lg',
animated && 'transition-[width,background-color]',
colorClass
)}
+1 -1
View File
@@ -64,7 +64,7 @@ export function WarningBox({
>
<WarningIcon></WarningIcon>
</div>
<div className="flex flex-col">
<div className="flex flex-col justify-center">
<Typography
color="text-background-60"
whitespace={whitespace ? 'whitespace-pre-line' : undefined}
@@ -0,0 +1,138 @@
import classNames from 'classnames';
import { CheckIcon } from './icon/CheckIcon';
import { Typography } from './Typography';
import {
FC,
ReactNode,
useEffect,
useLayoutEffect,
useRef,
useState,
} from 'react';
import { useElemSize } from '@/hooks/layout';
import { useDebouncedEffect } from '@/hooks/timeout';
export function VerticalStep({
active,
index,
children,
title,
}: {
active: number;
index: number;
children: ReactNode;
title: string;
}) {
const ref = useRef<HTMLDivElement | null>(null);
const refTop = useRef<HTMLLIElement | null>(null);
const [shouldAnimate, setShouldAnimate] = useState(false);
const { height } = useElemSize(ref);
const isSelected = active === index;
const isPrevious = active > index;
useEffect(() => {
if (!refTop.current) return;
if (isSelected)
setTimeout(() => {
if (!refTop.current) return;
refTop.current.scrollIntoView({ behavior: 'smooth' });
}, 500);
}, [isSelected]);
useLayoutEffect(() => {
setShouldAnimate(true);
}, [active]);
// Make it so it wont try to animate the size
// if we are not changing active step
useDebouncedEffect(
() => {
setShouldAnimate(false);
},
[active],
1000
);
return (
<li className="mb-10 scroll-m-4" ref={refTop}>
<span
className={classNames(
'absolute flex items-center justify-center w-8 h-8 rounded-full -left-4 transition-colors fill-background-10',
{
'bg-accent-background-20': isSelected || isPrevious,
'bg-background-40': !isSelected && !isPrevious,
}
)}
>
{isPrevious ? (
<CheckIcon></CheckIcon>
) : (
<Typography variant="section-title">{index + 1}</Typography>
)}
</span>
<div className="ml-7 pt-1.5">
<div className="px-1">
<Typography variant="section-title">{title}</Typography>
</div>
<div
style={{ height: !isSelected ? 0 : height }}
className={classNames('overflow-clip px-1', {
'duration-500 transition-[height]': shouldAnimate,
})}
>
<div ref={ref}>{children}</div>
</div>
</div>
</li>
);
}
type VerticalStepComponentType = FC<{
nextStep: () => void;
prevStep: () => void;
goTo: (id: string) => void;
isActive: boolean;
}>;
export type VerticalStep = {
title: string;
id?: string;
component: VerticalStepComponentType;
};
export default function VerticalStepper({ steps }: { steps: VerticalStep[] }) {
const [currStep, setStep] = useState(0);
const nextStep = () => {
if (currStep + 1 === steps.length) return;
setStep(currStep + 1);
};
const prevStep = () => {
if (currStep - 1 < 0) return;
setStep(currStep - 1);
};
const goTo = (id: string) => {
const step = steps.findIndex(({ id: stepId }) => stepId === id);
if (step === -1) throw new Error('step not found');
setStep(step);
};
return (
<ol className="relative border-l border-gray-700 text-gray-400">
{steps.map(({ title, component: StepComponent }, index) => (
<VerticalStep active={currStep} index={index} title={title} key={index}>
<StepComponent
nextStep={nextStep}
prevStep={prevStep}
goTo={goTo}
isActive={currStep === index}
></StepComponent>
</VerticalStep>
))}
</ol>
);
}
@@ -1,7 +1,5 @@
import classNames from 'classnames';
export function CloseIcon({
className,
className = 'stroke-window-icon',
size = 35,
}: {
className?: string;
@@ -11,7 +9,7 @@ export function CloseIcon({
<svg
width={size}
height={size}
className={classNames('stroke-window-icon', className)}
className={className}
viewBox="0 0 31 29"
fill="none"
xmlns="http://www.w3.org/2000/svg"
+2 -11
View File
@@ -1,12 +1,4 @@
import classNames from 'classnames';
export function FileIcon({
width = 24,
isDragging = false,
}: {
width?: number;
isDragging?: boolean;
}) {
export function FileIcon({ width = 24 }: { width?: number }) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
@@ -14,11 +6,10 @@ export function FileIcon({
width={width}
height="24"
fill="currentColor"
className={classNames('transition-transform', isDragging && 'scale-150')}
>
<path
fillRule="evenodd"
d="M5.625 1.5H9a3.75 3.75 0 013.75 3.75v1.875c0 1.036.84 1.875 1.875 1.875H16.5a3.75 3.75 0 013.75 3.75v7.875c0 1.035-.84 1.875-1.875 1.875H5.625a1.875 1.875 0 01-1.875-1.875V3.375c0-1.036.84-1.875 1.875-1.875zm6.905 9.97a.75.75 0 00-1.06 0l-3 3a.75.75 0 101.06 1.06l1.72-1.72V18a.75.75 0 001.5 0v-4.19l1.72 1.72a.75.75 0 101.06-1.06l-3-3z"
d="M 5.625 1.5 L 9 1.5 C 11.071 1.5 12.75 3.179 12.75 5.25 L 12.75 7.125 C 12.75 8.161 13.59 9 14.625 9 L 16.5 9 C 18.571 9 20.25 10.679 20.25 12.75 L 20.25 20.625 C 20.25 21.66 19.41 22.5 18.375 22.5 L 5.625 22.5 C 4.589 22.5 3.75 21.661 3.75 20.625 L 3.75 3.375 C 3.75 2.339 4.59 1.5 5.625 1.5 Z"
clipRule="evenodd"
/>
<path d="M14.25 5.25a5.23 5.23 0 00-1.279-3.434 9.768 9.768 0 016.963 6.963A5.23 5.23 0 0016.5 7.5h-1.875a.375.375 0 01-.375-.375V5.25z" />
@@ -0,0 +1,27 @@
import classNames from 'classnames';
export function UploadFileIcon({
width = 24,
isDragging = false,
}: {
width?: number;
isDragging?: boolean;
}) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
width={width}
height="24"
fill="currentColor"
className={classNames('transition-transform', isDragging && 'scale-150')}
>
<path
fillRule="evenodd"
d="M5.625 1.5H9a3.75 3.75 0 013.75 3.75v1.875c0 1.036.84 1.875 1.875 1.875H16.5a3.75 3.75 0 013.75 3.75v7.875c0 1.035-.84 1.875-1.875 1.875H5.625a1.875 1.875 0 01-1.875-1.875V3.375c0-1.036.84-1.875 1.875-1.875zm6.905 9.97a.75.75 0 00-1.06 0l-3 3a.75.75 0 101.06 1.06l1.72-1.72V18a.75.75 0 001.5 0v-4.19l1.72 1.72a.75.75 0 101.06-1.06l-3-3z"
clipRule="evenodd"
/>
<path d="M14.25 5.25a5.23 5.23 0 00-1.279-3.434 9.768 9.768 0 016.963 6.963A5.23 5.23 0 0016.5 7.5h-1.875a.375.375 0 01-.375-.375V5.25z" />
</svg>
);
}
@@ -0,0 +1,308 @@
import { Localized, useLocalization } from '@fluent/react';
import { Typography } from '@/components/commons/Typography';
import { LoaderIcon, SlimeState } from '@/components/commons/icon/LoaderIcon';
import { useFirmwareTool } from '@/hooks/firmware-tool';
import { Button } from '@/components/commons/Button';
import { Control, useForm } from 'react-hook-form';
import {
CreateImuConfigDTO,
Imudto,
} from '@/firmware-tool-api/firmwareToolSchemas';
import { Dropdown } from '@/components/commons/Dropdown';
import { TrashIcon } from '@/components/commons/icon/TrashIcon';
import { Input } from '@/components/commons/Input';
import {
ArrowDownIcon,
ArrowUpIcon,
} from '@/components/commons/icon/ArrowIcons';
import { useEffect, useRef, useState } from 'react';
import classNames from 'classnames';
import { useElemSize } from '@/hooks/layout';
import { useGetFirmwaresImus } from '@/firmware-tool-api/firmwareToolComponents';
import { CheckBox } from '@/components/commons/Checkbox';
function IMUCard({
control,
imuTypes,
hasIntPin,
index,
onDelete,
}: {
imuTypes: Imudto[];
hasIntPin: boolean;
control: Control<{ imus: CreateImuConfigDTO[] }, any>;
index: number;
onDelete: () => void;
}) {
const { l10n } = useLocalization();
const [open, setOpen] = useState(false);
const ref = useRef<HTMLDivElement | null>(null);
const { height } = useElemSize(ref);
return (
<div className="rounded-lg flex flex-col text-background-10">
<div className="flex gap-3 p-4 shadow-md bg-background-50 rounded-md">
<div className="bg-accent-background-40 rounded-full h-8 w-9 mt-[28px] flex flex-col items-center justify-center">
<Typography variant="section-title" bold>
{index + 1}
</Typography>
</div>
<div className={'w-full flex flex-col gap-2'}>
<div className="grid xs-settings:grid-cols-2 mobile-settings:grid-cols-1 gap-3 fill-background-10">
<label className="flex flex-col justify-end gap-1">
<Localized id="firmware_tool-add_imus_step-imu_type-label"></Localized>
<Dropdown
control={control}
name={`imus[${index}].type`}
items={imuTypes.map(({ type }) => ({
label: type.split('_').slice(1).join(' '),
value: type,
}))}
variant="secondary"
maxHeight="25vh"
placeholder={l10n.getString(
'firmware_tool-add_imus_step-imu_type-placeholder'
)}
direction="down"
display="block"
></Dropdown>
</label>
<Localized
id="firmware_tool-add_imus_step-imu_rotation"
attrs={{ label: true, placeholder: true }}
>
<Input
control={control}
rules={{
required: true,
}}
type="number"
name={`imus[${index}].rotation`}
variant="primary"
label="Rotation Degree"
placeholder="Rotation Degree"
autocomplete="off"
></Input>
</Localized>
</div>
<div
className="duration-500 transition-[height] overflow-hidden"
style={{ height: open ? height : 0 }}
>
<div
ref={ref}
className="grid xs-settings:grid-cols-2 mobile-settings:grid-cols-1 gap-2"
>
<Localized
id="firmware_tool-add_imus_step-scl_pin"
attrs={{ label: true, placeholder: true }}
>
<Input
control={control}
rules={{ required: true }}
type="text"
name={`imus[${index}].sclPin`}
variant="primary"
autocomplete="off"
></Input>
</Localized>
<Localized
id="firmware_tool-add_imus_step-sda_pin"
attrs={{ label: true, placeholder: true }}
>
<Input
control={control}
rules={{ required: true }}
type="text"
name={`imus[${index}].sdaPin`}
variant="primary"
label="SDA Pin"
placeholder="SDA Pin"
autocomplete="off"
></Input>
</Localized>
{hasIntPin && (
<Localized
id="firmware_tool-add_imus_step-int_pin"
attrs={{ label: true, placeholder: true }}
>
<Input
control={control}
rules={{ required: true }}
type="text"
name={`imus[${index}].intPin`}
variant="primary"
autocomplete="off"
></Input>
</Localized>
)}
<label className="flex flex-col justify-end gap-1 md:pt-3 sm:pt-3">
<Localized
id="firmware_tool-add_imus_step-optional_tracker"
attrs={{ label: true }}
>
<CheckBox
control={control}
name={`imus[${index}].optional`}
variant="toggle"
color="tertiary"
label=""
></CheckBox>
</Localized>
</label>
</div>
</div>
</div>
<div className="flex flex-col items-center mt-[25px] fill-background-10">
<Button variant="quaternary" rounded onClick={onDelete}>
<TrashIcon size={15}></TrashIcon>
</Button>
</div>
</div>
<div
className="items-center flex justify-center hover:bg-background-60 bg-background-80 -mt-0.5 transition-colors duration-300 fill-background-10 rounded-b-lg pt-1 pb-0.5"
onClick={() => setOpen(!open)}
>
<Typography>
{l10n.getString(
open
? 'firmware_tool-add_imus_step-show_less'
: 'firmware_tool-add_imus_step-show_more'
)}
</Typography>
{!open && <ArrowDownIcon></ArrowDownIcon>}
{open && <ArrowUpIcon></ArrowUpIcon>}
</div>
</div>
);
}
export function AddImusStep({
nextStep,
prevStep,
isActive,
}: {
nextStep: () => void;
prevStep: () => void;
goTo: (id: string) => void;
isActive: boolean;
}) {
const { l10n } = useLocalization();
const {
isStepLoading: isLoading,
newConfig,
defaultConfig,
updateImus,
} = useFirmwareTool();
const {
control,
formState: { isValid: isValidState },
reset,
watch,
} = useForm<{ imus: CreateImuConfigDTO[] }>({
defaultValues: {
imus: [],
},
reValidateMode: 'onChange',
mode: 'onChange',
});
useEffect(() => {
reset({
imus: newConfig?.imusConfig || [],
});
}, [isActive]);
const { isFetching, data: imuTypes } = useGetFirmwaresImus({});
const isAckchuallyLoading = isFetching || isLoading;
const form = watch();
const addImu = () => {
if (!newConfig || !defaultConfig) throw new Error('unreachable');
const imuPinToAdd =
defaultConfig.imuDefaults[form.imus.length ?? 0] ??
defaultConfig.imuDefaults[0];
const imuTypeToAdd: CreateImuConfigDTO['type'] =
form.imus[0]?.type ?? 'IMU_BNO085';
reset({
imus: [...form.imus, { ...imuPinToAdd, type: imuTypeToAdd }],
});
};
const deleteImu = (index: number) => {
reset({ imus: form.imus.filter((_, i) => i !== index) });
};
return (
<>
<div className="flex flex-col w-full">
<div className="flex flex-col gap-4">
<Typography color="secondary">
{l10n.getString('firmware_tool-board_pins_step-description')}
</Typography>
</div>
<div className="my-4 flex flex-col gap-4">
{!isAckchuallyLoading && imuTypes && newConfig && (
<>
<div className="flex flex-col gap-3">
<div
className={classNames(
'grid gap-2 px-2',
form.imus.length > 1
? 'md:grid-cols-2 mobile-settings:grid-cols-1'
: 'grid-cols-1'
)}
>
{form.imus.map((imu, index) => (
<IMUCard
control={control}
imuTypes={imuTypes}
key={`${index}:${imu.type}`}
hasIntPin={
imuTypes?.find(({ type: t }) => t == imu.type)
?.hasIntPin ?? false
}
index={index}
onDelete={() => deleteImu(index)}
></IMUCard>
))}
</div>
<div className="flex justify-center">
<Localized id="firmware_tool-add_imus_step-add_more">
<Button variant="primary" onClick={addImu}></Button>
</Localized>
</div>
</div>
<div className="flex justify-between">
<Localized id="firmware_tool-previous_step">
<Button variant="tertiary" onClick={prevStep}></Button>
</Localized>
<Localized id="firmware_tool-next_step">
<Button
variant="primary"
disabled={!isValidState || form.imus.length === 0}
onClick={() => {
updateImus(form.imus);
nextStep();
}}
></Button>
</Localized>
</div>
</>
)}
{isAckchuallyLoading && (
<div className="flex justify-center flex-col items-center gap-3 h-44">
<LoaderIcon slimeState={SlimeState.JUMPY}></LoaderIcon>
<Localized id="firmware_tool-loading">
<Typography color="secondary"></Typography>
</Localized>
</div>
)}
</div>
</div>
</>
);
}
@@ -0,0 +1,198 @@
import { Localized, useLocalization } from '@fluent/react';
import { Typography } from '@/components/commons/Typography';
import { LoaderIcon, SlimeState } from '@/components/commons/icon/LoaderIcon';
import { useFirmwareTool } from '@/hooks/firmware-tool';
import { Button } from '@/components/commons/Button';
import { useForm } from 'react-hook-form';
import { Input } from '@/components/commons/Input';
import { useEffect } from 'react';
import { CheckBox } from '@/components/commons/Checkbox';
import { CreateBoardConfigDTO } from '@/firmware-tool-api/firmwareToolSchemas';
import { Dropdown } from '@/components/commons/Dropdown';
import classNames from 'classnames';
import { useGetFirmwaresBatteries } from '@/firmware-tool-api/firmwareToolComponents';
export type BoardPinsForm = Omit<CreateBoardConfigDTO, 'type'>;
export function BoardPinsStep({
nextStep,
prevStep,
}: {
nextStep: () => void;
prevStep: () => void;
}) {
const { l10n } = useLocalization();
const {
isStepLoading: isLoading,
defaultConfig,
updatePins,
} = useFirmwareTool();
const { isFetching, data: batteryTypes } = useGetFirmwaresBatteries({});
const { reset, control, watch, formState } = useForm<BoardPinsForm>({
reValidateMode: 'onChange',
defaultValues: {
batteryResistances: [0, 0, 0],
},
mode: 'onChange',
});
const formValue = watch();
const ledEnabled = watch('enableLed');
const batteryType = watch('batteryType');
useEffect(() => {
if (!defaultConfig) return;
const { type, ...resetConfig } = defaultConfig.boardConfig;
reset({
...resetConfig,
});
}, [defaultConfig]);
return (
<>
<div className="flex flex-col w-full justify-between text-background-10">
<div className="flex flex-col gap-4">
<Typography color="secondary">
{l10n.getString('firmware_tool-board_pins_step-description')}
</Typography>
</div>
<div className="my-4 p-2">
{!isLoading && !isFetching && batteryTypes && (
<form className="flex flex-col gap-2">
<div className="grid xs-settings:grid-cols-2 mobile-settings:grid-cols-1 gap-2">
<label className="flex flex-col justify-end">
{/* Allows to have the right spacing at the top of the checkbox */}
<CheckBox
control={control}
color="tertiary"
name="enableLed"
variant="toggle"
outlined
label={l10n.getString(
'firmware_tool-board_pins_step-enable_led'
)}
></CheckBox>
</label>
<Localized
id="firmware_tool-board_pins_step-led_pin"
attrs={{ placeholder: true, label: true }}
>
<Input
control={control}
rules={{ required: true }}
type="text"
name="ledPin"
variant="secondary"
disabled={!ledEnabled}
></Input>
</Localized>
</div>
<div
className={classNames(
batteryType === 'BAT_EXTERNAL' &&
'bg-background-80 p-2 rounded-md',
'transition-all duration-500 flex-col flex gap-2'
)}
>
<Dropdown
control={control}
name="batteryType"
variant="primary"
placeholder={l10n.getString(
'firmware_tool-board_pins_step-battery_type'
)}
direction="up"
display="block"
items={batteryTypes.map((battery) => ({
label: l10n.getString(
'firmware_tool-board_pins_step-battery_type-' + battery
),
value: battery,
}))}
></Dropdown>
{batteryType === 'BAT_EXTERNAL' && (
<div className="grid grid-cols-2 gap-2">
<Localized
id="firmware_tool-board_pins_step-battery_sensor_pin"
attrs={{ placeholder: true, label: true }}
>
<Input
control={control}
rules={{ required: true }}
type="text"
name="batteryPin"
variant="secondary"
></Input>
</Localized>
<Localized
id="firmware_tool-board_pins_step-battery_resistor"
attrs={{ placeholder: true, label: true }}
>
<Input
control={control}
rules={{ required: true, min: 0 }}
type="number"
name="batteryResistances[0]"
variant="secondary"
label="Battery Resistor"
placeholder="Battery Resistor"
></Input>
</Localized>
<Localized
id="firmware_tool-board_pins_step-battery_shield_resistor-0"
attrs={{ placeholder: true, label: true }}
>
<Input
control={control}
rules={{ required: true, min: 0 }}
type="number"
name="batteryResistances[1]"
variant="secondary"
></Input>
</Localized>
<Localized
id="firmware_tool-board_pins_step-battery_shield_resistor-1"
attrs={{ placeholder: true, label: true }}
>
<Input
control={control}
rules={{ required: true, min: 0 }}
type="number"
name="batteryResistances[2]"
variant="secondary"
></Input>
</Localized>
</div>
)}
</div>
</form>
)}
{(isLoading || isFetching) && (
<div className="flex justify-center flex-col items-center gap-3 h-44">
<LoaderIcon slimeState={SlimeState.JUMPY}></LoaderIcon>
<Localized id="firmware_tool-loading">
<Typography color="secondary"></Typography>
</Localized>
</div>
)}
</div>
<div className="flex justify-between">
<Localized id="firmware_tool-previous_step">
<Button variant="tertiary" onClick={prevStep}></Button>
</Localized>
<Localized id="firmware_tool-ok">
<Button
variant="primary"
disabled={Object.keys(formState.errors).length !== 0}
onClick={() => {
updatePins(formValue);
nextStep();
}}
></Button>
</Localized>
</div>
</div>
</>
);
}
@@ -0,0 +1,111 @@
import { Localized, useLocalization } from '@fluent/react';
import { Typography } from '@/components/commons/Typography';
import { fetchPostFirmwaresBuild } from '@/firmware-tool-api/firmwareToolComponents';
import { LoaderIcon, SlimeState } from '@/components/commons/icon/LoaderIcon';
import { useFirmwareTool } from '@/hooks/firmware-tool';
import {
BuildResponseDTO,
CreateBuildFirmwareDTO,
} from '@/firmware-tool-api/firmwareToolSchemas';
import { useEffect, useMemo } from 'react';
import { firmwareToolBaseUrl } from '@/firmware-tool-api/firmwareToolFetcher';
import { Button } from '@/components/commons/Button';
export function BuildStep({
isActive,
goTo,
nextStep,
}: {
nextStep: () => void;
prevStep: () => void;
goTo: (id: string) => void;
isActive: boolean;
}) {
const { l10n } = useLocalization();
const { isGlobalLoading, newConfig, setBuildStatus, buildStatus } =
useFirmwareTool();
const startBuild = async () => {
try {
const res = await fetchPostFirmwaresBuild({
body: newConfig as CreateBuildFirmwareDTO,
});
setBuildStatus(res);
if (res.status !== 'DONE') {
const events = new EventSource(
`${firmwareToolBaseUrl}/firmwares/build-status/${res.id}`
);
events.onmessage = ({ data }) => {
const buildEvent: BuildResponseDTO = JSON.parse(data);
setBuildStatus(buildEvent);
};
}
} catch (e) {
console.error(e);
setBuildStatus({ id: '', status: 'ERROR' });
}
};
useEffect(() => {
if (!isActive) return;
startBuild();
}, [isActive]);
useEffect(() => {
if (!isActive) return;
if (buildStatus.status === 'DONE') {
nextStep();
}
}, [buildStatus]);
const hasPendingBuild = useMemo(
() => !['DONE', 'ERROR'].includes(buildStatus.status),
[buildStatus.status]
);
return (
<>
<div className="flex flex-col w-full">
<div className="flex flex-grow flex-col gap-4">
<Typography color="secondary">
{l10n.getString('firmware_tool-build_step-description')}
</Typography>
</div>
<div className="my-4">
{!isGlobalLoading && (
<div className="flex justify-center flex-col items-center gap-3 h-44">
<LoaderIcon
slimeState={
buildStatus.status !== 'ERROR'
? SlimeState.JUMPY
: SlimeState.SAD
}
></LoaderIcon>
<Typography variant="section-title" color="secondary">
{l10n.getString('firmware_tool-build-' + buildStatus.status)}
</Typography>
</div>
)}
{isGlobalLoading && (
<div className="flex justify-center flex-col items-center gap-3 h-44">
<LoaderIcon slimeState={SlimeState.JUMPY}></LoaderIcon>
<Localized id="firmware_tool-loading">
<Typography color="secondary"></Typography>
</Localized>
</div>
)}
</div>
<div className="flex justify-end">
<Localized id="firmware_tool-retry">
<Button
variant="secondary"
disabled={hasPendingBuild}
onClick={() => goTo('FlashingMethod')}
></Button>
</Localized>
</div>
</div>
</>
);
}
@@ -0,0 +1,132 @@
import { CHECKBOX_CLASSES } from '@/components/commons/Checkbox';
import { ProgressBar } from '@/components/commons/ProgressBar';
import { Typography } from '@/components/commons/Typography';
import { firmwareUpdateErrorStatus } from '@/hooks/firmware-tool';
import { useLocalization } from '@fluent/react';
import classNames from 'classnames';
import { Control, Controller } from 'react-hook-form';
import {
FirmwareUpdateStatus,
TrackerStatus as TrackerStatusEnum,
} from 'solarxr-protocol';
import { TrackerStatus } from '@/components/tracker/TrackerStatus';
interface DeviceCardProps {
deviceNames: string[];
status?: FirmwareUpdateStatus;
online?: boolean | null;
}
interface DeviceCardControlProps {
control?: Control<any>;
name?: string;
progress?: number;
disabled?: boolean;
}
export function DeviceCardContent({ deviceNames, status }: DeviceCardProps) {
const { l10n } = useLocalization();
return (
<div className="p-2 flex h-full gap-2 justify-between flex-col">
<div className="flex flex-row flex-wrap gap-2 items-center h-full">
{deviceNames.map((name) => (
<span
key={name}
className="p-1 px-3 rounded-l-full rounded-r-full bg-background-40"
>
<Typography>{name}</Typography>
</span>
))}
</div>
{status !== undefined ? (
<Typography color="secondary">
{l10n.getString(
'firmware_update-status-' + FirmwareUpdateStatus[status]
)}
</Typography>
) : (
<Typography> </Typography> // placeholder so the size of the component does not change if there is no status
)}
</div>
);
}
export function DeviceCardControl({
control,
name,
progress,
disabled = false,
online = null,
...props
}: DeviceCardControlProps & DeviceCardProps) {
return (
<div
className={classNames(
'rounded-md bg-background-60 h-[86px] pt-2 flex flex-col justify-between border-2 relative',
props.status &&
firmwareUpdateErrorStatus.includes(props.status) &&
'border-status-critical',
props.status === FirmwareUpdateStatus.DONE && 'border-status-success',
(!props.status ||
(props.status !== FirmwareUpdateStatus.DONE &&
!firmwareUpdateErrorStatus.includes(props.status))) &&
'border-transparent'
)}
>
{control && name ? (
<Controller
control={control}
name={name}
render={({ field: { onChange, value, ref } }) => (
<label className="flex flex-row gap-2 px-4 h-full">
<div className="flex justify-center flex-col">
<input
ref={ref}
onChange={onChange}
className={CHECKBOX_CLASSES}
checked={value || false}
type="checkbox"
disabled={disabled}
></input>
</div>
<div className="w-full">
<DeviceCardContent {...props}></DeviceCardContent>
</div>
</label>
)}
></Controller>
) : (
<div className="px-2 h-full">
<DeviceCardContent {...props}></DeviceCardContent>
</div>
)}
<div
className={classNames(
'align-bottom',
props.status != FirmwareUpdateStatus.UPLOADING ||
progress === undefined
? 'opacity-0'
: 'opacity-100'
)}
>
<ProgressBar
progress={progress || 0}
bottom
height={6}
colorClass="bg-accent-background-20"
></ProgressBar>
</div>
{online !== null && (
<div className="absolute top-2 right-2">
<TrackerStatus
status={
online ? TrackerStatusEnum.OK : TrackerStatusEnum.DISCONNECTED
}
></TrackerStatus>
</div>
)}
</div>
);
}
@@ -0,0 +1,140 @@
import { Localized, useLocalization } from '@fluent/react';
import { Typography } from '@/components/commons/Typography';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import {
FirmwareToolContextC,
useFirmwareToolContext,
} from '@/hooks/firmware-tool';
import { AddImusStep } from './AddImusStep';
import { SelectBoardStep } from './SelectBoardStep';
import { BoardPinsStep } from './BoardPinsStep';
import VerticalStepper from '@/components/commons/VerticalStepper';
import { LoaderIcon, SlimeState } from '@/components/commons/icon/LoaderIcon';
import { Button } from '@/components/commons/Button';
import { SelectFirmwareStep } from './SelectFirmwareStep';
import { BuildStep } from './BuildStep';
import { FlashingMethodStep } from './FlashingMethodStep';
import { FlashingStep } from './FlashingStep';
import { FlashBtnStep } from './FlashBtnStep';
import { FirmwareUpdateMethod } from 'solarxr-protocol';
import { useMemo } from 'react';
function FirmwareToolContent() {
const { l10n } = useLocalization();
const context = useFirmwareToolContext();
const { isError, isGlobalLoading: isLoading, retry, isCompatible } = context;
const steps = useMemo(() => {
const steps = [
{
id: 'SelectBoard',
component: SelectBoardStep,
title: l10n.getString('firmware_tool-board_step'),
},
{
component: BoardPinsStep,
title: l10n.getString('firmware_tool-board_pins_step'),
},
{
component: AddImusStep,
title: l10n.getString('firmware_tool-add_imus_step'),
},
{
id: 'SelectFirmware',
component: SelectFirmwareStep,
title: l10n.getString('firmware_tool-select_firmware_step'),
},
{
component: FlashingMethodStep,
id: 'FlashingMethod',
title: l10n.getString('firmware_tool-flash_method_step'),
},
{
component: BuildStep,
title: l10n.getString('firmware_tool-build_step'),
},
{
component: FlashingStep,
title: l10n.getString('firmware_tool-flashing_step'),
},
];
if (
context.defaultConfig?.needBootPress &&
context.selectedDevices?.find(
({ type }) => type === FirmwareUpdateMethod.SerialFirmwareUpdate
)
) {
steps.splice(5, 0, {
component: FlashBtnStep,
title: l10n.getString('firmware_tool-flashbtn_step'),
});
}
return steps;
}, [context.defaultConfig?.needBootPress, context.selectedDevices, l10n]);
return (
<FirmwareToolContextC.Provider value={context}>
<div className="flex flex-col bg-background-70 p-4 rounded-md">
<Typography variant="main-title">
{l10n.getString('firmware_tool')}
</Typography>
<div className="flex flex-col pt-2 pb-4">
<>
{l10n
.getString('firmware_tool-description')
.split('\n')
.map((line, i) => (
<Typography color="secondary" key={i}>
{line}
</Typography>
))}
</>
</div>
<div className="m-4 h-full">
{isError && (
<div className="w-full flex flex-col justify-center items-center gap-3 h-full">
<LoaderIcon slimeState={SlimeState.SAD}></LoaderIcon>
{!isCompatible ? (
<Localized id="firmware_tool-not_compatible">
<Typography variant="section-title"></Typography>
</Localized>
) : (
<Localized id="firmware_tool-not_available">
<Typography variant="section-title"></Typography>
</Localized>
)}
<Localized id="firmware_tool-retry">
<Button variant="primary" onClick={retry}></Button>
</Localized>
</div>
)}
{isLoading && (
<div className="w-full flex flex-col justify-center items-center gap-3 h-full">
<LoaderIcon slimeState={SlimeState.JUMPY}></LoaderIcon>
<Localized id="firmware_tool-loading">
<Typography variant="section-title"></Typography>
</Localized>
</div>
)}
{!isError && !isLoading && <VerticalStepper steps={steps} />}
</div>
</div>
</FirmwareToolContextC.Provider>
);
}
export function FirmwareToolSettings() {
const queryClient = new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: false, // default: true
},
},
});
return (
<QueryClientProvider client={queryClient}>
<FirmwareToolContent />
</QueryClientProvider>
);
}
@@ -0,0 +1,86 @@
import { Localized, useLocalization } from '@fluent/react';
import { Typography } from '@/components/commons/Typography';
import { Button } from '@/components/commons/Button';
import {
boardTypeToFirmwareToolBoardType,
useFirmwareTool,
} from '@/hooks/firmware-tool';
import { BoardType } from 'solarxr-protocol';
export function FlashBtnStep({
nextStep,
}: {
nextStep: () => void;
prevStep: () => void;
goTo: (id: string) => void;
isActive: boolean;
}) {
const { l10n } = useLocalization();
const { defaultConfig } = useFirmwareTool();
return (
<>
<div className="flex flex-col w-full">
<div className="flex flex-grow flex-col gap-4">
<Typography color="secondary">
{l10n.getString('firmware_tool-flashbtn_step-description')}
</Typography>
{defaultConfig?.boardConfig.type ===
boardTypeToFirmwareToolBoardType[BoardType.SLIMEVR] ? (
<>
<Typography variant="standard" whitespace="whitespace-pre">
{l10n.getString('firmware_tool-flashbtn_step-board_SLIMEVR')}
</Typography>
<div className="gap-2 grid lg:grid-cols-3 md:grid-cols-2 mobile:grid-cols-1">
<div className="bg-background-80 p-2 rounded-lg gap-2 flex flex-col justify-between">
<Typography variant="main-title">R11</Typography>
<Typography variant="standard">
{l10n.getString(
'firmware_tool-flashbtn_step-board_SLIMEVR-r11'
)}
</Typography>
<img src="/images/R11_board_reset.webp"></img>
</div>
<div className="bg-background-80 p-2 rounded-lg gap-2 flex flex-col justify-between">
<Typography variant="main-title">R12</Typography>
<Typography variant="standard">
{l10n.getString(
'firmware_tool-flashbtn_step-board_SLIMEVR-r12'
)}
</Typography>
<img src="/images/R12_board_reset.webp"></img>
</div>
<div className="bg-background-80 p-2 rounded-lg gap-2 flex flex-col justify-between">
<Typography variant="main-title">R14</Typography>
<Typography variant="standard">
{l10n.getString(
'firmware_tool-flashbtn_step-board_SLIMEVR-r14'
)}
</Typography>
<img src="/images/R14_board_reset_sw.webp"></img>
</div>
</div>
</>
) : (
<>
<Typography variant="standard" whitespace="whitespace-pre">
{l10n.getString('firmware_tool-flashbtn_step-board_OTHER')}
</Typography>
</>
)}
<div className="flex justify-end">
<Localized id="firmware_tool-next_step">
<Button
variant="primary"
onClick={() => {
nextStep();
}}
></Button>
</Localized>
</div>
</div>
</div>
</>
);
}
@@ -0,0 +1,421 @@
import { Localized, useLocalization } from '@fluent/react';
import { Typography } from '@/components/commons/Typography';
import { LoaderIcon, SlimeState } from '@/components/commons/icon/LoaderIcon';
import {
boardTypeToFirmwareToolBoardType,
useFirmwareTool,
} from '@/hooks/firmware-tool';
import { Control, UseFormReset, UseFormWatch, useForm } from 'react-hook-form';
import { Radio } from '@/components/commons/Radio';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { useEffect, useLayoutEffect, useState } from 'react';
import { yupResolver } from '@hookform/resolvers/yup';
import {
BoardType,
DeviceDataT,
FirmwareUpdateMethod,
NewSerialDeviceResponseT,
RpcMessage,
SerialDeviceT,
SerialDevicesRequestT,
SerialDevicesResponseT,
TrackerStatus,
} from 'solarxr-protocol';
import { Button } from '@/components/commons/Button';
import { useAppContext } from '@/hooks/app';
import { Input } from '@/components/commons/Input';
import { Dropdown } from '@/components/commons/Dropdown';
import { useOnboarding } from '@/hooks/onboarding';
import { DeviceCardControl } from './DeviceCard';
import { getTrackerName } from '@/hooks/tracker';
import { ObjectSchema, object, string } from 'yup';
interface FlashingMethodForm {
flashingMethod?: string;
serial?: {
selectedDevicePort: string;
ssid: string;
password?: string;
};
ota?: {
selectedDevices: { [key: string]: boolean };
};
}
function SerialDevicesList({
control,
watch,
reset,
}: {
control: Control<FlashingMethodForm>;
watch: UseFormWatch<FlashingMethodForm>;
reset: UseFormReset<FlashingMethodForm>;
}) {
const { l10n } = useLocalization();
const { selectDevices } = useFirmwareTool();
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const [devices, setDevices] = useState<Record<string, SerialDeviceT>>({});
const { state, setWifiCredentials } = useOnboarding();
useLayoutEffect(() => {
sendRPCPacket(RpcMessage.SerialDevicesRequest, new SerialDevicesRequestT());
selectDevices(null);
reset({
flashingMethod: FirmwareUpdateMethod.SerialFirmwareUpdate.toString(),
serial: {
...state.wifi,
selectedDevicePort: undefined,
},
ota: undefined,
});
}, []);
useRPCPacket(
RpcMessage.SerialDevicesResponse,
(res: SerialDevicesResponseT) => {
setDevices((old) =>
res.devices.reduce(
(curr, device) => ({
...curr,
[device?.port?.toString() ?? 'unknown']: device,
}),
old
)
);
}
);
useRPCPacket(
RpcMessage.NewSerialDeviceResponse,
({ device }: NewSerialDeviceResponseT) => {
if (device?.port)
setDevices((old) => ({
...old,
[device?.port?.toString() ?? 'unknown']: device,
}));
}
);
const serialValues = watch('serial');
useEffect(() => {
if (!serialValues) {
selectDevices(null);
return;
}
setWifiCredentials(serialValues.ssid, serialValues.password);
if (
serialValues.selectedDevicePort &&
devices[serialValues.selectedDevicePort]
) {
selectDevices([
{
type: FirmwareUpdateMethod.SerialFirmwareUpdate,
deviceId: serialValues.selectedDevicePort,
deviceNames: [
devices[serialValues.selectedDevicePort].name?.toString() ??
'unknown',
],
},
]);
} else {
selectDevices(null);
}
}, [JSON.stringify(serialValues), devices]);
return (
<>
<Localized id="firmware_tool-flash_method_serial-wifi">
<Typography variant="section-title"></Typography>
</Localized>
<div className="grid xs-settings:grid-cols-2 mobile-settings:grid-cols-1 gap-3 text-background-10">
<Localized
id="onboarding-wifi_creds-ssid"
attrs={{ placeholder: true, label: true }}
>
<Input
control={control}
name="serial.ssid"
label="SSID"
variant="secondary"
/>
</Localized>
<Localized
id="onboarding-wifi_creds-password"
attrs={{ placeholder: true, label: true }}
>
<Input
control={control}
name="serial.password"
type="password"
variant="secondary"
/>
</Localized>
</div>
<Localized id="firmware_tool-flash_method_serial-devices-label">
<Typography variant="section-title"></Typography>
</Localized>
{Object.keys(devices).length === 0 ? (
<Localized id="firmware_tool-flash_method_serial-no_devices">
<Typography variant="standard" color="secondary"></Typography>
</Localized>
) : (
<Dropdown
control={control}
name="serial.selectedDevicePort"
items={Object.keys(devices).map((port) => ({
label: devices[port].name?.toString() ?? 'unknown',
value: port,
}))}
placeholder={l10n.getString(
'firmware_tool-flash_method_serial-devices-placeholder'
)}
display="block"
direction="down"
></Dropdown>
)}
</>
);
}
function OTADevicesList({
control,
watch,
reset,
}: {
control: Control<FlashingMethodForm>;
watch: UseFormWatch<FlashingMethodForm>;
reset: UseFormReset<FlashingMethodForm>;
}) {
const { l10n } = useLocalization();
const { selectDevices, newConfig } = useFirmwareTool();
const { state } = useAppContext();
const devices =
state.datafeed?.devices.filter(({ trackers, hardwareInfo }) => {
// We make sure the device is not one of these types
if (
hardwareInfo?.officialBoardType === BoardType.SLIMEVR_LEGACY ||
hardwareInfo?.officialBoardType === BoardType.SLIMEVR_DEV ||
hardwareInfo?.officialBoardType === BoardType.CUSTOM
)
return false;
// if the device has no trackers it is prob misconfigured so we skip for safety
if (trackers.length <= 0) return false;
// We make sure that the tracker is in working condition before doing ota as an error (that could be hardware)
// could cause an error during the update
if (!trackers.every(({ status }) => status === TrackerStatus.OK))
return false;
const boardType = hardwareInfo?.officialBoardType ?? BoardType.UNKNOWN;
return (
boardTypeToFirmwareToolBoardType[boardType] ===
newConfig?.boardConfig?.type
);
}) || [];
const deviceNames = ({ trackers }: DeviceDataT) =>
trackers
.map(({ info }) => getTrackerName(l10n, info))
.filter((i): i is string => !!i);
const selectedDevices = watch('ota.selectedDevices');
useLayoutEffect(() => {
reset({
flashingMethod: FirmwareUpdateMethod.OTAFirmwareUpdate.toString(),
ota: {
selectedDevices: devices.reduce(
(curr, { id }) => ({ ...curr, [id?.id ?? 0]: false }),
{}
),
},
serial: undefined,
});
selectDevices(null);
}, []);
useEffect(() => {
if (selectedDevices) {
selectDevices(
Object.keys(selectedDevices)
.filter((d) => selectedDevices[d])
.map((id) => id.substring('id-'.length))
.map((id) => {
const device = devices.find(
({ id: dId }) => id === dId?.id.toString()
);
if (!device) throw new Error('no device found');
return {
type: FirmwareUpdateMethod.OTAFirmwareUpdate,
deviceId: id,
deviceNames: deviceNames(device),
};
})
);
}
}, [JSON.stringify(selectedDevices)]);
return (
<>
<Localized id="firmware_tool-flash_method_ota-devices">
<Typography variant="section-title"></Typography>
</Localized>
{devices.length === 0 && (
<Localized id="firmware_tool-flash_method_ota-no_devices">
<Typography color="secondary"></Typography>
</Localized>
)}
<div className="grid xs-settings:grid-cols-2 mobile-settings:grid-cols-1 gap-2">
{devices.map((device) => (
<DeviceCardControl
control={control}
key={device.id?.id ?? 0}
name={`ota.selectedDevices.id-${device.id?.id ?? 0}`}
deviceNames={deviceNames(device)}
></DeviceCardControl>
))}
</div>
</>
);
}
export function FlashingMethodStep({
nextStep,
prevStep,
}: {
nextStep: () => void;
prevStep: () => void;
isActive: boolean;
}) {
const { l10n } = useLocalization();
const { isGlobalLoading, selectedDevices } = useFirmwareTool();
const {
control,
watch,
reset,
formState: { isValid },
} = useForm<FlashingMethodForm>({
reValidateMode: 'onChange',
mode: 'onChange',
resolver: yupResolver(
object({
flashingMethod: string().optional(),
serial: object().when('flashingMethod', {
is: FirmwareUpdateMethod.SerialFirmwareUpdate.toString(),
then: (s) =>
s
.shape({
selectedDevicePort: string().required(),
ssid: string().required(
l10n.getString('onboarding-wifi_creds-ssid-required')
),
password: string(),
})
.required(),
otherwise: (s) => s.optional(),
}),
ota: object().when('flashingMethod', {
is: FirmwareUpdateMethod.OTAFirmwareUpdate.toString(),
then: (s) =>
s
.shape({
selectedDevices: object(),
})
.required(),
otherwise: (s) => s.optional(),
}),
}) as ObjectSchema<FlashingMethodForm>
),
});
const flashingMethod = watch('flashingMethod');
return (
<>
<div className="flex flex-col w-full">
<div className="flex flex-grow flex-col gap-4">
<Typography color="secondary">
{l10n.getString('firmware_tool-flash_method_step-description')}
</Typography>
</div>
<div className="my-4">
{!isGlobalLoading && (
<div className="flex flex-col gap-3">
<div className="grid xs-settings:grid-cols-2 mobile-settings:grid-cols-1 gap-3">
<Localized
id="firmware_tool-flash_method_step-ota"
attrs={{ label: true, description: true }}
>
<Radio
control={control}
name="flashingMethod"
value={FirmwareUpdateMethod.OTAFirmwareUpdate.toString()}
label=""
></Radio>
</Localized>
<Localized
id="firmware_tool-flash_method_step-serial"
attrs={{ label: true, description: true }}
>
<Radio
control={control}
name="flashingMethod"
value={FirmwareUpdateMethod.SerialFirmwareUpdate.toString()}
label=""
></Radio>
</Localized>
</div>
{flashingMethod ===
FirmwareUpdateMethod.SerialFirmwareUpdate.toString() && (
<SerialDevicesList
control={control}
watch={watch}
reset={reset}
></SerialDevicesList>
)}
{flashingMethod ===
FirmwareUpdateMethod.OTAFirmwareUpdate.toString() && (
<OTADevicesList
control={control}
watch={watch}
reset={reset}
></OTADevicesList>
)}
<div className="flex justify-between">
<Localized id="firmware_tool-previous_step">
<Button variant="secondary" onClick={prevStep}></Button>
</Localized>
<Localized id="firmware_tool-next_step">
<Button
variant="primary"
disabled={
!isValid ||
selectedDevices === null ||
selectedDevices.length === 0
}
onClick={nextStep}
></Button>
</Localized>
</div>
</div>
)}
{isGlobalLoading && (
<div className="flex justify-center flex-col items-center gap-3 h-44">
<LoaderIcon slimeState={SlimeState.JUMPY}></LoaderIcon>
<Localized id="firmware_tool-loading">
<Typography color="secondary"></Typography>
</Localized>
</div>
)}
</div>
</div>
</>
);
}
@@ -0,0 +1,220 @@
import { Localized, useLocalization } from '@fluent/react';
import { Typography } from '@/components/commons/Typography';
import {
SelectedDevice,
firmwareUpdateErrorStatus,
getFlashingRequests,
useFirmwareTool,
} from '@/hooks/firmware-tool';
import { useEffect, useMemo, useState } from 'react';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import {
DeviceIdTableT,
FirmwareUpdateMethod,
FirmwareUpdateStatus,
FirmwareUpdateStatusResponseT,
FirmwareUpdateStopQueuesRequestT,
RpcMessage,
} from 'solarxr-protocol';
import { useOnboarding } from '@/hooks/onboarding';
import { DeviceCardControl } from './DeviceCard';
import { WarningBox } from '@/components/commons/TipBox';
import { Button } from '@/components/commons/Button';
import { useNavigate } from 'react-router-dom';
import { firmwareToolS3BaseUrl } from '@/firmware-tool-api/firmwareToolFetcher';
export function FlashingStep({
goTo,
isActive,
}: {
nextStep: () => void;
prevStep: () => void;
goTo: (id: string) => void;
isActive: boolean;
}) {
const nav = useNavigate();
const { l10n } = useLocalization();
const { selectedDevices, buildStatus, selectDevices, defaultConfig } =
useFirmwareTool();
const { state: onboardingState } = useOnboarding();
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const [status, setStatus] = useState<{
[key: string]: {
status: FirmwareUpdateStatus;
type: FirmwareUpdateMethod;
progress: number;
deviceNames: string[];
};
}>({});
const clear = () => {
setStatus({});
sendRPCPacket(
RpcMessage.FirmwareUpdateStopQueuesRequest,
new FirmwareUpdateStopQueuesRequestT()
);
};
const queueFlashing = (selectedDevices: SelectedDevice[]) => {
clear();
if (!buildStatus.firmwareFiles)
throw new Error('invalid state - no firmware files');
const requests = getFlashingRequests(
selectedDevices,
buildStatus.firmwareFiles.map(({ url, ...fields }) => ({
url: `${firmwareToolS3BaseUrl}/${url}`,
...fields,
})),
onboardingState,
defaultConfig
);
requests.forEach((req) => {
sendRPCPacket(RpcMessage.FirmwareUpdateRequest, req);
});
};
useEffect(() => {
if (!isActive) return;
if (!selectedDevices)
throw new Error('invalid state - no selected devices');
queueFlashing(selectedDevices);
return () => clear();
}, [isActive]);
useRPCPacket(
RpcMessage.FirmwareUpdateStatusResponse,
(data: FirmwareUpdateStatusResponseT) => {
if (!data.deviceId) throw new Error('no device id');
const id =
data.deviceId instanceof DeviceIdTableT
? data.deviceId.id?.id
: data.deviceId.port;
if (!id) throw new Error('invalid device id');
const selectedDevice = selectedDevices?.find(
({ deviceId }) => deviceId == id.toString()
);
// We skip the status as it can be old trackers still sending status
if (!selectedDevice) return;
setStatus((last) => ({
...last,
[id.toString()]: {
progress: data.progress / 100,
status: data.status,
type: selectedDevice.type,
deviceNames: selectedDevice.deviceNames,
},
}));
}
);
const trackerWithErrors = useMemo(
() =>
Object.keys(status).filter((id) =>
firmwareUpdateErrorStatus.includes(status[id].status)
),
[status, firmwareUpdateErrorStatus]
);
const retryError = () => {
const devices = trackerWithErrors.map((id) => {
const device = status[id];
return {
type: device.type,
deviceId: id,
deviceNames: device.deviceNames,
};
});
selectDevices(devices);
queueFlashing(devices);
};
const hasPendingTrackers = useMemo(
() =>
Object.keys(status).filter((id) =>
[
FirmwareUpdateStatus.NEED_MANUAL_REBOOT,
FirmwareUpdateStatus.DOWNLOADING,
FirmwareUpdateStatus.AUTHENTICATING,
FirmwareUpdateStatus.REBOOTING,
FirmwareUpdateStatus.SYNCING_WITH_MCU,
FirmwareUpdateStatus.UPLOADING,
FirmwareUpdateStatus.PROVISIONING,
].includes(status[id].status)
).length > 0,
[status]
);
const shouldShowRebootWarning = useMemo(
() =>
Object.keys(status).find((id) =>
[
FirmwareUpdateStatus.REBOOTING,
FirmwareUpdateStatus.UPLOADING,
].includes(status[id].status)
),
[status]
);
return (
<>
<div className="flex flex-col w-full">
<div className="flex flex-grow flex-col gap-4">
<Typography color="secondary">
{l10n.getString('firmware_tool-flashing_step-description')}
</Typography>
</div>
<div className="my-4 flex gap-2 flex-col">
{shouldShowRebootWarning && (
<Localized id="firmware_tool-flashing_step-warning">
<WarningBox>Warning</WarningBox>
</Localized>
)}
{Object.keys(status).map((id) => {
const val = status[id];
return (
<DeviceCardControl
status={val.status}
progress={val.progress}
key={id}
deviceNames={val.deviceNames}
></DeviceCardControl>
);
})}
<div className="flex gap-2 self-end">
<Localized id="firmware_tool-retry">
<Button
variant="secondary"
disabled={trackerWithErrors.length === 0}
onClick={retryError}
></Button>
</Localized>
<Localized id="firmware_tool-flashing_step-flash_more">
<Button
variant="secondary"
disabled={hasPendingTrackers}
onClick={() => goTo('FlashingMethod')}
></Button>
</Localized>
<Localized id="firmware_tool-flashing_step-exit">
<Button
variant="primary"
onClick={() => {
clear();
nav('/');
}}
></Button>
</Localized>
</div>
</div>
</div>
</>
);
}
@@ -0,0 +1,95 @@
import { Localized, useLocalization } from '@fluent/react';
import { Typography } from '@/components/commons/Typography';
import { LoaderIcon, SlimeState } from '@/components/commons/icon/LoaderIcon';
import {
firmwareToolToBoardType,
useFirmwareTool,
} from '@/hooks/firmware-tool';
import { CreateBoardConfigDTO } from '@/firmware-tool-api/firmwareToolSchemas';
import classNames from 'classnames';
import { Button } from '@/components/commons/Button';
import { useGetFirmwaresBoards } from '@/firmware-tool-api/firmwareToolComponents';
import { BoardType } from 'solarxr-protocol';
export function SelectBoardStep({
nextStep,
goTo,
}: {
nextStep: () => void;
prevStep: () => void;
goTo: (id: string) => void;
}) {
const { l10n } = useLocalization();
const { selectBoard, newConfig, defaultConfig } = useFirmwareTool();
const { isFetching, data: boards } = useGetFirmwaresBoards({});
return (
<>
<div className="flex flex-col w-full">
<div className="flex flex-grow flex-col gap-4">
<Typography color="secondary">
{l10n.getString('firmware_tool-board_step-description')}
</Typography>
</div>
<div className="my-4">
{!isFetching && (
<div className="gap-2 flex flex-col">
<div className="grid sm:grid-cols-2 mobile-settings:grid-cols-1 gap-2">
{boards?.map((board) => (
<div
key={board}
className={classNames(
'p-3 rounded-md hover:bg-background-50',
{
'bg-background-50 text-background-10':
newConfig?.boardConfig?.type === board,
'bg-background-60':
newConfig?.boardConfig?.type !== board,
}
)}
onClick={() => {
selectBoard(board as CreateBoardConfigDTO['type']);
}}
>
{l10n.getString(
`board_type-${
BoardType[
firmwareToolToBoardType[
board as CreateBoardConfigDTO['type']
] ?? BoardType.UNKNOWN
]
}`
)}
</div>
))}
</div>
<div className="flex justify-end">
<Localized id="firmware_tool-next_step">
<Button
variant="primary"
disabled={!newConfig?.boardConfig?.type}
onClick={() => {
if (defaultConfig?.shouldOnlyUseDefaults) {
goTo('SelectFirmware');
} else {
nextStep();
}
}}
></Button>
</Localized>
</div>
</div>
)}
{isFetching && (
<div className="flex justify-center flex-col items-center gap-3 h-44">
<LoaderIcon slimeState={SlimeState.JUMPY}></LoaderIcon>
<Localized id="firmware_tool-loading">
<Typography color="secondary"></Typography>
</Localized>
</div>
)}
</div>
</div>
</>
);
}
@@ -0,0 +1,120 @@
import { Localized, useLocalization } from '@fluent/react';
import { Typography } from '@/components/commons/Typography';
import { useGetFirmwaresVersions } from '@/firmware-tool-api/firmwareToolComponents';
import { LoaderIcon, SlimeState } from '@/components/commons/icon/LoaderIcon';
import { useFirmwareTool } from '@/hooks/firmware-tool';
import classNames from 'classnames';
import { Button } from '@/components/commons/Button';
import { useMemo } from 'react';
import { CheckBox } from '@/components/commons/Checkbox';
import { useForm } from 'react-hook-form';
export function SelectFirmwareStep({
nextStep,
prevStep,
goTo,
}: {
nextStep: () => void;
prevStep: () => void;
goTo: (id: string) => void;
}) {
const { l10n } = useLocalization();
const { selectVersion, newConfig, defaultConfig } = useFirmwareTool();
const { isFetching, data: firmwares } = useGetFirmwaresVersions({});
const { control, watch } = useForm<{ thirdParty: boolean }>({});
const showThirdParty = watch('thirdParty');
const getName = (name: string) => {
return showThirdParty ? name : name.substring(name.indexOf('/') + 1);
};
const filteredFirmwares = useMemo(() => {
return firmwares?.filter(
({ name }) => name.split('/')[0] === 'SlimeVR' || showThirdParty
);
}, [firmwares, showThirdParty]);
return (
<>
<div className="flex flex-col w-full">
<div className="flex justify-between items-center mobile:flex-col gap-4">
<Typography color="secondary">
{l10n.getString('firmware_tool-select_firmware_step-description')}
</Typography>
<div>
<Localized
id="firmware_tool-select_firmware_step-show-third-party"
attrs={{ label: true }}
>
<CheckBox
control={control}
name="thirdParty"
label="Show third party firmwares"
></CheckBox>
</Localized>
</div>
</div>
<div className="my-4">
{!isFetching && (
<div className="flex flex-col gap-4">
<div className="xs-settings:max-h-96 xs-settings:overflow-y-auto xs-settings:px-2">
<div className="grid sm:grid-cols-2 mobile-settings:grid-cols-1 gap-2">
{filteredFirmwares?.map((firmware) => (
<div
key={firmware.id}
className={classNames(
'p-3 rounded-md hover:bg-background-50',
{
'bg-background-50 text-background-10':
newConfig?.version === firmware.name,
'bg-background-60':
newConfig?.version !== firmware.name,
}
)}
onClick={() => {
selectVersion(firmware.name);
}}
>
{getName(firmware.name)}
</div>
))}
</div>
</div>
<div className="flex justify-between">
<Localized id="firmware_tool-previous_step">
<Button
variant="tertiary"
onClick={() => {
if (defaultConfig?.shouldOnlyUseDefaults) {
goTo('SelectBoard');
} else {
prevStep();
}
}}
></Button>
</Localized>
<Localized id="firmware_tool-next_step">
<Button
variant="primary"
disabled={!newConfig?.version}
onClick={nextStep}
></Button>
</Localized>
</div>
</div>
)}
{isFetching && (
<div className="flex justify-center flex-col items-center gap-3 h-44">
<LoaderIcon slimeState={SlimeState.JUMPY}></LoaderIcon>
<Localized id="firmware_tool-loading">
<Typography color="secondary"></Typography>
</Localized>
</div>
)}
</div>
</div>
</>
);
}
@@ -0,0 +1,402 @@
import { Localized, ReactLocalization, useLocalization } from '@fluent/react';
import { Typography } from '@/components/commons/Typography';
import { getTrackerName } from '@/hooks/tracker';
import { ComponentProps, useEffect, useMemo, useState } from 'react';
import {
BoardType,
DeviceDataT,
DeviceIdTableT,
FirmwareUpdateMethod,
FirmwareUpdateStatus,
FirmwareUpdateStatusResponseT,
FirmwareUpdateStopQueuesRequestT,
HardwareInfoT,
RpcMessage,
TrackerStatus,
} from 'solarxr-protocol';
import semver from 'semver';
import classNames from 'classnames';
import { Button } from '@/components/commons/Button';
import Markdown from 'react-markdown';
import remark from 'remark-gfm';
import { WarningBox } from '@/components/commons/TipBox';
import { FirmwareRelease, useAppContext } from '@/hooks/app';
import { DeviceCardControl } from '@/components/firmware-tool/DeviceCard';
import { Control, useForm } from 'react-hook-form';
import { useNavigate } from 'react-router-dom';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import {
firmwareUpdateErrorStatus,
getFlashingRequests,
SelectedDevice,
} from '@/hooks/firmware-tool';
import { yupResolver } from '@hookform/resolvers/yup';
import { object } from 'yup';
import { LoaderIcon, SlimeState } from '@/components/commons/icon/LoaderIcon';
import { A } from '@/components/commons/A';
export function checkForUpdate(
currentFirmwareRelease: FirmwareRelease,
hardwareInfo: HardwareInfoT
) {
return (
// TODO: This is temporary, end goal is to support all board types
hardwareInfo.officialBoardType === BoardType.SLIMEVR &&
semver.valid(currentFirmwareRelease.version) &&
semver.valid(hardwareInfo.firmwareVersion?.toString() ?? 'none') &&
semver.lt(
hardwareInfo.firmwareVersion?.toString() ?? 'none',
currentFirmwareRelease.version
)
);
}
interface FirmwareUpdateForm {
selectedDevices: { [key: string]: boolean };
}
interface UpdateStatus {
status: FirmwareUpdateStatus;
type: FirmwareUpdateMethod;
progress: number;
deviceNames: string[];
}
const deviceNames = ({ trackers }: DeviceDataT, l10n: ReactLocalization) =>
trackers
.map(({ info }) => getTrackerName(l10n, info))
.filter((i): i is string => !!i);
const DeviceList = ({
control,
devices,
}: {
control: Control<any>;
devices: DeviceDataT[];
}) => {
const { l10n } = useLocalization();
return devices.map((device, index) => (
<DeviceCardControl
key={index}
control={control}
name={`selectedDevices.${device.id?.id ?? 0}`}
deviceNames={deviceNames(device, l10n)}
/>
));
};
const StatusList = ({ status }: { status: Record<string, UpdateStatus> }) => {
const statusKeys = Object.keys(status);
return statusKeys.map((id, index) => {
const val = status[id];
if (!val) throw new Error('there should always be a val');
const { state } = useAppContext();
const device = state.datafeed?.devices.find(
({ id: dId }) => id === dId?.id.toString()
);
return (
<DeviceCardControl
status={val.status}
progress={val.progress}
key={index}
deviceNames={val.deviceNames}
online={device?.trackers.some(
({ status }) => status === TrackerStatus.OK
)}
></DeviceCardControl>
);
});
};
const MarkdownLink = (props: ComponentProps<'a'>) => (
<A href={props.href}>{props.children}</A>
);
export function FirmwareUpdate() {
const navigate = useNavigate();
const { l10n } = useLocalization();
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const [selectedDevices, setSelectedDevices] = useState<SelectedDevice[]>([]);
const { state, currentFirmwareRelease } = useAppContext();
const [status, setStatus] = useState<Record<string, UpdateStatus>>({});
const devices =
state.datafeed?.devices.filter(
({ trackers, hardwareInfo }) =>
trackers.length > 0 &&
currentFirmwareRelease &&
hardwareInfo &&
checkForUpdate(currentFirmwareRelease, hardwareInfo) &&
trackers.every(({ status }) => status === TrackerStatus.OK)
) || [];
useRPCPacket(
RpcMessage.FirmwareUpdateStatusResponse,
(data: FirmwareUpdateStatusResponseT) => {
if (!data.deviceId) throw new Error('no device id');
const id =
data.deviceId instanceof DeviceIdTableT
? data.deviceId.id?.id
: data.deviceId.port;
if (!id) throw new Error('invalid device id');
const selectedDevice = selectedDevices?.find(
({ deviceId }) => deviceId === id.toString()
);
// We skip the status as it can be old trackers still sending status
if (!selectedDevice) return;
setStatus((last) => ({
...last,
[id.toString()]: {
progress: data.progress / 100,
status: data.status,
type: selectedDevice.type,
deviceNames: selectedDevice.deviceNames,
},
}));
}
);
const {
control,
watch,
reset,
formState: { isValid },
} = useForm<FirmwareUpdateForm>({
reValidateMode: 'onChange',
mode: 'onChange',
defaultValues: {
selectedDevices: devices.reduce(
(curr, { id }) => ({ ...curr, [id?.id ?? 0]: false }),
{}
),
},
resolver: yupResolver(
object({
selectedDevices: object().test(
'at-least-one-true',
'At least one field must be true',
(value) => {
if (typeof value !== 'object' || value === null) return false;
return Object.values(value).some((val) => val === true);
}
),
})
),
});
const selectedDevicesForm = watch('selectedDevices');
const clear = () => {
setStatus({});
sendRPCPacket(
RpcMessage.FirmwareUpdateStopQueuesRequest,
new FirmwareUpdateStopQueuesRequestT()
);
};
useEffect(() => {
if (!currentFirmwareRelease) {
navigate('/');
return;
}
return () => {
clear();
};
}, []);
const queueFlashing = (selectedDevices: SelectedDevice[]) => {
clear();
const firmwareFile = currentFirmwareRelease?.firmwareFile;
if (!firmwareFile) throw new Error('invalid state - no firmware file');
const requests = getFlashingRequests(
selectedDevices,
[{ isFirmware: true, firmwareId: '', url: firmwareFile, offset: 0 }],
{ wifi: undefined, alonePage: false, progress: 0 }, // we do not use serial
null // we do not use serial
);
requests.forEach((req) => {
sendRPCPacket(RpcMessage.FirmwareUpdateRequest, req);
});
};
const trackerWithErrors = useMemo(
() =>
Object.keys(status).filter((id) =>
firmwareUpdateErrorStatus.includes(status[id].status)
),
[status]
);
const hasPendingTrackers = useMemo(
() =>
Object.keys(status).filter((id) =>
[
FirmwareUpdateStatus.NEED_MANUAL_REBOOT,
FirmwareUpdateStatus.DOWNLOADING,
FirmwareUpdateStatus.AUTHENTICATING,
FirmwareUpdateStatus.REBOOTING,
FirmwareUpdateStatus.SYNCING_WITH_MCU,
FirmwareUpdateStatus.UPLOADING,
FirmwareUpdateStatus.PROVISIONING,
].includes(status[id].status)
).length > 0,
[status]
);
const shouldShowRebootWarning = useMemo(
() =>
Object.keys(status).find((id) =>
[
FirmwareUpdateStatus.REBOOTING,
FirmwareUpdateStatus.UPLOADING,
].includes(status[id].status)
),
[status]
);
const retryError = () => {
const devices = trackerWithErrors.map((id) => {
const device = status[id];
return {
type: device.type,
deviceId: id,
deviceNames: device.deviceNames,
};
});
reset({
selectedDevices: devices.reduce(
(curr, { deviceId }) => ({ ...curr, [deviceId]: true }),
{}
),
});
queueFlashing(devices);
};
const startUpdate = () => {
const selectedDevices = Object.keys(selectedDevicesForm)
.filter((d) => selectedDevicesForm[d])
.map((id) => {
const device = devices.find(({ id: dId }) => id === dId?.id.toString());
if (!device) throw new Error('no device found');
return {
type: FirmwareUpdateMethod.OTAFirmwareUpdate,
deviceId: id,
deviceNames: deviceNames(device, l10n),
};
});
if (!selectedDevices)
throw new Error('invalid state - no selected devices');
setSelectedDevices(selectedDevices);
queueFlashing(selectedDevices);
};
const canStartUpdate =
isValid &&
devices.length !== 0 &&
!hasPendingTrackers &&
trackerWithErrors.length === 0;
const canRetry =
isValid && devices.length !== 0 && trackerWithErrors.length !== 0;
const statusKeys = Object.keys(status);
return (
<div className="flex flex-col p-4 w-full items-center justify-center">
<div className="mobile:w-full w-10/12 h-full flex flex-col gap-2">
<Localized id="firmware_update-title">
<Typography variant="main-title"></Typography>
</Localized>
<div className="grid md:grid-cols-2 xs:grid-cols-1 gap-5">
<div className="flex flex-col gap-2">
<Localized id="firmware_update-devices">
<Typography variant="section-title"></Typography>
</Localized>
<Localized id="firmware_update-devices-description">
<Typography variant="standard" color="secondary"></Typography>
</Localized>
<div className="flex flex-col gap-4 overflow-y-auto xs:max-h-[530px]">
{devices.length === 0 &&
!hasPendingTrackers &&
statusKeys.length == 0 && (
<Localized id="firmware_update-no_devices">
<WarningBox>Warning</WarningBox>
</Localized>
)}
{shouldShowRebootWarning && (
<Localized id="firmware_tool-flashing_step-warning">
<WarningBox>Warning</WarningBox>
</Localized>
)}
<div className="flex flex-col gap-4 h-full">
{statusKeys.length > 0 ? (
<StatusList status={status}></StatusList>
) : (
<DeviceList control={control} devices={devices}></DeviceList>
)}
{devices.length === 0 && statusKeys.length === 0 && (
<div
className={classNames(
'rounded-xl bg-background-60 justify-center flex-col items-center flex pb-10 py-5 gap-5'
)}
>
<LoaderIcon slimeState={SlimeState.JUMPY}></LoaderIcon>
<Localized id="firmware_update-looking_for_devices">
<Typography></Typography>
</Localized>
</div>
)}
</div>
</div>
</div>
<div className="h-fit w-full flex flex-col gap-2">
<Localized
id="firmware_update-changelog-title"
vars={{ version: currentFirmwareRelease?.name ?? 'unknown' }}
>
<Typography variant="main-title"></Typography>
</Localized>
<div className="overflow-y-scroll max-h-[430px] md:h-[430px] bg-background-60 rounded-lg p-4">
<Markdown
remarkPlugins={[remark]}
components={{ a: MarkdownLink }}
className={classNames(
'w-full text-sm prose-xl prose text-background-10 prose-h1:text-background-10',
'prose-h2:text-background-10 prose-a:text-background-20 prose-strong:text-background-10',
'prose-code:text-background-20'
)}
>
{currentFirmwareRelease?.changelog}
</Markdown>
</div>
</div>
</div>
<div className="flex justify-end pb-2 gap-2 mobile:flex-col">
<Localized id="firmware_update-retry">
<Button
variant="secondary"
disabled={!canRetry}
onClick={retryError}
></Button>
</Localized>
<Localized id="firmware_update-update">
<Button
variant="primary"
disabled={!canStartUpdate}
onClick={startUpdate}
></Button>
</Localized>
</div>
</div>
</div>
);
}
+4 -3
View File
@@ -51,7 +51,7 @@ export function Home() {
<div className="h-full overflow-y-auto">
<div
className={classNames(
'px-2 pt-2 gap-3 w-full grid md:grid-cols-2 mobile:grid-cols-1',
'px-3 pt-3 gap-3 w-full grid md:grid-cols-2 mobile:grid-cols-1',
filteredStatuses.filter(([, status]) => status.prioritized)
.length === 0 && 'hidden'
)}
@@ -70,7 +70,7 @@ export function Home() {
</Localized>
))}
</div>
<div className="overflow-y-auto flex flex-col gap-2">
<div className="overflow-y-auto flex flex-col gap-3">
{trackers.length === 0 && (
<div className="flex px-5 pt-5 justify-center">
<Typography variant="standard">
@@ -80,7 +80,7 @@ export function Home() {
)}
{!config?.debug && trackers.length > 0 && (
<div className="grid sm:grid-cols-1 md:grid-cols-2 gap-3 px-2 my-2">
<div className="grid sm:grid-cols-1 md:grid-cols-2 gap-4 px-5 my-5">
{trackers.map(({ tracker, device }, index) => (
<TrackerCard
key={index}
@@ -88,6 +88,7 @@ export function Home() {
device={device}
onClick={() => sendToSettings(tracker)}
smol
showUpdates
interactable
warning={Object.values(statuses).some((status) =>
trackerStatusRelated(tracker, status)
@@ -94,30 +94,42 @@ export function StepDot({
export function StepperSlider({
variant,
steps,
back,
forward,
}: {
variant: 'alone' | 'onboarding';
steps: Step[];
/**
* Ran when step is 0 and `prevStep` is executed
*/
back?: () => void;
/**
* Ran when step is `steps.length - 1` and nextStep is executed
*/
forward?: () => void;
}) {
const ref = useRef<HTMLDivElement | null>(null);
const { width } = useElemSize(ref);
const [stepsContainers, setSteps] = useState(0);
const [shouldAnimate, setShouldAnimate] = useState(true);
const [step, setStep] = useState(0);
useEffect(() => {
if (!ref.current) return;
const stepsContainers =
ref.current.getElementsByClassName('step-container');
setSteps(stepsContainers.length);
}, [ref]);
setStep((x) => Math.min(x, steps.length - 1));
}, [steps.length]);
const nextStep = () => {
if (step + 1 === stepsContainers) return;
if (step + 1 === steps.length) {
forward?.();
return;
}
setStep(step + 1);
};
const prevStep = () => {
if (step - 1 < 0) return;
if (step - 1 < 0) {
back?.();
return;
}
setStep(step - 1);
};
@@ -168,7 +180,7 @@ export function StepperSlider({
</div>
</div>
<div className="flex justify-center items-center gap-2">
{Array.from({ length: stepsContainers }).map((_, index) => (
{Array.from({ length: steps.length }).map((_, index) => (
<div key={index} className="flex items-center gap-2">
{index !== 0 && (
<div className="w-5 h-1 bg-background-50 rounded-full"></div>
@@ -3,11 +3,9 @@ import classNames from 'classnames';
import { useEffect, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
AddUnknownDeviceRequestT,
RpcMessage,
StartWifiProvisioningRequestT,
StopWifiProvisioningRequestT,
UnknownDeviceHandshakeNotificationT,
WifiProvisioningStatus,
WifiProvisioningStatusResponseT,
} from 'solarxr-protocol';
@@ -97,15 +95,6 @@ export function ConnectTrackersPage() {
}
);
useRPCPacket(
RpcMessage.UnknownDeviceHandshakeNotification,
({ macAddress }: UnknownDeviceHandshakeNotificationT) =>
sendRPCPacket(
RpcMessage.AddUnknownDeviceRequest,
new AddUnknownDeviceRequestT(macAddress)
)
);
const isError =
provisioningStatus === WifiProvisioningStatus.CONNECTION_ERROR ||
provisioningStatus === WifiProvisioningStatus.COULD_NOT_FIND_SERVER;
+1 -1
View File
@@ -13,7 +13,7 @@ export function HomePage() {
return (
<>
<div className="flex flex-col gap-5 h-full items-center w-full justify-center px-4">
<div className="flex relative flex-col gap-5 h-full items-center w-full justify-center px-4 overflow-clip">
<div className="flex flex-col gap-5 items-center z-10 scale-150 mb-20">
<SlimeVRIcon></SlimeVRIcon>
<Typography variant="mobile-title">
@@ -1,9 +1,6 @@
import { useLocalization } from '@fluent/react';
import { RpcMessage, SkeletonResetAllRequestT } from 'solarxr-protocol';
import { AutoboneContextC, useProvideAutobone } from '@/hooks/autobone';
import { useOnboarding } from '@/hooks/onboarding';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { Button } from '@/components/commons/Button';
import { Typography } from '@/components/commons/Typography';
import { StepperSlider } from '@/components/onboarding/StepperSlider';
import { DoneStep } from './autobone-steps/Done';
@@ -12,83 +9,55 @@ import { PutTrackersOnStep } from './autobone-steps/PutTrackersOn';
import { Recording } from './autobone-steps/Recording';
import { StartRecording } from './autobone-steps/StartRecording';
import { VerifyResultsStep } from './autobone-steps/VerifyResults';
import { useCountdown } from '@/hooks/countdown';
import { CheckHeight } from './autobone-steps/CheckHeight';
import { CheckHeightStep } from './autobone-steps/CheckHeight';
import { PreparationStep } from './autobone-steps/Preparation';
import { useState } from 'react';
import { ProportionsResetModal } from './ProportionsResetModal';
import { HeightContextC, useProvideHeightContext } from '@/hooks/height';
import { CheckFloorHeightStep } from './autobone-steps/CheckFloorHeight';
export function AutomaticProportionsPage() {
const { l10n } = useLocalization();
const { applyProgress, state } = useOnboarding();
const { sendRPCPacket } = useWebsocketAPI();
const context = useProvideAutobone();
const { isCounting, startCountdown, timer } = useCountdown({
onCountdownEnd: () => {
sendRPCPacket(
RpcMessage.SkeletonResetAllRequest,
new SkeletonResetAllRequestT()
);
},
});
const [showWarning, setShowWarning] = useState(false);
const heightContext = useProvideHeightContext();
applyProgress(0.9);
return (
<AutoboneContextC.Provider value={context}>
<div className="flex flex-col gap-5 h-full items-center w-full xs:justify-center overflow-y-auto overflow-x-hidden relative px-4 pb-4">
<div className="flex flex-col w-full xs:h-full xs:justify-center max-w-3xl gap-5">
<div className="flex flex-col max-w-lg gap-3">
<Typography variant="main-title">
{l10n.getString('onboarding-automatic_proportions-title')}
</Typography>
<div>
<Typography color="secondary">
{l10n.getString('onboarding-automatic_proportions-description')}
<HeightContextC.Provider value={heightContext}>
<div className="flex flex-col gap-5 h-full items-center w-full xs:justify-center overflow-y-auto overflow-x-hidden relative px-4 pb-4">
<div className="flex flex-col w-full xs:h-full xs:justify-center max-w-3xl gap-5">
<div className="flex flex-col max-w-lg gap-3">
<Typography variant="main-title">
{l10n.getString('onboarding-automatic_proportions-title')}
</Typography>
</div>
</div>
<div className="flex">
<StepperSlider
variant={state.alonePage ? 'alone' : 'onboarding'}
steps={[
{ type: 'numbered', component: PutTrackersOnStep },
{ type: 'numbered', component: PreparationStep },
{ type: 'numbered', component: RequirementsStep },
{ type: 'numbered', component: CheckHeight },
{ type: 'numbered', component: StartRecording },
{ type: 'fullsize', component: Recording },
{ type: 'numbered', component: VerifyResultsStep },
{ type: 'fullsize', component: DoneStep },
]}
></StepperSlider>
</div>
</div>
<div className="w-full pb-4 flex flex-row mobile:justify-center">
<Button
variant="secondary"
onClick={() => setShowWarning(true)}
disabled={isCounting}
>
<div className="relative">
<div className="opacity-0 h-0">
{l10n.getString('reset-reset_all')}
<div>
<Typography color="secondary">
{l10n.getString(
'onboarding-automatic_proportions-description'
)}
</Typography>
</div>
{!isCounting ? l10n.getString('reset-reset_all') : timer}
</div>
</Button>
<div className="flex">
<StepperSlider
variant={state.alonePage ? 'alone' : 'onboarding'}
steps={[
{ type: 'numbered', component: PutTrackersOnStep },
{ type: 'numbered', component: RequirementsStep },
{ type: 'numbered', component: CheckHeightStep },
{ type: 'numbered', component: CheckFloorHeightStep },
{ type: 'numbered', component: PreparationStep },
{ type: 'numbered', component: StartRecording },
{ type: 'fullsize', component: Recording },
{ type: 'numbered', component: VerifyResultsStep },
{ type: 'fullsize', component: DoneStep },
]}
></StepperSlider>
</div>
</div>
</div>
<ProportionsResetModal
accept={() => {
startCountdown();
setShowWarning(false);
}}
onClose={() => setShowWarning(false)}
isOpen={showWarning}
></ProportionsResetModal>
</div>
</HeightContextC.Provider>
</AutoboneContextC.Provider>
);
}
@@ -1,6 +1,6 @@
import { useOnboarding } from '@/hooks/onboarding';
import { Localized, useLocalization } from '@fluent/react';
import { useMemo, useState } from 'react';
import { useMemo, useRef, useState } from 'react';
import classNames from 'classnames';
import { Typography } from '@/components/commons/Typography';
import { Button } from '@/components/commons/Button';
@@ -9,6 +9,7 @@ import {
SkeletonConfigRequestT,
SkeletonBone,
ChangeSkeletonConfigRequestT,
SkeletonResetAllRequestT,
} from 'solarxr-protocol';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { save } from '@tauri-apps/plugin-dialog';
@@ -18,6 +19,7 @@ import { useAppContext } from '@/hooks/app';
import { error } from '@/utils/logging';
import { fileOpen, fileSave } from 'browser-fs-access';
import { useDebouncedEffect } from '@/hooks/timeout';
import { ProportionsResetModal } from './ProportionsResetModal';
export const MIN_HEIGHT = 0.4;
export const MAX_HEIGHT = 4;
@@ -36,7 +38,9 @@ export function ProportionsChoose() {
const { applyProgress, state } = useOnboarding();
const { useRPCPacket, sendRPCPacket } = useWebsocketAPI();
const [animated, setAnimated] = useState(false);
const [showProportionWarning, setShowProportionWarning] = useState(false);
const [importState, setImportState] = useState(ImportStatus.OK);
const exporting = useRef(false);
const { computedTrackers } = useAppContext();
useDebouncedEffect(
@@ -78,6 +82,8 @@ export function ProportionsChoose() {
useRPCPacket(
RpcMessage.SkeletonConfigResponse,
(data: SkeletonConfigExport) => {
if (!exporting.current) return;
exporting.current = false;
// Convert the skeleton part enums into a string
data.skeletonParts.forEach((x) => {
if (typeof x.bone === 'number')
@@ -151,6 +157,13 @@ export function ProportionsChoose() {
setImportState(ImportStatus.SUCCESS);
};
const resetAll = () => {
sendRPCPacket(
RpcMessage.SkeletonResetAllRequest,
new SkeletonResetAllRequestT()
);
};
return (
<>
<div className="flex flex-col gap-5 h-full items-center w-full xs:justify-center mobile:overflow-y-auto relative px-4 pb-4">
@@ -217,62 +230,122 @@ export function ProportionsChoose() {
</Button>
</div>
</div>
<div
className={classNames(
'rounded-lg p-4 flex flex-row relative',
!state.alonePage && 'bg-background-70',
state.alonePage && 'bg-background-60'
)}
>
<div className="flex flex-col gap-4">
<div className="flex flex-grow flex-col gap-4 max-w-sm">
<img
onMouseEnter={() => setAnimated(() => true)}
onAnimationEnd={() => setAnimated(() => false)}
src="/images/slimetower.webp"
className={classNames(
'absolute w-[100px] -right-2 -top-24',
animated && 'animate-[bounce_1s_1]'
)}
></img>
<div>
<Typography variant="main-title" bold>
{l10n.getString(
'onboarding-choose_proportions-auto_proportions'
{state.alonePage && (
<div
className={classNames(
'rounded-lg p-4 flex flex-row relative',
!state.alonePage && 'bg-background-70',
state.alonePage && 'bg-background-60'
)}
>
<div className="flex flex-col gap-4">
<div className="flex flex-grow flex-col gap-4 max-w-sm">
<img
onMouseEnter={() => setAnimated(() => true)}
onAnimationEnd={() => setAnimated(() => false)}
src="/images/slimetower.webp"
className={classNames(
'absolute w-[100px] -right-2 -top-24',
animated && 'animate-[bounce_1s_1]'
)}
</Typography>
<Typography variant="vr-accessible" italic>
{l10n.getString(
'onboarding-choose_proportions-auto_proportions-subtitle'
)}
</Typography>
</div>
<div>
<Localized
id="onboarding-choose_proportions-auto_proportions-descriptionv3"
elems={{ b: <b></b> }}
>
<Typography
color="secondary"
whitespace="whitespace-pre-line"
>
Description for autobone
></img>
<div>
<Typography variant="main-title" bold>
{l10n.getString(
'onboarding-choose_proportions-auto_proportions'
)}
</Typography>
</Localized>
<Typography variant="vr-accessible" italic>
{l10n.getString(
'onboarding-choose_proportions-auto_proportions-subtitle'
)}
</Typography>
</div>
<div>
<Localized
id="onboarding-choose_proportions-auto_proportions-descriptionv3"
elems={{ b: <b></b> }}
>
<Typography
color="secondary"
whitespace="whitespace-pre-line"
>
Description for autobone
</Typography>
</Localized>
</div>
</div>
<Button
variant="primary"
// Check if we are in dev mode and just let it be used
disabled={beneathFloor && import.meta.env.PROD}
to="/onboarding/body-proportions/auto"
className="self-start mt-auto"
state={{ alonePage: state.alonePage }}
>
{l10n.getString('onboarding-manual_proportions-auto')}
</Button>
</div>
<Button
variant="primary"
// Check if we are in dev mode and just let it be used
disabled={beneathFloor && import.meta.env.PROD}
to="/onboarding/body-proportions/auto"
className="self-start mt-auto"
state={{ alonePage: state.alonePage }}
>
{l10n.getString('onboarding-manual_proportions-auto')}
</Button>
</div>
</div>
)}
{!state.alonePage && (
<div
className={classNames(
'rounded-lg p-4 flex flex-row relative',
!state.alonePage && 'bg-background-70',
state.alonePage && 'bg-background-60'
)}
>
<div className="flex flex-col gap-4">
<div className="flex flex-grow flex-col gap-4 max-w-sm">
<img
onMouseEnter={() => setAnimated(() => true)}
onAnimationEnd={() => setAnimated(() => false)}
src="/images/slimetower.webp"
className={classNames(
'absolute w-[100px] -right-2 -top-24',
animated && 'animate-[bounce_1s_1]'
)}
></img>
<div>
<Typography variant="main-title" bold>
{l10n.getString(
'onboarding-choose_proportions-scaled_proportions'
)}
</Typography>
<Typography variant="vr-accessible" italic>
{l10n.getString(
'onboarding-choose_proportions-scaled_proportions-subtitle'
)}
</Typography>
</div>
<div>
<Localized
id="onboarding-choose_proportions-scaled_proportions-description"
elems={{ b: <b></b> }}
>
<Typography
color="secondary"
whitespace="whitespace-pre-line"
>
Description for scaled proportions
</Typography>
</Localized>
</div>
</div>
<Button
variant="primary"
to="/onboarding/body-proportions/scaled"
className="self-start mt-auto"
state={{ alonePage: state.alonePage }}
>
{l10n.getString(
'onboarding-choose_proportions-scaled_proportions-button'
)}
</Button>
</div>
</div>
)}
</div>
<div className="flex flex-row gap-3">
{!state.alonePage && (
@@ -280,15 +353,33 @@ export function ProportionsChoose() {
{l10n.getString('onboarding-previous_step')}
</Button>
)}
{state.alonePage && (
<Button
variant="secondary"
onClick={() => setShowProportionWarning(true)}
>
{l10n.getString('reset-reset_all')}
</Button>
)}
<ProportionsResetModal
accept={() => {
resetAll();
setShowProportionWarning(false);
}}
onClose={() => setShowProportionWarning(false)}
isOpen={showProportionWarning}
></ProportionsResetModal>
<Button
variant={!state.alonePage ? 'secondary' : 'tertiary'}
className="ml-auto"
onClick={() =>
onClick={() => {
exporting.current = true;
sendRPCPacket(
RpcMessage.SkeletonConfigRequest,
new SkeletonConfigRequestT()
)
}
);
}}
>
{l10n.getString('onboarding-choose_proportions-export')}
</Button>
@@ -3,6 +3,13 @@ import { WarningBox } from '@/components/commons/TipBox';
import { Localized, useLocalization } from '@fluent/react';
import { BaseModal } from '@/components/commons/BaseModal';
import ReactModal from 'react-modal';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { useEffect, useState } from 'react';
import {
RpcMessage,
SettingsRequestT,
SettingsResponseT,
} from 'solarxr-protocol';
export function ProportionsResetModal({
isOpen = true,
@@ -24,6 +31,16 @@ export function ProportionsResetModal({
accept: () => void;
} & ReactModal.Props) {
const { l10n } = useLocalization();
const { useRPCPacket, sendRPCPacket } = useWebsocketAPI();
const [usingDefaultHeight, setUsingDefaultHeight] = useState(true);
useEffect(
() => sendRPCPacket(RpcMessage.SettingsRequest, new SettingsRequestT()),
[]
);
useRPCPacket(RpcMessage.SettingsResponse, (res: SettingsResponseT) =>
setUsingDefaultHeight(!res.modelSettings?.skeletonHeight?.hmdHeight)
);
return (
<BaseModal
@@ -35,7 +52,14 @@ export function ProportionsResetModal({
>
<div className="flex w-full h-full flex-col ">
<div className="flex flex-col flex-grow items-center gap-3">
<Localized id="reset-reset_all_warning" elems={{ b: <b></b> }}>
<Localized
id={
usingDefaultHeight
? 'reset-reset_all_warning_default'
: 'reset-reset_all_warning'
}
elems={{ b: <b></b> }}
>
<WarningBox>
<b>Warning:</b> This will reset your proportions to being just
based on your height.
@@ -0,0 +1,75 @@
import { useLocalization } from '@fluent/react';
import { useOnboarding } from '@/hooks/onboarding';
import { Typography } from '@/components/commons/Typography';
import { StepperSlider } from '@/components/onboarding/StepperSlider';
import { CheckHeightStep } from './autobone-steps/CheckHeight';
import { HeightContextC, useProvideHeightContext } from '@/hooks/height';
import { CheckFloorHeightStep } from './autobone-steps/CheckFloorHeight';
import { ResetProportionsStep } from './scaled-steps/ResetProportions';
import { DoneStep } from './scaled-steps/Done';
import { useNavigate } from 'react-router-dom';
import { useMemo } from 'react';
import { ManualHeightStep } from './scaled-steps/ManualHeightStep';
import { useTrackers } from '@/hooks/tracker';
import { BodyPart } from 'solarxr-protocol';
export function ScaledProportionsPage() {
const { l10n } = useLocalization();
const { applyProgress, state } = useOnboarding();
const heightContext = useProvideHeightContext();
const navigate = useNavigate();
const { trackers } = useTrackers();
const hmdTracker = useMemo(
() =>
trackers.some(
(tracker) =>
tracker.tracker.info?.bodyPart === BodyPart.HEAD &&
(tracker.tracker.info.isHmd || tracker.tracker.position?.y)
),
[trackers]
);
applyProgress(0.9);
return (
<HeightContextC.Provider value={heightContext}>
<div className="flex flex-col gap-5 h-full items-center w-full xs:justify-center overflow-y-auto overflow-x-hidden relative px-4 pb-4">
<div className="flex flex-col w-full xs:h-full xs:justify-center max-w-3xl gap-5">
<div className="flex flex-col max-w-lg gap-3">
<Typography variant="main-title">
{l10n.getString('onboarding-scaled_proportions-title')}
</Typography>
<div>
<Typography color="secondary">
{l10n.getString('onboarding-scaled_proportions-description')}
</Typography>
</div>
</div>
<div className="flex">
<StepperSlider
variant={state.alonePage ? 'alone' : 'onboarding'}
steps={
!hmdTracker
? [
{ type: 'numbered', component: ManualHeightStep },
{ type: 'numbered', component: ResetProportionsStep },
{ type: 'fullsize', component: DoneStep },
]
: [
{ type: 'numbered', component: CheckHeightStep },
{ type: 'numbered', component: CheckFloorHeightStep },
{ type: 'numbered', component: ResetProportionsStep },
{ type: 'fullsize', component: DoneStep },
]
}
back={() =>
navigate('/onboarding/body-proportions/choose', { state })
}
></StepperSlider>
</div>
</div>
</div>
</HeightContextC.Provider>
);
}
@@ -0,0 +1,207 @@
import {
ChangeSettingsRequestT,
HeightRequestT,
HeightResponseT,
ModelSettingsT,
RpcMessage,
SkeletonHeightT,
} from 'solarxr-protocol';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { Button } from '@/components/commons/Button';
import { Typography } from '@/components/commons/Typography';
import { Localized, useLocalization } from '@fluent/react';
import { useEffect, useMemo, useState } from 'react';
import { useLocaleConfig } from '@/i18n/config';
import { useHeightContext } from '@/hooks/height';
import { useInterval } from '@/hooks/timeout';
import { TooSmolModal } from './TooSmolModal';
export function CheckFloorHeightStep({
nextStep,
prevStep,
variant,
}: {
nextStep: () => void;
prevStep: () => void;
variant: 'onboarding' | 'alone';
}) {
const { l10n } = useLocalization();
const { floorHeight, hmdHeight, setFloorHeight, validateHeight } =
useHeightContext();
const [fetchHeight, setFetchHeight] = useState(false);
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const [isOpen, setOpen] = useState(false);
const { currentLocales } = useLocaleConfig();
useEffect(() => setFloorHeight(0), []);
useInterval(() => {
if (fetchHeight) {
sendRPCPacket(RpcMessage.HeightRequest, new HeightRequestT());
}
}, 100);
const mFormat = useMemo(
() =>
new Intl.NumberFormat(currentLocales, {
style: 'unit',
unit: 'meter',
maximumFractionDigits: 2,
}),
[currentLocales]
);
useRPCPacket(RpcMessage.HeightResponse, ({ minHeight }: HeightResponseT) => {
if (fetchHeight) {
setFloorHeight((val) =>
val === null ? minHeight : Math.min(minHeight, val)
);
}
});
return (
<>
<div className="flex flex-col">
<div className="flex flex-grow">
<div className="flex flex-grow flex-col gap-4">
<Typography variant="main-title" bold>
{l10n.getString(
'onboarding-automatic_proportions-check_floor_height-title'
)}
</Typography>
<div>
<Typography color="secondary">
{l10n.getString(
'onboarding-automatic_proportions-check_floor_height-description'
)}
</Typography>
<Localized
id="onboarding-automatic_proportions-check_floor_height-calculation_warning"
elems={{ u: <span className="underline"></span> }}
>
<Typography color="secondary" bold>
Press the button to get your height!
</Typography>
</Localized>
</div>
<div className="flex flex-grow items-center justify-center">
<div className="flex flex-col gap-3 items-center">
{!fetchHeight && (
<Button
variant="primary"
onClick={() => {
setFloorHeight(null);
setFetchHeight(true);
}}
>
<Typography textAlign="text-center">
{l10n.getString(
floorHeight !== null
? 'onboarding-automatic_proportions-check_floor_height-measure-reset'
: 'onboarding-automatic_proportions-check_floor_height-measure-start'
)}
</Typography>
</Button>
)}
{fetchHeight && (
<Button
variant="primary"
onClick={() => {
setFetchHeight(false);
}}
>
<Typography textAlign="text-center">
{l10n.getString(
'onboarding-automatic_proportions-check_floor_height-measure-stop'
)}
</Typography>
</Button>
)}
<Typography>
{l10n.getString(
'onboarding-automatic_proportions-check_floor_height-floor_height'
)}
</Typography>
<Typography
color={fetchHeight ? 'text-status-success' : undefined}
>
{floorHeight === null
? l10n.getString(
'onboarding-automatic_proportions-check_height-unknown'
)
: mFormat.format(floorHeight)}
</Typography>
</div>
</div>
</div>
{/* TODO: Get image of person putting controller in floor */}
{/* <div className="self-center">
<img
src="/images/front-standing-pose.webp"
width={isMobile ? 400 : 300}
alt="Reset position"
/>
</div> */}
</div>
<div className="flex gap-3 mobile:justify-between">
<Button
variant={variant === 'onboarding' ? 'secondary' : 'tertiary'}
onClick={prevStep}
>
{l10n.getString('onboarding-automatic_proportions-prev_step')}
</Button>
<Button
variant={variant === 'onboarding' ? 'secondary' : 'tertiary'}
disabled={hmdHeight === null || fetchHeight}
onClick={() => {
if (!validateHeight(hmdHeight, 0)) {
setOpen(true);
return;
}
setFloorHeight(0);
const settingsRequest = new ChangeSettingsRequestT();
settingsRequest.modelSettings = new ModelSettingsT(
null,
null,
null,
new SkeletonHeightT(hmdHeight, 0)
);
sendRPCPacket(RpcMessage.ChangeSettingsRequest, settingsRequest);
nextStep();
}}
>
{l10n.getString(
'onboarding-automatic_proportions-check_floor_height-skip_step'
)}
</Button>
<Button
variant="primary"
onClick={() => {
if (!validateHeight(hmdHeight, floorHeight)) {
setOpen(true);
return;
}
const settingsRequest = new ChangeSettingsRequestT();
settingsRequest.modelSettings = new ModelSettingsT(
null,
null,
null,
new SkeletonHeightT(hmdHeight, floorHeight)
);
sendRPCPacket(RpcMessage.ChangeSettingsRequest, settingsRequest);
nextStep();
}}
disabled={floorHeight === null || hmdHeight === null || fetchHeight}
>
{l10n.getString(
'onboarding-automatic_proportions-check_floor_height-next_step'
)}
</Button>
</div>
</div>
<TooSmolModal isOpen={isOpen} onClose={() => setOpen(false)} />
</>
);
}
@@ -1,27 +1,15 @@
import {
AutoBoneSettingsT,
ChangeSettingsRequestT,
HeightRequestT,
HeightResponseT,
RpcMessage,
} from 'solarxr-protocol';
import { HeightRequestT, HeightResponseT, RpcMessage } from 'solarxr-protocol';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { Button } from '@/components/commons/Button';
import { Typography } from '@/components/commons/Typography';
import { Localized, useLocalization } from '@fluent/react';
import { useForm } from 'react-hook-form';
import { useMemo, useState } from 'react';
import { NumberSelector } from '@/components/commons/NumberSelector';
import { MIN_HEIGHT } from '@/components/onboarding/pages/body-proportions/ProportionsChoose';
import { useLocaleConfig } from '@/i18n/config';
import { useCountdown } from '@/hooks/countdown';
import { TipBox } from '@/components/commons/TipBox';
import { useHeightContext } from '@/hooks/height';
import { useInterval } from '@/hooks/timeout';
interface HeightForm {
hmdHeight: number;
}
export function CheckHeight({
export function CheckHeightStep({
nextStep,
prevStep,
variant,
@@ -31,18 +19,17 @@ export function CheckHeight({
variant: 'onboarding' | 'alone';
}) {
const { l10n } = useLocalization();
const { control, handleSubmit, setValue } = useForm<HeightForm>();
const [fetchedHeight, setFetchedHeight] = useState(false);
const { hmdHeight, setHmdHeight } = useHeightContext();
const [fetchHeight, setFetchHeight] = useState(false);
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const { timer, isCounting, startCountdown } = useCountdown({
duration: 3,
onCountdownEnd: () => {
setFetchedHeight(true);
sendRPCPacket(RpcMessage.HeightRequest, new HeightRequestT());
},
});
const { currentLocales } = useLocaleConfig();
useInterval(() => {
if (fetchHeight) {
sendRPCPacket(RpcMessage.HeightRequest, new HeightRequestT());
}
}, 100);
const mFormat = useMemo(
() =>
new Intl.NumberFormat(currentLocales, {
@@ -53,88 +40,103 @@ export function CheckHeight({
[currentLocales]
);
const sFormat = useMemo(
() => new Intl.RelativeTimeFormat(currentLocales, { style: 'short' }),
[currentLocales]
);
useRPCPacket(RpcMessage.HeightResponse, ({ hmdHeight }: HeightResponseT) => {
setValue('hmdHeight', hmdHeight);
useRPCPacket(RpcMessage.HeightResponse, ({ maxHeight }: HeightResponseT) => {
if (fetchHeight) {
setHmdHeight((val) =>
val === null ? maxHeight : Math.max(maxHeight, val)
);
}
});
const onSubmit = (values: HeightForm) => {
const changeSettings = new ChangeSettingsRequestT();
const autobone = new AutoBoneSettingsT();
autobone.targetHmdHeight = values.hmdHeight;
changeSettings.autoBoneSettings = autobone;
sendRPCPacket(RpcMessage.ChangeSettingsRequest, changeSettings);
nextStep();
};
return (
<>
<div className="flex flex-col flex-grow">
<div className="flex flex-grow flex-col gap-4">
<Typography variant="main-title" bold>
{l10n.getString(
'onboarding-automatic_proportions-check_height-title'
)}
</Typography>
<div>
<Typography color="secondary">
<div className="flex gap-2 flex-grow">
<div className="flex flex-grow flex-col gap-4">
<Typography variant="main-title" bold>
{l10n.getString(
'onboarding-automatic_proportions-check_height-description'
'onboarding-automatic_proportions-check_height-title-v2'
)}
</Typography>
<Localized
id="onboarding-automatic_proportions-check_height-calculation_warning"
elems={{ u: <span className="underline"></span> }}
>
<Typography color="secondary" bold>
Press the button to get your height!
</Typography>
</Localized>
<div className="flex flex-row items-center mt-2 gap-2 mobile:flex-col">
<Button
variant="primary"
onClick={startCountdown}
disabled={isCounting}
>
{isCounting
? sFormat.format(timer, 'second')
: l10n.getString(
'onboarding-automatic_proportions-check_height-fetch_height'
)}
</Button>
<TipBox className="break-words">
<div>
<Typography color="secondary">
{l10n.getString(
'onboarding-automatic_proportions-check_height-guardian_tip'
'onboarding-automatic_proportions-check_height-description-v2'
)}
</TipBox>
</Typography>
<Localized
id="onboarding-automatic_proportions-check_height-calculation_warning-v2"
elems={{ u: <span className="underline"></span> }}
>
<Typography color="secondary" bold>
Press the button to get your height!
</Typography>
</Localized>
<div className="flex flex-row items-center mt-2 gap-2 mobile:flex-col">
<TipBox className="break-words">
{l10n.getString(
'onboarding-automatic_proportions-check_height-guardian_tip'
)}
</TipBox>
</div>
</div>
<div className="flex flex-grow items-center justify-center">
<div className="flex flex-col gap-3 items-center">
{!fetchHeight && (
<Button
variant="primary"
onClick={() => {
setHmdHeight(null);
setFetchHeight(true);
}}
>
<Typography textAlign="text-center">
{l10n.getString(
hmdHeight !== null
? 'onboarding-automatic_proportions-check_height-measure-reset'
: 'onboarding-automatic_proportions-check_height-measure-start'
)}
</Typography>
</Button>
)}
{fetchHeight && (
<Button
variant="primary"
onClick={() => {
setFetchHeight(false);
}}
>
<Typography textAlign="text-center">
{l10n.getString(
'onboarding-automatic_proportions-check_height-measure-stop'
)}
</Typography>
</Button>
)}
<Typography>
{l10n.getString(
'onboarding-automatic_proportions-check_height-hmd_height2'
)}
</Typography>
<Typography
color={fetchHeight ? 'text-status-success' : undefined}
>
{hmdHeight === null
? l10n.getString(
'onboarding-automatic_proportions-check_height-unknown'
)
: mFormat.format(hmdHeight)}
</Typography>
</div>
</div>
</div>
<form className="flex flex-col self-center items-center justify-center">
<NumberSelector
control={control}
name="hmdHeight"
label={l10n.getString(
'onboarding-automatic_proportions-check_height-hmd_height1'
)}
valueLabelFormat={(value) =>
isNaN(value)
? l10n.getString(
'onboarding-automatic_proportions-check_height-unknown'
)
: mFormat.format(value)
}
min={MIN_HEIGHT}
max={4}
step={0.01}
disabled={true}
<div className="self-center">
<img
src="/images/front-standing-pose.webp"
className="mobile:w-[150px] min-w-[120px] w-[34vh]"
alt="Reset position"
/>
</form>
</div>
</div>
<div className="flex gap-3 mobile:justify-between">
@@ -146,8 +148,8 @@ export function CheckHeight({
</Button>
<Button
variant="primary"
onClick={handleSubmit(onSubmit)}
disabled={!fetchedHeight}
onClick={nextStep}
disabled={hmdHeight === null || fetchHeight}
>
{l10n.getString(
'onboarding-automatic_proportions-check_height-next_step'
@@ -41,7 +41,7 @@ export function PreparationStep({
<div className="flex flex-col pt-1 items-center fill-background-50 justify-center px-12">
<img
src="/images/reset-pose.webp"
width={100}
width={50}
alt="Reset position"
/>
</div>
@@ -0,0 +1,73 @@
import { BaseModal } from '@/components/commons/BaseModal';
import { Button } from '@/components/commons/Button';
import { WarningBox } from '@/components/commons/TipBox';
import { useHeightContext } from '@/hooks/height';
import { useLocaleConfig } from '@/i18n/config';
import { Localized, useLocalization } from '@fluent/react';
import { useMemo } from 'react';
import { MIN_HEIGHT } from '@/components/onboarding/pages/body-proportions/ProportionsChoose';
export function TooSmolModal({
isOpen = true,
onClose,
...props
}: {
/**
* Is the parent/sibling component opened?
*/
isOpen: boolean;
/**
* Function to trigger when the warning hasn't been accepted
*/
onClose: () => void;
} & ReactModal.Props) {
const { l10n } = useLocalization();
const { hmdHeight, floorHeight } = useHeightContext();
const { currentLocales } = useLocaleConfig();
const mFormat = useMemo(
() =>
new Intl.NumberFormat(currentLocales, {
style: 'unit',
unit: 'meter',
maximumFractionDigits: 2,
}),
[currentLocales]
);
return (
<BaseModal
isOpen={isOpen}
shouldCloseOnOverlayClick
shouldCloseOnEsc
onRequestClose={onClose}
className={props.className}
overlayClassName={props.overlayClassName}
>
<div className="flex w-full h-full flex-col ">
<div className="flex flex-col flex-grow items-center gap-3">
<Localized
id="onboarding-automatic_proportions-smol_warning"
elems={{ b: <b></b> }}
vars={{
height: mFormat.format(hmdHeight ?? 0 - (floorHeight ?? 0)),
minHeight: mFormat.format(MIN_HEIGHT),
}}
>
<WarningBox whitespace>
<b>Warning:</b> You are too smol to continue
</WarningBox>
</Localized>
<div className="flex flex-col gap-3 pt-5 place-content-center">
<Button variant="primary" onClick={onClose}>
{l10n.getString(
'onboarding-automatic_proportions-smol_warning-cancel'
)}
</Button>
</div>
</div>
</div>
</BaseModal>
);
}
@@ -0,0 +1,30 @@
import { Typography } from '@/components/commons/Typography';
import { useLocalization } from '@fluent/react';
import { Button } from '@/components/commons/Button';
import { SkeletonVisualizerWidget } from '@/components/widgets/SkeletonVisualizerWidget';
export function DoneStep({ variant }: { variant: 'onboarding' | 'alone' }) {
const { l10n } = useLocalization();
return (
<div className="flex flex-col items-center w-full justify-center gap-5">
<div className="flex gap-2 flex-col justify-center items-center">
<Typography variant="section-title">
{l10n.getString('onboarding-scaled_proportions-done-title')}
</Typography>
<Typography color="secondary">
{l10n.getString('onboarding-scaled_proportions-done-description')}
</Typography>
</div>
<div className="flex gap-3">
{variant === 'onboarding' && (
<Button variant="primary" to="/onboarding/done">
{l10n.getString('onboarding-continue')}
</Button>
)}
</div>
<SkeletonVisualizerWidget />
</div>
);
}
@@ -0,0 +1,158 @@
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { Button } from '@/components/commons/Button';
import { Typography } from '@/components/commons/Typography';
import { Localized, useLocalization } from '@fluent/react';
import { useMemo } from 'react';
import { useLocaleConfig } from '@/i18n/config';
import { useHeightContext } from '@/hooks/height';
import { useForm } from 'react-hook-form';
import {
ChangeSettingsRequestT,
ModelSettingsT,
RpcMessage,
SkeletonHeightT,
StatusData,
StatusSteamVRDisconnectedT,
} from 'solarxr-protocol';
import { NumberSelector } from '@/components/commons/NumberSelector';
import { MIN_HEIGHT } from '@/components/onboarding/pages/body-proportions/ProportionsChoose';
import { WarningBox } from '@/components/commons/TipBox';
import { useStatusContext } from '@/hooks/status-system';
interface HeightForm {
height: number;
}
export function ManualHeightStep({
nextStep,
prevStep,
variant,
}: {
nextStep: () => void;
prevStep: () => void;
variant: 'onboarding' | 'alone';
}) {
const { l10n } = useLocalization();
const { hmdHeight, setHmdHeight } = useHeightContext();
const { control, handleSubmit } = useForm<HeightForm>({
defaultValues: { height: 1.5 },
});
const { sendRPCPacket } = useWebsocketAPI();
const { currentLocales } = useLocaleConfig();
const { statuses } = useStatusContext();
const missingSteamConnection = useMemo(
() =>
Object.values(statuses).some(
(x) =>
x.dataType === StatusData.StatusSteamVRDisconnected &&
(x.data as StatusSteamVRDisconnectedT).bridgeSettingsName ===
'steamvr'
),
[statuses]
);
const mFormat = useMemo(
() =>
new Intl.NumberFormat(currentLocales, {
style: 'unit',
unit: 'meter',
maximumFractionDigits: 2,
}),
[currentLocales]
);
handleSubmit((values) => {
setHmdHeight(values.height);
});
return (
<>
<div className="flex flex-col flex-grow">
<div className="flex gap-2 flex-grow">
<div className="flex flex-grow flex-col gap-4">
<Typography variant="main-title" bold>
{l10n.getString(
'onboarding-scaled_proportions-manual_height-title'
)}
</Typography>
<div>
<Typography color="secondary">
{l10n.getString(
'onboarding-scaled_proportions-manual_height-description'
)}
</Typography>
{/* <Localized
id="onboarding-scaled_proportions-manual_height-warning"
elems={{ u: <span className="underline"></span> }}
>
<Typography color="secondary" bold>
Input your height manually!
</Typography>
</Localized> */}
{missingSteamConnection && (
<div className="flex flex-row items-center mt-2 gap-2 mobile:flex-col">
<Localized
id="onboarding-scaled_proportions-manual_height-missing_steamvr"
elems={{ b: <b></b> }}
// TODO: Add link to docs!
>
<WarningBox>You don't have SteamVR connected!</WarningBox>
</Localized>
</div>
)}
</div>
<form className="flex flex-col self-center items-center justify-center">
<NumberSelector
control={control}
name="height"
label={l10n.getString(
'onboarding-scaled_proportions-manual_height-height'
)}
valueLabelFormat={(value) =>
isNaN(value)
? l10n.getString(
'onboarding-scaled_proportions-manual_height-unknown'
)
: mFormat.format(value)
}
min={MIN_HEIGHT}
max={4}
step={0.01}
showButtonWithNumber
doubleStep={0.1}
/>
</form>
</div>
</div>
<div className="flex gap-3 mobile:justify-between">
<Button
variant={variant === 'onboarding' ? 'secondary' : 'tertiary'}
onClick={prevStep}
>
{l10n.getString('onboarding-automatic_proportions-prev_step')}
</Button>
<Button
variant="primary"
onClick={() => {
const settingsRequest = new ChangeSettingsRequestT();
settingsRequest.modelSettings = new ModelSettingsT(
null,
null,
null,
new SkeletonHeightT(hmdHeight, 0)
);
sendRPCPacket(RpcMessage.ChangeSettingsRequest, settingsRequest);
nextStep();
}}
>
{l10n.getString(
'onboarding-scaled_proportions-manual_height-next_step'
)}
</Button>
</div>
</div>
</>
);
}
@@ -0,0 +1,62 @@
import { RpcMessage, SkeletonResetAllRequestT } from 'solarxr-protocol';
import { Button } from '@/components/commons/Button';
import { Typography } from '@/components/commons/Typography';
import { useLocalization } from '@fluent/react';
import { useWebsocketAPI } from '@/hooks/websocket-api';
export function ResetProportionsStep({
nextStep,
prevStep,
variant,
}: {
nextStep: () => void;
prevStep: () => void;
variant: 'onboarding' | 'alone';
}) {
const { l10n } = useLocalization();
const { sendRPCPacket } = useWebsocketAPI();
return (
<>
<div className="flex flex-col flex-grow">
<div className="flex flex-grow flex-col gap-4 max-w-sm">
<Typography variant="main-title" bold>
{l10n.getString(
'onboarding-scaled_proportions-reset_proportion-title'
)}
</Typography>
<div>
<Typography color="secondary">
{l10n.getString(
'onboarding-scaled_proportions-reset_proportion-description'
)}
</Typography>
</div>
</div>
<div className="flex flex-col gap-3">
<div className="flex gap-3 mobile:justify-between">
<Button
variant={variant === 'onboarding' ? 'secondary' : 'tertiary'}
onClick={prevStep}
>
{l10n.getString('onboarding-automatic_proportions-prev_step')}
</Button>
<Button
variant="secondary"
onClick={() => {
sendRPCPacket(
RpcMessage.SkeletonResetAllRequest,
new SkeletonResetAllRequestT()
);
nextStep();
}}
>
{l10n.getString('reset-reset_all')}
</Button>
</div>
</div>
</div>
</>
);
}
@@ -98,10 +98,10 @@ export const mapPart: Record<
<FootIcon width={width} flipped></FootIcon>
),
[BodyPart.WAIST]: ({ width }) => <FootIcon width={width}></FootIcon>,
[BodyPart.LEFT_THUMB_PROXIMAL]: ({ width }) => (
[BodyPart.LEFT_THUMB_METACARPAL]: ({ width }) => (
<FingersIcon width={width}></FingersIcon>
),
[BodyPart.LEFT_THUMB_INTERMEDIATE]: ({ width }) => (
[BodyPart.LEFT_THUMB_PROXIMAL]: ({ width }) => (
<FingersIcon width={width}></FingersIcon>
),
[BodyPart.LEFT_THUMB_DISTAL]: ({ width }) => (
@@ -143,10 +143,10 @@ export const mapPart: Record<
[BodyPart.LEFT_LITTLE_DISTAL]: ({ width }) => (
<FingersIcon width={width}></FingersIcon>
),
[BodyPart.RIGHT_THUMB_PROXIMAL]: ({ width }) => (
[BodyPart.RIGHT_THUMB_METACARPAL]: ({ width }) => (
<FingersIcon width={width}></FingersIcon>
),
[BodyPart.RIGHT_THUMB_INTERMEDIATE]: ({ width }) => (
[BodyPart.RIGHT_THUMB_PROXIMAL]: ({ width }) => (
<FingersIcon width={width}></FingersIcon>
),
[BodyPart.RIGHT_THUMB_DISTAL]: ({ width }) => (
@@ -40,6 +40,10 @@ export function SettingSelectorMobile() {
label: l10n.getString('settings-sidebar-serial'),
value: { url: '/settings/serial' },
},
{
label: l10n.getString('settings-sidebar-firmware-tool'),
value: { url: '/settings/firmware-tool' },
},
{
label: l10n.getString('settings-sidebar-advanced'),
value: { url: '/settings/advanced' },
@@ -99,7 +103,7 @@ export function SettingsLayout({ children }: { children: ReactNode }) {
<div style={{ gridArea: 'n' }}>
<Navbar></Navbar>
</div>
<div style={{ gridArea: 's' }} className="my-2">
<div style={{ gridArea: 's' }} className="my-2 mobile:hidden">
<SettingsSidebar></SettingsSidebar>
</div>
<div
@@ -100,6 +100,9 @@ export function SettingsSidebar() {
<SettingsLink to="/settings/serial">
{l10n.getString('settings-sidebar-serial')}
</SettingsLink>
<SettingsLink to="/settings/firmware-tool">
{l10n.getString('settings-sidebar-firmware-tool')}
</SettingsLink>
</div>
<div className="flex flex-col gap-2">
<SettingsLink to="/settings/advanced">
@@ -69,6 +69,9 @@ interface SettingsForm {
toeSnap: boolean;
footPlant: boolean;
selfLocalization: boolean;
usePosition: boolean;
enforceConstraints: boolean;
correctConstraints: boolean;
};
ratios: {
imputeWaistFromChestHip: number;
@@ -128,6 +131,9 @@ const defaultValues: SettingsForm = {
toeSnap: false,
footPlant: true,
selfLocalization: false,
usePosition: true,
enforceConstraints: true,
correctConstraints: true,
},
ratios: {
imputeWaistFromChestHip: 0.3,
@@ -235,6 +241,9 @@ export function GeneralSettings() {
toggles.toeSnap = values.toggles.toeSnap;
toggles.footPlant = values.toggles.footPlant;
toggles.selfLocalization = values.toggles.selfLocalization;
toggles.usePosition = values.toggles.usePosition;
toggles.enforceConstraints = values.toggles.enforceConstraints;
toggles.correctConstraints = values.toggles.correctConstraints;
modelSettings.toggles = toggles;
}
@@ -981,6 +990,7 @@ export function GeneralSettings() {
)}
/>
</div>
<Typography color="secondary">
{l10n.getString(
'settings-general-fk_settings-arm_fk-reset_mode-description'
@@ -1033,6 +1043,48 @@ export function GeneralSettings() {
></Radio>
</div>
<div className="flex flex-col pt-2 pb-3">
<Typography bold>
{l10n.getString(
'settings-general-fk_settings-enforce_joint_constraints'
)}
</Typography>
<Typography color="secondary">
{l10n.getString(
'settings-general-fk_settings-enforce_joint_constraints-enforce_constraints-description'
)}
</Typography>
</div>
<div className="grid sm:grid-cols-1 pb-3">
<CheckBox
variant="toggle"
outlined
control={control}
name="toggles.enforceConstraints"
label={l10n.getString(
'settings-general-fk_settings-enforce_joint_constraints-enforce_constraints'
)}
/>
</div>
<div className="flex flex-col pt-2 pb-3">
<Typography color="secondary">
{l10n.getString(
'settings-general-fk_settings-enforce_joint_constraints-correct_constraints-description'
)}
</Typography>
</div>
<div className="grid sm:grid-cols-1 pb-3">
<CheckBox
variant="toggle"
outlined
control={control}
name="toggles.correctConstraints"
label={l10n.getString(
'settings-general-fk_settings-enforce_joint_constraints-correct_constraints'
)}
/>
</div>
{config?.debug && (
<>
<div className="flex flex-col pt-2 pb-3">
@@ -53,12 +53,6 @@ export function VMCSettings() {
const { l10n } = useLocalization();
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const [modelName, setModelName] = useState<string | null>(null);
const [flashLoaded, setFlashLoaded] = useState(false);
const toggleFlash = (bool: boolean) => {
setFlashLoaded(bool);
setTimeout(() => setFlashLoaded(!bool), 1000);
};
const { reset, control, watch, handleSubmit } = useForm<VMCSettingsForm>({
defaultValues,
@@ -74,11 +68,17 @@ export function VMCSettings() {
new OSCSettingsT(),
values.vmc.oscSettings
);
if (values.vmc.vrmJson?.length) {
vmcOsc.vrmJson = await parseVRMFile(values.vmc.vrmJson[0]);
if (vmcOsc.vrmJson) {
toggleFlash(true);
setModelName(JSON.parse(vmcOsc.vrmJson).extensions.VRM.meta.title);
if (values.vmc.vrmJson !== undefined) {
if (values.vmc.vrmJson.length > 0) {
vmcOsc.vrmJson = await parseVRMFile(values.vmc.vrmJson[0]);
if (vmcOsc.vrmJson) {
setModelName(
JSON.parse(vmcOsc.vrmJson)?.extensions?.VRM?.meta?.title || ''
);
}
} else {
vmcOsc.vrmJson = '';
setModelName(null);
}
}
vmcOsc.anchorHip = values.vmc.anchorHip;
@@ -114,7 +114,7 @@ export function VMCSettings() {
}
const vrmJson = settings.vmcOsc.vrmJson?.toString();
if (vrmJson) {
setModelName(JSON.parse(vrmJson).extensions.VRM.meta.title);
setModelName(JSON.parse(vrmJson)?.extensions?.VRM?.meta?.title || '');
}
formData.vmc.anchorHip = settings.vmcOsc.anchorHip;
@@ -236,16 +236,6 @@ export function VMCSettings() {
{l10n.getString('settings-osc-vmc-vrm-description')}
</Typography>
</div>
<div className="flex flex-col pb-2">
<Typography color={flashLoaded ? 'primary' : 'secondary'}>
{modelName === null
? l10n.getString('settings-osc-vmc-vrm-model_unloaded')
: l10n.getString('settings-osc-vmc-vrm-model_loaded', {
name: modelName,
titled: (!!modelName).toString(),
})}
</Typography>
</div>
<div className="grid gap-3 pb-5">
<FileInput
control={control}
@@ -254,6 +244,12 @@ export function VMCSettings() {
required: false,
}}
value="help"
importedFileName={
// if modelname is an empty string, it's an untitled model
modelName === ''
? l10n.getString('settings-osc-vmc-vrm-untitled_model')
: modelName
}
label="settings-osc-vmc-vrm-file_select"
accept="model/gltf-binary, model/gltf+json, model/vrml, .vrm, .glb, .gltf"
></FileInput>
+44 -21
View File
@@ -11,6 +11,10 @@ import { TrackerStatus } from './TrackerStatus';
import classNames from 'classnames';
import { useTracker } from '@/hooks/tracker';
import { BodyPartIcon } from '@/components/commons/BodyPartIcon';
import { DownloadIcon } from '@/components/commons/icon/DownloadIcon';
import { Link } from 'react-router-dom';
import { useAppContext } from '@/hooks/app';
import { checkForUpdate } from '@/components/firmware-update/FirmwareUpdate';
function TrackerBig({
device,
@@ -120,6 +124,7 @@ export function TrackerCard({
bg = 'bg-background-60',
shakeHighlight = true,
warning = false,
showUpdates = false,
}: {
tracker: TrackerDataT;
device?: DeviceDataT;
@@ -130,33 +135,51 @@ export function TrackerCard({
shakeHighlight?: boolean;
onClick?: MouseEventHandler<HTMLDivElement>;
warning?: boolean;
showUpdates?: boolean;
}) {
const { currentFirmwareRelease } = useAppContext();
const { useVelocity } = useTracker(tracker);
const velocity = useVelocity();
return (
<div
onClick={onClick}
className={classNames(
'rounded-lg overflow-hidden',
interactable && 'hover:bg-background-50 cursor-pointer',
outlined && 'outline outline-2 outline-accent-background-40',
warning && 'border-status-warning border-solid border-2',
bg
)}
style={
shakeHighlight
? {
boxShadow: `0px 0px ${Math.floor(velocity * 8)}px ${Math.floor(
velocity * 8
)}px rgb(var(--accent-background-30))`,
}
: {}
}
>
{smol && <TrackerSmol tracker={tracker} device={device}></TrackerSmol>}
{!smol && <TrackerBig tracker={tracker} device={device}></TrackerBig>}
<div className="relative">
<div
onClick={onClick}
className={classNames(
'rounded-lg overflow-hidden',
interactable && 'hover:bg-background-50 cursor-pointer',
outlined && 'outline outline-2 outline-accent-background-40',
warning && 'border-status-warning border-solid border-2',
bg
)}
style={
shakeHighlight
? {
boxShadow: `0px 0px ${Math.floor(velocity * 8)}px ${Math.floor(
velocity * 8
)}px rgb(var(--accent-background-30))`,
}
: {}
}
>
{smol && <TrackerSmol tracker={tracker} device={device}></TrackerSmol>}
{!smol && <TrackerBig tracker={tracker} device={device}></TrackerBig>}
</div>
{showUpdates &&
tracker.status !== TrackerStatusEnum.DISCONNECTED &&
currentFirmwareRelease &&
device?.hardwareInfo &&
checkForUpdate(currentFirmwareRelease, device.hardwareInfo) && (
<Link to="/firmware-update" className="absolute right-5 -top-2.5">
<div className="relative">
<div className="absolute rounded-full h-6 w-6 left-1 top-1 bg-accent-background-10 animate-[ping_2s_linear_infinite]"></div>
<div className="absolute rounded-full h-8 w-8 hover:bg-background-40 hover:cursor-pointer bg-background-50 justify-center flex items-center">
<DownloadIcon width={15}></DownloadIcon>
</div>
</div>
</Link>
)}
</div>
);
}
+85 -34
View File
@@ -1,4 +1,4 @@
import { useLocalization } from '@fluent/react';
import { Localized, useLocalization } from '@fluent/react';
import classNames from 'classnames';
import { IPv4 } from 'ip-num/IPNumber';
import { useEffect, useMemo, useState } from 'react';
@@ -6,6 +6,7 @@ import { useForm } from 'react-hook-form';
import { useParams } from 'react-router-dom';
import {
AssignTrackerRequestT,
BoardType,
BodyPart,
ForgetDeviceRequestT,
ImuType,
@@ -36,6 +37,8 @@ import { TrackerCard } from './TrackerCard';
import { Quaternion } from 'three';
import { useAppContext } from '@/hooks/app';
import { MagnetometerToggleSetting } from '@/components/settings/pages/MagnetometerToggleSetting';
import semver from 'semver';
import { checkForUpdate } from '@/components/firmware-update/FirmwareUpdate';
const rotationsLabels: [Quaternion, string][] = [
[rotationToQuatMap.BACK, 'tracker-rotation-back'],
@@ -149,6 +152,26 @@ export function TrackerSettingsPage() {
}
}, [firstLoad]);
const boardType = useMemo(() => {
if (tracker?.device?.hardwareInfo?.officialBoardType) {
return l10n.getString(
'board_type-' +
BoardType[
tracker?.device?.hardwareInfo?.officialBoardType ??
BoardType.UNKNOWN
]
);
} else if (tracker?.device?.hardwareInfo?.boardType) {
return tracker?.device?.hardwareInfo?.boardType;
} else {
return '--';
}
}, [
tracker?.device?.hardwareInfo?.officialBoardType,
tracker?.device?.hardwareInfo?.boardType,
l10n,
]);
const macAddress = useMemo(() => {
if (
/(?:[a-zA-Z\d]{2}:){5}[a-zA-Z\d]{2}/.test(
@@ -161,6 +184,18 @@ export function TrackerSettingsPage() {
return null;
}, [tracker?.device?.hardwareInfo?.hardwareIdentifier]);
const { currentFirmwareRelease } = useAppContext();
const needUpdate =
currentFirmwareRelease &&
tracker?.device?.hardwareInfo &&
checkForUpdate(currentFirmwareRelease, tracker?.device?.hardwareInfo);
const updateUnavailable =
tracker?.device?.hardwareInfo?.officialBoardType !== BoardType.SLIMEVR ||
!semver.valid(
tracker?.device?.hardwareInfo?.firmwareVersion?.toString() ?? 'none'
);
return (
<form
className="h-full overflow-y-auto"
@@ -188,21 +223,55 @@ export function TrackerSettingsPage() {
shakeHighlight={false}
></TrackerCard>
)}
{/* <div className="flex flex-col bg-background-70 p-3 rounded-lg gap-2">
<Typography bold>Firmware version</Typography>
<div className="flex gap-2">
<Typography color="secondary">
{tracker?.device?.hardwareInfo?.firmwareVersion}
</Typography>
<Typography color="secondary">-</Typography>
<Typography color="text-accent-background-10">
Up to date
</Typography>
{
<div className="flex flex-col bg-background-70 p-3 rounded-lg gap-2">
<Localized id="tracker-settings-update-title">
<Typography variant="section-title">
Firmware version
</Typography>
</Localized>
<div className="flex gap-2">
<Typography color="secondary">
v{tracker?.device?.hardwareInfo?.firmwareVersion}
</Typography>
<Typography color="secondary">-</Typography>
{updateUnavailable && (
<Localized id="tracker-settings-update-unavailable">
<Typography>Cannot be updated (DIY)</Typography>
</Localized>
)}
{!updateUnavailable && (
<>
{!needUpdate && (
<Localized id="tracker-settings-update-up_to_date">
<Typography>Up to date</Typography>
</Localized>
)}
{needUpdate && (
<Localized
id="tracker-settings-update-available"
vars={{ versionName: currentFirmwareRelease?.name }}
>
<Typography color="text-accent-background-10">
New version available
</Typography>
</Localized>
)}
</>
)}
</div>
<Localized id="tracker-settings-update">
<Button
variant={needUpdate ? 'primary' : 'secondary'}
disabled={!needUpdate}
to="/firmware-update"
>
Update now
</Button>
</Localized>
</div>
<Button variant="primary" disabled>
Update now
</Button>
</div> */}
}
<div className="flex flex-col bg-background-70 p-3 rounded-lg gap-2 overflow-x-auto">
<div className="flex justify-between">
<Typography color="secondary">
@@ -237,22 +306,6 @@ export function TrackerSettingsPage() {
).toString()}
</Typography>
</div>
<div className="flex justify-between">
<Typography color="secondary">
{l10n.getString('tracker-infos-version')}
</Typography>
<Typography>
{tracker?.device?.hardwareInfo?.firmwareVersion || '--'}
</Typography>
</div>
{/* <div className="flex justify-between">
<Typography color="secondary">
{l10n.getString('tracker-infos-hardware_rev')}
</Typography>
<Typography>
{tracker?.device?.hardwareInfo?.hardwareRevision || '--'}
</Typography>
</div> */}
<div className="flex justify-between">
<Typography color="secondary">
{l10n.getString('tracker-infos-hardware_identifier')}
@@ -285,9 +338,7 @@ export function TrackerSettingsPage() {
<Typography color="secondary">
{l10n.getString('tracker-infos-board_type')}
</Typography>
<Typography>
{tracker?.device?.hardwareInfo?.boardType || '--'}
</Typography>
<Typography>{boardType}</Typography>
</div>
<div className="flex justify-between">
<Typography color="secondary">
+2 -1
View File
@@ -45,7 +45,8 @@ const displayColumns: { [k: string]: boolean } = {
};
const isSlime = ({ device }: FlatDeviceTracker) =>
device?.hardwareInfo?.manufacturer === 'SlimeVR';
device?.hardwareInfo?.manufacturer === 'SlimeVR' ||
device?.hardwareInfo?.manufacturer === 'HID Device';
const getDeviceName = ({ device }: FlatDeviceTracker) =>
device?.customName?.toString() || '';
@@ -0,0 +1,659 @@
/**
* Generated by @openapi-codegen
*
* @version 0.0.1
*/
import * as reactQuery from '@tanstack/react-query';
import { useFirmwareToolContext, FirmwareToolContext } from './firmwareToolContext';
import type * as Fetcher from './firmwareToolFetcher';
import { firmwareToolFetch } from './firmwareToolFetcher';
import type * as Schemas from './firmwareToolSchemas';
export type GetIsCompatibleVersionPathParams = {
version: string;
};
export type GetIsCompatibleVersionError = Fetcher.ErrorWrapper<undefined>;
export type GetIsCompatibleVersionVariables = {
pathParams: GetIsCompatibleVersionPathParams;
} & FirmwareToolContext['fetcherOptions'];
/**
* Is this api compatible with the server version given
*/
export const fetchGetIsCompatibleVersion = (
variables: GetIsCompatibleVersionVariables,
signal?: AbortSignal
) =>
firmwareToolFetch<
Schemas.VerionCheckResponse,
GetIsCompatibleVersionError,
undefined,
{},
{},
GetIsCompatibleVersionPathParams
>({ url: '/is-compatible/{version}', method: 'get', ...variables, signal });
/**
* Is this api compatible with the server version given
*/
export const useGetIsCompatibleVersion = <TData = Schemas.VerionCheckResponse>(
variables: GetIsCompatibleVersionVariables,
options?: Omit<
reactQuery.UseQueryOptions<
Schemas.VerionCheckResponse,
GetIsCompatibleVersionError,
TData
>,
'queryKey' | 'queryFn' | 'initialData'
>
) => {
const { fetcherOptions, queryOptions, queryKeyFn } = useFirmwareToolContext(options);
return reactQuery.useQuery<
Schemas.VerionCheckResponse,
GetIsCompatibleVersionError,
TData
>({
queryKey: queryKeyFn({
path: '/is-compatible/{version}',
operationId: 'getIsCompatibleVersion',
variables,
}),
queryFn: ({ signal }) =>
fetchGetIsCompatibleVersion({ ...fetcherOptions, ...variables }, signal),
...options,
...queryOptions,
});
};
export type GetFirmwaresError = Fetcher.ErrorWrapper<undefined>;
export type GetFirmwaresResponse = Schemas.FirmwareDTO[];
export type GetFirmwaresVariables = FirmwareToolContext['fetcherOptions'];
/**
* List all the built firmwares
*/
export const fetchGetFirmwares = (
variables: GetFirmwaresVariables,
signal?: AbortSignal
) =>
firmwareToolFetch<GetFirmwaresResponse, GetFirmwaresError, undefined, {}, {}, {}>({
url: '/firmwares',
method: 'get',
...variables,
signal,
});
/**
* List all the built firmwares
*/
export const useGetFirmwares = <TData = GetFirmwaresResponse>(
variables: GetFirmwaresVariables,
options?: Omit<
reactQuery.UseQueryOptions<GetFirmwaresResponse, GetFirmwaresError, TData>,
'queryKey' | 'queryFn' | 'initialData'
>
) => {
const { fetcherOptions, queryOptions, queryKeyFn } = useFirmwareToolContext(options);
return reactQuery.useQuery<GetFirmwaresResponse, GetFirmwaresError, TData>({
queryKey: queryKeyFn({
path: '/firmwares',
operationId: 'getFirmwares',
variables,
}),
queryFn: ({ signal }) =>
fetchGetFirmwares({ ...fetcherOptions, ...variables }, signal),
...options,
...queryOptions,
});
};
export type PostFirmwaresBuildError = Fetcher.ErrorWrapper<{
status: 400;
payload: Schemas.VersionNotFoundExeption;
}>;
export type PostFirmwaresBuildVariables = {
body: Schemas.CreateBuildFirmwareDTO;
} & FirmwareToolContext['fetcherOptions'];
/**
* Build a firmware from the requested configuration
*/
export const fetchPostFirmwaresBuild = (
variables: PostFirmwaresBuildVariables,
signal?: AbortSignal
) =>
firmwareToolFetch<
Schemas.BuildResponseDTO,
PostFirmwaresBuildError,
Schemas.CreateBuildFirmwareDTO,
{},
{},
{}
>({ url: '/firmwares/build', method: 'post', ...variables, signal });
/**
* Build a firmware from the requested configuration
*/
export const usePostFirmwaresBuild = (
options?: Omit<
reactQuery.UseMutationOptions<
Schemas.BuildResponseDTO,
PostFirmwaresBuildError,
PostFirmwaresBuildVariables
>,
'mutationFn'
>
) => {
const { fetcherOptions } = useFirmwareToolContext();
return reactQuery.useMutation<
Schemas.BuildResponseDTO,
PostFirmwaresBuildError,
PostFirmwaresBuildVariables
>({
mutationFn: (variables: PostFirmwaresBuildVariables) =>
fetchPostFirmwaresBuild({ ...fetcherOptions, ...variables }),
...options,
});
};
export type GetFirmwaresBuildStatusIdPathParams = {
id: string;
};
export type GetFirmwaresBuildStatusIdError = Fetcher.ErrorWrapper<undefined>;
export type GetFirmwaresBuildStatusIdVariables = {
pathParams: GetFirmwaresBuildStatusIdPathParams;
} & FirmwareToolContext['fetcherOptions'];
/**
* Get the build status of a firmware
* This is a SSE (Server Sent Event)
* you can use the web browser api to check for the build status and update the ui in real time
*/
export const fetchGetFirmwaresBuildStatusId = (
variables: GetFirmwaresBuildStatusIdVariables,
signal?: AbortSignal
) =>
firmwareToolFetch<
Schemas.ObservableType,
GetFirmwaresBuildStatusIdError,
undefined,
{},
{},
GetFirmwaresBuildStatusIdPathParams
>({
url: '/firmwares/build-status/{id}',
method: 'get',
...variables,
signal,
});
/**
* Get the build status of a firmware
* This is a SSE (Server Sent Event)
* you can use the web browser api to check for the build status and update the ui in real time
*/
export const useGetFirmwaresBuildStatusId = <TData = Schemas.ObservableType>(
variables: GetFirmwaresBuildStatusIdVariables,
options?: Omit<
reactQuery.UseQueryOptions<
Schemas.ObservableType,
GetFirmwaresBuildStatusIdError,
TData
>,
'queryKey' | 'queryFn' | 'initialData'
>
) => {
const { fetcherOptions, queryOptions, queryKeyFn } = useFirmwareToolContext(options);
return reactQuery.useQuery<
Schemas.ObservableType,
GetFirmwaresBuildStatusIdError,
TData
>({
queryKey: queryKeyFn({
path: '/firmwares/build-status/{id}',
operationId: 'getFirmwaresBuildStatusId',
variables,
}),
queryFn: ({ signal }) =>
fetchGetFirmwaresBuildStatusId({ ...fetcherOptions, ...variables }, signal),
...options,
...queryOptions,
});
};
export type GetFirmwaresBoardsError = Fetcher.ErrorWrapper<undefined>;
export type GetFirmwaresBoardsResponse = string[];
export type GetFirmwaresBoardsVariables = FirmwareToolContext['fetcherOptions'];
/**
* List all the possible board types
*/
export const fetchGetFirmwaresBoards = (
variables: GetFirmwaresBoardsVariables,
signal?: AbortSignal
) =>
firmwareToolFetch<
GetFirmwaresBoardsResponse,
GetFirmwaresBoardsError,
undefined,
{},
{},
{}
>({ url: '/firmwares/boards', method: 'get', ...variables, signal });
/**
* List all the possible board types
*/
export const useGetFirmwaresBoards = <TData = GetFirmwaresBoardsResponse>(
variables: GetFirmwaresBoardsVariables,
options?: Omit<
reactQuery.UseQueryOptions<
GetFirmwaresBoardsResponse,
GetFirmwaresBoardsError,
TData
>,
'queryKey' | 'queryFn' | 'initialData'
>
) => {
const { fetcherOptions, queryOptions, queryKeyFn } = useFirmwareToolContext(options);
return reactQuery.useQuery<
GetFirmwaresBoardsResponse,
GetFirmwaresBoardsError,
TData
>({
queryKey: queryKeyFn({
path: '/firmwares/boards',
operationId: 'getFirmwaresBoards',
variables,
}),
queryFn: ({ signal }) =>
fetchGetFirmwaresBoards({ ...fetcherOptions, ...variables }, signal),
...options,
...queryOptions,
});
};
export type GetFirmwaresVersionsError = Fetcher.ErrorWrapper<undefined>;
export type GetFirmwaresVersionsResponse = Schemas.ReleaseDTO[];
export type GetFirmwaresVersionsVariables = FirmwareToolContext['fetcherOptions'];
/**
* List all the possible versions to build a firmware from
*/
export const fetchGetFirmwaresVersions = (
variables: GetFirmwaresVersionsVariables,
signal?: AbortSignal
) =>
firmwareToolFetch<
GetFirmwaresVersionsResponse,
GetFirmwaresVersionsError,
undefined,
{},
{},
{}
>({ url: '/firmwares/versions', method: 'get', ...variables, signal });
/**
* List all the possible versions to build a firmware from
*/
export const useGetFirmwaresVersions = <TData = GetFirmwaresVersionsResponse>(
variables: GetFirmwaresVersionsVariables,
options?: Omit<
reactQuery.UseQueryOptions<
GetFirmwaresVersionsResponse,
GetFirmwaresVersionsError,
TData
>,
'queryKey' | 'queryFn' | 'initialData'
>
) => {
const { fetcherOptions, queryOptions, queryKeyFn } = useFirmwareToolContext(options);
return reactQuery.useQuery<
GetFirmwaresVersionsResponse,
GetFirmwaresVersionsError,
TData
>({
queryKey: queryKeyFn({
path: '/firmwares/versions',
operationId: 'getFirmwaresVersions',
variables,
}),
queryFn: ({ signal }) =>
fetchGetFirmwaresVersions({ ...fetcherOptions, ...variables }, signal),
...options,
...queryOptions,
});
};
export type GetFirmwaresImusError = Fetcher.ErrorWrapper<undefined>;
export type GetFirmwaresImusResponse = Schemas.Imudto[];
export type GetFirmwaresImusVariables = FirmwareToolContext['fetcherOptions'];
/**
* List all the possible imus to use
*/
export const fetchGetFirmwaresImus = (
variables: GetFirmwaresImusVariables,
signal?: AbortSignal
) =>
firmwareToolFetch<
GetFirmwaresImusResponse,
GetFirmwaresImusError,
undefined,
{},
{},
{}
>({ url: '/firmwares/imus', method: 'get', ...variables, signal });
/**
* List all the possible imus to use
*/
export const useGetFirmwaresImus = <TData = GetFirmwaresImusResponse>(
variables: GetFirmwaresImusVariables,
options?: Omit<
reactQuery.UseQueryOptions<GetFirmwaresImusResponse, GetFirmwaresImusError, TData>,
'queryKey' | 'queryFn' | 'initialData'
>
) => {
const { fetcherOptions, queryOptions, queryKeyFn } = useFirmwareToolContext(options);
return reactQuery.useQuery<GetFirmwaresImusResponse, GetFirmwaresImusError, TData>({
queryKey: queryKeyFn({
path: '/firmwares/imus',
operationId: 'getFirmwaresImus',
variables,
}),
queryFn: ({ signal }) =>
fetchGetFirmwaresImus({ ...fetcherOptions, ...variables }, signal),
...options,
...queryOptions,
});
};
export type GetFirmwaresBatteriesError = Fetcher.ErrorWrapper<undefined>;
export type GetFirmwaresBatteriesResponse = string[];
export type GetFirmwaresBatteriesVariables = FirmwareToolContext['fetcherOptions'];
/**
* List all the battery types
*/
export const fetchGetFirmwaresBatteries = (
variables: GetFirmwaresBatteriesVariables,
signal?: AbortSignal
) =>
firmwareToolFetch<
GetFirmwaresBatteriesResponse,
GetFirmwaresBatteriesError,
undefined,
{},
{},
{}
>({ url: '/firmwares/batteries', method: 'get', ...variables, signal });
/**
* List all the battery types
*/
export const useGetFirmwaresBatteries = <TData = GetFirmwaresBatteriesResponse>(
variables: GetFirmwaresBatteriesVariables,
options?: Omit<
reactQuery.UseQueryOptions<
GetFirmwaresBatteriesResponse,
GetFirmwaresBatteriesError,
TData
>,
'queryKey' | 'queryFn' | 'initialData'
>
) => {
const { fetcherOptions, queryOptions, queryKeyFn } = useFirmwareToolContext(options);
return reactQuery.useQuery<
GetFirmwaresBatteriesResponse,
GetFirmwaresBatteriesError,
TData
>({
queryKey: queryKeyFn({
path: '/firmwares/batteries',
operationId: 'getFirmwaresBatteries',
variables,
}),
queryFn: ({ signal }) =>
fetchGetFirmwaresBatteries({ ...fetcherOptions, ...variables }, signal),
...options,
...queryOptions,
});
};
export type GetFirmwaresDefaultConfigBoardPathParams = {
board:
| 'BOARD_SLIMEVR'
| 'BOARD_NODEMCU'
| 'BOARD_WROOM32'
| 'BOARD_WEMOSD1MINI'
| 'BOARD_TTGO_TBASE'
| 'BOARD_ESP01'
| 'BOARD_LOLIN_C3_MINI'
| 'BOARD_BEETLE32C3'
| 'BOARD_ES32C3DEVKITM1';
};
export type GetFirmwaresDefaultConfigBoardError = Fetcher.ErrorWrapper<undefined>;
export type GetFirmwaresDefaultConfigBoardVariables = {
pathParams: GetFirmwaresDefaultConfigBoardPathParams;
} & FirmwareToolContext['fetcherOptions'];
/**
* Gives the default pins / configuration of a given board
*/
export const fetchGetFirmwaresDefaultConfigBoard = (
variables: GetFirmwaresDefaultConfigBoardVariables,
signal?: AbortSignal
) =>
firmwareToolFetch<
Schemas.DefaultBuildConfigDTO,
GetFirmwaresDefaultConfigBoardError,
undefined,
{},
{},
GetFirmwaresDefaultConfigBoardPathParams
>({
url: '/firmwares/default-config/{board}',
method: 'get',
...variables,
signal,
});
/**
* Gives the default pins / configuration of a given board
*/
export const useGetFirmwaresDefaultConfigBoard = <
TData = Schemas.DefaultBuildConfigDTO,
>(
variables: GetFirmwaresDefaultConfigBoardVariables,
options?: Omit<
reactQuery.UseQueryOptions<
Schemas.DefaultBuildConfigDTO,
GetFirmwaresDefaultConfigBoardError,
TData
>,
'queryKey' | 'queryFn' | 'initialData'
>
) => {
const { fetcherOptions, queryOptions, queryKeyFn } = useFirmwareToolContext(options);
return reactQuery.useQuery<
Schemas.DefaultBuildConfigDTO,
GetFirmwaresDefaultConfigBoardError,
TData
>({
queryKey: queryKeyFn({
path: '/firmwares/default-config/{board}',
operationId: 'getFirmwaresDefaultConfigBoard',
variables,
}),
queryFn: ({ signal }) =>
fetchGetFirmwaresDefaultConfigBoard({ ...fetcherOptions, ...variables }, signal),
...options,
...queryOptions,
});
};
export type GetFirmwaresIdPathParams = {
id: string;
};
export type GetFirmwaresIdError = Fetcher.ErrorWrapper<{
status: 404;
payload: Schemas.HttpException;
}>;
export type GetFirmwaresIdVariables = {
pathParams: GetFirmwaresIdPathParams;
} & FirmwareToolContext['fetcherOptions'];
/**
* Get the inforamtions about a firmware from its id
* also provide more informations than the simple list, like pins and imus and files
*/
export const fetchGetFirmwaresId = (
variables: GetFirmwaresIdVariables,
signal?: AbortSignal
) =>
firmwareToolFetch<
Schemas.FirmwareDetailDTO,
GetFirmwaresIdError,
undefined,
{},
{},
GetFirmwaresIdPathParams
>({ url: '/firmwares/{id}', method: 'get', ...variables, signal });
/**
* Get the inforamtions about a firmware from its id
* also provide more informations than the simple list, like pins and imus and files
*/
export const useGetFirmwaresId = <TData = Schemas.FirmwareDetailDTO>(
variables: GetFirmwaresIdVariables,
options?: Omit<
reactQuery.UseQueryOptions<Schemas.FirmwareDetailDTO, GetFirmwaresIdError, TData>,
'queryKey' | 'queryFn' | 'initialData'
>
) => {
const { fetcherOptions, queryOptions, queryKeyFn } = useFirmwareToolContext(options);
return reactQuery.useQuery<Schemas.FirmwareDetailDTO, GetFirmwaresIdError, TData>({
queryKey: queryKeyFn({
path: '/firmwares/{id}',
operationId: 'getFirmwaresId',
variables,
}),
queryFn: ({ signal }) =>
fetchGetFirmwaresId({ ...fetcherOptions, ...variables }, signal),
...options,
...queryOptions,
});
};
export type GetHealthError = Fetcher.ErrorWrapper<undefined>;
export type GetHealthVariables = FirmwareToolContext['fetcherOptions'];
/**
* Gives the status of the api
* this endpoint will always return true
*/
export const fetchGetHealth = (variables: GetHealthVariables, signal?: AbortSignal) =>
firmwareToolFetch<boolean, GetHealthError, undefined, {}, {}, {}>({
url: '/health',
method: 'get',
...variables,
signal,
});
/**
* Gives the status of the api
* this endpoint will always return true
*/
export const useGetHealth = <TData = boolean>(
variables: GetHealthVariables,
options?: Omit<
reactQuery.UseQueryOptions<boolean, GetHealthError, TData>,
'queryKey' | 'queryFn' | 'initialData'
>
) => {
const { fetcherOptions, queryOptions, queryKeyFn } = useFirmwareToolContext(options);
return reactQuery.useQuery<boolean, GetHealthError, TData>({
queryKey: queryKeyFn({
path: '/health',
operationId: 'getHealth',
variables,
}),
queryFn: ({ signal }) =>
fetchGetHealth({ ...fetcherOptions, ...variables }, signal),
...options,
...queryOptions,
});
};
export type QueryOperation =
| {
path: '/is-compatible/{version}';
operationId: 'getIsCompatibleVersion';
variables: GetIsCompatibleVersionVariables;
}
| {
path: '/firmwares';
operationId: 'getFirmwares';
variables: GetFirmwaresVariables;
}
| {
path: '/firmwares/build-status/{id}';
operationId: 'getFirmwaresBuildStatusId';
variables: GetFirmwaresBuildStatusIdVariables;
}
| {
path: '/firmwares/boards';
operationId: 'getFirmwaresBoards';
variables: GetFirmwaresBoardsVariables;
}
| {
path: '/firmwares/versions';
operationId: 'getFirmwaresVersions';
variables: GetFirmwaresVersionsVariables;
}
| {
path: '/firmwares/imus';
operationId: 'getFirmwaresImus';
variables: GetFirmwaresImusVariables;
}
| {
path: '/firmwares/batteries';
operationId: 'getFirmwaresBatteries';
variables: GetFirmwaresBatteriesVariables;
}
| {
path: '/firmwares/default-config/{board}';
operationId: 'getFirmwaresDefaultConfigBoard';
variables: GetFirmwaresDefaultConfigBoardVariables;
}
| {
path: '/firmwares/{id}';
operationId: 'getFirmwaresId';
variables: GetFirmwaresIdVariables;
}
| {
path: '/health';
operationId: 'getHealth';
variables: GetHealthVariables;
};
@@ -0,0 +1,99 @@
import type { QueryKey, UseQueryOptions } from '@tanstack/react-query';
import { QueryOperation } from './firmwareToolComponents';
export type FirmwareToolContext = {
fetcherOptions: {
/**
* Headers to inject in the fetcher
*/
headers?: {};
/**
* Query params to inject in the fetcher
*/
queryParams?: {};
};
queryOptions: {
/**
* Set this to `false` to disable automatic refetching when the query mounts or changes query keys.
* Defaults to `true`.
*/
enabled?: boolean;
};
/**
* Query key manager.
*/
queryKeyFn: (operation: QueryOperation) => QueryKey;
};
/**
* Context injected into every react-query hook wrappers
*
* @param queryOptions options from the useQuery wrapper
*/
export function useFirmwareToolContext<
TQueryFnData = unknown,
TError = unknown,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
>(
_queryOptions?: Omit<
UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
'queryKey' | 'queryFn'
>
): FirmwareToolContext {
return {
fetcherOptions: {},
queryOptions: {},
queryKeyFn,
};
}
export const queryKeyFn = (operation: QueryOperation) => {
const queryKey: unknown[] = hasPathParams(operation)
? operation.path
.split('/')
.filter(Boolean)
.map((i) => resolvePathParam(i, operation.variables.pathParams))
: operation.path.split('/').filter(Boolean);
if (hasQueryParams(operation)) {
queryKey.push(operation.variables.queryParams);
}
if (hasBody(operation)) {
queryKey.push(operation.variables.body);
}
return queryKey;
};
// Helpers
const resolvePathParam = (key: string, pathParams: Record<string, string>) => {
if (key.startsWith('{') && key.endsWith('}')) {
return pathParams[key.slice(1, -1)];
}
return key;
};
const hasPathParams = (
operation: QueryOperation
): operation is QueryOperation & {
variables: { pathParams: Record<string, string> };
} => {
return Boolean((operation.variables as any).pathParams);
};
const hasBody = (
operation: QueryOperation
): operation is QueryOperation & {
variables: { body: Record<string, unknown> };
} => {
return Boolean((operation.variables as any).body);
};
const hasQueryParams = (
operation: QueryOperation
): operation is QueryOperation & {
variables: { queryParams: Record<string, unknown> };
} => {
return Boolean((operation.variables as any).queryParams);
};
@@ -0,0 +1,109 @@
import { FirmwareToolContext } from './firmwareToolContext';
export const firmwareToolBaseUrl =
import.meta.env.VITE_FIRMWARE_TOOL_URL ?? 'http://localhost:3000';
export const firmwareToolS3BaseUrl =
import.meta.env.VITE_FIRMWARE_TOOL_S3_URL ?? 'http://localhost:9099';
export type ErrorWrapper<TError> = TError | { status: 'unknown'; payload: string };
export type FirmwareToolFetcherOptions<TBody, THeaders, TQueryParams, TPathParams> = {
url: string;
method: string;
body?: TBody;
headers?: THeaders;
queryParams?: TQueryParams;
pathParams?: TPathParams;
signal?: AbortSignal;
} & FirmwareToolContext['fetcherOptions'];
export async function firmwareToolFetch<
TData,
TError,
TBody extends {} | FormData | undefined | null,
THeaders extends {},
TQueryParams extends {},
TPathParams extends {},
>({
url,
method,
body,
headers,
pathParams,
queryParams,
signal,
}: FirmwareToolFetcherOptions<
TBody,
THeaders,
TQueryParams,
TPathParams
>): Promise<TData> {
try {
const requestHeaders: HeadersInit = {
'Content-Type': 'application/json',
...headers,
};
/**
* As the fetch API is being used, when multipart/form-data is specified
* the Content-Type header must be deleted so that the browser can set
* the correct boundary.
* https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects#sending_files_using_a_formdata_object
*/
if (requestHeaders['Content-Type'].toLowerCase().includes('multipart/form-data')) {
delete requestHeaders['Content-Type'];
}
const response = await window.fetch(
`${firmwareToolBaseUrl}${resolveUrl(url, queryParams, pathParams)}`,
{
signal,
method: method.toUpperCase(),
body: body
? body instanceof FormData
? body
: JSON.stringify(body)
: undefined,
headers: requestHeaders,
}
);
if (!response.ok) {
let error: ErrorWrapper<TError>;
try {
error = await response.json();
} catch (e) {
error = {
status: 'unknown' as const,
payload:
e instanceof Error ? `Unexpected error (${e.message})` : 'Unexpected error',
};
}
throw error;
}
if (response.headers.get('content-type')?.includes('json')) {
return await response.json();
} else {
// if it is not a json response, assume it is a blob and cast it to TData
return (await response.blob()) as unknown as TData;
}
} catch (e) {
let errorObject: Error = {
name: 'unknown' as const,
message: e instanceof Error ? `Network error (${e.message})` : 'Network error',
stack: e as string,
};
throw errorObject;
}
}
const resolveUrl = (
url: string,
queryParams: Record<string, string> = {},
pathParams: Record<string, string> = {}
) => {
let query = new URLSearchParams(queryParams).toString();
if (query) query = `?${query}`;
return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + query;
};
@@ -0,0 +1,608 @@
/**
* Generated by @openapi-codegen
*
* @version 0.0.1
*/
export type VerionCheckResponse = {
success: boolean;
reason?: {
message: string;
versions: string;
};
};
/**
* Root object declaring a built firmware
* this object contains:
* - the status of the build
* - the the repository and commit used as source
*/
export type FirmwareDTO = {
/**
* UUID of the firmware
*
* @format uuid
*/
id: string;
/**
* Id of the firmware version used.
* Usually the commit id of the source
* used to build the firmware
*/
releaseId: string;
/**
* Current status of the build
* this value will change during the build
* process
*
* BUILDING -> DONE \\ the firmwrare is build and ready
* -> FAILED \\ the build failled and will be garbage collected
*/
buildStatus:
| 'CREATING_BUILD_FOLDER'
| 'DOWNLOADING_FIRMWARE'
| 'EXTRACTING_FIRMWARE'
| 'SETTING_UP_DEFINES'
| 'BUILDING'
| 'SAVING'
| 'DONE'
| 'ERROR';
/**
* The repository and branch used as source of the firmware
*/
buildVersion: string;
/**
* The date of creation of this firmware build
*
* @format date-time
*/
createdAt: string;
};
export type BuildResponseDTO = {
/**
* Id of the firmware
*
* @format uuid
*/
id: string;
/**
* Build status of the firmware
*/
status:
| 'CREATING_BUILD_FOLDER'
| 'DOWNLOADING_FIRMWARE'
| 'EXTRACTING_FIRMWARE'
| 'SETTING_UP_DEFINES'
| 'BUILDING'
| 'SAVING'
| 'DONE'
| 'ERROR';
/**
* List of built firmware files, only set if the build succeeded
*/
firmwareFiles?: FirmwareFileDTO[];
};
export type FirmwareFileDTO = {
/**
* Url to the file
*/
url: string;
/**
* Address of the partition
*/
offset: number;
/**
* Is this file the main firmware
*/
isFirmware: boolean;
/**
* Id of the linked firmware
*
* @format uuid
*/
firmwareId: string;
};
export type CreateBuildFirmwareDTO = {
/**
* Repository of the firmware used
*/
version: string;
/**
* Board config, used to declare the pins used by the board
*/
boardConfig: CreateBoardConfigDTO;
/**
* Imu config, list of all the imus used and their pins
*
* @minItems 1
*/
imusConfig: CreateImuConfigDTO[];
};
export type CreateBoardConfigDTO = {
/**
* Type of the board
*/
type:
| 'BOARD_SLIMEVR'
| 'BOARD_NODEMCU'
| 'BOARD_WROOM32'
| 'BOARD_WEMOSD1MINI'
| 'BOARD_TTGO_TBASE'
| 'BOARD_ESP01'
| 'BOARD_LOLIN_C3_MINI'
| 'BOARD_BEETLE32C3'
| 'BOARD_ES32C3DEVKITM1';
/**
* Pin address of the indicator LED
*/
ledPin: string;
/**
* Is the indicator LED enabled
*/
enableLed: boolean;
/**
* Is the led inverted
*/
ledInverted: boolean;
/**
* Pin address of the battery indicator
*/
batteryPin: string;
/**
* Type of battery
*/
batteryType: 'BAT_EXTERNAL' | 'BAT_INTERNAL' | 'BAT_MCP3021' | 'BAT_INTERNAL_MCP3021';
/**
* Array of the different battery resistors, [indicator, SHIELD_R1, SHIELD_R2]
*
* @minItems 3
* @maxItems 3
*/
batteryResistances: number[];
};
export type CreateImuConfigDTO = {
/**
* Type of the imu
*/
type:
| 'IMU_BNO085'
| 'IMU_MPU9250'
| 'IMU_MPU6500'
| 'IMU_BNO080'
| 'IMU_BNO055'
| 'IMU_BNO086'
| 'IMU_MPU6050'
| 'IMU_BMI160'
| 'IMU_ICM20948'
| 'IMU_BMI270';
/**
* Pin address of the imu int pin
* not all imus use it
*/
intPin: string | null;
/**
* Rotation of the imu in degrees
*/
rotation: number;
/**
* Pin address of the scl pin
*/
sclPin: string;
/**
* Pin address of the sda pin
*/
sdaPin: string;
/**
* Is this imu optionnal
* Allows for extensions to be unplugged
*/
optional: boolean;
};
export type VersionNotFoundExeption = {
cause: void;
name: string;
message: string;
stack?: string;
};
/**
* A representation of any set of values over any amount of time. This is the most basic building block
* of RxJS.
*/
export type ObservableType = {
/**
* @deprecated true
*/
source?: Observableany;
/**
* @deprecated true
*/
operator?: OperatoranyType;
};
/**
* A representation of any set of values over any amount of time. This is the most basic building block
* of RxJS.
*/
export type Observableany = {
/**
* @deprecated true
*/
source?: Observableany;
/**
* @deprecated true
*/
operator?: Operatoranyany;
};
/**
* *
*/
export type Operatoranyany = {};
/**
* *
*/
export type OperatoranyType = {};
export type ReleaseDTO = {
/**
* id of the release, usually the commit id
*/
id: string;
/**
* url of the release
*/
url: string;
/**
* name of the release
*/
name: string;
/**
* url of the source archive
*/
zipball_url: string;
/**
* Is this release a pre release
*/
prerelease: boolean;
/**
* Is this release a draft
*/
draft: boolean;
};
export type Imudto = {
/**
* Type of the imu
*/
type:
| 'IMU_BNO085'
| 'IMU_MPU9250'
| 'IMU_MPU6500'
| 'IMU_BNO080'
| 'IMU_BNO055'
| 'IMU_BNO086'
| 'IMU_MPU6050'
| 'IMU_BMI160'
| 'IMU_ICM20948'
| 'IMU_BMI270';
/**
* Does that imu type require a int pin
*/
hasIntPin: boolean;
/**
* First address of the imu
*/
imuStartAddress: number;
/**
* Increment of the address for each new imus
*/
addressIncrement: number;
};
export type DefaultBuildConfigDTO = {
/**
* Default config of the selected board
* contains all the default pins information about the selected board
*/
boardConfig: CreateBoardConfigDTO;
/**
* Inform the flashing utility that the user need to press the boot (or Flash) button
* on the tracker
*/
needBootPress?: boolean;
/**
* Inform the flashing utility that the board will need a reboot after
* being flashed
*/
needManualReboot?: boolean;
/**
* Will use the default values and skip the customisation options
*/
shouldOnlyUseDefaults?: boolean;
/**
* List of the possible imus pins, usually only two items will be sent
*
* @minItems 1
*/
imuDefaults: IMUDefaultDTO[];
/**
* Gives the offset of the firmare file in the eeprom. Used for flashing
*/
application_offset: number;
};
export type IMUDefaultDTO = {
/**
* Type of the imu
*/
type?:
| 'IMU_BNO085'
| 'IMU_MPU9250'
| 'IMU_MPU6500'
| 'IMU_BNO080'
| 'IMU_BNO055'
| 'IMU_BNO086'
| 'IMU_MPU6050'
| 'IMU_BMI160'
| 'IMU_ICM20948'
| 'IMU_BMI270';
/**
* Pin address of the imu int pin
* not all imus use it
*/
intPin: string | null;
/**
* Rotation of the imu in degrees
*/
rotation?: number;
/**
* Pin address of the scl pin
*/
sclPin: string;
/**
* Pin address of the sda pin
*/
sdaPin: string;
/**
* Is this imu optionnal
* Allows for extensions to be unplugged
*/
optional: boolean;
};
export type BoardConfigDTONullable = {
/**
* Unique id of the board config, used for relations
*
* @format uuid
*/
id: string;
/**
* Type of the board
*/
type:
| 'BOARD_SLIMEVR'
| 'BOARD_NODEMCU'
| 'BOARD_WROOM32'
| 'BOARD_WEMOSD1MINI'
| 'BOARD_TTGO_TBASE'
| 'BOARD_ESP01'
| 'BOARD_LOLIN_C3_MINI'
| 'BOARD_BEETLE32C3'
| 'BOARD_ES32C3DEVKITM1';
/**
* Pin address of the indicator LED
*/
ledPin: string;
/**
* Is the indicator LED enabled
*/
enableLed: boolean;
/**
* Is the led inverted
*/
ledInverted: boolean;
/**
* Pin address of the battery indicator
*/
batteryPin: string;
/**
* Type of battery
*/
batteryType: 'BAT_EXTERNAL' | 'BAT_INTERNAL' | 'BAT_MCP3021' | 'BAT_INTERNAL_MCP3021';
/**
* Array of the different battery resistors, [indicator, SHIELD_R1, SHIELD_R2]
*
* @minItems 3
* @maxItems 3
*/
batteryResistances: number[];
/**
* Id of the linked firmware, used for relations
*
* @format uuid
*/
firmwareId: string;
};
export type FirmwareDetailDTO = {
/**
* Pins informations about the board
*/
boardConfig: BoardConfigDTONullable;
/**
* List of the declared imus, and their pin configuration
*
* @minItems 1
*/
imusConfig: ImuConfigDTO[];
/**
* List of the built files / partitions with their url and offsets
*/
firmwareFiles: FirmwareFileDTO[];
/**
* UUID of the firmware
*
* @format uuid
*/
id: string;
/**
* Id of the firmware version used.
* Usually the commit id of the source
* used to build the firmware
*/
releaseId: string;
/**
* Current status of the build
* this value will change during the build
* process
*
* BUILDING -> DONE \\ the firmwrare is build and ready
* -> FAILED \\ the build failled and will be garbage collected
*/
buildStatus:
| 'CREATING_BUILD_FOLDER'
| 'DOWNLOADING_FIRMWARE'
| 'EXTRACTING_FIRMWARE'
| 'SETTING_UP_DEFINES'
| 'BUILDING'
| 'SAVING'
| 'DONE'
| 'ERROR';
/**
* The repository and branch used as source of the firmware
*/
buildVersion: string;
/**
* The date of creation of this firmware build
*
* @format date-time
*/
createdAt: string;
};
export type BoardConfigDTO = {
/**
* Unique id of the board config, used for relations
*
* @format uuid
*/
id: string;
/**
* Type of the board
*/
type:
| 'BOARD_SLIMEVR'
| 'BOARD_NODEMCU'
| 'BOARD_WROOM32'
| 'BOARD_WEMOSD1MINI'
| 'BOARD_TTGO_TBASE'
| 'BOARD_ESP01'
| 'BOARD_LOLIN_C3_MINI'
| 'BOARD_BEETLE32C3'
| 'BOARD_ES32C3DEVKITM1';
/**
* Pin address of the indicator LED
*/
ledPin: string;
/**
* Is the indicator LED enabled
*/
enableLed: boolean;
/**
* Is the led inverted
*/
ledInverted: boolean;
/**
* Pin address of the battery indicator
*/
batteryPin: string;
/**
* Type of battery
*/
batteryType: 'BAT_EXTERNAL' | 'BAT_INTERNAL' | 'BAT_MCP3021' | 'BAT_INTERNAL_MCP3021';
/**
* Array of the different battery resistors, [indicator, SHIELD_R1, SHIELD_R2]
*
* @minItems 3
* @maxItems 3
*/
batteryResistances: number[];
/**
* Id of the linked firmware, used for relations
*
* @format uuid
*/
firmwareId: string;
};
export type ImuConfigDTO = {
/**
* Unique id of the config
* this probably will never be shown to the user as it is moslty use for relations
*
* @format uuid
*/
id: string;
/**
* Type of the imu
*/
type:
| 'IMU_BNO085'
| 'IMU_MPU9250'
| 'IMU_MPU6500'
| 'IMU_BNO080'
| 'IMU_BNO055'
| 'IMU_BNO086'
| 'IMU_MPU6050'
| 'IMU_BMI160'
| 'IMU_ICM20948'
| 'IMU_BMI270';
/**
* Rotation of the imu in degrees
*/
rotation: number;
/**
* Pin address of the imu int pin
* not all imus use it
*/
intPin: string | null;
/**
* Pin address of the scl pin
*/
sclPin: string;
/**
* Pin address of the sda pin
*/
sdaPin: string;
/**
* Is this imu optionnal
* Allows for extensions to be unplugged
*/
optional: boolean;
/**
* id of the linked firmware, used for relations
*
* @format uuid
*/
firmwareId: string;
};
/**
* Defines the base Nest HTTP exception, which is handled by the default
* Exceptions Handler.
*/
export type HttpException = {
cause: void;
name: string;
message: string;
stack?: string;
};
@@ -0,0 +1,15 @@
type ComputeRange<
N extends number,
Result extends Array<unknown> = [],
> = Result['length'] extends N
? Result
: ComputeRange<N, [...Result, Result['length']]>;
export type ClientErrorStatus = Exclude<
ComputeRange<500>[number],
ComputeRange<400>[number]
>;
export type ServerErrorStatus = Exclude<
ComputeRange<600>[number],
ComputeRange<500>[number]
>;
+60
View File
@@ -6,6 +6,7 @@ import {
useEffect,
useMemo,
useReducer,
useState,
} from 'react';
import {
BoneT,
@@ -23,6 +24,14 @@ import { useConfig } from './config';
import { useDataFeedConfig } from './datafeed-config';
import { useWebsocketAPI } from './websocket-api';
import { error } from '@/utils/logging';
import { cacheWrap } from './cache';
export interface FirmwareRelease {
name: string;
version: string;
changelog: string;
firmwareFile: string;
}
export interface FlatDeviceTracker {
device?: DeviceDataT;
@@ -39,6 +48,7 @@ export interface AppState {
}
export interface AppContext {
currentFirmwareRelease: FirmwareRelease | null;
state: AppState;
trackers: FlatDeviceTracker[];
dispatch: Dispatch<AppStateAction>;
@@ -69,6 +79,8 @@ export function useProvideAppContext(): AppContext {
datafeed: new DataFeedUpdateT(),
ignoredTrackers: new Set(),
});
const [currentFirmwareRelease, setCurrentFirmwareRelease] =
useState<FirmwareRelease | null>(null);
useEffect(() => {
if (isConnected) {
@@ -115,7 +127,55 @@ export function useProvideAppContext(): AppContext {
}
});
useEffect(() => {
const fetchCurrentFirmwareRelease = async () => {
const releases: any[] | null = JSON.parse(
await cacheWrap(
'firmware-releases',
() =>
fetch('https://api.github.com/repos/SlimeVR/SlimeVR-Tracker-ESP/releases')
.then((res) => res.text())
.catch(() => 'null'),
1000 * 60 * 60
)
);
if (!releases) return null;
const firstRelease = releases.find(
(release) =>
release.prerelease === false &&
release.assets &&
release.assets.find(
(asset: any) =>
asset.name === 'BOARD_SLIMEVR-firmware.bin' && asset.browser_download_url
)
);
let version = firstRelease.tag_name;
if (version.charAt(0) === 'v') {
version = version.substring(1);
}
if (firstRelease) {
return {
name: firstRelease.name,
version,
changelog: firstRelease.body,
firmwareFile: firstRelease.assets.find(
(asset: any) =>
asset.name === 'BOARD_SLIMEVR-firmware.bin' && asset.browser_download_url
).browser_download_url,
};
} else {
return null;
}
};
fetchCurrentFirmwareRelease().then((res) => setCurrentFirmwareRelease(res));
}, []);
return {
currentFirmwareRelease,
state,
trackers,
dispatch,
+1 -2
View File
@@ -3,9 +3,8 @@ import { useMediaQuery } from 'react-responsive';
import tailwindConfig from '../../tailwind.config';
const fullConfig = resolveConfig(tailwindConfig as any);
const breakpoints = tailwindConfig.theme.screens;
type BreakpointKey = keyof typeof breakpoints;
type BreakpointKey = keyof typeof tailwindConfig.theme.screens;
export function useBreakpoint<K extends BreakpointKey>(breakpointKey: K) {
// FIXME There is a flickering issue caused by this, because isMobile is not resolved fast enough
+68
View File
@@ -0,0 +1,68 @@
import { isTauri } from '@tauri-apps/api/core';
import { createStore } from '@tauri-apps/plugin-store';
interface CrossStorage {
set(key: string, value: string): Promise<void>;
get(key: string): Promise<string | null>;
delete(key: string): Promise<boolean>;
}
const localStore: CrossStorage = {
get: async (key) => localStorage.getItem(`slimevr-cache/${key}`),
set: async (key, value) => localStorage.setItem(`slimevr-cache/${key}`, value),
delete: async (key) => {
localStorage.removeItem(`slimevr-cache/${key}`);
return true;
},
};
const store: CrossStorage = isTauri()
? await createStore('gui-cache.dat', { autoSave: 100 as never })
: localStore;
export async function cacheGet(key: string): Promise<string | null> {
const itemStr = await store.get(key);
if (!itemStr) {
return null;
}
const item = JSON.parse(itemStr);
const now = new Date();
if (now.getTime() > item.expiry) {
await store.delete(key);
return null;
}
return item.value;
}
export async function cacheSet(key: string, value: unknown, ttl: number | undefined) {
const now = new Date();
const item = {
value,
expiry: ttl ? now.getTime() + ttl : 0,
};
await store.set(key, JSON.stringify(item));
}
export async function cacheWrap(
key: string,
orDefault: () => Promise<string>,
ttl: number | undefined
) {
const realItem = await store.get(key);
if (!realItem) {
const defaultItem = await orDefault();
await cacheSet(key, defaultItem, ttl);
return defaultItem;
} else {
return (await cacheGet(key))!;
}
}
export async function cacheDelete(key: string) {
await store.delete(key);
}
+252
View File
@@ -0,0 +1,252 @@
import { createContext, useContext, useState } from 'react';
import {
fetchGetFirmwaresDefaultConfigBoard,
useGetHealth,
useGetIsCompatibleVersion,
} from '@/firmware-tool-api/firmwareToolComponents';
import {
BuildResponseDTO,
CreateBoardConfigDTO,
CreateBuildFirmwareDTO,
DefaultBuildConfigDTO,
FirmwareFileDTO,
} from '@/firmware-tool-api/firmwareToolSchemas';
import { BoardPinsForm } from '@/components/firmware-tool/BoardPinsStep';
import { DeepPartial } from 'react-hook-form';
import {
BoardType,
DeviceIdT,
FirmwarePartT,
FirmwareUpdateMethod,
FirmwareUpdateRequestT,
FirmwareUpdateStatus,
OTAFirmwareUpdateT,
SerialDevicePortT,
SerialFirmwareUpdateT,
} from 'solarxr-protocol';
import { OnboardingContext } from './onboarding';
export type PartialBuildFirmware = DeepPartial<CreateBuildFirmwareDTO>;
export type FirmwareBuildStatus = BuildResponseDTO;
export type SelectedDevice = {
type: FirmwareUpdateMethod;
deviceId: string | number;
deviceNames: string[];
};
export const boardTypeToFirmwareToolBoardType: Record<
Exclude<
BoardType,
// This boards will not be handled by the firmware tool.
// These are either impossible to compile automatically or deprecated
BoardType.CUSTOM | BoardType.SLIMEVR_DEV | BoardType.SLIMEVR_LEGACY
>,
CreateBoardConfigDTO['type'] | null
> = {
[BoardType.UNKNOWN]: null,
[BoardType.NODEMCU]: 'BOARD_NODEMCU',
[BoardType.WROOM32]: 'BOARD_WROOM32',
[BoardType.WEMOSD1MINI]: 'BOARD_WEMOSD1MINI',
[BoardType.TTGO_TBASE]: 'BOARD_TTGO_TBASE',
[BoardType.ESP01]: 'BOARD_ESP01',
[BoardType.SLIMEVR]: 'BOARD_SLIMEVR',
[BoardType.LOLIN_C3_MINI]: 'BOARD_LOLIN_C3_MINI',
[BoardType.BEETLE32C3]: 'BOARD_BEETLE32C3',
[BoardType.ES32C3DEVKITM1]: 'BOARD_ES32C3DEVKITM1',
};
export const firmwareToolToBoardType: Record<CreateBoardConfigDTO['type'], BoardType> =
Object.fromEntries(
Object.entries(boardTypeToFirmwareToolBoardType).map((a) => a.reverse())
);
export const firmwareUpdateErrorStatus = [
FirmwareUpdateStatus.ERROR_AUTHENTICATION_FAILED,
FirmwareUpdateStatus.ERROR_DEVICE_NOT_FOUND,
FirmwareUpdateStatus.ERROR_DOWNLOAD_FAILED,
FirmwareUpdateStatus.ERROR_PROVISIONING_FAILED,
FirmwareUpdateStatus.ERROR_TIMEOUT,
FirmwareUpdateStatus.ERROR_UNKNOWN,
FirmwareUpdateStatus.ERROR_UNSUPPORTED_METHOD,
FirmwareUpdateStatus.ERROR_UPLOAD_FAILED,
];
export interface FirmwareToolContext {
selectBoard: (boardType: CreateBoardConfigDTO['type']) => Promise<void>;
selectVersion: (version: CreateBuildFirmwareDTO['version']) => void;
updatePins: (form: BoardPinsForm) => void;
updateImus: (imus: CreateBuildFirmwareDTO['imusConfig']) => void;
setBuildStatus: (buildStatus: FirmwareBuildStatus) => void;
selectDevices: (device: SelectedDevice[] | null) => void;
retry: () => void;
buildStatus: FirmwareBuildStatus;
defaultConfig: DefaultBuildConfigDTO | null;
newConfig: PartialBuildFirmware | null;
selectedDevices: SelectedDevice[] | null;
isStepLoading: boolean;
isGlobalLoading: boolean;
isCompatible: boolean;
isError: boolean;
}
export const FirmwareToolContextC = createContext<FirmwareToolContext>(
undefined as any
);
export function useFirmwareTool() {
const context = useContext<FirmwareToolContext>(FirmwareToolContextC);
if (!context) {
throw new Error('useFirmwareTool must be within a FirmwareToolContext Provider');
}
return context;
}
export function useFirmwareToolContext(): FirmwareToolContext {
const [defaultConfig, setDefaultConfig] = useState<DefaultBuildConfigDTO | null>(
null
);
const [selectedDevices, selectDevices] = useState<SelectedDevice[] | null>(null);
const [newConfig, setNewConfig] = useState<PartialBuildFirmware>({});
const [isLoading, setLoading] = useState(false);
const { isError, isLoading: isInitialLoading, refetch } = useGetHealth({});
const compatibilityCheckEnabled = !!__VERSION_TAG__;
const { isLoading: isCompatibilityLoading, data: compatibilityData } =
useGetIsCompatibleVersion(
{ pathParams: { version: __VERSION_TAG__ } },
{ enabled: compatibilityCheckEnabled }
);
const [buildStatus, setBuildStatus] = useState<FirmwareBuildStatus>({
status: 'CREATING_BUILD_FOLDER',
id: '',
});
return {
selectBoard: async (boardType: CreateBoardConfigDTO['type']) => {
setLoading(true);
const boardDefaults = await fetchGetFirmwaresDefaultConfigBoard({
pathParams: { board: boardType },
});
setDefaultConfig(boardDefaults);
if (boardDefaults.shouldOnlyUseDefaults) {
setNewConfig((currConfig) => ({
...currConfig,
...boardDefaults,
imusConfig: boardDefaults.imuDefaults,
}));
} else {
setNewConfig((currConfig) => ({
...currConfig,
boardConfig: { ...currConfig.boardConfig, type: boardType },
imusConfig: [],
}));
}
setLoading(false);
},
updatePins: (form: BoardPinsForm) => {
setNewConfig((currConfig) => {
return {
...currConfig,
imusConfig: [...(currConfig?.imusConfig || [])],
boardConfig: {
...currConfig.boardConfig,
...form,
},
};
});
},
updateImus: (imus: CreateBuildFirmwareDTO['imusConfig']) => {
setNewConfig((currConfig) => {
return {
...currConfig,
imusConfig: imus.map(({ rotation, ...fields }) => ({
...fields,
rotation: Number(rotation),
})), // Make sure that the rotation is handled as number
};
});
},
retry: async () => {
setLoading(true);
await refetch();
setLoading(false);
},
selectVersion: (version: CreateBuildFirmwareDTO['version']) => {
setNewConfig((currConfig) => ({ ...currConfig, version }));
},
setBuildStatus,
selectDevices,
selectedDevices,
buildStatus,
defaultConfig,
newConfig,
isStepLoading: isLoading,
isGlobalLoading: isInitialLoading || isCompatibilityLoading,
isCompatible: !compatibilityCheckEnabled || (compatibilityData?.success ?? false),
isError: isError || (!compatibilityData?.success && compatibilityCheckEnabled),
};
}
export const getFlashingRequests = (
devices: SelectedDevice[],
firmwareFiles: FirmwareFileDTO[],
onboardingState: OnboardingContext['state'],
defaultConfig: DefaultBuildConfigDTO | null
) => {
const firmware = firmwareFiles.find(({ isFirmware }) => isFirmware);
if (!firmware) throw new Error('invalid state - no firmware to find');
const requests = [];
for (const device of devices) {
switch (device.type) {
case FirmwareUpdateMethod.OTAFirmwareUpdate: {
const dId = new DeviceIdT();
dId.id = +device.deviceId;
const part = new FirmwarePartT();
part.offset = 0;
part.url = firmware.url;
const method = new OTAFirmwareUpdateT();
method.deviceId = dId;
method.firmwarePart = part;
const req = new FirmwareUpdateRequestT();
req.method = method;
req.methodType = FirmwareUpdateMethod.OTAFirmwareUpdate;
requests.push(req);
break;
}
case FirmwareUpdateMethod.SerialFirmwareUpdate: {
const id = new SerialDevicePortT();
id.port = device.deviceId.toString();
if (!onboardingState.wifi?.ssid || !onboardingState.wifi?.password)
throw new Error('invalid state, wifi should be set');
const method = new SerialFirmwareUpdateT();
method.deviceId = id;
method.ssid = onboardingState.wifi.ssid;
method.password = onboardingState.wifi.password;
method.needManualReboot = defaultConfig?.needManualReboot ?? false;
method.firmwarePart = firmwareFiles.map(({ offset, url }) => {
const part = new FirmwarePartT();
part.offset = offset;
part.url = url;
return part;
});
const req = new FirmwareUpdateRequestT();
req.method = method;
req.methodType = FirmwareUpdateMethod.SerialFirmwareUpdate;
requests.push(req);
break;
}
default: {
throw new Error('unsupported flashing method');
}
}
}
return requests;
};
+58
View File
@@ -0,0 +1,58 @@
import { createContext, useContext, useEffect, useState } from 'react';
import { useWebsocketAPI } from './websocket-api';
import { RpcMessage, SettingsRequestT, SettingsResponseT } from 'solarxr-protocol';
import { MIN_HEIGHT } from '@/components/onboarding/pages/body-proportions/ProportionsChoose';
export interface HeightContext {
hmdHeight: number | null;
setHmdHeight: React.Dispatch<React.SetStateAction<number | null>>;
floorHeight: number | null;
setFloorHeight: React.Dispatch<React.SetStateAction<number | null>>;
validateHeight: (
hmdHeight: number | null | undefined,
floorHeight: number | null | undefined
) => boolean;
}
export function useProvideHeightContext(): HeightContext {
const [hmdHeight, setHmdHeight] = useState<number | null>(null);
const [floorHeight, setFloorHeight] = useState<number | null>(null);
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
function validateHeight(
hmdHeight: number | null | undefined,
floorHeight: number | null | undefined
) {
return (
hmdHeight !== undefined &&
hmdHeight !== null &&
hmdHeight - (floorHeight ?? 0) > MIN_HEIGHT
);
}
useEffect(
() => sendRPCPacket(RpcMessage.SettingsRequest, new SettingsRequestT()),
[]
);
useRPCPacket(RpcMessage.SettingsResponse, (res: SettingsResponseT) => {
const hmd = res.modelSettings?.skeletonHeight?.hmdHeight;
const floor = res.modelSettings?.skeletonHeight?.floorHeight;
if (validateHeight(hmd, floor)) {
setHmdHeight(hmd ?? null);
setFloorHeight(floor ?? null);
}
});
return { hmdHeight, setHmdHeight, floorHeight, setFloorHeight, validateHeight };
}
export const HeightContextC = createContext<HeightContext>(undefined as never);
export function useHeightContext() {
const context = useContext(HeightContextC);
if (!context) {
throw new Error('useHeightContext must be within a HeightContext Provider');
}
return context;
}
+3 -3
View File
@@ -16,7 +16,7 @@ interface OnboardingState {
export interface OnboardingContext {
state: OnboardingState;
applyProgress: (value: number) => void;
setWifiCredentials: (ssid: string, password: string) => void;
setWifiCredentials: (ssid: string, password?: string) => void;
skipSetup: () => void;
}
@@ -68,8 +68,8 @@ export function useProvideOnboarding(): OnboardingContext {
dispatch({ type: 'progress', value });
}, []);
},
setWifiCredentials: (ssid: string, password: string) => {
dispatch({ type: 'wifi-creds', ssid, password });
setWifiCredentials: (ssid: string, password?: string) => {
dispatch({ type: 'wifi-creds', ssid, password: password ?? '' });
},
skipSetup: () => {
setConfig({ doneOnboarding: true });
+9 -8
View File
@@ -1,8 +1,8 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { BodyPart, TrackerDataT, TrackerStatus } from 'solarxr-protocol';
import { BodyPart, TrackerDataT, TrackerInfoT, TrackerStatus } from 'solarxr-protocol';
import { QuaternionFromQuatT, QuaternionToEulerDegrees } from '@/maths/quaternion';
import { useAppContext } from './app';
import { useLocalization } from '@fluent/react';
import { ReactLocalization, useLocalization } from '@fluent/react';
import { useDataFeedConfig } from './datafeed-config';
import { Quaternion, Vector3 } from 'three';
import { Vector3FromVec3fT } from '@/maths/vector3';
@@ -36,18 +36,19 @@ export function useTrackers() {
};
}
export function getTrackerName(l10n: ReactLocalization, info: TrackerInfoT | null) {
if (info?.customName) return info?.customName;
if (info?.bodyPart) return l10n.getString('body_part-' + BodyPart[info?.bodyPart]);
return info?.displayName || 'NONE';
}
export function useTracker(tracker: TrackerDataT) {
const { l10n } = useLocalization();
const { feedMaxTps } = useDataFeedConfig();
return {
useName: () =>
useMemo(() => {
if (tracker.info?.customName) return tracker.info?.customName;
if (tracker.info?.bodyPart)
return l10n.getString('body_part-' + BodyPart[tracker.info?.bodyPart]);
return tracker.info?.displayName || 'NONE';
}, [tracker.info]),
useMemo(() => getTrackerName(l10n, tracker.info), [tracker.info, l10n]),
useRawRotationEulerDegrees: () =>
useMemo(() => QuaternionToEulerDegrees(tracker?.rotation), [tracker.rotation]),
useRefAdjRotationEulerDegrees: () =>
+9 -1
View File
@@ -84,7 +84,7 @@ body {
}
:root {
overflow: hidden;
// overflow: hidden; -- NEVER EVER BRING THIS BACK <3
background: theme('colors.background.20');
--navbar-w: 101px;
@@ -382,6 +382,14 @@ body {
background: theme('colors.background.60');
}
.bg-background-60::-webkit-scrollbar-thumb:hover {
background: theme('colors.background.40');
}
.bg-background-60 {
scrollbar-color: theme('colors.background.50') transparent;
}
.dropdown-scroll {
scrollbar-color: theme('colors.background.40') theme('colors.background.50');
}
+16 -16
View File
@@ -223,8 +223,8 @@ export class BoneKind extends Bone {
case BodyPart.LEFT_HIP:
case BodyPart.RIGHT_HIP:
return new Color('pink');
case BodyPart.LEFT_THUMB_METACARPAL:
case BodyPart.LEFT_THUMB_PROXIMAL:
case BodyPart.LEFT_THUMB_INTERMEDIATE:
case BodyPart.LEFT_THUMB_DISTAL:
case BodyPart.LEFT_INDEX_PROXIMAL:
case BodyPart.LEFT_INDEX_INTERMEDIATE:
@@ -238,8 +238,8 @@ export class BoneKind extends Bone {
case BodyPart.LEFT_LITTLE_PROXIMAL:
case BodyPart.LEFT_LITTLE_INTERMEDIATE:
case BodyPart.LEFT_LITTLE_DISTAL:
case BodyPart.RIGHT_THUMB_METACARPAL:
case BodyPart.RIGHT_THUMB_PROXIMAL:
case BodyPart.RIGHT_THUMB_INTERMEDIATE:
case BodyPart.RIGHT_THUMB_DISTAL:
case BodyPart.RIGHT_INDEX_PROXIMAL:
case BodyPart.RIGHT_INDEX_INTERMEDIATE:
@@ -307,7 +307,7 @@ export class BoneKind extends Bone {
return [BodyPart.RIGHT_HAND];
case BodyPart.LEFT_HAND:
return [
BodyPart.LEFT_THUMB_PROXIMAL,
BodyPart.LEFT_THUMB_METACARPAL,
BodyPart.LEFT_INDEX_PROXIMAL,
BodyPart.LEFT_MIDDLE_PROXIMAL,
BodyPart.LEFT_RING_PROXIMAL,
@@ -315,16 +315,16 @@ export class BoneKind extends Bone {
];
case BodyPart.RIGHT_HAND:
return [
BodyPart.RIGHT_THUMB_PROXIMAL,
BodyPart.RIGHT_THUMB_METACARPAL,
BodyPart.RIGHT_INDEX_PROXIMAL,
BodyPart.RIGHT_MIDDLE_PROXIMAL,
BodyPart.RIGHT_RING_PROXIMAL,
BodyPart.RIGHT_LITTLE_PROXIMAL,
];
case BodyPart.LEFT_THUMB_METACARPAL:
return [BodyPart.LEFT_THUMB_PROXIMAL];
case BodyPart.LEFT_THUMB_PROXIMAL:
return [BodyPart.LEFT_THUMB_INTERMEDIATE];
case BodyPart.LEFT_THUMB_INTERMEDIATE:
return [BodyPart.LEFT_THUMB_DISTAL];
case BodyPart.LEFT_THUMB_DISTAL:
return [];
@@ -352,9 +352,9 @@ export class BoneKind extends Bone {
return [BodyPart.LEFT_LITTLE_DISTAL];
case BodyPart.LEFT_LITTLE_DISTAL:
return [];
case BodyPart.RIGHT_THUMB_METACARPAL:
return [BodyPart.RIGHT_THUMB_PROXIMAL];
case BodyPart.RIGHT_THUMB_PROXIMAL:
return [BodyPart.RIGHT_THUMB_INTERMEDIATE];
case BodyPart.RIGHT_THUMB_INTERMEDIATE:
return [BodyPart.RIGHT_THUMB_DISTAL];
case BodyPart.RIGHT_THUMB_DISTAL:
return [];
@@ -434,12 +434,12 @@ export class BoneKind extends Bone {
case BodyPart.RIGHT_HAND:
return BodyPart.RIGHT_LOWER_ARM;
case BodyPart.LEFT_THUMB_PROXIMAL:
case BodyPart.LEFT_THUMB_METACARPAL:
return BodyPart.LEFT_HAND;
case BodyPart.LEFT_THUMB_INTERMEDIATE:
return BodyPart.LEFT_THUMB_PROXIMAL;
case BodyPart.LEFT_THUMB_PROXIMAL:
return BodyPart.LEFT_THUMB_METACARPAL;
case BodyPart.LEFT_THUMB_DISTAL:
return BodyPart.LEFT_THUMB_INTERMEDIATE;
return BodyPart.LEFT_THUMB_PROXIMAL;
case BodyPart.LEFT_INDEX_PROXIMAL:
return BodyPart.LEFT_HAND;
case BodyPart.LEFT_INDEX_INTERMEDIATE:
@@ -464,12 +464,12 @@ export class BoneKind extends Bone {
return BodyPart.LEFT_LITTLE_PROXIMAL;
case BodyPart.LEFT_LITTLE_DISTAL:
return BodyPart.LEFT_LITTLE_INTERMEDIATE;
case BodyPart.RIGHT_THUMB_PROXIMAL:
case BodyPart.RIGHT_THUMB_METACARPAL:
return BodyPart.RIGHT_HAND;
case BodyPart.RIGHT_THUMB_INTERMEDIATE:
return BodyPart.RIGHT_THUMB_PROXIMAL;
case BodyPart.RIGHT_THUMB_PROXIMAL:
return BodyPart.RIGHT_THUMB_METACARPAL;
case BodyPart.RIGHT_THUMB_DISTAL:
return BodyPart.RIGHT_THUMB_INTERMEDIATE;
return BodyPart.RIGHT_THUMB_PROXIMAL;
case BodyPart.RIGHT_INDEX_PROXIMAL:
return BodyPart.RIGHT_HAND;
case BodyPart.RIGHT_INDEX_INTERMEDIATE:
+5 -1
View File
@@ -1,5 +1,6 @@
import plugin from 'tailwindcss/plugin';
import forms from '@tailwindcss/forms';
import typography from '@tailwindcss/typography';
import gradient from 'tailwind-gradient-mask-image';
import type { Config } from 'tailwindcss';
@@ -150,7 +151,7 @@ const colors = {
700: '#b3b3b3',
900: '#d8d8d8',
},
'asexual': {
asexual: {
100: '#000000',
200: '#A3A3A3',
300: '#FFFFFF',
@@ -162,9 +163,11 @@ const config = {
content: ['./src/**/*.{js,jsx,ts,tsx}'],
theme: {
screens: {
'mobile-settings': { raw: 'not (min-width: 900px)' },
nsmol: { raw: 'not (min-width: 525px)' },
smol: '525px',
mobile: { raw: 'not (min-width: 800px)' },
'xs-settings': '900px',
xs: '800px',
nsm: { raw: 'not (min-width: 900px)' },
sm: '900px',
@@ -245,6 +248,7 @@ const config = {
plugins: [
forms,
gradient,
typography,
plugin(function ({ addUtilities }) {
const textConfig = (fontSize: any, fontWeight: any) => ({
fontSize,
+4 -2
View File
@@ -10,7 +10,9 @@ const versionTag = execSync('git --no-pager tag --sort -taggerdate --points-at H
.split('\n')[0]
.trim();
// If not empty then it's not clean
const gitClean = execSync('git status --porcelain').toString() ? false : true;
const gitCleanString = execSync('git status --porcelain').toString();
const gitClean = gitCleanString ? false : true;
if (!gitClean) console.log('Git is dirty because of:\n' + gitCleanString);
console.log(`version is ${versionTag || commitHash}${gitClean ? '' : '-dirty'}`);
@@ -21,7 +23,7 @@ export function i18nHotReload(): PluginOption {
handleHotUpdate({ file, server }) {
if (file.endsWith('.ftl')) {
console.log('Fluent files updated');
server.ws.send({
server.hot.send({
type: 'custom',
event: 'locales-update',
});
+3112 -547
View File
File diff suppressed because it is too large. Load diff
+2 -6
View File
@@ -57,12 +57,8 @@ tasks.withType<Javadoc> {
options.encoding = "UTF-8"
}
allprojects {
repositories {
google()
mavenCentral()
maven(url = "https://jitpack.io")
}
repositories {
google()
}
dependencies {
@@ -90,10 +90,16 @@ class AndroidSerialHandler(val activity: AppCompatActivity) :
listeners.forEach { it.onNewSerialDevice(port) }
}
private fun onDeviceDel(port: SerialPortWrapper) {
listeners.forEach { it.onSerialDeviceDeleted(port) }
}
private fun detectNewPorts() {
val differences = knownPorts.asSequence() - lastKnownPorts
val addDifferences = knownPorts.asSequence() - lastKnownPorts
val delDifferences = lastKnownPorts - knownPorts.asSequence().toSet()
lastKnownPorts = knownPorts.asSequence().toSet()
differences.forEach { onNewDevice(it) }
addDifferences.forEach { onNewDevice(it) }
delDifferences.forEach { onDeviceDel(it) }
}
override fun addListener(channel: SerialListener) {
@@ -226,12 +232,18 @@ class AndroidSerialHandler(val activity: AppCompatActivity) :
}
}
override fun write(buff: ByteArray) {
usbIoManager?.writeAsync(buff)
}
@Synchronized
override fun setWifi(ssid: String, passwd: String) {
writeSerial("SET WIFI \"${ssid}\" \"${passwd}\"")
addLog("-> SET WIFI \"$ssid\" \"${passwd.replace(".".toRegex(), "*")}\"\n")
}
override fun getCurrentPort(): SlimeSerialPort? = this.currentPort
private fun addLog(str: String) {
LogManager.info("[Serial] $str")
listeners.forEach { it.onSerialLog(str) }
+10 -5
View File
@@ -2,8 +2,11 @@ plugins {
id("com.diffplug.spotless")
}
repositories {
mavenCentral()
allprojects {
repositories {
mavenCentral()
maven("https://jitpack.io")
}
}
configure<com.diffplug.gradle.spotless.SpotlessExtension> {
@@ -17,7 +20,7 @@ configure<com.diffplug.gradle.spotless.SpotlessExtension> {
// define the steps to apply to those files
trimTrailingWhitespace()
endWithNewline()
indentWithTabs()
leadingSpacesToTabs()
}
// format "yaml", {
// target "*.yml", "*.yaml",
@@ -35,7 +38,7 @@ configure<com.diffplug.gradle.spotless.SpotlessExtension> {
"ktlint_standard_property-naming" to "disabled",
"ij_kotlin_packages_to_use_import_on_demand" to
"java.util.*,kotlin.math.*,dev.slimevr.autobone.errors.*" +
",io.github.axisangles.ktmath.*,kotlinx.atomicfu.*" +
",io.github.axisangles.ktmath.*,kotlinx.atomicfu.*,kotlinx.coroutines.*" +
",dev.slimevr.tracking.trackers.*,dev.slimevr.desktop.platform.ProtobufMessages.*" +
",solarxr_protocol.rpc.*,kotlinx.coroutines.*,com.illposed.osc.*,android.app.*",
"ij_kotlin_allow_trailing_comma" to true,
@@ -58,6 +61,8 @@ configure<com.diffplug.gradle.spotless.SpotlessExtension> {
removeUnusedImports()
// Use eclipse JDT formatter
eclipse().configFile("spotless.xml")
eclipse()
.configFile("spotless.xml")
.withP2Mirrors(mapOf("https://download.eclipse.org/" to "https://mirror.umd.edu/eclipse/"))
}
}
+7
View File
@@ -77,6 +77,12 @@ dependencies {
implementation("com.melloware:jintellitype:1.+")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.8.1")
implementation("com.mayakapps.kache:kache:2.1.0")
api("com.github.loucass003:EspflashKotlin:v0.10.0")
// Allow the use of reflection
implementation(kotlin("reflect"))
// Jitpack
implementation("com.github.SlimeVR:oscquery-kt:566a0cba58")
@@ -87,6 +93,7 @@ dependencies {
testImplementation("org.junit.jupiter:junit-jupiter")
testImplementation("org.junit.platform:junit-platform-launcher")
}
tasks.test {
useJUnitPlatform()
}
@@ -5,6 +5,8 @@ import dev.slimevr.autobone.AutoBoneHandler
import dev.slimevr.bridge.Bridge
import dev.slimevr.bridge.ISteamVRBridge
import dev.slimevr.config.ConfigManager
import dev.slimevr.firmware.FirmwareUpdateHandler
import dev.slimevr.firmware.SerialFlashingHandler
import dev.slimevr.osc.OSCHandler
import dev.slimevr.osc.OSCRouter
import dev.slimevr.osc.VMCHandler
@@ -36,20 +38,22 @@ import java.util.concurrent.atomic.AtomicInteger
import java.util.function.Consumer
import kotlin.concurrent.schedule
typealias SteamBridgeProvider = (
typealias BridgeProvider = (
server: VRServer,
computedTrackers: List<Tracker>,
) -> ISteamVRBridge?
) -> Sequence<Bridge>
const val SLIMEVR_IDENTIFIER = "dev.slimevr.SlimeVR"
class VRServer @JvmOverloads constructor(
driverBridgeProvider: SteamBridgeProvider = { _, _ -> null },
feederBridgeProvider: (VRServer) -> ISteamVRBridge? = { _ -> null },
bridgeProvider: BridgeProvider = { _, _ -> sequence {} },
serialHandlerProvider: (VRServer) -> SerialHandler = { _ -> SerialHandlerStub() },
flashingHandlerProvider: (VRServer) -> SerialFlashingHandler? = { _ -> null },
acquireMulticastLock: () -> Any? = { null },
// configPath is used by VRWorkout, do not remove!
configPath: String,
) : Thread("VRServer") {
@JvmField
val configManager: ConfigManager
@@ -60,6 +64,7 @@ class VRServer @JvmOverloads constructor(
private val bridges: MutableList<Bridge> = FastList()
private val tasks: Queue<Runnable> = LinkedBlockingQueue()
private val newTrackersConsumers: MutableList<Consumer<Tracker>> = FastList()
private val trackerStatusListeners: MutableList<TrackerStatusListener> = FastList()
private val onTick: MutableList<Runnable> = FastList()
private val lock = acquireMulticastLock()
val oSCRouter: OSCRouter
@@ -77,6 +82,10 @@ class VRServer @JvmOverloads constructor(
@JvmField
val serialHandler: SerialHandler
var serialFlashingHandler: SerialFlashingHandler?
val firmwareUpdateHandler: FirmwareUpdateHandler
@JvmField
val autoBoneHandler: AutoBoneHandler
@@ -106,12 +115,14 @@ class VRServer @JvmOverloads constructor(
configManager.loadConfig()
deviceManager = DeviceManager(this)
serialHandler = serialHandlerProvider(this)
serialFlashingHandler = flashingHandlerProvider(this)
provisioningHandler = ProvisioningHandler(this)
resetHandler = ResetHandler()
tapSetupHandler = TapSetupHandler()
humanPoseManager = HumanPoseManager(this)
// AutoBone requires HumanPoseManager first
autoBoneHandler = AutoBoneHandler(this)
firmwareUpdateHandler = FirmwareUpdateHandler(this)
protocolAPI = ProtocolAPI(this)
val computedTrackers = humanPoseManager.computedTrackers
@@ -123,22 +134,11 @@ class VRServer @JvmOverloads constructor(
"Sensors UDP server",
) { tracker: Tracker -> registerTracker(tracker) }
// Start bridges for SteamVR and Feeder
val driverBridge = driverBridgeProvider(this, computedTrackers)
if (driverBridge != null) {
tasks.add(Runnable { driverBridge.startBridge() })
bridges.add(driverBridge)
// Start bridges and WebSocket server
for (bridge in bridgeProvider(this, computedTrackers) + sequenceOf(WebSocketVRBridge(computedTrackers, this))) {
tasks.add(Runnable { bridge.startBridge() })
bridges.add(bridge)
}
val feederBridge = feederBridgeProvider(this)
if (feederBridge != null) {
tasks.add(Runnable { feederBridge.startBridge() })
bridges.add(feederBridge)
}
// Create WebSocket server
val wsBridge = WebSocketVRBridge(computedTrackers, this)
tasks.add(Runnable { wsBridge.startBridge() })
bridges.add(wsBridge)
// Initialize OSC handlers
vrcOSCHandler = VRCOSCHandler(
@@ -409,6 +409,18 @@ class VRServer @JvmOverloads constructor(
}
}
fun trackerStatusChanged(tracker: Tracker, oldStatus: TrackerStatus, newStatus: TrackerStatus) {
trackerStatusListeners.forEach { it.onTrackerStatusChanged(tracker, oldStatus, newStatus) }
}
fun addTrackerStatusListener(listener: TrackerStatusListener) {
trackerStatusListeners.add(listener)
}
fun removeTrackerStatusListener(listener: TrackerStatusListener) {
trackerStatusListeners.removeIf { listener == it }
}
companion object {
private val nextLocalTrackerId = AtomicInteger()
lateinit var instance: VRServer
@@ -4,8 +4,10 @@ import dev.slimevr.SLIMEVR_IDENTIFIER
import dev.slimevr.VRServer
import dev.slimevr.autobone.errors.*
import dev.slimevr.config.AutoBoneConfig
import dev.slimevr.config.SkeletonConfig
import dev.slimevr.poseframeformat.PoseFrameIO
import dev.slimevr.poseframeformat.PoseFrames
import dev.slimevr.tracking.processor.BoneType
import dev.slimevr.tracking.processor.HumanPoseManager
import dev.slimevr.tracking.processor.config.SkeletonConfigManager
import dev.slimevr.tracking.processor.config.SkeletonConfigOffsets
@@ -22,7 +24,7 @@ import java.util.function.Consumer
import java.util.function.Function
import kotlin.math.*
class AutoBone(server: VRServer) {
class AutoBone(private val server: VRServer) {
// This is filled by loadConfigValues()
val offsets = EnumMap<SkeletonConfigOffsets, Float>(
SkeletonConfigOffsets::class.java,
@@ -48,8 +50,6 @@ class AutoBone(server: VRServer) {
// The total height of the normalized adjusted offsets
var adjustedHeightNormalized: Float = 1f
private val server: VRServer
// #region Error functions
var slideError = SlideError()
var offsetSlideError = OffsetSlideError()
@@ -62,11 +62,10 @@ class AutoBone(server: VRServer) {
private val rand = Random()
val globalConfig: AutoBoneConfig
val globalConfig: AutoBoneConfig = server.configManager.vrConfig.autoBone
val globalSkeletonConfig: SkeletonConfig = server.configManager.vrConfig.skeleton
init {
globalConfig = server.configManager.vrConfig.autoBone
this.server = server
loadConfigValues()
}
@@ -94,38 +93,73 @@ class AutoBone(server: VRServer) {
}
}
fun getBoneDirection(
/**
* Computes the local tail position of the bone after rotation.
*/
fun getBoneLocalTail(
skeleton: HumanPoseManager,
configOffset: SkeletonConfigOffsets,
rightSide: Boolean,
boneType: BoneType,
): Vector3 {
// IMPORTANT: This assumption for acquiring BoneType only works if
// SkeletonConfigOffsets is set up to only affect one BoneType, make sure no
// changes to SkeletonConfigOffsets goes against this assumption, please!
val boneType = when (configOffset) {
SkeletonConfigOffsets.HIPS_WIDTH, SkeletonConfigOffsets.SHOULDERS_WIDTH,
SkeletonConfigOffsets.SHOULDERS_DISTANCE, SkeletonConfigOffsets.UPPER_ARM,
SkeletonConfigOffsets.LOWER_ARM, SkeletonConfigOffsets.UPPER_LEG,
SkeletonConfigOffsets.LOWER_LEG, SkeletonConfigOffsets.FOOT_LENGTH,
->
if (rightSide) configOffset.affectedOffsets[1] else configOffset.affectedOffsets[0]
else -> configOffset.affectedOffsets[0]
}
return skeleton.getBone(boneType).getGlobalRotation().toRotationVector()
val bone = skeleton.getBone(boneType)
return bone.getTailPosition() - bone.getPosition()
}
fun getDotProductDiff(
/**
* Computes the direction of the bone tail's movement between skeletons 1 and 2.
*/
fun getBoneLocalTailDir(
skeleton1: HumanPoseManager,
skeleton2: HumanPoseManager,
configOffset: SkeletonConfigOffsets,
rightSide: Boolean,
offset: Vector3,
boneType: BoneType,
): Vector3? {
val boneOff = getBoneLocalTail(skeleton2, boneType) - getBoneLocalTail(skeleton1, boneType)
val boneOffLen = boneOff.len()
return if (boneOffLen > MIN_SLIDE_DIST) boneOff / boneOffLen else null
}
/**
* Predicts how much the provided config should be affecting the slide offsets
* of the left and right ankles.
*/
fun getSlideDot(
skeleton1: HumanPoseManager,
skeleton2: HumanPoseManager,
config: SkeletonConfigOffsets,
slideL: Vector3?,
slideR: Vector3?,
): Float {
val normalizedOffset = offset.unit()
val dot1 = normalizedOffset.dot(getBoneDirection(skeleton1, configOffset, rightSide))
val dot2 = normalizedOffset.dot(getBoneDirection(skeleton2, configOffset, rightSide))
return dot2 - dot1
var slideDot = 0f
// Used for right offset if not a symmetric bone
var boneOffL: Vector3? = null
if (slideL != null) {
boneOffL = getBoneLocalTailDir(skeleton1, skeleton2, config.affectedOffsets[0])
if (boneOffL != null) {
slideDot += slideL.dot(boneOffL)
}
}
if (slideR != null) {
// IMPORTANT: This assumption for acquiring BoneType only works if
// SkeletonConfigOffsets is set up to only affect one BoneType, make sure no
// changes to SkeletonConfigOffsets goes against this assumption, please!
val boneOffR = if (SYMM_CONFIGS.contains(config)) {
getBoneLocalTailDir(skeleton1, skeleton2, config.affectedOffsets[1])
} else if (slideL != null) {
// Use cached offset if slideL was used
boneOffL
} else {
// Compute offset if missing because of slideL
getBoneLocalTailDir(skeleton1, skeleton2, config.affectedOffsets[0])
}
if (boneOffR != null) {
slideDot += slideR.dot(boneOffR)
}
}
return slideDot / 2f
}
fun applyConfig(
@@ -155,6 +189,7 @@ class AutoBone(server: VRServer) {
// Get the current skeleton from the server
val humanPoseManager = server.humanPoseManager
// Still compensate for a null skeleton, as it may not be initialized yet
@Suppress("SENSELESS_COMPARISON")
if (config.useSkeletonHeight && humanPoseManager != null) {
// If there is a skeleton available, calculate the target height
// from its configs
@@ -193,6 +228,7 @@ class AutoBone(server: VRServer) {
fun processFrames(
frames: PoseFrames,
config: AutoBoneConfig = globalConfig,
skeletonConfig: SkeletonConfig = globalSkeletonConfig,
epochCallback: Consumer<Epoch>? = null,
): AutoBoneResults {
check(frames.frameHolders.isNotEmpty()) { "Recording has no trackers." }
@@ -202,16 +238,11 @@ class AutoBone(server: VRServer) {
loadConfigValues()
// Set the target heights either from config or calculate them
val targetHmdHeight = if (config.targetHmdHeight > 0f) {
config.targetHmdHeight
val targetHmdHeight = if (skeletonConfig.userHeight > MIN_HEIGHT) {
skeletonConfig.userHeight
} else {
calcTargetHmdHeight(frames, config)
}
val targetFullHeight = if (config.targetFullHeight > 0f) {
config.targetFullHeight
} else {
targetHmdHeight / BodyProportionError.eyeHeightToHeightRatio
}
check(targetHmdHeight > MIN_HEIGHT) { "Configured height ($targetHmdHeight) is too small (<= $MIN_HEIGHT)." }
// Set up the current state, making all required players and setting up the
@@ -219,7 +250,6 @@ class AutoBone(server: VRServer) {
val trainingStep = AutoBoneStep(
config = config,
targetHmdHeight = targetHmdHeight,
targetFullHeight = targetFullHeight,
frames = frames,
epochCallback = epochCallback,
serverConfig = server.configManager,
@@ -488,13 +518,15 @@ class AutoBone(server: VRServer) {
return
}
val slideLeft = skeleton2
.getComputedTracker(TrackerRole.LEFT_FOOT).position -
val slideL = skeleton2.getComputedTracker(TrackerRole.LEFT_FOOT).position -
skeleton1.getComputedTracker(TrackerRole.LEFT_FOOT).position
val slideLLen = slideL.len()
val slideLUnit: Vector3? = if (slideLLen > MIN_SLIDE_DIST) slideL / slideLLen else null
val slideRight = skeleton2
.getComputedTracker(TrackerRole.RIGHT_FOOT).position -
val slideR = skeleton2.getComputedTracker(TrackerRole.RIGHT_FOOT).position -
skeleton1.getComputedTracker(TrackerRole.RIGHT_FOOT).position
val slideRLen = slideR.len()
val slideRUnit: Vector3? = if (slideRLen > MIN_SLIDE_DIST) slideR / slideRLen else null
val intermediateOffsets = EnumMap(offsets)
for (entry in intermediateOffsets.entries) {
@@ -505,28 +537,23 @@ class AutoBone(server: VRServer) {
}
val originalLength = entry.value
val leftDotProduct = getDotProductDiff(
skeleton1,
skeleton2,
entry.key,
false,
slideLeft,
)
val rightDotProduct = getDotProductDiff(
skeleton1,
skeleton2,
entry.key,
true,
slideRight,
)
// Calculate the total effect of the bone based on change in rotation
val dotLength = originalLength * ((leftDotProduct + rightDotProduct) / 2f)
val slideDot = getSlideDot(
skeleton1,
skeleton2,
entry.key,
slideLUnit,
slideRUnit,
)
val dotLength = originalLength * slideDot
// Scale by the total effect of the bone
val curAdjustVal = adjustVal * -dotLength
val newLength = originalLength + curAdjustVal
if (curAdjustVal == 0f) {
continue
}
val newLength = originalLength + curAdjustVal
// No small or negative numbers!!! Bad algorithm!
if (newLength < 0.01f) {
continue
@@ -754,6 +781,7 @@ class AutoBone(server: VRServer) {
companion object {
const val MIN_HEIGHT = 0.4f
const val MIN_SLIDE_DIST = 0.002f
const val AUTOBONE_FOLDER = "AutoBone Recordings"
const val LOADAUTOBONE_FOLDER = "Load AutoBone Recordings"
@@ -773,5 +801,16 @@ class AutoBone(server: VRServer) {
private fun errorFunc(errorDeriv: Float): Float = 0.5f * (errorDeriv * errorDeriv)
private fun decayFunc(initialAdjustRate: Float, adjustRateDecay: Float, epoch: Int): Float = if (epoch >= 0) initialAdjustRate / (1 + (adjustRateDecay * epoch)) else 0.0f
private val SYMM_CONFIGS = arrayOf(
SkeletonConfigOffsets.HIPS_WIDTH,
SkeletonConfigOffsets.SHOULDERS_WIDTH,
SkeletonConfigOffsets.SHOULDERS_DISTANCE,
SkeletonConfigOffsets.UPPER_ARM,
SkeletonConfigOffsets.LOWER_ARM,
SkeletonConfigOffsets.UPPER_LEG,
SkeletonConfigOffsets.LOWER_LEG,
SkeletonConfigOffsets.FOOT_LENGTH,
)
}
}
@@ -10,7 +10,6 @@ import java.util.function.Consumer
class AutoBoneStep(
val config: AutoBoneConfig,
val targetHmdHeight: Float,
val targetFullHeight: Float,
val frames: PoseFrames,
val epochCallback: Consumer<AutoBone.Epoch>?,
serverConfig: ConfigManager,
@@ -20,9 +19,6 @@ class AutoBoneStep(
var cursor2: Int = 0,
var currentHmdHeight: Float = 0f,
) {
val eyeHeightToHeightRatio: Float = targetHmdHeight / targetFullHeight
var maxFrameCount = frames.maxFrameCount
val framePlayer1 = TrackerFramesPlayer(frames)
@@ -40,7 +36,7 @@ class AutoBoneStep(
// Load server configs into the skeleton
skeleton1.loadFromConfig(serverConfig)
skeleton2.loadFromConfig(serverConfig)
// Disable leg tweaks, this will mess with the resulting positions
// Disable leg tweaks and IK solver, these will mess with the resulting positions
skeleton1.setLegTweaksEnabled(false)
skeleton2.setLegTweaksEnabled(false)
}
@@ -4,6 +4,7 @@ import dev.slimevr.autobone.AutoBoneStep
import dev.slimevr.autobone.errors.proportions.ProportionLimiter
import dev.slimevr.autobone.errors.proportions.RangeProportionLimiter
import dev.slimevr.tracking.processor.HumanPoseManager
import dev.slimevr.tracking.processor.config.SkeletonConfigManager
import dev.slimevr.tracking.processor.config.SkeletonConfigOffsets
import kotlin.math.*
@@ -32,84 +33,58 @@ class BodyProportionError : IAutoBoneError {
@JvmField
var eyeHeightToHeightRatio = 0.936f
// Default config
// Height: 1.58
// Full Height: 1.58 / 0.936 = 1.688034
// Neck: 0.1 / 1.688034 = 0.059241
// Torso: 0.56 / 1.688034 = 0.331747
// Upper Chest: 0.16 / 1.688034 = 0.094784
// Chest: 0.16 / 1.688034 = 0.094784
// Waist: (0.56 - 0.32 - 0.04) / 1.688034 = 0.118481
// Hip: 0.04 / 1.688034 = 0.023696
// Hip Width: 0.26 / 1.688034 = 0.154025
// Upper Leg: (0.92 - 0.50) / 1.688034 = 0.24881
// Lower Leg: 0.50 / 1.688034 = 0.296203
private val defaultHeight = SkeletonConfigManager.HEIGHT_OFFSETS.sumOf { it.defaultValue.toDouble() }.toFloat()
private fun makeLimiter(offset: SkeletonConfigOffsets, range: Float): RangeProportionLimiter = RangeProportionLimiter(
offset.defaultValue / defaultHeight,
offset,
range,
)
// "Expected" are values from Drillis and Contini (1966)
// "Experimental" are values from experimentation by the SlimeVR community
// Default are values from experimentation by the SlimeVR community
/**
* Proportions are based off the headset height (or eye height), not the total height of the user.
* To use the total height of the user, multiply it by [eyeHeightToHeightRatio] and use that in the limiters.
*/
val proportionLimits = arrayOf<ProportionLimiter>(
// Head
// Experimental: 0.059
RangeProportionLimiter(
0.059f,
makeLimiter(
SkeletonConfigOffsets.HEAD,
0.01f,
),
// Neck
// Expected: 0.052
// Experimental: 0.059
RangeProportionLimiter(
0.054f,
makeLimiter(
SkeletonConfigOffsets.NECK,
0.0015f,
0.002f,
),
// Upper Chest
// Experimental: 0.0945
RangeProportionLimiter(
0.0945f,
makeLimiter(
SkeletonConfigOffsets.UPPER_CHEST,
0.01f,
),
// Chest
// Experimental: 0.0945
RangeProportionLimiter(
0.0945f,
makeLimiter(
SkeletonConfigOffsets.CHEST,
0.01f,
),
// Waist
// Experimental: 0.118
RangeProportionLimiter(
0.118f,
makeLimiter(
SkeletonConfigOffsets.WAIST,
0.05f,
),
// Hip
// Experimental: 0.0237
RangeProportionLimiter(
0.0237f,
makeLimiter(
SkeletonConfigOffsets.HIP,
0.01f,
),
// Hip Width
// Expected: 0.191
// Experimental: 0.154
RangeProportionLimiter(
0.184f,
makeLimiter(
SkeletonConfigOffsets.HIPS_WIDTH,
0.04f,
),
// Upper Leg
// Expected: 0.245
RangeProportionLimiter(
0.245f,
makeLimiter(
SkeletonConfigOffsets.UPPER_LEG,
0.015f,
0.02f,
),
// Lower Leg
// Expected: 0.246 (0.285 including below ankle, could use a separate
// offset?)
RangeProportionLimiter(
0.285f,
makeLimiter(
SkeletonConfigOffsets.LOWER_LEG,
0.02f,
),
Loaded 100 of 158 files, more files were not shown because too many files have changed in this diff. Show more