Compare commits
183 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 07fc90eb71 | |||
| 7bc11bf94b | |||
| 59f6089335 | |||
| 64ef3d31eb | |||
| b14f005b22 | |||
| 72a288145d | |||
| af0815b01f | |||
| df3e813470 | |||
| 1b28b8b7fd | |||
| c449cb3390 | |||
| 05a420f345 | |||
| df395657e3 | |||
| 8970457353 | |||
| 0aab42f0e9 | |||
| 76d965ff43 | |||
| 0b9921e592 | |||
| aee29c47e4 | |||
| f2ee454b89 | |||
| a77eb0b1e0 | |||
| 91a7b170fe | |||
| 4d51b9f556 | |||
| 92a98064c3 | |||
| 1fbddd483c | |||
| d47ce02cc6 | |||
| 01c4a80c8f | |||
| 174d77a9fd | |||
| a078f28a82 | |||
| f3f3864b83 | |||
| 46bb5f74b1 | |||
| 89a0316fb4 | |||
| 51ee910fb6 | |||
| a198de05c2 | |||
| d3db2b3650 | |||
| 5a6f195f56 | |||
| 0cae981779 | |||
| c541b3f474 | |||
| ceccb2c901 | |||
| 8c21f3e2e4 | |||
| 55eecdc8d7 | |||
| b98c0e866b | |||
| 3d294f38c2 | |||
| a237dc3995 | |||
| 80c74dc745 | |||
| fb9313913d | |||
| 33e7fac74c | |||
| 2face72aee | |||
| 1f8e7efdb2 | |||
| b184449e7b | |||
| bc31b1b2dd | |||
| 12e1f80830 | |||
| 1cadcf8bdb | |||
| 06d27e0644 | |||
| 98b519dee8 | |||
| 4da2d7fa20 | |||
| 0f992b26e9 | |||
| 2a57d1ecc3 | |||
| fd3180d08b | |||
| 43b5216d9f | |||
| e1e11346b4 | |||
| 3ce8c88a84 | |||
| 0285b522f1 | |||
| 4ea287b162 | |||
| c2d52449b4 | |||
| f9a0880cd9 | |||
| 1bb098e952 | |||
| 9c74c8e87b | |||
| 3f4d956903 | |||
| a5371c36b9 | |||
| 41b863a0eb | |||
| 7fd35f3f48 | |||
| 26c36b8302 | |||
| bfc259e660 | |||
| 6368bf9213 | |||
| cd802f1c22 | |||
| 59bb1d9579 | |||
| ae98ba76f7 | |||
| bd8c8fd988 | |||
| 7de5a1aa7c | |||
| a3e4fdd8a5 | |||
| f82fa051f2 | |||
| b66ddc3e81 | |||
| c85ac41ebc | |||
| 78d01533f4 | |||
| 18d4d66758 | |||
| 1b9dc9bb9e | |||
| 767d1157df | |||
| 1799889712 | |||
| 0b5d7b1534 | |||
| 10b78e6919 | |||
| 3fd72d081e | |||
| 1f3a465d3e | |||
| cddb6023e7 | |||
| 2f46484e0a | |||
| 4fcaf5d77d | |||
| ea8ddb43ef | |||
| 774c546487 | |||
| 6f46c1f598 | |||
| bc810ee2dd | |||
| 54a0419770 | |||
| d7a6bffe0a | |||
| df087decdb | |||
| 527764b0b5 | |||
| 8c97c68d11 | |||
| e5bf10cdb0 | |||
| de3912ff10 | |||
| 251a791876 | |||
| e36365ead6 | |||
| cb5c095888 | |||
| 281fa32c89 | |||
| d899701195 | |||
| 7061166fcd | |||
| 36b39d41ba | |||
| 7d0a7861ea | |||
| bf8c9bce95 | |||
| 9c984d3215 | |||
| 43e76770a8 | |||
| 6e10eabd9f | |||
| 922a4e3665 | |||
| 5e162ffb71 | |||
| f21ce92d43 | |||
| 98f3fc674b | |||
| c5901c65b3 | |||
| 2eab893dd7 | |||
| a3be035f98 | |||
| 743aa073b7 | |||
| a3de13c619 | |||
| 90be771211 | |||
| 7d79ec39ab | |||
| 211ff7205b | |||
| d0aa3b7b42 | |||
| d529eaa201 | |||
| c8ee64d7f4 | |||
| ec4c3fd98e | |||
| 0cc372cd36 | |||
| 9be405a89d | |||
| e3cfe89e19 | |||
| 144b99c180 | |||
| c788e118e3 | |||
| aae16335b3 | |||
| a43c250ed1 | |||
| 01d46f283b | |||
| 7c8c5b40a1 | |||
| 632f603fda | |||
| 4101ad033c | |||
| 3ee096bfab | |||
| 753e692fe2 | |||
| 40025a55c3 | |||
| 98262b2efc | |||
| 01e174f337 | |||
| a9fea7fd56 | |||
| e09ec81f1d | |||
| ee17f6862c | |||
| 8be7546eba | |||
| e156b732eb | |||
| 20c5a8ee92 | |||
| dac21a499f | |||
| 9a6c240140 | |||
| 8733ecd9b7 | |||
| fba531d3e8 | |||
| fc04d1b8d6 | |||
| 4c33a75164 | |||
| 6015e67d05 | |||
| f59f32ce26 | |||
| 3671610860 | |||
| c346f7f553 | |||
| f864616303 | |||
| ad2d28c9ba | |||
| 967923321f | |||
| 6b7e3281cf | |||
| fdf70f7eb8 | |||
| e4cb035ad9 | |||
| c02938b567 | |||
| c24740e8ec | |||
| e0d3912d83 | |||
| b113a30942 | |||
| 9534529e50 | |||
| 23a41d26b1 | |||
| 569c19ad1d | |||
| 17e30ebfe9 | |||
| 170e180c11 | |||
| 5a24038d68 | |||
| 99660b9a23 | |||
| 72f3bcfd78 |
@@ -0,0 +1,61 @@
|
|||||||
|
name: Deploy GitHub Pages
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
pages: write
|
||||||
|
id-token: write
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: "pages"
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: ./app
|
||||||
|
env:
|
||||||
|
BASE_PATH: /SpotMicroESP32-Leika
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- uses: pnpm/action-setup@v2
|
||||||
|
with:
|
||||||
|
version: 9
|
||||||
|
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 20
|
||||||
|
cache: "pnpm"
|
||||||
|
cache-dependency-path: "./app/pnpm-lock.yaml"
|
||||||
|
|
||||||
|
- run: pnpm install
|
||||||
|
- run: pnpm run build
|
||||||
|
|
||||||
|
- name: Setup Pages
|
||||||
|
uses: actions/configure-pages@v4
|
||||||
|
with:
|
||||||
|
static_site_generator: "sveltekit"
|
||||||
|
|
||||||
|
- name: Upload artifact
|
||||||
|
uses: actions/upload-pages-artifact@v3
|
||||||
|
with:
|
||||||
|
path: app/build/
|
||||||
|
|
||||||
|
deploy:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: build
|
||||||
|
environment:
|
||||||
|
name: github-pages
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Deploy
|
||||||
|
id: deployment
|
||||||
|
uses: actions/deploy-pages@v4
|
||||||
@@ -2,20 +2,19 @@ name: PlatformIO CI
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [ master ]
|
branches: [master]
|
||||||
paths:
|
paths:
|
||||||
- 'esp32/**'
|
- "esp32/**"
|
||||||
|
- "platformio.ini"
|
||||||
pull_request:
|
pull_request:
|
||||||
branches: [ master ]
|
branches: [master]
|
||||||
paths:
|
paths:
|
||||||
- 'esp32/**'
|
- "esp32/**"
|
||||||
|
- "platformio.ini"
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
working-directory: ./esp32
|
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
@@ -28,8 +27,8 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/setup-python@v4
|
- uses: actions/setup-python@v4
|
||||||
with:
|
with:
|
||||||
python-version: '3.x'
|
python-version: "3.x"
|
||||||
- run: pip install -r ./scripts/requirements.txt
|
- run: pip install -r esp32/scripts/requirements.txt
|
||||||
- name: Install PlatformIO Core
|
- name: Install PlatformIO Core
|
||||||
run: pip install --upgrade platformio
|
run: pip install --upgrade platformio
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -2,7 +2,7 @@
|
|||||||
.vscode/c_cpp_properties.json
|
.vscode/c_cpp_properties.json
|
||||||
.vscode/launch.json
|
.vscode/launch.json
|
||||||
.vscode/ipch
|
.vscode/ipch
|
||||||
|
|
||||||
__pycache__/
|
__pycache__/
|
||||||
*.py[cod]
|
*.py[cod]
|
||||||
*$py.class
|
*$py.class
|
||||||
|
.pio
|
||||||
|
|||||||
Vendored
+3
-3
@@ -2,10 +2,10 @@
|
|||||||
// See http://go.microsoft.com/fwlink/?LinkId=827846
|
// See http://go.microsoft.com/fwlink/?LinkId=827846
|
||||||
// for the documentation about the extensions.json format
|
// for the documentation about the extensions.json format
|
||||||
"recommendations": [
|
"recommendations": [
|
||||||
"platformio.platformio-ide",
|
|
||||||
"svelte.svelte-vscode",
|
|
||||||
"bradlc.vscode-tailwindcss",
|
"bradlc.vscode-tailwindcss",
|
||||||
"esbenp.prettier-vscode"
|
"esbenp.prettier-vscode",
|
||||||
|
"platformio.platformio-ide",
|
||||||
|
"svelte.svelte-vscode"
|
||||||
],
|
],
|
||||||
"unwantedRecommendations": [
|
"unwantedRecommendations": [
|
||||||
"ms-vscode.cpptools-extension-pack"
|
"ms-vscode.cpptools-extension-pack"
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
PUBLIC_VITE_USE_HOST_NAME=true
|
||||||
|
PUBLIC_USE_JSON=true
|
||||||
|
PUBLIC_USE_MSGPACK=true
|
||||||
+1
-1
@@ -28,4 +28,4 @@ module.exports = {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
};
|
}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ node_modules
|
|||||||
/build
|
/build
|
||||||
/.svelte-kit
|
/.svelte-kit
|
||||||
/package
|
/package
|
||||||
.env
|
|
||||||
.env.*
|
.env.*
|
||||||
!.env.example
|
!.env.example
|
||||||
vite.config.js.timestamp-*
|
vite.config.js.timestamp-*
|
||||||
|
|||||||
+1
-2
@@ -1,13 +1,12 @@
|
|||||||
{
|
{
|
||||||
"useTabs": false,
|
"useTabs": false,
|
||||||
"singleQuote": true,
|
"singleQuote": true,
|
||||||
"tabWidth": 2,
|
"tabWidth": 4,
|
||||||
"trailingComma": "none",
|
"trailingComma": "none",
|
||||||
"arrowParens": "avoid",
|
"arrowParens": "avoid",
|
||||||
"experimentalTernaries": true,
|
"experimentalTernaries": true,
|
||||||
"printWidth": 100,
|
"printWidth": 100,
|
||||||
"semi": false,
|
"semi": false,
|
||||||
"svelteBracketNewLine": false,
|
|
||||||
"plugins": ["prettier-plugin-svelte"],
|
"plugins": ["prettier-plugin-svelte"],
|
||||||
"overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]
|
"overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+5
-1
@@ -1,3 +1,7 @@
|
|||||||
{
|
{
|
||||||
"recommendations": ["svelte.svelte-vscode", "bradlc.vscode-tailwindcss", "esbenp.prettier-vscode"]
|
"recommendations": [
|
||||||
|
"svelte.svelte-vscode",
|
||||||
|
"bradlc.vscode-tailwindcss",
|
||||||
|
"esbenp.prettier-vscode"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
+8
-17
@@ -8,30 +8,21 @@ If you're seeing this, you've probably already done this step. Congrats!
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
# create a new project in the current directory
|
# create a new project in the current directory
|
||||||
npm create svelte@latest
|
npx sv create
|
||||||
|
|
||||||
# create a new project in my-app
|
|
||||||
npm create svelte@latest my-app
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Developing
|
## Developing
|
||||||
|
|
||||||
Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:
|
Once you've created your project, follow these steps:
|
||||||
|
|
||||||
```bash
|
1: Delete package-lock.json
|
||||||
npm run dev
|
2: Check `git status`. If you see any changes other than package-lock.json or favicon.ico, run the command `git restore ./` (See below)
|
||||||
|
3: Run `npm install` or `pnpm install` or `yarn` to install the dependencies
|
||||||
|
4: Run `npm run build` to build the project
|
||||||
|
|
||||||
# or start the server and open the app in a new browser tab
|
Running `git status` should show:
|
||||||
npm run dev -- --open
|
|
||||||
```
|
|
||||||
|
|
||||||
## Building
|
[](https://postimg.cc/7CFsp2bq)
|
||||||
|
|
||||||
To create a production version of your app:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm run build
|
|
||||||
```
|
|
||||||
|
|
||||||
You can preview the production build with `npm run preview`.
|
You can preview the production build with `npm run preview`.
|
||||||
|
|
||||||
|
|||||||
Vendored
+4
-4
@@ -1,8 +1,8 @@
|
|||||||
declare module "app-env" {
|
declare module 'app-env' {
|
||||||
interface ENV {
|
interface ENV {
|
||||||
VITE_USE_HOST_NAME: boolean;
|
VITE_USE_HOST_NAME: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
const appEnv: ENV;
|
const appEnv: ENV
|
||||||
export default appEnv;
|
export default appEnv
|
||||||
}
|
}
|
||||||
|
|||||||
+38
-38
@@ -16,50 +16,50 @@
|
|||||||
"test:unit": "vitest"
|
"test:unit": "vitest"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@iconify-json/mdi": "^1.1.64",
|
"@iconify-json/mdi": "^1.2.3",
|
||||||
"@iconify-json/tabler": "^1.1.109",
|
"@iconify-json/tabler": "^1.2.23",
|
||||||
"@playwright/test": "^1.49.1",
|
"@playwright/test": "^1.56.0",
|
||||||
"@sveltejs/adapter-static": "^3.0.1",
|
"@sveltejs/adapter-static": "^3.0.10",
|
||||||
"@sveltejs/kit": "^2.5.27",
|
"@sveltejs/kit": "^2.46.4",
|
||||||
"@sveltejs/vite-plugin-svelte": "^5.0.3",
|
"@sveltejs/vite-plugin-svelte": "^6.2.1",
|
||||||
"@types/eslint": "^8.56.0",
|
"@types/eslint": "^9.6.1",
|
||||||
"@types/three": "^0.162.0",
|
"@types/three": "^0.180.0",
|
||||||
"@typescript-eslint/eslint-plugin": "^7.0.0",
|
"@typescript-eslint/eslint-plugin": "^8.46.0",
|
||||||
"@typescript-eslint/parser": "^7.0.0",
|
"@typescript-eslint/parser": "^8.46.0",
|
||||||
"autoprefixer": "^10.4.19",
|
"autoprefixer": "^10.4.21",
|
||||||
"eslint": "^8.56.0",
|
"eslint": "^9.37.0",
|
||||||
"eslint-config-prettier": "^9.1.0",
|
"eslint-config-prettier": "^10.1.8",
|
||||||
"eslint-plugin-svelte": "^2.45.1",
|
"eslint-plugin-svelte": "^3.12.4",
|
||||||
"jsdom": "^24.0.0",
|
"jsdom": "^27.0.0",
|
||||||
"prettier": "^3.1.1",
|
"prettier": "^3.6.2",
|
||||||
"prettier-plugin-svelte": "^3.2.6",
|
"prettier-plugin-svelte": "^3.4.0",
|
||||||
"svelte": "^5.0.0",
|
"svelte": "^5.39.11",
|
||||||
"svelte-check": "^4.0.0",
|
"svelte-check": "^4.3.3",
|
||||||
"svelte-focus-trap": "^1.2.0",
|
"svelte-focus-trap": "^1.2.0",
|
||||||
"tailwindcss": "^4.0.12",
|
"tailwindcss": "^4.1.14",
|
||||||
"tslib": "^2.6.1",
|
"tslib": "^2.8.1",
|
||||||
"typescript": "^5.5.0",
|
"typescript": "^5.9.3",
|
||||||
"unplugin-icons": "^0.18.5",
|
"unplugin-icons": "^22.4.2",
|
||||||
"vite": "^6.2.1",
|
"vite": "^7.1.9",
|
||||||
"vitest": "^1.2.0"
|
"vitest": "^3.2.4"
|
||||||
},
|
},
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@niku/vite-env-caster": "^1.0.2",
|
"@msgpack/msgpack": "^3.1.2",
|
||||||
"@sveltejs/adapter-auto": "^4.0.0",
|
"@niku/vite-env-caster": "^1.1.2",
|
||||||
"@tailwindcss/vite": "^4.0.12",
|
"@sveltejs/adapter-auto": "^6.1.1",
|
||||||
"chart.js": "^4.4.2",
|
"@tailwindcss/vite": "^4.1.14",
|
||||||
"compare-versions": "^6.1.0",
|
"chart.js": "^4.5.0",
|
||||||
"cross-env": "^7.0.3",
|
"compare-versions": "^6.1.1",
|
||||||
"daisyui": "^5.0.0",
|
"cross-env": "^10.1.0",
|
||||||
"jwt-decode": "^4.0.0",
|
"daisyui": "^5.2.0",
|
||||||
"nipplejs": "^0.10.1",
|
"nipplejs": "^0.10.2",
|
||||||
"svelte-dnd-list": "^0.1.8",
|
"svelte-dnd-list": "^0.1.8",
|
||||||
"svelte-modals": "^2.0.0",
|
"svelte-modals": "^2.0.1",
|
||||||
"three": "^0.162.0",
|
"three": "^0.180.0",
|
||||||
"urdf-loader": "^0.12.1",
|
"urdf-loader": "^0.12.6",
|
||||||
"uzip": "^0.20201231.0",
|
"uzip": "^0.20201231.0",
|
||||||
"xacro-parser": "^0.3.9"
|
"xacro-parser": "^0.3.10"
|
||||||
},
|
},
|
||||||
"packageManager": "pnpm@9.3.0"
|
"packageManager": "pnpm@9.3.0"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { PlaywrightTestConfig } from '@playwright/test';
|
import type { PlaywrightTestConfig } from '@playwright/test'
|
||||||
|
|
||||||
const config: PlaywrightTestConfig = {
|
const config: PlaywrightTestConfig = {
|
||||||
webServer: {
|
webServer: {
|
||||||
@@ -7,6 +7,6 @@ const config: PlaywrightTestConfig = {
|
|||||||
},
|
},
|
||||||
testDir: 'tests/integration',
|
testDir: 'tests/integration',
|
||||||
testMatch: /(.+\.)?(test|spec)\.[jt]s/
|
testMatch: /(.+\.)?(test|spec)\.[jt]s/
|
||||||
};
|
}
|
||||||
|
|
||||||
export default config;
|
export default config
|
||||||
|
|||||||
Generated
+1890
-2159
File diff suppressed because it is too large
Load Diff
@@ -23,6 +23,14 @@
|
|||||||
--base-content: oklch(0.3 0.012 256);
|
--base-content: oklch(0.3 0.012 256);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
button {
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
button:disabled {
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
#nipple_0_0,
|
#nipple_0_0,
|
||||||
#nipple_1_1 {
|
#nipple_1_1 {
|
||||||
z-index: 10 !important;
|
z-index: 10 !important;
|
||||||
|
|||||||
Vendored
+1
-1
@@ -10,4 +10,4 @@ declare global {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export {};
|
export {}
|
||||||
|
|||||||
+4
-1
@@ -3,7 +3,10 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8" />
|
<meta charset="utf-8" />
|
||||||
<link rel="icon" href="%sveltekit.assets%/logo512.png" />
|
<link rel="icon" href="%sveltekit.assets%/logo512.png" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1" />
|
<meta
|
||||||
|
name="viewport"
|
||||||
|
content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1"
|
||||||
|
/>
|
||||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||||
<meta name="mobile-web-app-capable" content="yes" />
|
<meta name="mobile-web-app-capable" content="yes" />
|
||||||
%sveltekit.head%
|
%sveltekit.head%
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
import { describe, it, expect } from 'vitest';
|
|
||||||
|
|
||||||
describe('sum test', () => {
|
|
||||||
it('adds 1 + 2 to equal 3', () => {
|
|
||||||
expect(1 + 2).toBe(3);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
+33
-34
@@ -1,22 +1,22 @@
|
|||||||
import { get } from 'svelte/store';
|
import { get } from 'svelte/store'
|
||||||
import { Err, Ok, type Result } from './utilities';
|
import { Err, Ok, type Result } from './utilities'
|
||||||
import { location } from './stores';
|
import { apiLocation } from './stores'
|
||||||
|
|
||||||
export namespace api {
|
export const api = {
|
||||||
export function get<TResponse>(endpoint: string, params?: RequestInit) {
|
get<TResponse>(endpoint: string, params?: RequestInit) {
|
||||||
return sendRequest<TResponse>(endpoint, 'GET', null, params);
|
return sendRequest<TResponse>(endpoint, 'GET', null, params)
|
||||||
}
|
},
|
||||||
|
|
||||||
export function post<TResponse>(endpoint: string, data?: unknown) {
|
post<TResponse>(endpoint: string, data?: unknown) {
|
||||||
return sendRequest<TResponse>(endpoint, 'POST', data);
|
return sendRequest<TResponse>(endpoint, 'POST', data)
|
||||||
}
|
},
|
||||||
|
|
||||||
export function put<TResponse>(endpoint: string, data?: unknown) {
|
put<TResponse>(endpoint: string, data?: unknown) {
|
||||||
return sendRequest<TResponse>(endpoint, 'PUT', data);
|
return sendRequest<TResponse>(endpoint, 'PUT', data)
|
||||||
}
|
},
|
||||||
|
|
||||||
export function remove<TResponse>(endpoint: string) {
|
remove<TResponse>(endpoint: string) {
|
||||||
return sendRequest<TResponse>(endpoint, 'DELETE');
|
return sendRequest<TResponse>(endpoint, 'DELETE')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -26,8 +26,8 @@ async function sendRequest<TResponse>(
|
|||||||
data?: unknown,
|
data?: unknown,
|
||||||
params?: RequestInit
|
params?: RequestInit
|
||||||
): Promise<Result<TResponse, Error>> {
|
): Promise<Result<TResponse, Error>> {
|
||||||
endpoint = resolveUrl(endpoint);
|
endpoint = resolveUrl(endpoint)
|
||||||
const body = data !== null && typeof data !== 'undefined' ? JSON.stringify(data) : undefined;
|
const body = data !== null && typeof data !== 'undefined' ? JSON.stringify(data) : undefined
|
||||||
|
|
||||||
const request = {
|
const request = {
|
||||||
...params,
|
...params,
|
||||||
@@ -38,43 +38,42 @@ async function sendRequest<TResponse>(
|
|||||||
Authorization: 'Basic',
|
Authorization: 'Basic',
|
||||||
'Content-Type': 'application/json'
|
'Content-Type': 'application/json'
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
let response;
|
let response
|
||||||
|
|
||||||
try {
|
try {
|
||||||
response = await fetch(endpoint, request);
|
response = await fetch(endpoint, request)
|
||||||
} catch (error) {
|
} catch {
|
||||||
return Err.new(new Error(), 'An error has occurred');
|
return Err.new(new Error(), 'An error has occurred')
|
||||||
}
|
}
|
||||||
|
|
||||||
const isResponseOk = response.status >= 200 && response.status < 400;
|
const isResponseOk = response.status >= 200 && response.status < 400
|
||||||
if (!isResponseOk) {
|
if (!isResponseOk) {
|
||||||
if (response.status === 401) {
|
if (response.status === 401) {
|
||||||
return Err.new(new ApiError(response), 'User was not authorized');
|
return Err.new(new ApiError(response), 'User was not authorized')
|
||||||
}
|
}
|
||||||
return Err.new(new ApiError(response), 'An error has occurred');
|
return Err.new(new ApiError(response), 'An error has occurred')
|
||||||
}
|
}
|
||||||
|
|
||||||
const contentType =
|
const contentType = response.headers.get('Content-Type') ?? response.headers.get('Content-Type')
|
||||||
response.headers.get('Content-Type') ?? response.headers.get('Content-Type');
|
|
||||||
if (contentType && contentType.includes('application/json')) {
|
if (contentType && contentType.includes('application/json')) {
|
||||||
const data = await response.json();
|
const data = await response.json()
|
||||||
return Ok.new(data as TResponse);
|
return Ok.new(data as TResponse)
|
||||||
} else {
|
} else {
|
||||||
// Handle empty object as response
|
// Handle empty object as response
|
||||||
return Ok.new(null as TResponse);
|
return Ok.new(null as TResponse)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function resolveUrl(url: string): string {
|
function resolveUrl(url: string): string {
|
||||||
if (url.startsWith('http') || !get(location)) return url;
|
if (url.startsWith('http') || !get(apiLocation)) return url
|
||||||
const protocol = window.location.protocol;
|
const protocol = window.location.protocol
|
||||||
return `${protocol}//${get(location)}${url.startsWith('/') ? '' : '/'}${url}`;
|
return `${protocol}//${get(apiLocation)}${url.startsWith('/') ? '' : '/'}${url}`
|
||||||
}
|
}
|
||||||
|
|
||||||
export class ApiError extends Error {
|
export class ApiError extends Error {
|
||||||
constructor(public readonly response: Response) {
|
constructor(public readonly response: Response) {
|
||||||
super(`${response.status}`);
|
super(`${response.status}`)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,18 +1,18 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { slide } from 'svelte/transition';
|
import { slide } from 'svelte/transition'
|
||||||
import { cubicOut } from 'svelte/easing';
|
import { cubicOut } from 'svelte/easing'
|
||||||
import { Down } from './icons';
|
import { Down } from './icons'
|
||||||
|
|
||||||
function openCollapsible() {
|
function openCollapsible() {
|
||||||
open = !open;
|
open = !open
|
||||||
if (open) {
|
if (open) {
|
||||||
opened();
|
opened()
|
||||||
} else {
|
} else {
|
||||||
closed();
|
closed()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let { icon, title, children, open, opened, closed, class: klass } = $props();
|
let { icon, title, children, open, opened, closed, class: klass } = $props()
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="{klass} relative grid w-full max-w-2xl self-center overflow-hidden">
|
<div class="{klass} relative grid w-full max-w-2xl self-center overflow-hidden">
|
||||||
|
|||||||
@@ -1,18 +1,8 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { focusTrap } from 'svelte-focus-trap';
|
import { focusTrap } from 'svelte-focus-trap'
|
||||||
import { fly } from 'svelte/transition';
|
import { fly } from 'svelte/transition'
|
||||||
import { Cancel, Check } from '$lib/components/icons';
|
import { Cancel, Check } from '$lib/components/icons'
|
||||||
import { modals, exitBeforeEnter } from 'svelte-modals';
|
import { modals, exitBeforeEnter, type ModalProps } from 'svelte-modals'
|
||||||
|
|
||||||
// provided by <Modals />
|
|
||||||
|
|
||||||
interface Props {
|
|
||||||
isOpen: boolean;
|
|
||||||
title: string;
|
|
||||||
message: string;
|
|
||||||
onConfirm: any;
|
|
||||||
labels?: any;
|
|
||||||
}
|
|
||||||
|
|
||||||
let {
|
let {
|
||||||
isOpen,
|
isOpen,
|
||||||
@@ -23,7 +13,7 @@
|
|||||||
cancel: { label: 'Cancel', icon: Cancel },
|
cancel: { label: 'Cancel', icon: Cancel },
|
||||||
confirm: { label: 'OK', icon: Check }
|
confirm: { label: 'OK', icon: Check }
|
||||||
}
|
}
|
||||||
}: Props = $props();
|
}: ModalProps = $props()
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
{#if isOpen}
|
{#if isOpen}
|
||||||
@@ -44,15 +34,12 @@
|
|||||||
<div class="divider my-2"></div>
|
<div class="divider my-2"></div>
|
||||||
<div class="flex justify-end gap-2">
|
<div class="flex justify-end gap-2">
|
||||||
<button
|
<button
|
||||||
class="btn btn-primary inline-flex items-center"
|
class="btn btn-error inline-flex items-center"
|
||||||
onclick={() => modals.close()}
|
onclick={() => modals.close()}
|
||||||
>
|
>
|
||||||
<labels.cancel.icon class="mr-2 h-5 w-5" /><span>{labels?.cancel.label}</span>
|
<labels.cancel.icon class="mr-2 h-5 w-5" /><span>{labels?.cancel.label}</span>
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button class="btn btn-primary inline-flex items-center" onclick={onConfirm}>
|
||||||
class="btn btn-warning text-warning-content inline-flex items-center"
|
|
||||||
onclick={onConfirm}
|
|
||||||
>
|
|
||||||
<SvelteComponent class="mr-2 h-5 w-5" /><span>{labels?.confirm.label}</span>
|
<SvelteComponent class="mr-2 h-5 w-5" /><span>{labels?.confirm.label}</span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,61 +1,61 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { focusTrap } from 'svelte-focus-trap';
|
import { focusTrap } from 'svelte-focus-trap'
|
||||||
import { fly } from 'svelte/transition';
|
import { fly } from 'svelte/transition'
|
||||||
import { telemetry } from '$lib/stores/telemetry';
|
import { telemetry } from '$lib/stores/telemetry'
|
||||||
import { Cancel } from './icons';
|
import { Cancel } from './icons'
|
||||||
import { modals, exitBeforeEnter, onBeforeClose } from 'svelte-modals';
|
import { modals, exitBeforeEnter, onBeforeClose } from 'svelte-modals'
|
||||||
|
|
||||||
// provided by <Modals />
|
// provided by <Modals />
|
||||||
interface Props {
|
interface Props {
|
||||||
isOpen: boolean;
|
isOpen: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
let { isOpen }: Props = $props();
|
let { isOpen }: Props = $props()
|
||||||
|
|
||||||
let updating = $state(true);
|
let updating = $state(true)
|
||||||
|
|
||||||
let progress = $state(0);
|
let progress = $state(0)
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
if ($telemetry.download_ota.status == 'progress') {
|
if ($telemetry.download_ota.status == 'progress') {
|
||||||
progress = $telemetry.download_ota.progress;
|
progress = $telemetry.download_ota.progress
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
if ($telemetry.download_ota.status == 'error') {
|
if ($telemetry.download_ota.status == 'error') {
|
||||||
updating = false;
|
updating = false
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
|
|
||||||
let message = $state('Preparing ...');
|
let message = $state('Preparing ...')
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
if ($telemetry.download_ota.status == 'progress') {
|
if ($telemetry.download_ota.status == 'progress') {
|
||||||
message = 'Downloading ...';
|
message = 'Downloading ...'
|
||||||
} else if ($telemetry.download_ota.status == 'error') {
|
} else if ($telemetry.download_ota.status == 'error') {
|
||||||
message = $telemetry.download_ota.error;
|
message = $telemetry.download_ota.error
|
||||||
} else if ($telemetry.download_ota.status == 'finished') {
|
} else if ($telemetry.download_ota.status == 'finished') {
|
||||||
message = 'Restarting ...';
|
message = 'Restarting ...'
|
||||||
progress = 0;
|
progress = 0
|
||||||
// Reload page after 5 sec
|
// Reload page after 5 sec
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
modals.closeAll();
|
modals.closeAll()
|
||||||
location.reload();
|
location.reload()
|
||||||
}, 5000);
|
}, 5000)
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
|
|
||||||
onBeforeClose(() => {
|
onBeforeClose(() => {
|
||||||
if (updating) {
|
if (updating) {
|
||||||
// prevents modal from closing
|
// prevents modal from closing
|
||||||
return false;
|
return false
|
||||||
} else {
|
} else {
|
||||||
$telemetry.download_ota.status = 'idle';
|
$telemetry.download_ota.status = 'idle'
|
||||||
$telemetry.download_ota.error = '';
|
$telemetry.download_ota.error = ''
|
||||||
$telemetry.download_ota.progress = 0;
|
$telemetry.download_ota.progress = 0
|
||||||
return true;
|
return true
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
{#if isOpen}
|
{#if isOpen}
|
||||||
@@ -89,8 +89,8 @@
|
|||||||
class="btn btn-warning text-warning-content inline-flex flex-none items-center"
|
class="btn btn-warning text-warning-content inline-flex flex-none items-center"
|
||||||
disabled={updating}
|
disabled={updating}
|
||||||
onclick={() => {
|
onclick={() => {
|
||||||
modals.closeAll();
|
modals.closeAll()
|
||||||
location.reload();
|
location.reload()
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Cancel class="mr-2 h-5 w-5" /><span>Close</span></button
|
<Cancel class="mr-2 h-5 w-5" /><span>Close</span></button
|
||||||
|
|||||||
@@ -1,26 +1,18 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { focusTrap } from 'svelte-focus-trap';
|
import { focusTrap } from 'svelte-focus-trap'
|
||||||
import { fly } from 'svelte/transition';
|
import { fly } from 'svelte/transition'
|
||||||
import { Check } from './icons';
|
import { Check } from './icons'
|
||||||
import { exitBeforeEnter } from 'svelte-modals';
|
import { exitBeforeEnter, type ModalProps } from 'svelte-modals'
|
||||||
|
|
||||||
// provided by <Modals />
|
|
||||||
|
|
||||||
interface Props {
|
|
||||||
isOpen: boolean;
|
|
||||||
title: string;
|
|
||||||
message: string;
|
|
||||||
onDismiss: any;
|
|
||||||
dismiss?: any;
|
|
||||||
}
|
|
||||||
|
|
||||||
let {
|
let {
|
||||||
isOpen,
|
isOpen,
|
||||||
title,
|
title,
|
||||||
message,
|
message,
|
||||||
onDismiss,
|
onDismiss,
|
||||||
dismiss = { label: 'Dismiss', icon: Check }
|
labels = {
|
||||||
}: Props = $props();
|
dismiss: { label: 'Dismiss', icon: Check }
|
||||||
|
}
|
||||||
|
}: ModalProps = $props()
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
{#if isOpen}
|
{#if isOpen}
|
||||||
@@ -43,7 +35,7 @@
|
|||||||
class="btn btn-warning text-warning-content inline-flex items-center"
|
class="btn btn-warning text-warning-content inline-flex items-center"
|
||||||
onclick={onDismiss}
|
onclick={onDismiss}
|
||||||
>
|
>
|
||||||
<dismiss.icon class="mr-2 h-5 w-5" /><span>{dismiss.label}</span>
|
<labels.dismiss.icon class="mr-2 h-5 w-5" /><span>{labels.dismiss.label}</span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { onMount, onDestroy } from 'svelte'
|
||||||
|
import * as THREE from 'three'
|
||||||
|
import { imu } from '$lib/stores/imu'
|
||||||
|
import SceneBuilder from '$lib/sceneBuilder'
|
||||||
|
|
||||||
|
let canvas: HTMLCanvasElement
|
||||||
|
let sceneBuilder: SceneBuilder
|
||||||
|
let cube: THREE.Mesh
|
||||||
|
let targetRotation = new THREE.Euler()
|
||||||
|
let lastUpdateTime = 0
|
||||||
|
const LERP_SPEED = 5 // rotations per second
|
||||||
|
|
||||||
|
const initThreeJS = () => {
|
||||||
|
sceneBuilder = new SceneBuilder()
|
||||||
|
.addRenderer({ canvas: canvas, antialias: true, alpha: true })
|
||||||
|
.addPerspectiveCamera({ x: 2, y: 0, z: 2 })
|
||||||
|
.addOrbitControls(1, 10, false)
|
||||||
|
.addAmbientLight({ color: 0x404040, intensity: 0.5 })
|
||||||
|
.addDirectionalLight({ color: 0xffffff, intensity: 3, x: 10, y: 20, z: 7 })
|
||||||
|
.fillParent()
|
||||||
|
|
||||||
|
const geometry = new THREE.BoxGeometry(1, 1, 1)
|
||||||
|
const material = new THREE.MeshPhongMaterial({
|
||||||
|
color: 0x00ff00,
|
||||||
|
transparent: true,
|
||||||
|
opacity: 0.8
|
||||||
|
})
|
||||||
|
cube = new THREE.Mesh(geometry, material)
|
||||||
|
sceneBuilder.scene.add(cube)
|
||||||
|
|
||||||
|
sceneBuilder.addRenderCb(() => {
|
||||||
|
if (!cube) return
|
||||||
|
const currentTime = performance.now()
|
||||||
|
const deltaTime = (currentTime - lastUpdateTime) / 1000 // convert to seconds
|
||||||
|
lastUpdateTime = currentTime
|
||||||
|
|
||||||
|
const lerpFactor = Math.min(1, LERP_SPEED * deltaTime)
|
||||||
|
cube.rotation.x = THREE.MathUtils.lerp(cube.rotation.x, targetRotation.x, lerpFactor)
|
||||||
|
cube.rotation.y = THREE.MathUtils.lerp(cube.rotation.y, targetRotation.y, lerpFactor)
|
||||||
|
cube.rotation.z = THREE.MathUtils.lerp(cube.rotation.z, targetRotation.z, lerpFactor)
|
||||||
|
})
|
||||||
|
|
||||||
|
sceneBuilder.startRenderLoop()
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateOrientation = () => {
|
||||||
|
if (!cube) return
|
||||||
|
|
||||||
|
const y = -$imu.x[$imu.x.length - 1] || 0
|
||||||
|
const x = $imu.y[$imu.y.length - 1] || 0
|
||||||
|
const z = -$imu.z[$imu.z.length - 1] || 0
|
||||||
|
|
||||||
|
targetRotation.set(
|
||||||
|
THREE.MathUtils.degToRad(x),
|
||||||
|
THREE.MathUtils.degToRad(y),
|
||||||
|
THREE.MathUtils.degToRad(z)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
initThreeJS()
|
||||||
|
})
|
||||||
|
|
||||||
|
onDestroy(() => {
|
||||||
|
sceneBuilder?.renderer?.dispose()
|
||||||
|
})
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
if ($imu) {
|
||||||
|
updateOrientation()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="h-60 w-60 border-2 border-base-300 rounded-md">
|
||||||
|
<canvas class="w-full h-full" bind:this={canvas}></canvas>
|
||||||
|
</div>
|
||||||
@@ -1,13 +1,14 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { slide } from 'svelte/transition';
|
import { slide } from 'svelte/transition'
|
||||||
import { cubicOut } from 'svelte/easing';
|
import { cubicOut } from 'svelte/easing'
|
||||||
import { Down } from './icons';
|
import { Down } from './icons'
|
||||||
interface Props {
|
interface Props {
|
||||||
open?: boolean;
|
open?: boolean
|
||||||
collapsible?: boolean;
|
collapsible?: boolean
|
||||||
icon?: import('svelte').Snippet;
|
icon?: import('svelte').Snippet
|
||||||
title?: import('svelte').Snippet;
|
title?: import('svelte').Snippet
|
||||||
children?: import('svelte').Snippet;
|
children?: import('svelte').Snippet
|
||||||
|
right?: import('svelte').Snippet
|
||||||
}
|
}
|
||||||
|
|
||||||
let {
|
let {
|
||||||
@@ -15,8 +16,9 @@
|
|||||||
collapsible = true,
|
collapsible = true,
|
||||||
icon,
|
icon,
|
||||||
title,
|
title,
|
||||||
children
|
children,
|
||||||
}: Props = $props();
|
right
|
||||||
|
}: Props = $props()
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
{#if collapsible}
|
{#if collapsible}
|
||||||
@@ -33,12 +35,14 @@
|
|||||||
<button
|
<button
|
||||||
class="btn btn-circle btn-ghost btn-sm"
|
class="btn btn-circle btn-ghost btn-sm"
|
||||||
onclick={() => {
|
onclick={() => {
|
||||||
open = !open;
|
open = !open
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Down
|
<Down
|
||||||
class="text-base-content h-auto w-6 transition-transform duration-300 ease-in-out {open
|
class="text-base-content h-auto w-6 transition-transform duration-300 ease-in-out {(
|
||||||
? 'rotate-180'
|
open
|
||||||
|
) ?
|
||||||
|
'rotate-180'
|
||||||
: ''}"
|
: ''}"
|
||||||
/>
|
/>
|
||||||
</button>
|
</button>
|
||||||
@@ -56,11 +60,14 @@
|
|||||||
<div
|
<div
|
||||||
class="bg-base-200 rounded-box relative grid w-full max-w-2xl self-center overflow-hidden shadow-lg"
|
class="bg-base-200 rounded-box relative grid w-full max-w-2xl self-center overflow-hidden shadow-lg"
|
||||||
>
|
>
|
||||||
<div class="min-h-16 w-full p-4 text-xl font-medium">
|
<div
|
||||||
|
class="min-h-16 flex w-full items-center justify-between space-x-3 p-4 text-xl font-medium"
|
||||||
|
>
|
||||||
<span class="inline-flex items-baseline">
|
<span class="inline-flex items-baseline">
|
||||||
{@render icon?.()}
|
{@render icon?.()}
|
||||||
{@render title?.()}
|
{@render title?.()}
|
||||||
</span>
|
</span>
|
||||||
|
{@render right?.()}
|
||||||
</div>
|
</div>
|
||||||
<div class="flex flex-col gap-2 p-4 pt-0">
|
<div class="flex flex-col gap-2 p-4 pt-0">
|
||||||
{@render children?.()}
|
{@render children?.()}
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { Loader } from "./icons";
|
import { Loader } from './icons'
|
||||||
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="flex h-full w-full flex-col items-center justify-center p-6">
|
<div class="flex h-full w-full flex-col items-center justify-center p-6">
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { ComponentType } from 'svelte'
|
||||||
|
|
||||||
|
type Variant = 'success' | 'error' | 'primary' | 'info' | 'warning'
|
||||||
|
|
||||||
|
const {
|
||||||
|
icon,
|
||||||
|
title,
|
||||||
|
description = '',
|
||||||
|
variant = 'primary',
|
||||||
|
class: klass = '',
|
||||||
|
children = null
|
||||||
|
} = $props<{
|
||||||
|
icon?: ComponentType
|
||||||
|
title: string
|
||||||
|
description?: string | number
|
||||||
|
variant?: Variant
|
||||||
|
class?: string
|
||||||
|
children?: () => ComponentType
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const Icon = $derived(icon)
|
||||||
|
|
||||||
|
const variants: Record<Variant, [string, string]> = {
|
||||||
|
success: ['bg-success', 'text-success-content'],
|
||||||
|
error: ['bg-error', 'text-error-content'],
|
||||||
|
primary: ['bg-primary', 'text-primary-content'],
|
||||||
|
info: ['bg-info', 'text-info-content'],
|
||||||
|
warning: ['bg-warning', 'text-warning-content']
|
||||||
|
}
|
||||||
|
|
||||||
|
const variantKey: Variant = (variant as Variant) in variants ? (variant as Variant) : 'primary'
|
||||||
|
const [bgColor, textColor] = variants[variantKey]
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="rounded-box bg-base-100 flex items-center space-x-3 px-4 py-2 {klass}">
|
||||||
|
{#if icon}
|
||||||
|
<div class="mask mask-hexagon {bgColor} h-auto w-10 flex-none">
|
||||||
|
<Icon class="{textColor} h-auto w-full scale-75" />
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
<div class="grow">
|
||||||
|
<div class="font-bold">{title}</div>
|
||||||
|
<div class="text-sm opacity-75 grow">{description}</div>
|
||||||
|
</div>
|
||||||
|
{@render children?.()}
|
||||||
|
</div>
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { onDestroy } from 'svelte';
|
import { onDestroy } from 'svelte'
|
||||||
import { location } from '$lib/stores';
|
import { apiLocation } from '$lib/stores'
|
||||||
|
|
||||||
let source = $state(`${$location}/api/camera/stream`);
|
let source = $state(`${$apiLocation}/api/camera/stream`)
|
||||||
|
|
||||||
onDestroy(() => (source = '#'));
|
onDestroy(() => (source = '#'))
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="w-full h-full">
|
<div class="w-full h-full">
|
||||||
|
|||||||
@@ -1,22 +1,24 @@
|
|||||||
<script>
|
<script>
|
||||||
import { flip } from 'svelte/animate';
|
import { flip } from 'svelte/animate'
|
||||||
import { fly } from 'svelte/transition';
|
import { fly } from 'svelte/transition'
|
||||||
import { notifications } from '$lib/components/toasts/notifications';
|
import { notifications } from '$lib/components/toasts/notifications'
|
||||||
import { error, info, success, warning } from './icons';
|
import { error, info, success, warning } from './icons'
|
||||||
|
|
||||||
|
|
||||||
/** @type {{theme?: any, icon?: any}} */
|
/** @type {{theme?: any, icon?: any}} */
|
||||||
let { theme = {
|
let {
|
||||||
|
theme = {
|
||||||
error: 'alert-error',
|
error: 'alert-error',
|
||||||
success: 'alert-success',
|
success: 'alert-success',
|
||||||
warning: 'alert-warning',
|
warning: 'alert-warning',
|
||||||
info: 'alert-info'
|
info: 'alert-info'
|
||||||
}, icon = {
|
},
|
||||||
|
icon = {
|
||||||
error: error,
|
error: error,
|
||||||
success: success,
|
success: success,
|
||||||
warning: warning,
|
warning: warning,
|
||||||
info: info
|
info: info
|
||||||
} } = $props();
|
}
|
||||||
|
} = $props()
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="toast toast-end mr-4">
|
<div class="toast toast-end mr-4">
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
LineBasicMaterial,
|
LineBasicMaterial,
|
||||||
Mesh,
|
Mesh,
|
||||||
MeshBasicMaterial,
|
MeshBasicMaterial,
|
||||||
Object3D,
|
type Object3D,
|
||||||
SphereGeometry,
|
SphereGeometry,
|
||||||
Vector3,
|
Vector3,
|
||||||
type NormalBufferAttributes,
|
type NormalBufferAttributes,
|
||||||
@@ -21,18 +21,25 @@
|
|||||||
servoAnglesOut,
|
servoAnglesOut,
|
||||||
servoAngles,
|
servoAngles,
|
||||||
mpu,
|
mpu,
|
||||||
jointNames
|
jointNames,
|
||||||
|
currentKinematic,
|
||||||
|
walkGait,
|
||||||
|
walkGaitToMode
|
||||||
} from '$lib/stores'
|
} from '$lib/stores'
|
||||||
import { footColor, populateModelCache, throttler, toeWorldPositions } from '$lib/utilities'
|
import {
|
||||||
|
extractFootColor,
|
||||||
|
populateModelCache,
|
||||||
|
throttler,
|
||||||
|
getToeWorldPositions
|
||||||
|
} from '$lib/utilities'
|
||||||
import SceneBuilder from '$lib/sceneBuilder'
|
import SceneBuilder from '$lib/sceneBuilder'
|
||||||
import { lerp, degToRad } from 'three/src/math/MathUtils'
|
import { lerp, degToRad } from 'three/src/math/MathUtils'
|
||||||
import { GUI } from 'three/addons/libs/lil-gui.module.min.js'
|
import { GUI } from 'three/addons/libs/lil-gui.module.min.js'
|
||||||
import Kinematic, { type body_state_t } from '$lib/kinematic'
|
import { type body_state_t } from '$lib/kinematic'
|
||||||
import {
|
import {
|
||||||
|
Animater,
|
||||||
BezierState,
|
BezierState,
|
||||||
CalibrationState,
|
CalibrationState,
|
||||||
EightPhaseWalkState,
|
|
||||||
FourPhaseWalkState,
|
|
||||||
IdleState,
|
IdleState,
|
||||||
RestState,
|
RestState,
|
||||||
StandState
|
StandState
|
||||||
@@ -47,33 +54,23 @@
|
|||||||
panel?: boolean
|
panel?: boolean
|
||||||
debug?: boolean
|
debug?: boolean
|
||||||
ground?: boolean
|
ground?: boolean
|
||||||
zoom?: number
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let {
|
let { sky = true, orbit = false, panel = true, debug = false, ground = true }: Props = $props()
|
||||||
sky = true,
|
|
||||||
orbit = false,
|
|
||||||
panel = true,
|
|
||||||
debug = false,
|
|
||||||
ground = true,
|
|
||||||
zoom = 8
|
|
||||||
}: Props = $props()
|
|
||||||
|
|
||||||
let sceneManager = $state(new SceneBuilder())
|
let sceneManager = $state(new SceneBuilder())
|
||||||
let canvas: HTMLCanvasElement = $state()
|
let canvas: HTMLCanvasElement
|
||||||
|
|
||||||
let currentModelAngles: number[] = new Array(12).fill(0)
|
let currentModelAngles: number[] = new Array(12).fill(0)
|
||||||
let modelTargetAngles: number[] = new Array(12).fill(0)
|
let modelTargetAngles: number[] = new Array(12).fill(0)
|
||||||
let gui_panel: GUI
|
let gui_panel: GUI
|
||||||
let Throttler = new throttler()
|
let Throttler = new throttler()
|
||||||
|
|
||||||
let feet_trace = new Array(4).fill([])
|
|
||||||
let trace_lines: BufferGeometry<NormalBufferAttributes>[] = []
|
|
||||||
let target: Object3D<Object3DEventMap>
|
let target: Object3D<Object3DEventMap>
|
||||||
|
|
||||||
let target_position = { x: 0, z: 0, yaw: 0 }
|
let target_position = { x: 0, z: 0, yaw: 0 }
|
||||||
|
|
||||||
let kinematic = new Kinematic()
|
let kinematic = get(currentKinematic)
|
||||||
|
|
||||||
let planners = {
|
let planners = {
|
||||||
[ModesEnum.Deactivated]: new IdleState(),
|
[ModesEnum.Deactivated]: new IdleState(),
|
||||||
@@ -81,8 +78,8 @@
|
|||||||
[ModesEnum.Calibration]: new CalibrationState(),
|
[ModesEnum.Calibration]: new CalibrationState(),
|
||||||
[ModesEnum.Rest]: new RestState(),
|
[ModesEnum.Rest]: new RestState(),
|
||||||
[ModesEnum.Stand]: new StandState(),
|
[ModesEnum.Stand]: new StandState(),
|
||||||
[ModesEnum.Crawl]: new EightPhaseWalkState(),
|
[ModesEnum.Walk]: new BezierState(),
|
||||||
[ModesEnum.Walk]: new BezierState()
|
[ModesEnum.Animate]: new Animater()
|
||||||
}
|
}
|
||||||
let lastTick = performance.now()
|
let lastTick = performance.now()
|
||||||
|
|
||||||
@@ -95,7 +92,13 @@
|
|||||||
xm: 0,
|
xm: 0,
|
||||||
ym: 0.5,
|
ym: 0.5,
|
||||||
zm: 0,
|
zm: 0,
|
||||||
feet: planners[ModesEnum.Idle].default_feet_pos
|
feet: kinematic.getDefaultFeetPos(),
|
||||||
|
cumulative_x: 0,
|
||||||
|
cumulative_y: 0,
|
||||||
|
cumulative_z: 0,
|
||||||
|
cumulative_roll: 0,
|
||||||
|
cumulative_pitch: 0,
|
||||||
|
cumulative_yaw: 0
|
||||||
}
|
}
|
||||||
|
|
||||||
let settings = {
|
let settings = {
|
||||||
@@ -120,6 +123,7 @@
|
|||||||
await populateModelCache()
|
await populateModelCache()
|
||||||
await createScene()
|
await createScene()
|
||||||
servoAngles.subscribe(updateAnglesFromStore)
|
servoAngles.subscribe(updateAnglesFromStore)
|
||||||
|
walkGait.subscribe(gait => planners[ModesEnum.Walk].set_mode(walkGaitToMode(gait)))
|
||||||
if (panel) createPanel()
|
if (panel) createPanel()
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -173,18 +177,21 @@
|
|||||||
|
|
||||||
const updateAngles = (name: string, angle: number) => {
|
const updateAngles = (name: string, angle: number) => {
|
||||||
modelTargetAngles[$jointNames.indexOf(name)] = angle * (180 / Math.PI)
|
modelTargetAngles[$jointNames.indexOf(name)] = angle * (180 / Math.PI)
|
||||||
Throttler.throttle(() => servoAnglesOut.set(modelTargetAngles.map(num => Math.round(num))), 100)
|
Throttler.throttle(
|
||||||
|
() => servoAnglesOut.set(modelTargetAngles.map(num => Math.round(num))),
|
||||||
|
100
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const createScene = async () => {
|
const createScene = async () => {
|
||||||
sceneManager
|
sceneManager
|
||||||
.addRenderer({ antialias: true, canvas, alpha: true })
|
.addRenderer({ antialias: true, canvas, alpha: true })
|
||||||
.addPerspectiveCamera({ x: -0.5, y: 0.5, z: 1 })
|
.addPerspectiveCamera({ x: -0.5, y: 0.5, z: 1 })
|
||||||
.addOrbitControls(Math.min(zoom, 8), 30, orbit)
|
.addOrbitControls(2, 20, orbit)
|
||||||
.addDirectionalLight({ x: 10, y: 20, z: 10, color: 0xffffff, intensity: 3 })
|
.addDirectionalLight({ x: 10, y: 20, z: 10, color: 0xffffff, intensity: 3 })
|
||||||
.addAmbientLight({ color: 0xffffff, intensity: 0.5 })
|
.addAmbientLight({ color: 0xffffff, intensity: 0.5 })
|
||||||
.addFogExp2(0xcccccc, 0.015)
|
.addFogExp2(0xcccccc, 0.015)
|
||||||
.addModel($model)
|
.addModel($model as URDFRobot)
|
||||||
.addTransformControls(sceneManager.model)
|
.addTransformControls(sceneManager.model)
|
||||||
.fillParent()
|
.fillParent()
|
||||||
.addRenderCb(render)
|
.addRenderCb(render)
|
||||||
@@ -198,32 +205,13 @@
|
|||||||
sceneManager.scene.add(target)
|
sceneManager.scene.add(target)
|
||||||
|
|
||||||
if (debug) {
|
if (debug) {
|
||||||
sceneManager.addDragControl(updateAngles)
|
sceneManager.addDragControl((angles: Record<string, number>) => {
|
||||||
|
Object.entries(angles).forEach(([name, angle]) => {
|
||||||
|
updateAngles(name, angle)
|
||||||
|
})
|
||||||
|
})
|
||||||
}
|
}
|
||||||
if (sky) sceneManager.addSky()
|
if (sky) sceneManager.addSky()
|
||||||
|
|
||||||
for (let i = 0; i < 4; i++) {
|
|
||||||
const geometry = new BufferGeometry()
|
|
||||||
const material = new LineBasicMaterial({ color: footColor() })
|
|
||||||
const line = new Line(geometry, material)
|
|
||||||
trace_lines.push(geometry)
|
|
||||||
sceneManager.scene.add(line)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const renderTraceLines = (foot_positions: Vector3[]) => {
|
|
||||||
if (!settings['Trace feet']) {
|
|
||||||
if (!feet_trace.length) return
|
|
||||||
trace_lines.forEach((line, i) => line.setFromPoints(feet_trace[i].slice(-1)))
|
|
||||||
feet_trace = new Array(4).fill([])
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
trace_lines.forEach((line, i) => {
|
|
||||||
feet_trace[i].push(foot_positions[i])
|
|
||||||
feet_trace[i] = feet_trace[i].slice(-settings['Trace points'])
|
|
||||||
line.setFromPoints(feet_trace[i])
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const calculate_kinematics = () => {
|
const calculate_kinematics = () => {
|
||||||
@@ -235,7 +223,13 @@
|
|||||||
xm: settings.xm,
|
xm: settings.xm,
|
||||||
ym: settings.ym,
|
ym: settings.ym,
|
||||||
zm: settings.zm,
|
zm: settings.zm,
|
||||||
feet: body_state.feet
|
feet: body_state.feet,
|
||||||
|
cumulative_x: body_state.cumulative_x,
|
||||||
|
cumulative_y: body_state.cumulative_y,
|
||||||
|
cumulative_z: body_state.cumulative_z,
|
||||||
|
cumulative_roll: body_state.cumulative_roll,
|
||||||
|
cumulative_pitch: body_state.cumulative_pitch,
|
||||||
|
cumulative_yaw: body_state.cumulative_yaw
|
||||||
}
|
}
|
||||||
|
|
||||||
let new_angles = kinematic.calcIK(position).map((x, i) => radToDeg(x * dir[i]))
|
let new_angles = kinematic.calcIK(position).map((x, i) => radToDeg(x * dir[i]))
|
||||||
@@ -246,12 +240,26 @@
|
|||||||
if (settings['Robot transform controls'] || !settings['Auto orient robot']) return
|
if (settings['Robot transform controls'] || !settings['Auto orient robot']) return
|
||||||
robot.position.y = robot.position.y - Math.min(...toes.map(toe => toe.y))
|
robot.position.y = robot.position.y - Math.min(...toes.map(toe => toe.y))
|
||||||
|
|
||||||
robot.position.z = smooth(robot.position.z, -settings.xm, 0.1)
|
const cumulativeYaw = body_state.cumulative_yaw
|
||||||
robot.position.x = smooth(robot.position.x, -settings.zm, 0.1)
|
|
||||||
|
|
||||||
robot.rotation.z = smooth(robot.rotation.z, degToRad(-settings.phi + $mpu.heading + 90), 0.1)
|
const cosYaw = Math.cos(cumulativeYaw)
|
||||||
robot.rotation.y = smooth(robot.rotation.y, degToRad(settings.omega), 0.1)
|
const sinYaw = Math.sin(cumulativeYaw)
|
||||||
robot.rotation.x = smooth(robot.rotation.x, degToRad(settings.psi - 90), 0.1)
|
const rotatedXm = settings.xm * cosYaw - settings.zm * sinYaw
|
||||||
|
const rotatedZm = settings.xm * sinYaw + settings.zm * cosYaw
|
||||||
|
|
||||||
|
robot.position.x = smooth(robot.position.x, -rotatedZm - body_state.cumulative_z * 1.2, 0.1)
|
||||||
|
robot.position.z = smooth(robot.position.z, -rotatedXm - body_state.cumulative_x * 1.2, 0.1)
|
||||||
|
|
||||||
|
const pitch = degToRad(settings.psi - 90) + body_state.cumulative_pitch
|
||||||
|
const roll = degToRad(settings.omega) + body_state.cumulative_roll
|
||||||
|
|
||||||
|
robot.rotation.z = smooth(
|
||||||
|
robot.rotation.z,
|
||||||
|
degToRad(-settings.phi + $mpu.heading + 90) + cumulativeYaw,
|
||||||
|
0.1
|
||||||
|
)
|
||||||
|
robot.rotation.y = smooth(robot.rotation.y, roll, 0.1)
|
||||||
|
robot.rotation.x = smooth(robot.rotation.x, pitch, 0.1)
|
||||||
}
|
}
|
||||||
|
|
||||||
const update_camera = (robot: URDFRobot) => {
|
const update_camera = (robot: URDFRobot) => {
|
||||||
@@ -267,16 +275,15 @@
|
|||||||
if (sceneManager.isDragging || !settings['Internal kinematic']) return
|
if (sceneManager.isDragging || !settings['Internal kinematic']) return
|
||||||
const controlData = get(outControllerData)
|
const controlData = get(outControllerData)
|
||||||
const data = {
|
const data = {
|
||||||
stop: controlData[0],
|
lx: controlData[0],
|
||||||
lx: controlData[1],
|
ly: controlData[1],
|
||||||
ly: controlData[2],
|
rx: controlData[2],
|
||||||
rx: controlData[3],
|
ry: controlData[3],
|
||||||
ry: controlData[4],
|
h: controlData[4],
|
||||||
h: controlData[5],
|
s: controlData[5],
|
||||||
s: controlData[6],
|
s1: controlData[6]
|
||||||
s1: controlData[7]
|
|
||||||
}
|
}
|
||||||
body_state.ym = ((data.h + 127) * 0.75) / 100
|
body_state.ym = data.h
|
||||||
|
|
||||||
let planner = planners[get(mode)]
|
let planner = planners[get(mode)]
|
||||||
const delta = performance.now() - lastTick
|
const delta = performance.now() - lastTick
|
||||||
@@ -311,9 +318,8 @@
|
|||||||
const robot = sceneManager.model
|
const robot = sceneManager.model
|
||||||
if (!robot) return
|
if (!robot) return
|
||||||
|
|
||||||
const toes = toeWorldPositions(robot)
|
const toes = getToeWorldPositions(robot)
|
||||||
|
|
||||||
renderTraceLines(toes)
|
|
||||||
update_camera(robot)
|
update_camera(robot)
|
||||||
update_gait()
|
update_gait()
|
||||||
calculate_kinematics()
|
calculate_kinematics()
|
||||||
|
|||||||
@@ -35,6 +35,9 @@ export { default as Hamburger } from '~icons/mdi/hamburger-menu'
|
|||||||
export { default as FileIcon } from '~icons/mdi/file'
|
export { default as FileIcon } from '~icons/mdi/file'
|
||||||
export { default as FolderIcon } from '~icons/mdi/folder-outline'
|
export { default as FolderIcon } from '~icons/mdi/folder-outline'
|
||||||
export { default as FolderOpenOutline } from '~icons/mdi/folder-open-outline'
|
export { default as FolderOpenOutline } from '~icons/mdi/folder-open-outline'
|
||||||
|
export { default as TrashIcon } from '~icons/mdi/trash'
|
||||||
|
export { default as RotateCcw } from '~icons/mdi/rotate-left'
|
||||||
|
export { default as RotateCw } from '~icons/mdi/rotate-right'
|
||||||
|
|
||||||
export { default as Down } from '~icons/tabler/chevron-down'
|
export { default as Down } from '~icons/tabler/chevron-down'
|
||||||
export { default as Cancel } from '~icons/tabler/x'
|
export { default as Cancel } from '~icons/tabler/x'
|
||||||
@@ -50,13 +53,14 @@ export { default as Power } from '~icons/tabler/power'
|
|||||||
export { default as MAC } from '~icons/tabler/dna-2'
|
export { default as MAC } from '~icons/tabler/dna-2'
|
||||||
export { default as Home } from '~icons/tabler/home'
|
export { default as Home } from '~icons/tabler/home'
|
||||||
export { default as SSID } from '~icons/tabler/router'
|
export { default as SSID } from '~icons/tabler/router'
|
||||||
export { default as DNS } from '~icons/tabler/address-book'
|
export { default as DNS } from '~icons/mdi/dns'
|
||||||
export { default as Gateway } from '~icons/tabler/torii'
|
export { default as Gateway } from '~icons/tabler/torii'
|
||||||
export { default as Subnet } from '~icons/tabler/grid-dots'
|
export { default as Subnet } from '~icons/tabler/grid-dots'
|
||||||
export { default as Channel } from '~icons/tabler/antenna'
|
export { default as Channel } from '~icons/tabler/antenna'
|
||||||
export { default as Scan } from '~icons/tabler/radar-2'
|
export { default as Scan } from '~icons/tabler/radar-2'
|
||||||
export { default as Add } from '~icons/tabler/circle-plus'
|
export { default as Add } from '~icons/tabler/circle-plus'
|
||||||
export { default as Edit } from '~icons/tabler/pencil'
|
export { default as Edit } from '~icons/mdi/edit'
|
||||||
|
export { default as EditOff } from '~icons/mdi/edit-off'
|
||||||
export { default as Delete } from '~icons/tabler/trash'
|
export { default as Delete } from '~icons/tabler/trash'
|
||||||
|
|
||||||
export { default as Network } from '~icons/tabler/router'
|
export { default as Network } from '~icons/tabler/router'
|
||||||
|
|||||||
@@ -1,19 +1,19 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { MdiEyeOffOutline, MdiEyeOutline } from "../icons";
|
import { MdiEyeOffOutline, MdiEyeOutline } from '../icons'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
show?: boolean;
|
show?: boolean
|
||||||
value?: string;
|
value?: string
|
||||||
id?: string;
|
id?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
let { show = $bindable(false), value = $bindable(''), id = '' }: Props = $props();
|
let { show = $bindable(false), value = $bindable(''), id = '' }: Props = $props()
|
||||||
|
|
||||||
let type = $derived(show ? 'text' : 'password');
|
let type = $derived(show ? 'text' : 'password')
|
||||||
|
|
||||||
const handleInput = (e: any) => value = e.target.value
|
const handleInput = (e: Event) => (value = (e.target as HTMLInputElement).value)
|
||||||
|
|
||||||
const togglePassword = () => show = !show
|
const togglePassword = () => (show = !show)
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<label class="input input-bordered flex items-center gap-2">
|
<label class="input input-bordered flex items-center gap-2">
|
||||||
|
|||||||
@@ -3,8 +3,8 @@
|
|||||||
min?: number
|
min?: number
|
||||||
max?: number
|
max?: number
|
||||||
step?: number
|
step?: number
|
||||||
value?: any
|
value?: number
|
||||||
oninput?: any
|
oninput?: (value: number) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
let {
|
let {
|
||||||
@@ -24,7 +24,8 @@
|
|||||||
{max}
|
{max}
|
||||||
{step}
|
{step}
|
||||||
bind:value
|
bind:value
|
||||||
{...rest} />
|
{...rest}
|
||||||
|
/>
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
input[type='range']::-webkit-slider-runnable-track {
|
input[type='range']::-webkit-slider-runnable-track {
|
||||||
|
|||||||
@@ -1,2 +1,2 @@
|
|||||||
export { default as PasswordInput } from './InputPassword.svelte';
|
export { default as PasswordInput } from './InputPassword.svelte'
|
||||||
export { default as VerticalSlider } from './VerticalSlider.svelte';
|
export { default as VerticalSlider } from './VerticalSlider.svelte'
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
interface Props {
|
interface Props {
|
||||||
children?: import('svelte').Snippet;
|
children?: import('svelte').Snippet
|
||||||
}
|
}
|
||||||
|
|
||||||
let { children }: Props = $props();
|
let { children }: Props = $props()
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="box-border overflow-hidden flex-1">
|
<div class="box-border overflow-hidden flex-1">
|
||||||
|
|||||||
@@ -1,13 +1,17 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import WidgetContainer from './WidgetContainer.svelte';
|
import WidgetContainer from './WidgetContainer.svelte'
|
||||||
import { WidgetComponents, type WidgetContainerConfig, isWidgetConfig } from '$lib/stores/application';
|
import {
|
||||||
import Widget from './Widget.svelte';
|
WidgetComponents,
|
||||||
|
type WidgetContainerConfig,
|
||||||
|
isWidgetConfig
|
||||||
|
} from '$lib/stores/application'
|
||||||
|
import Widget from './Widget.svelte'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
container: WidgetContainerConfig;
|
container: WidgetContainerConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
let { container }: Props = $props();
|
let { container }: Props = $props()
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="w-full h-full flex flex-col overflow-hidden">
|
<div class="w-full h-full flex flex-col overflow-hidden">
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { Github } from "../icons";
|
import { Github } from '../icons'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
github: any;
|
github: { url: string; version: string; active?: boolean; href?: string }
|
||||||
}
|
}
|
||||||
|
|
||||||
let { github }: Props = $props();
|
let { github }: Props = $props()
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
{#if github.active}
|
{#if github.active}
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
<script>
|
<script>
|
||||||
import logo from '$lib/assets/logo512.png';
|
import logo from '$lib/assets/logo512.png'
|
||||||
|
import { resolve } from '$app/paths'
|
||||||
|
|
||||||
/** @type {{appName: any}} */
|
/** @type {{appName: any}} */
|
||||||
let { appName } = $props();
|
let { appName } = $props()
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<a
|
<a
|
||||||
href="/"
|
href={resolve('/')}
|
||||||
class="rounded-box mb-4 flex items-center hover:scale-[1.02] active:scale-[0.98]"
|
class="rounded-box mb-4 flex items-center hover:scale-[1.02] active:scale-[0.98]"
|
||||||
>
|
>
|
||||||
<img src={logo} alt="Logo" class="h-12 w-12" />
|
<img src={logo} alt="Logo" class="h-12 w-12" />
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { page } from '$app/state'
|
import { page } from '$app/state'
|
||||||
|
import { base } from '$app/paths'
|
||||||
import { useFeatureFlags } from '$lib/stores/featureFlags'
|
import { useFeatureFlags } from '$lib/stores/featureFlags'
|
||||||
import GithubButton from '../menu/GithubButton.svelte'
|
import GithubButton from '../menu/GithubButton.svelte'
|
||||||
import LogoButton from '../menu/LogoButton.svelte'
|
import LogoButton from '../menu/LogoButton.svelte'
|
||||||
@@ -19,9 +20,10 @@
|
|||||||
Router,
|
Router,
|
||||||
AP,
|
AP,
|
||||||
Copyright,
|
Copyright,
|
||||||
Metrics
|
Metrics,
|
||||||
|
DNS
|
||||||
} from '$lib/components/icons'
|
} from '$lib/components/icons'
|
||||||
import appEnv from 'app-env'
|
import { PUBLIC_VITE_USE_HOST_NAME } from '$env/static/public'
|
||||||
|
|
||||||
const features = useFeatureFlags()
|
const features = useFeatureFlags()
|
||||||
|
|
||||||
@@ -31,15 +33,21 @@
|
|||||||
|
|
||||||
const github = { href: 'https://github.com/' + page.data.github, active: true }
|
const github = { href: 'https://github.com/' + page.data.github, active: true }
|
||||||
|
|
||||||
|
import type { ComponentType } from 'svelte'
|
||||||
|
|
||||||
type menuItem = {
|
type menuItem = {
|
||||||
title: string
|
title: string
|
||||||
icon: ConstructorOfATypedSvelteComponent
|
icon: ComponentType
|
||||||
href?: string
|
href?: string
|
||||||
feature: boolean
|
feature: boolean
|
||||||
active?: boolean
|
active?: boolean
|
||||||
submenu?: menuItem[]
|
submenu?: menuItem[]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function withBase(path: string) {
|
||||||
|
return `${base}${path.startsWith('/') ? path : '/' + path}`
|
||||||
|
}
|
||||||
|
|
||||||
let menuItems = $state<menuItem[]>([])
|
let menuItems = $state<menuItem[]>([])
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
@@ -47,13 +55,13 @@
|
|||||||
{
|
{
|
||||||
title: 'Connection',
|
title: 'Connection',
|
||||||
icon: WiFi,
|
icon: WiFi,
|
||||||
href: '/connection',
|
href: withBase('/connection'),
|
||||||
feature: !appEnv.VITE_USE_HOST_NAME
|
feature: !PUBLIC_VITE_USE_HOST_NAME
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'Controller',
|
title: 'Controller',
|
||||||
icon: MdiController,
|
icon: MdiController,
|
||||||
href: '/controller',
|
href: withBase('/controller'),
|
||||||
feature: true
|
feature: true
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -64,25 +72,25 @@
|
|||||||
{
|
{
|
||||||
title: 'I2C',
|
title: 'I2C',
|
||||||
icon: Connection,
|
icon: Connection,
|
||||||
href: '/peripherals/i2c',
|
href: withBase('/peripherals/i2c'),
|
||||||
feature: true
|
feature: true
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'Camera',
|
title: 'Camera',
|
||||||
icon: Camera,
|
icon: Camera,
|
||||||
href: '/peripherals/camera',
|
href: withBase('/peripherals/camera'),
|
||||||
feature: $features.camera
|
feature: $features.camera
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'Servo',
|
title: 'Servo',
|
||||||
icon: MotorOutline,
|
icon: MotorOutline,
|
||||||
href: '/peripherals/servo',
|
href: withBase('/peripherals/servo'),
|
||||||
feature: true
|
feature: true
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'IMU',
|
title: 'IMU',
|
||||||
icon: Rotate3d,
|
icon: Rotate3d,
|
||||||
href: '/peripherals/imu',
|
href: withBase('/peripherals/imu'),
|
||||||
feature: $features.imu || $features.mag || $features.bmp
|
feature: $features.imu || $features.mag || $features.bmp
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
@@ -95,13 +103,19 @@
|
|||||||
{
|
{
|
||||||
title: 'WiFi Station',
|
title: 'WiFi Station',
|
||||||
icon: Router,
|
icon: Router,
|
||||||
href: '/wifi/sta',
|
href: withBase('/wifi/sta'),
|
||||||
feature: true
|
feature: true
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'Access Point',
|
title: 'Access Point',
|
||||||
icon: AP,
|
icon: AP,
|
||||||
href: '/wifi/ap',
|
href: withBase('/wifi/ap'),
|
||||||
|
feature: true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'mDNS',
|
||||||
|
icon: DNS,
|
||||||
|
href: withBase('/wifi/mdns'),
|
||||||
feature: true
|
feature: true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
@@ -114,26 +128,29 @@
|
|||||||
{
|
{
|
||||||
title: 'System Status',
|
title: 'System Status',
|
||||||
icon: Health,
|
icon: Health,
|
||||||
href: '/system/status',
|
href: withBase('/system/status'),
|
||||||
feature: true
|
feature: true
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'File System',
|
title: 'File System',
|
||||||
icon: Folder,
|
icon: Folder,
|
||||||
href: '/system/filesystem',
|
href: withBase('/system/filesystem'),
|
||||||
feature: true
|
feature: true
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'System Metrics',
|
title: 'System Metrics',
|
||||||
icon: Metrics,
|
icon: Metrics,
|
||||||
href: '/system/metrics',
|
href: withBase('/system/metrics'),
|
||||||
feature: $features.analytics
|
feature: true
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'Firmware Update',
|
title: 'Firmware Update',
|
||||||
icon: Update,
|
icon: Update,
|
||||||
href: '/system/update',
|
href: withBase('/system/update'),
|
||||||
feature: $features.ota || $features.upload_firmware || $features.download_firmware
|
feature:
|
||||||
|
$features.ota ||
|
||||||
|
$features.upload_firmware ||
|
||||||
|
$features.download_firmware
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -157,7 +174,7 @@
|
|||||||
setActiveMenuItem(page.data.title)
|
setActiveMenuItem(page.data.title)
|
||||||
})
|
})
|
||||||
|
|
||||||
const updateMenu = (event: any) => {
|
const updateMenu = (event: CustomEvent) => {
|
||||||
setActiveMenuItem(event.details)
|
setActiveMenuItem(event.details)
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
@@ -165,7 +182,12 @@
|
|||||||
<div class="flex h-full w-80 flex-col p-4 bg-base-200 text-base-content">
|
<div class="flex h-full w-80 flex-col p-4 bg-base-200 text-base-content">
|
||||||
<LogoButton {appName} />
|
<LogoButton {appName} />
|
||||||
|
|
||||||
<MenuList {menuItems} select={updateMenu} class="grow flex-nowrap overflow-y-auto" level="0" />
|
<MenuList
|
||||||
|
{menuItems}
|
||||||
|
select={updateMenu}
|
||||||
|
class="grow flex-nowrap overflow-y-auto overflow-x-hidden"
|
||||||
|
level="0"
|
||||||
|
/>
|
||||||
|
|
||||||
<div class="divider my-0"></div>
|
<div class="divider my-0"></div>
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import MenuList from './MenuList.svelte'
|
import MenuList from './MenuList.svelte'
|
||||||
|
import type { ComponentType } from 'svelte'
|
||||||
|
|
||||||
type MenuItem = {
|
type MenuItem = {
|
||||||
title: string
|
title: string
|
||||||
icon: ConstructorOfATypedSvelteComponent
|
icon: ComponentType
|
||||||
href?: string
|
href?: string
|
||||||
feature: boolean
|
feature: boolean
|
||||||
active?: boolean
|
active?: boolean
|
||||||
@@ -16,18 +18,23 @@
|
|||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<ul class={klass + ' menu'}>
|
<ul class={klass + ' menu w-full'}>
|
||||||
{#each menuItems as MenuItem[] as menuItem, i (menuItem.title)}
|
{#each menuItems as MenuItem[] as menuItem (menuItem.title)}
|
||||||
{#if menuItem.feature}
|
{#if menuItem.feature}
|
||||||
<li>
|
<li>
|
||||||
{#if menuItem.submenu}
|
{#if menuItem.submenu}
|
||||||
<details open={menuItem.submenu.some(subItem => subItem.active)}>
|
<details open={menuItem.submenu.some(subItem => subItem.active)}>
|
||||||
<summary class="text-lg font-bold">
|
<summary class="font-bold">
|
||||||
<menuItem.icon class="h-6 w-6" />
|
<menuItem.icon class="h-6 w-6" />
|
||||||
{menuItem.title}
|
{menuItem.title}
|
||||||
</summary>
|
</summary>
|
||||||
<div class="pl-4">
|
<div class="pl-4">
|
||||||
<MenuList menuItems={menuItem.submenu} level={level + 1} {select} class={klass} />
|
<MenuList
|
||||||
|
menuItems={menuItem.submenu}
|
||||||
|
level={level + 1}
|
||||||
|
{select}
|
||||||
|
class={klass}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</details>
|
</details>
|
||||||
{:else}
|
{:else}
|
||||||
@@ -37,7 +44,8 @@
|
|||||||
class:bg-base-100={menuItem.active}
|
class:bg-base-100={menuItem.active}
|
||||||
class:text-lg={level === 0}
|
class:text-lg={level === 0}
|
||||||
class:text-md={level === 1}
|
class:text-md={level === 1}
|
||||||
onclick={() => selectMenuItem(menuItem.title)}>
|
onclick={() => selectMenuItem(menuItem.title)}
|
||||||
|
>
|
||||||
<menuItem.icon class="h-6 w-6" />
|
<menuItem.icon class="h-6 w-6" />
|
||||||
{menuItem.title}
|
{menuItem.title}
|
||||||
</a>
|
</a>
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { isFullscreen, toggleFullscreen } from '$lib/stores';
|
import { isFullscreen, toggleFullscreen } from '$lib/stores'
|
||||||
import { MdiFullscreenExit, MdiFullscreen } from '../icons';
|
import { MdiFullscreenExit, MdiFullscreen } from '../icons'
|
||||||
|
|
||||||
const SvelteComponent = $derived($isFullscreen ? MdiFullscreenExit : MdiFullscreen);
|
const SvelteComponent = $derived($isFullscreen ? MdiFullscreenExit : MdiFullscreen)
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<button onclick={toggleFullscreen}>
|
<button onclick={toggleFullscreen}>
|
||||||
|
|||||||
@@ -1,26 +1,26 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { WiFi, WiFi0, WiFi1, WiFi2, WifiOff } from "../icons";
|
import { WiFi, WiFi0, WiFi1, WiFi2, WifiOff } from '../icons'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
showDBm?: boolean;
|
showDBm?: boolean
|
||||||
rssi?: number;
|
rssi?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
let { showDBm = false, rssi = 0 }: Props = $props();
|
let { showDBm = false, rssi = 0 }: Props = $props()
|
||||||
|
|
||||||
const getWiFiIcon = () => {
|
const getWiFiIcon = () => {
|
||||||
if (rssi === 0) return WifiOff;
|
if (rssi === 0) return WifiOff
|
||||||
if (rssi >= -55) return WiFi;
|
if (rssi >= -55) return WiFi
|
||||||
if (rssi >= -75) return WiFi2;
|
if (rssi >= -75) return WiFi2
|
||||||
if (rssi >= -85) return WiFi1;
|
if (rssi >= -85) return WiFi1
|
||||||
return WiFi0;
|
return WiFi0
|
||||||
};
|
}
|
||||||
|
|
||||||
const SvelteComponent = $derived(getWiFiIcon());
|
const SvelteComponent = $derived(getWiFiIcon())
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="indicator">
|
<div class="indicator">
|
||||||
<div class="tooltip tooltip-left" data-tip={rssi + " dBm"}>
|
<div class="tooltip tooltip-left" data-tip={rssi + ' dBm'}>
|
||||||
{#if showDBm}
|
{#if showDBm}
|
||||||
<span class="indicator-item indicator-start badge badge-accent badge-outline badge-xs">
|
<span class="indicator-item indicator-start badge badge-accent badge-outline badge-xs">
|
||||||
{rssi} dBm
|
{rssi} dBm
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { useFeatureFlags } from '$lib/stores';
|
import { useFeatureFlags } from '$lib/stores'
|
||||||
import { modals } from 'svelte-modals';
|
import { modals } from 'svelte-modals'
|
||||||
import ConfirmDialog from '$lib/components/ConfirmDialog.svelte';
|
import ConfirmDialog from '$lib/components/ConfirmDialog.svelte'
|
||||||
import { api } from '$lib/api';
|
import { api } from '$lib/api'
|
||||||
import { Cancel, Power } from '../icons';
|
import { Cancel, Power } from '../icons'
|
||||||
|
|
||||||
const features = useFeatureFlags();
|
const features = useFeatureFlags()
|
||||||
|
|
||||||
const postSleep = async () => await api.post('/api/system/sleep');
|
const postSleep = async () => await api.post('/api/system/sleep')
|
||||||
|
|
||||||
const confirmSleep = () => {
|
const confirmSleep = () => {
|
||||||
modals.open(ConfirmDialog, {
|
modals.open(ConfirmDialog, {
|
||||||
@@ -18,11 +18,11 @@
|
|||||||
confirm: { label: 'Switch Off', icon: Power }
|
confirm: { label: 'Switch Off', icon: Power }
|
||||||
},
|
},
|
||||||
onConfirm: () => {
|
onConfirm: () => {
|
||||||
modals.close();
|
modals.close()
|
||||||
postSleep();
|
postSleep()
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
});
|
|
||||||
};
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
{#if $features.sleep}
|
{#if $features.sleep}
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { mode, modes } from "$lib/stores";
|
import { mode, modes } from '$lib/stores'
|
||||||
|
|
||||||
const deactivate = async () => {
|
const deactivate = async () => {
|
||||||
mode.set(modes.indexOf('deactivated'));
|
mode.set(modes.indexOf('deactivated'))
|
||||||
};
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
|
||||||
<button onclick={deactivate} class="bg-error text-white btn rounded-none">STOP</button>
|
<button onclick={deactivate} class="bg-error text-white btn rounded-none">STOP</button>
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { MdiWeatherSunny, MdiMoonAndStars } from "../icons";
|
import { MdiWeatherSunny, MdiMoonAndStars } from '../icons'
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<label class="swap swap-rotate">
|
<label class="swap swap-rotate">
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import {Hamburger} from '../icons'
|
import { Hamburger } from '../icons'
|
||||||
|
import { resolve } from '$app/paths'
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="topbar absolute left-0 top-0 w-full z-20 flex justify-between bg-zinc-800">
|
<div class="topbar absolute left-0 top-0 w-full z-20 flex justify-between bg-zinc-800">
|
||||||
<div class="flex gap-2 p-2">
|
<div class="flex gap-2 p-2">
|
||||||
<a href="/">
|
<a href={resolve('/')}>
|
||||||
<Hamburger class="h-8 w-8"/>
|
<Hamburger class="h-8 w-8" />
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,80 +1,80 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { page } from '$app/state';
|
import { page } from '$app/state'
|
||||||
import { modals } from 'svelte-modals';
|
import { modals } from 'svelte-modals'
|
||||||
import { notifications } from '$lib/components/toasts/notifications';
|
import { notifications } from '$lib/components/toasts/notifications'
|
||||||
import ConfirmDialog from '$lib/components/ConfirmDialog.svelte';
|
import ConfirmDialog from '$lib/components/ConfirmDialog.svelte'
|
||||||
import GithubUpdateDialog from '$lib/components/GithubUpdateDialog.svelte';
|
import GithubUpdateDialog from '$lib/components/GithubUpdateDialog.svelte'
|
||||||
import { compareVersions } from 'compare-versions';
|
import { compareVersions } from 'compare-versions'
|
||||||
import { onMount } from 'svelte';
|
import { onMount } from 'svelte'
|
||||||
import { api } from '$lib/api';
|
import { api } from '$lib/api'
|
||||||
import type { GithubRelease } from '$lib/types/models';
|
import type { GithubRelease } from '$lib/types/models'
|
||||||
import { useFeatureFlags } from '$lib/stores/featureFlags';
|
import { useFeatureFlags } from '$lib/stores/featureFlags'
|
||||||
import { Cancel, CloudDown, Firmware } from '../icons';
|
import { Cancel, CloudDown, Firmware } from '../icons'
|
||||||
|
|
||||||
const features = useFeatureFlags();
|
const features = useFeatureFlags()
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
update?: boolean;
|
update?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
let { update = $bindable(false) }: Props = $props();
|
let { update = $bindable(false) }: Props = $props()
|
||||||
|
|
||||||
let firmwareVersion: string = $state('');
|
let firmwareVersion: string = $state('')
|
||||||
let firmwareDownloadLink: string = $state('');
|
let firmwareDownloadLink: string = $state('')
|
||||||
|
|
||||||
async function getGithubAPI() {
|
async function getGithubAPI() {
|
||||||
const headers = {
|
const headers = {
|
||||||
accept: 'application/vnd.github+json',
|
accept: 'application/vnd.github+json',
|
||||||
'X-GitHub-Api-Version': '2022-11-28'
|
'X-GitHub-Api-Version': '2022-11-28'
|
||||||
};
|
}
|
||||||
const result = await api.get<GithubRelease>(
|
const result = await api.get<GithubRelease>(
|
||||||
`https://api.github.com/repos/${page.data.github}/releases/latest`,
|
`https://api.github.com/repos/${page.data.github}/releases/latest`,
|
||||||
{ headers }
|
{ headers }
|
||||||
);
|
)
|
||||||
if (result.inner.message === '404' || result.inner.message == 'Not Found') {
|
if (result.inner.message === '404' || result.inner.message == 'Not Found') {
|
||||||
console.warn('Error: Could not find releases in the repository');
|
console.warn('Error: Could not find releases in the repository')
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
if (result.isErr()) {
|
if (result.isErr()) {
|
||||||
console.error('Error:', result.inner);
|
console.error('Error:', result.inner)
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
const results = result.inner;
|
const results = result.inner
|
||||||
update = false;
|
update = false
|
||||||
firmwareVersion = '';
|
firmwareVersion = ''
|
||||||
|
|
||||||
if (compareVersions(results.tag_name, $features.firmware_version) === 1) {
|
if (compareVersions(results.tag_name, $features.firmware_version as string) === 1) {
|
||||||
// iterate over assets and find the correct one
|
// iterate over assets and find the correct one
|
||||||
for (let i = 0; i < results.assets.length; i++) {
|
for (let i = 0; i < results.assets.length; i++) {
|
||||||
// check if the asset is of type *.bin
|
// check if the asset is of type *.bin
|
||||||
if (
|
if (
|
||||||
results.assets[i].name.includes('.bin') &&
|
results.assets[i].name.includes('.bin') &&
|
||||||
results.assets[i].name.includes($features.firmware_built_target)
|
results.assets[i].name.includes($features.firmware_built_target as string)
|
||||||
) {
|
) {
|
||||||
update = true;
|
update = true
|
||||||
firmwareVersion = results.tag_name;
|
firmwareVersion = results.tag_name
|
||||||
firmwareDownloadLink = results.assets[i].browser_download_url;
|
firmwareDownloadLink = results.assets[i].browser_download_url
|
||||||
notifications.info('Firmware update available.', 5000);
|
notifications.info('Firmware update available.', 5000)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function postGithubDownload(url: string) {
|
async function postGithubDownload(url: string) {
|
||||||
const result = await api.post('/api/downloadUpdate', { download_url: url });
|
const result = await api.post('/api/downloadUpdate', { download_url: url })
|
||||||
if (result.isErr()) {
|
if (result.isErr()) {
|
||||||
console.error('Error:', result.inner);
|
console.error('Error:', result.inner)
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
onMount(async () => {
|
onMount(async () => {
|
||||||
if ($features.download_firmware) {
|
if ($features.download_firmware) {
|
||||||
await getGithubAPI();
|
await getGithubAPI()
|
||||||
setInterval(async () => await getGithubAPI(), 60 * 60 * 1000); // once per hour
|
setInterval(async () => await getGithubAPI(), 60 * 60 * 1000) // once per hour
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
|
|
||||||
function confirmGithubUpdate(url: string) {
|
function confirmGithubUpdate(url: string) {
|
||||||
modals.open(ConfirmDialog, {
|
modals.open(ConfirmDialog, {
|
||||||
@@ -85,12 +85,12 @@
|
|||||||
confirm: { label: 'Update', icon: CloudDown }
|
confirm: { label: 'Update', icon: CloudDown }
|
||||||
},
|
},
|
||||||
onConfirm: () => {
|
onConfirm: () => {
|
||||||
postGithubDownload(url);
|
postGithubDownload(url)
|
||||||
modals.open(GithubUpdateDialog, {
|
modals.open(GithubUpdateDialog, {
|
||||||
onConfirm: () => modals.closeAll()
|
onConfirm: () => modals.closeAll()
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { selectedView, views } from "$lib/stores/application";
|
import { selectedView, views } from '$lib/stores/application'
|
||||||
import Selector from "../widget/Selector.svelte";
|
import Selector from '../widget/Selector.svelte'
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<Selector bind:selectedOption={$selectedView} options={$views.map((v) => v.name)} />
|
<Selector bind:selectedOption={$selectedView} options={$views.map(v => v.name)} />
|
||||||
|
|||||||
@@ -1,22 +1,24 @@
|
|||||||
<script>
|
<script>
|
||||||
import { flip } from 'svelte/animate';
|
import { flip } from 'svelte/animate'
|
||||||
import { fly } from 'svelte/transition';
|
import { fly } from 'svelte/transition'
|
||||||
import { notifications } from '$lib/components/toasts/notifications';
|
import { notifications } from '$lib/components/toasts/notifications'
|
||||||
import { error, info, success, warning } from '../icons';
|
import { error, info, success, warning } from '../icons'
|
||||||
|
|
||||||
|
|
||||||
/** @type {{theme?: any, icon?: any}} */
|
/** @type {{theme?: any, icon?: any}} */
|
||||||
let { theme = {
|
let {
|
||||||
|
theme = {
|
||||||
error: 'alert-error',
|
error: 'alert-error',
|
||||||
success: 'alert-success',
|
success: 'alert-success',
|
||||||
warning: 'alert-warning',
|
warning: 'alert-warning',
|
||||||
info: 'alert-info'
|
info: 'alert-info'
|
||||||
}, icon = {
|
},
|
||||||
|
icon = {
|
||||||
error: error,
|
error: error,
|
||||||
success: success,
|
success: success,
|
||||||
warning: warning,
|
warning: warning,
|
||||||
info: info
|
info: info
|
||||||
} } = $props();
|
}
|
||||||
|
} = $props()
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="toast toast-end mr-4 z-20">
|
<div class="toast toast-end mr-4 z-20">
|
||||||
|
|||||||
@@ -1,42 +1,42 @@
|
|||||||
import { writable, derived, type Writable } from 'svelte/store';
|
import { writable } from 'svelte/store'
|
||||||
|
|
||||||
type StateType = 'info' | 'success' | 'warning' | 'error';
|
type StateType = 'info' | 'success' | 'warning' | 'error'
|
||||||
|
|
||||||
type State = {
|
type State = {
|
||||||
id: string;
|
id: string
|
||||||
type: StateType;
|
type: StateType
|
||||||
message: string;
|
message: string
|
||||||
};
|
}
|
||||||
|
|
||||||
function createNotificationStore() {
|
function createNotificationStore() {
|
||||||
const state: State[] = [];
|
const state: State[] = []
|
||||||
const notifications = writable(state);
|
const notifications = writable(state)
|
||||||
const { subscribe } = notifications;
|
const { subscribe } = notifications
|
||||||
|
|
||||||
function send(message: string, type: StateType = 'info', timeout: number) {
|
function send(message: string, type: StateType = 'info', timeout: number) {
|
||||||
const id = generateId();
|
const id = generateId()
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
notifications.update((state) => {
|
notifications.update(state => {
|
||||||
return state.filter((n) => n.id !== id);
|
return state.filter(n => n.id !== id)
|
||||||
});
|
})
|
||||||
}, timeout);
|
}, timeout)
|
||||||
notifications.update((state) => {
|
notifications.update(state => {
|
||||||
return [...state, { id, type, message }];
|
return [...state, { id, type, message }]
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
subscribe,
|
subscribe,
|
||||||
send,
|
send,
|
||||||
error: (msg: string, timeout: number) => send(msg, 'error', timeout),
|
error: (msg: string, timeout: number = 4000) => send(msg, 'error', timeout),
|
||||||
warning: (msg: string, timeout: number) => send(msg, 'warning', timeout),
|
warning: (msg: string, timeout: number = 4000) => send(msg, 'warning', timeout),
|
||||||
info: (msg: string, timeout: number) => send(msg, 'info', timeout),
|
info: (msg: string, timeout: number = 4000) => send(msg, 'info', timeout),
|
||||||
success: (msg: string, timeout: number) => send(msg, 'success', timeout)
|
success: (msg: string, timeout: number = 4000) => send(msg, 'success', timeout)
|
||||||
};
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function generateId() {
|
function generateId() {
|
||||||
return '_' + Math.random().toString(36).substr(2, 9);
|
return '_' + Math.random().toString(36).substr(2, 9)
|
||||||
}
|
}
|
||||||
|
|
||||||
export const notifications = createNotificationStore();
|
export const notifications = createNotificationStore()
|
||||||
|
|||||||
@@ -1,22 +1,22 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { daisyColor } from "$lib/utilities";
|
import { daisyColor } from '$lib/utilities'
|
||||||
import { Chart, registerables } from "chart.js";
|
import { Chart, registerables } from 'chart.js'
|
||||||
import { onMount } from "svelte";
|
import { onMount } from 'svelte'
|
||||||
import { cubicOut } from "svelte/easing";
|
import { cubicOut } from 'svelte/easing'
|
||||||
import { slide } from "svelte/transition";
|
import { slide } from 'svelte/transition'
|
||||||
|
|
||||||
let chartElement: HTMLCanvasElement = $state();
|
let chartElement: HTMLCanvasElement
|
||||||
let chart: Chart;
|
let chart: Chart<'line', number[], number>
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
label: any;
|
label: string
|
||||||
data: number[];
|
data: number[]
|
||||||
title: any;
|
title: string
|
||||||
}
|
}
|
||||||
|
|
||||||
let { label, data, title }: Props = $props();
|
let { label, data, title }: Props = $props()
|
||||||
|
|
||||||
Chart.register(...registerables);
|
Chart.register(...registerables)
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
chart = new Chart(chartElement, {
|
chart = new Chart(chartElement, {
|
||||||
@@ -31,7 +31,7 @@
|
|||||||
borderWidth: 2,
|
borderWidth: 2,
|
||||||
data,
|
data,
|
||||||
yAxisID: 'y'
|
yAxisID: 'y'
|
||||||
},
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
options: {
|
options: {
|
||||||
@@ -83,16 +83,15 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
|
|
||||||
setInterval(() => {
|
setInterval(() => {
|
||||||
chart.data.labels = data
|
chart.data.labels = data
|
||||||
chart.data.datasets[0].data = data
|
chart.data.datasets[0].data = data
|
||||||
}, 500);
|
}, 500)
|
||||||
})
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
|
||||||
<div class="w-full h-full overflow-x-auto">
|
<div class="w-full h-full overflow-x-auto">
|
||||||
<div
|
<div
|
||||||
class="flex w-full flex-col space-y-1 h-60"
|
class="flex w-full flex-col space-y-1 h-60"
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
interface Props {
|
interface Props {
|
||||||
options?: string[];
|
options?: string[]
|
||||||
selectedOption?: string;
|
selectedOption?: string
|
||||||
change: () => void;
|
change?: () => void
|
||||||
[key: string]: any;
|
[key: string]: unknown
|
||||||
}
|
}
|
||||||
|
|
||||||
let { options = [], selectedOption = $bindable(''), ...rest }: Props = $props();
|
let { options = [], selectedOption = $bindable(''), ...rest }: Props = $props()
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<select
|
<select
|
||||||
|
|||||||
+807
-305
File diff suppressed because it is too large
Load Diff
+129
-296
@@ -1,320 +1,153 @@
|
|||||||
|
|
||||||
export interface body_state_t {
|
export interface body_state_t {
|
||||||
omega: number;
|
omega: number
|
||||||
phi: number;
|
phi: number
|
||||||
psi: number;
|
psi: number
|
||||||
xm: number;
|
xm: number
|
||||||
ym: number;
|
ym: number
|
||||||
zm: number;
|
zm: number
|
||||||
feet: number[][];
|
feet: number[][]
|
||||||
|
cumulative_x: number
|
||||||
|
cumulative_y: number
|
||||||
|
cumulative_z: number
|
||||||
|
cumulative_roll: number
|
||||||
|
cumulative_pitch: number
|
||||||
|
cumulative_yaw: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface position {
|
export interface position {
|
||||||
x: number;
|
x: number
|
||||||
y: number;
|
y: number
|
||||||
z: number;
|
z: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface target_position {
|
export interface target_position {
|
||||||
x: number;
|
x: number
|
||||||
z: number;
|
z: number
|
||||||
yaw: number;
|
yaw: number
|
||||||
}
|
}
|
||||||
|
|
||||||
const { cos, sin, atan2, sqrt } = Math;
|
export interface KinematicParams {
|
||||||
|
coxa: number
|
||||||
|
coxa_offset: number
|
||||||
|
femur: number
|
||||||
|
tibia: number
|
||||||
|
L: number
|
||||||
|
W: number
|
||||||
|
}
|
||||||
|
|
||||||
const DEG2RAD = 0.017453292519943;
|
const { cos, sin, atan2, acos, sqrt, max, min } = Math
|
||||||
|
|
||||||
|
const DEG2RAD = 0.017453292519943
|
||||||
|
|
||||||
export default class Kinematic {
|
export default class Kinematic {
|
||||||
l1: number;
|
coxa: number
|
||||||
l2: number;
|
coxa_offset: number
|
||||||
l3: number;
|
femur: number
|
||||||
l4: number;
|
tibia: number
|
||||||
|
|
||||||
L: number;
|
L: number
|
||||||
W: number;
|
W: number
|
||||||
|
|
||||||
DEG2RAD = DEG2RAD;
|
DEG2RAD = DEG2RAD
|
||||||
|
|
||||||
sHp = sin(Math.PI / 2);
|
mountOffsets: number[][]
|
||||||
cHp = cos(Math.PI / 2);
|
|
||||||
|
|
||||||
Tlf: number[][] = [];
|
invMountRot = [
|
||||||
Trf: number[][] = [];
|
[0, 0, -1],
|
||||||
Tlb: number[][] = [];
|
[0, 1, 0],
|
||||||
Trb: number[][] = [];
|
[1, 0, 0]
|
||||||
|
]
|
||||||
|
|
||||||
point_lf: number[][];
|
constructor(params: KinematicParams) {
|
||||||
point_rf: number[][];
|
this.coxa = params.coxa
|
||||||
point_lb: number[][];
|
this.coxa_offset = params.coxa_offset
|
||||||
point_rb: number[][];
|
this.femur = params.femur
|
||||||
Ix: number[][];
|
this.tibia = params.tibia
|
||||||
|
this.L = params.L
|
||||||
|
this.W = params.W
|
||||||
|
|
||||||
constructor() {
|
this.mountOffsets = [
|
||||||
this.l1 = 60.5 / 100;
|
[this.L / 2, 0, this.W / 2],
|
||||||
this.l2 = 10 / 100;
|
[this.L / 2, 0, -this.W / 2],
|
||||||
this.l3 = 100.7 / 100;
|
[-this.L / 2, 0, this.W / 2],
|
||||||
this.l4 = 118.5 / 100;
|
[-this.L / 2, 0, -this.W / 2]
|
||||||
|
]
|
||||||
this.L = 207.5 / 100;
|
|
||||||
this.W = 78 / 100;
|
|
||||||
|
|
||||||
this.point_lf = [
|
|
||||||
[this.cHp, 0, this.sHp, this.L / 2],
|
|
||||||
[0, 1, 0, 0],
|
|
||||||
[-this.sHp, 0, this.cHp, this.W / 2],
|
|
||||||
[0, 0, 0, 1]
|
|
||||||
];
|
|
||||||
|
|
||||||
this.point_rf = [
|
|
||||||
[this.cHp, 0, this.sHp, this.L / 2],
|
|
||||||
[0, 1, 0, 0],
|
|
||||||
[-this.sHp, 0, this.cHp, -this.W / 2],
|
|
||||||
[0, 0, 0, 1]
|
|
||||||
];
|
|
||||||
|
|
||||||
this.point_lb = [
|
|
||||||
[this.cHp, 0, this.sHp, -this.L / 2],
|
|
||||||
[0, 1, 0, 0],
|
|
||||||
[-this.sHp, 0, this.cHp, this.W / 2],
|
|
||||||
[0, 0, 0, 1]
|
|
||||||
];
|
|
||||||
|
|
||||||
this.point_rb = [
|
|
||||||
[this.cHp, 0, this.sHp, -this.L / 2],
|
|
||||||
[0, 1, 0, 0],
|
|
||||||
[-this.sHp, 0, this.cHp, -this.W / 2],
|
|
||||||
[0, 0, 0, 1]
|
|
||||||
];
|
|
||||||
this.Ix = [
|
|
||||||
[-1, 0, 0, 0],
|
|
||||||
[0, 1, 0, 0],
|
|
||||||
[0, 0, 1, 0],
|
|
||||||
[0, 0, 0, 1]
|
|
||||||
];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public calcIK(body_state: body_state_t): number[] {
|
getDefaultFeetPos(): number[][] {
|
||||||
this.bodyIK(body_state);
|
return this.mountOffsets.map((offset, i) => {
|
||||||
|
return [offset[0], -1, offset[2] + (i % 2 === 1 ? -this.coxa : this.coxa)]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
calcIK(p: body_state_t): number[] {
|
||||||
|
const roll = p.omega * this.DEG2RAD
|
||||||
|
const pitch = p.phi * this.DEG2RAD
|
||||||
|
const yaw = p.psi * this.DEG2RAD
|
||||||
|
const rot = this.euler2R(roll, pitch, yaw)
|
||||||
|
const inv_rot = [
|
||||||
|
[rot[0][0], rot[1][0], rot[2][0]],
|
||||||
|
[rot[0][1], rot[1][1], rot[2][1]],
|
||||||
|
[rot[0][2], rot[1][2], rot[2][2]]
|
||||||
|
]
|
||||||
|
const inv_trans = [
|
||||||
|
-inv_rot[0][0] * p.xm - inv_rot[0][1] * p.ym - inv_rot[0][2] * p.zm,
|
||||||
|
-inv_rot[1][0] * p.xm - inv_rot[1][1] * p.ym - inv_rot[1][2] * p.zm,
|
||||||
|
-inv_rot[2][0] * p.xm - inv_rot[2][1] * p.ym - inv_rot[2][2] * p.zm
|
||||||
|
]
|
||||||
|
return p.feet.flatMap((foot, i) => {
|
||||||
|
const [wx, wy, wz] = foot
|
||||||
|
const bx = inv_rot[0][0] * wx + inv_rot[0][1] * wy + inv_rot[0][2] * wz + inv_trans[0]
|
||||||
|
const by = inv_rot[1][0] * wx + inv_rot[1][1] * wy + inv_rot[1][2] * wz + inv_trans[1]
|
||||||
|
const bz = inv_rot[2][0] * wx + inv_rot[2][1] * wy + inv_rot[2][2] * wz + inv_trans[2]
|
||||||
|
|
||||||
|
const [mx, my, mz] = this.mountOffsets[i]
|
||||||
|
const px = bx - mx,
|
||||||
|
py = by - my,
|
||||||
|
pz = bz - mz
|
||||||
|
|
||||||
|
const lx =
|
||||||
|
this.invMountRot[0][0] * px +
|
||||||
|
this.invMountRot[0][1] * py +
|
||||||
|
this.invMountRot[0][2] * pz
|
||||||
|
const ly =
|
||||||
|
this.invMountRot[1][0] * px +
|
||||||
|
this.invMountRot[1][1] * py +
|
||||||
|
this.invMountRot[1][2] * pz
|
||||||
|
const lz =
|
||||||
|
this.invMountRot[2][0] * px +
|
||||||
|
this.invMountRot[2][1] * py +
|
||||||
|
this.invMountRot[2][2] * pz
|
||||||
|
|
||||||
|
const xLocal = i % 2 === 1 ? -lx : lx
|
||||||
|
return this.legIK(xLocal, ly, lz)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
private legIK(x: number, y: number, z: number): [number, number, number] {
|
||||||
|
const F = sqrt(max(0, x * x + y * y - this.coxa * this.coxa))
|
||||||
|
const G = F - this.coxa_offset
|
||||||
|
const H = sqrt(G * G + z * z)
|
||||||
|
const t1 = -atan2(y, x) - atan2(F, -this.coxa)
|
||||||
|
const D =
|
||||||
|
(H * H - this.femur * this.femur - this.tibia * this.tibia) /
|
||||||
|
(2 * this.femur * this.tibia)
|
||||||
|
const t3 = acos(max(-1, min(1, D)))
|
||||||
|
const t2 = atan2(z, G) - atan2(this.tibia * sin(t3), this.femur + this.tibia * cos(t3))
|
||||||
|
return [t1, t2, t3]
|
||||||
|
}
|
||||||
|
|
||||||
|
private euler2R(roll: number, pitch: number, yaw: number): number[][] {
|
||||||
|
const cr = cos(roll),
|
||||||
|
sr = sin(roll)
|
||||||
|
const cp = cos(pitch),
|
||||||
|
sp = sin(pitch)
|
||||||
|
const cy = cos(yaw),
|
||||||
|
sy = sin(yaw)
|
||||||
return [
|
return [
|
||||||
...this.legIK(this.multiplyVector(this.inverse(this.Tlf), body_state.feet[0])),
|
[cp * cy, -cp * sy, sp],
|
||||||
...this.legIK(
|
[sr * sp * cy + sy * cr, -sr * sp * sy + cr * cy, -sr * cp],
|
||||||
this.multiplyVector(
|
[sr * sy - sp * cr * cy, sr * cy + sp * sy * cr, cr * cp]
|
||||||
this.Ix,
|
]
|
||||||
this.multiplyVector(this.inverse(this.Trf), body_state.feet[1])
|
|
||||||
)
|
|
||||||
),
|
|
||||||
...this.legIK(this.multiplyVector(this.inverse(this.Tlb), body_state.feet[2])),
|
|
||||||
...this.legIK(
|
|
||||||
this.multiplyVector(
|
|
||||||
this.Ix,
|
|
||||||
this.multiplyVector(this.inverse(this.Trb), body_state.feet[3])
|
|
||||||
)
|
|
||||||
)
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
bodyIK(p: body_state_t) {
|
|
||||||
const cos_omega = cos(p.omega * this.DEG2RAD);
|
|
||||||
const sin_omega = sin(p.omega * this.DEG2RAD);
|
|
||||||
const cos_phi = cos(p.phi * this.DEG2RAD);
|
|
||||||
const sin_phi = sin(p.phi * this.DEG2RAD);
|
|
||||||
const cos_psi = cos(p.psi * this.DEG2RAD);
|
|
||||||
const sin_psi = sin(p.psi * this.DEG2RAD);
|
|
||||||
|
|
||||||
const Tm: number[][] = [
|
|
||||||
[cos_phi * cos_psi, -sin_psi * cos_phi, sin_phi, p.xm],
|
|
||||||
[
|
|
||||||
sin_omega * sin_phi * cos_psi + sin_psi * cos_omega,
|
|
||||||
-sin_omega * sin_phi * sin_psi + cos_omega * cos_psi,
|
|
||||||
-sin_omega * cos_phi,
|
|
||||||
p.ym
|
|
||||||
],
|
|
||||||
[
|
|
||||||
sin_omega * sin_psi - sin_phi * cos_omega * cos_psi,
|
|
||||||
sin_omega * cos_psi + sin_phi * sin_psi * cos_omega,
|
|
||||||
cos_omega * cos_phi,
|
|
||||||
p.zm
|
|
||||||
],
|
|
||||||
[0, 0, 0, 1]
|
|
||||||
];
|
|
||||||
|
|
||||||
this.Tlf = this.matrixMultiply(Tm, this.point_lf);
|
|
||||||
this.Trf = this.matrixMultiply(Tm, this.point_rf);
|
|
||||||
this.Tlb = this.matrixMultiply(Tm, this.point_lb);
|
|
||||||
this.Trb = this.matrixMultiply(Tm, this.point_rb);
|
|
||||||
}
|
|
||||||
|
|
||||||
public legIK(point: number[]): number[] {
|
|
||||||
const [x, y, z] = point;
|
|
||||||
|
|
||||||
let F = sqrt(x ** 2 + y ** 2 - this.l1 ** 2);
|
|
||||||
if (isNaN(F)) F = this.l1;
|
|
||||||
|
|
||||||
const G = F - this.l2;
|
|
||||||
const H = sqrt(G ** 2 + z ** 2);
|
|
||||||
|
|
||||||
const theta1 = -atan2(y, x) - atan2(F, -this.l1);
|
|
||||||
const D = (H ** 2 - this.l3 ** 2 - this.l4 ** 2) / (2 * this.l3 * this.l4);
|
|
||||||
let theta3 = atan2(sqrt(1 - D ** 2), D);
|
|
||||||
if (isNaN(theta3)) theta3 = 0;
|
|
||||||
|
|
||||||
const theta2 = atan2(z, G) - atan2(this.l4 * sin(theta3), this.l3 + this.l4 * cos(theta3));
|
|
||||||
|
|
||||||
return [theta1, theta2, theta3];
|
|
||||||
}
|
|
||||||
|
|
||||||
matrixMultiply(a: number[][], b: number[][]): number[][] {
|
|
||||||
const result: number[][] = [];
|
|
||||||
|
|
||||||
for (let i = 0; i < a.length; i++) {
|
|
||||||
const row: number[] = [];
|
|
||||||
|
|
||||||
for (let j = 0; j < b[0].length; j++) {
|
|
||||||
let sum = 0;
|
|
||||||
|
|
||||||
for (let k = 0; k < a[i].length; k++) {
|
|
||||||
sum += a[i][k] * b[k][j];
|
|
||||||
}
|
|
||||||
|
|
||||||
row.push(sum);
|
|
||||||
}
|
|
||||||
|
|
||||||
result.push(row);
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
multiplyVector(matrix: number[][], vector: number[]): number[] {
|
|
||||||
const rows = matrix.length;
|
|
||||||
const cols = matrix[0].length;
|
|
||||||
const vectorLength = vector.length;
|
|
||||||
|
|
||||||
if (cols !== vectorLength) {
|
|
||||||
throw new Error('Matrix and vector dimensions do not match for multiplication.');
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = [];
|
|
||||||
|
|
||||||
for (let i = 0; i < rows; i++) {
|
|
||||||
let sum = 0;
|
|
||||||
|
|
||||||
for (let j = 0; j < cols; j++) {
|
|
||||||
sum += matrix[i][j] * vector[j];
|
|
||||||
}
|
|
||||||
|
|
||||||
result.push(sum);
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
private inverse(matrix: number[][]): number[][] {
|
|
||||||
const det = this.determinant(matrix);
|
|
||||||
const adjugate = this.adjugate(matrix);
|
|
||||||
const scalar = 1 / det;
|
|
||||||
const inverse: number[][] = [];
|
|
||||||
|
|
||||||
for (let i = 0; i < matrix.length; i++) {
|
|
||||||
const row: number[] = [];
|
|
||||||
|
|
||||||
for (let j = 0; j < matrix[i].length; j++) {
|
|
||||||
row.push(adjugate[i][j] * scalar);
|
|
||||||
}
|
|
||||||
|
|
||||||
inverse.push(row);
|
|
||||||
}
|
|
||||||
|
|
||||||
return inverse;
|
|
||||||
}
|
|
||||||
|
|
||||||
private determinant(matrix: number[][]): number {
|
|
||||||
if (matrix.length !== matrix[0].length) {
|
|
||||||
throw new Error('The matrix is not square.');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (matrix.length === 2) {
|
|
||||||
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
|
|
||||||
}
|
|
||||||
|
|
||||||
let det = 0;
|
|
||||||
|
|
||||||
for (let i = 0; i < matrix.length; i++) {
|
|
||||||
const sign = i % 2 === 0 ? 1 : -1;
|
|
||||||
const subMatrix: number[][] = [];
|
|
||||||
|
|
||||||
for (let j = 1; j < matrix.length; j++) {
|
|
||||||
const row: number[] = [];
|
|
||||||
|
|
||||||
for (let k = 0; k < matrix.length; k++) {
|
|
||||||
if (k !== i) {
|
|
||||||
row.push(matrix[j][k]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
subMatrix.push(row);
|
|
||||||
}
|
|
||||||
|
|
||||||
det += sign * matrix[0][i] * this.determinant(subMatrix);
|
|
||||||
}
|
|
||||||
|
|
||||||
return det;
|
|
||||||
}
|
|
||||||
|
|
||||||
private adjugate(matrix: number[][]): number[][] {
|
|
||||||
if (matrix.length !== matrix[0].length) {
|
|
||||||
throw new Error('The matrix is not square.');
|
|
||||||
}
|
|
||||||
|
|
||||||
const adjugate: number[][] = [];
|
|
||||||
|
|
||||||
for (let i = 0; i < matrix.length; i++) {
|
|
||||||
const row: number[] = [];
|
|
||||||
|
|
||||||
for (let j = 0; j < matrix[i].length; j++) {
|
|
||||||
const sign = (i + j) % 2 === 0 ? 1 : -1;
|
|
||||||
const subMatrix: number[][] = [];
|
|
||||||
|
|
||||||
for (let k = 0; k < matrix.length; k++) {
|
|
||||||
if (k !== i) {
|
|
||||||
const subRow: number[] = [];
|
|
||||||
|
|
||||||
for (let l = 0; l < matrix.length; l++) {
|
|
||||||
if (l !== j) {
|
|
||||||
subRow.push(matrix[k][l]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
subMatrix.push(subRow);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const cofactor = sign * this.determinant(subMatrix);
|
|
||||||
row.push(cofactor);
|
|
||||||
}
|
|
||||||
|
|
||||||
adjugate.push(row);
|
|
||||||
}
|
|
||||||
|
|
||||||
return this.transpose(adjugate);
|
|
||||||
}
|
|
||||||
|
|
||||||
private transpose(matrix: number[][]): number[][] {
|
|
||||||
const transposed: number[][] = [];
|
|
||||||
|
|
||||||
for (let i = 0; i < matrix.length; i++) {
|
|
||||||
const row: number[] = [];
|
|
||||||
|
|
||||||
for (let j = 0; j < matrix[i].length; j++) {
|
|
||||||
row.push(matrix[j][i]);
|
|
||||||
}
|
|
||||||
|
|
||||||
transposed.push(row);
|
|
||||||
}
|
|
||||||
|
|
||||||
return transposed;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -58,14 +58,14 @@ export default class SceneBuilder {
|
|||||||
public ground!: Mesh
|
public ground!: Mesh
|
||||||
public renderer!: WebGLRenderer
|
public renderer!: WebGLRenderer
|
||||||
public orbit: OrbitControls
|
public orbit: OrbitControls
|
||||||
public callback: Function | undefined
|
public callback: (() => void) | undefined
|
||||||
public gridHelper!: GridHelper
|
public gridHelper!: GridHelper
|
||||||
public model!: URDFRobot
|
public model!: URDFRobot
|
||||||
public liveStreamTexture!: CanvasTexture
|
public liveStreamTexture!: CanvasTexture
|
||||||
private fog!: FogExp2
|
private fog!: FogExp2
|
||||||
private isLoaded: boolean = false
|
private isLoaded: boolean = false
|
||||||
public isDragging: boolean = false
|
public isDragging: boolean = false
|
||||||
highlightMaterial: any
|
highlightMaterial: MeshPhongMaterial
|
||||||
sky!: Sky
|
sky!: Sky
|
||||||
transformControl: TransformControls
|
transformControl: TransformControls
|
||||||
public modelGroup!: Group
|
public modelGroup!: Group
|
||||||
@@ -157,10 +157,11 @@ export default class SceneBuilder {
|
|||||||
|
|
||||||
public addOrbitControls = (minDistance: number, maxDistance: number, autoRotate = true) => {
|
public addOrbitControls = (minDistance: number, maxDistance: number, autoRotate = true) => {
|
||||||
this.orbit = new OrbitControls(this.camera, this.renderer.domElement)
|
this.orbit = new OrbitControls(this.camera, this.renderer.domElement)
|
||||||
this.orbit.minDistance = 5
|
this.orbit.minDistance = minDistance + (maxDistance - minDistance) / 2
|
||||||
this.orbit.maxDistance = maxDistance
|
this.orbit.maxDistance = maxDistance
|
||||||
this.orbit.autoRotate = autoRotate
|
this.orbit.autoRotate = autoRotate
|
||||||
this.orbit.update()
|
this.orbit.update()
|
||||||
|
this.orbit.minDistance = minDistance
|
||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -228,7 +229,7 @@ export default class SceneBuilder {
|
|||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
|
|
||||||
public addRenderCb = (callback: Function) => {
|
public addRenderCb = (callback: () => void) => {
|
||||||
this.callback = callback
|
this.callback = callback
|
||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
@@ -274,7 +275,7 @@ export default class SceneBuilder {
|
|||||||
isJoint = (j: URDFJoint) => j.isURDFJoint && j.jointType !== 'fixed'
|
isJoint = (j: URDFJoint) => j.isURDFJoint && j.jointType !== 'fixed'
|
||||||
|
|
||||||
highlightLinkGeometry = (m: URDFMimicJoint, revert: boolean, material: MeshPhongMaterial) => {
|
highlightLinkGeometry = (m: URDFMimicJoint, revert: boolean, material: MeshPhongMaterial) => {
|
||||||
const traverse = (c: any) => {
|
const traverse = (c: Object3D) => {
|
||||||
if (c.type === 'Mesh') {
|
if (c.type === 'Mesh') {
|
||||||
if (revert) {
|
if (revert) {
|
||||||
c.material = c.__origMaterial
|
c.material = c.__origMaterial
|
||||||
@@ -297,9 +298,9 @@ export default class SceneBuilder {
|
|||||||
traverse(m)
|
traverse(m)
|
||||||
}
|
}
|
||||||
|
|
||||||
public addTransformControls = (model: any) => {
|
public addTransformControls = (model: Object3D) => {
|
||||||
this.transformControl = new TransformControls(this.camera, this.renderer.domElement)
|
this.transformControl = new TransformControls(this.camera, this.renderer.domElement)
|
||||||
this.transformControl.addEventListener('dragging-changed', (event: any) => {
|
this.transformControl.addEventListener('dragging-changed', (event: { value: boolean }) => {
|
||||||
this.orbit.enabled = !event.value
|
this.orbit.enabled = !event.value
|
||||||
this.isDragging = !event.value
|
this.isDragging = !event.value
|
||||||
})
|
})
|
||||||
@@ -309,7 +310,7 @@ export default class SceneBuilder {
|
|||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
|
|
||||||
public addModel = (model: any) => {
|
public addModel = (model: URDFRobot) => {
|
||||||
this.modelGroup = new Group()
|
this.modelGroup = new Group()
|
||||||
this.modelGroup.add(model)
|
this.modelGroup.add(model)
|
||||||
this.model = model
|
this.model = model
|
||||||
@@ -317,7 +318,7 @@ export default class SceneBuilder {
|
|||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
|
|
||||||
public addDragControl = (updateAngle: any) => {
|
public addDragControl = (updateAngle: (angles: Record<string, number>) => void) => {
|
||||||
const highlightColor = '#FFFFFF'
|
const highlightColor = '#FFFFFF'
|
||||||
const highlightMaterial = new MeshPhongMaterial({
|
const highlightMaterial = new MeshPhongMaterial({
|
||||||
shininess: 10,
|
shininess: 10,
|
||||||
|
|||||||
@@ -1,54 +1,53 @@
|
|||||||
import { Result } from '$lib/utilities/result';
|
import { Result } from '$lib/utilities/result'
|
||||||
import { browser } from '$app/environment';
|
import { browser } from '$app/environment'
|
||||||
|
|
||||||
class FileService {
|
class FileService {
|
||||||
private dbPromise: Promise<Result<IDBDatabase, string>> | null = browser
|
private dbPromise: Promise<Result<IDBDatabase, string>> | null =
|
||||||
? this.openDatabase()
|
browser ? this.openDatabase() : null
|
||||||
: null;
|
|
||||||
|
|
||||||
private async openDatabase(): Promise<Result<IDBDatabase, string>> {
|
private async openDatabase(): Promise<Result<IDBDatabase, string>> {
|
||||||
return new Promise((resolve) => {
|
return new Promise(resolve => {
|
||||||
const request = indexedDB.open('fileStorageDB', 1);
|
const request = indexedDB.open('fileStorageDB', 1)
|
||||||
|
|
||||||
request.onupgradeneeded = () => {
|
request.onupgradeneeded = () => {
|
||||||
request.result.createObjectStore('files');
|
request.result.createObjectStore('files')
|
||||||
};
|
}
|
||||||
request.onsuccess = () => resolve(Result.ok(request.result));
|
request.onsuccess = () => resolve(Result.ok(request.result))
|
||||||
request.onerror = () => resolve(Result.err('Error opening database'));
|
request.onerror = () => resolve(Result.err('Error opening database'))
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
private async getStore(mode: IDBTransactionMode): Promise<Result<IDBObjectStore, string>> {
|
private async getStore(mode: IDBTransactionMode): Promise<Result<IDBObjectStore, string>> {
|
||||||
if (!browser || !this.dbPromise)
|
if (!browser || !this.dbPromise)
|
||||||
return Result.err('Not running in browser or DB not initialized');
|
return Result.err('Not running in browser or DB not initialized')
|
||||||
const dbResult = await this.dbPromise;
|
const dbResult = await this.dbPromise
|
||||||
if (dbResult.isErr()) return Result.err('Database not initialized');
|
if (dbResult.isErr()) return Result.err('Database not initialized')
|
||||||
const store = dbResult.inner.transaction('files', mode).objectStore('files');
|
const store = dbResult.inner.transaction('files', mode).objectStore('files')
|
||||||
return Result.ok(store);
|
return Result.ok(store)
|
||||||
}
|
}
|
||||||
|
|
||||||
public async saveFile(key: string, file: Uint8Array): Promise<Result<IDBValidKey, string>> {
|
public async saveFile(key: string, file: Uint8Array): Promise<Result<IDBValidKey, string>> {
|
||||||
const storeResult = await this.getStore('readwrite');
|
const storeResult = await this.getStore('readwrite')
|
||||||
if (storeResult.isErr()) return Result.err('Failed to access store');
|
if (storeResult.isErr()) return Result.err('Failed to access store')
|
||||||
|
|
||||||
return new Promise((resolve) => {
|
return new Promise(resolve => {
|
||||||
const request = storeResult.inner.put(file, key);
|
const request = storeResult.inner.put(file, key)
|
||||||
request.onsuccess = () => resolve(Result.ok(request.result));
|
request.onsuccess = () => resolve(Result.ok(request.result))
|
||||||
request.onerror = () => resolve(Result.err('Failed to save file'));
|
request.onerror = () => resolve(Result.err('Failed to save file'))
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
public async getFile(key: string): Promise<Result<Uint8Array | undefined, string>> {
|
public async getFile(key: string): Promise<Result<Uint8Array | undefined, string>> {
|
||||||
const storeResult = await this.getStore('readonly');
|
const storeResult = await this.getStore('readonly')
|
||||||
if (storeResult.isErr()) return Result.err('Failed to access store');
|
if (storeResult.isErr()) return Result.err('Failed to access store')
|
||||||
|
|
||||||
return new Promise((resolve) => {
|
return new Promise(resolve => {
|
||||||
const request = storeResult.inner.get(key);
|
const request = storeResult.inner.get(key)
|
||||||
request.onsuccess = () =>
|
request.onsuccess = () =>
|
||||||
resolve(request.result ? Result.ok(request.result) : Result.err('File not found'));
|
resolve(request.result ? Result.ok(request.result) : Result.err('File not found'))
|
||||||
request.onerror = () => resolve(Result.err('Failed to retrieve file'));
|
request.onerror = () => resolve(Result.err('Failed to retrieve file'))
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default browser ? new FileService() : null;
|
export default browser ? new FileService() : null
|
||||||
|
|||||||
@@ -1,2 +1,2 @@
|
|||||||
export { default as fileService } from './file-service';
|
export { default as fileService } from './file-service'
|
||||||
export { default as resultService } from './result-service';
|
export { default as resultService } from './result-service'
|
||||||
|
|||||||
@@ -1,19 +1,19 @@
|
|||||||
import { errorLogs, latestErrorLog } from '$lib/stores';
|
import { errorLogs, latestErrorLog } from '$lib/stores'
|
||||||
import type { Result } from '$lib/utilities';
|
import type { Result } from '$lib/utilities'
|
||||||
|
|
||||||
class ResultService {
|
class ResultService {
|
||||||
public handleResult(result: Result<unknown, string>, tag?: string) {
|
public handleResult(result: Result<unknown, string>, tag?: string) {
|
||||||
if (result.isErr()) {
|
if (result.isErr()) {
|
||||||
const errorLogEntry = { tag, message: result.inner, exception: result.exception };
|
const errorLogEntry = { tag, message: result.inner, exception: result.exception }
|
||||||
latestErrorLog.set(errorLogEntry);
|
latestErrorLog.set(errorLogEntry)
|
||||||
errorLogs.update((entries) => {
|
errorLogs.update(entries => {
|
||||||
entries.push(errorLogEntry);
|
entries.push(errorLogEntry)
|
||||||
return entries;
|
return entries
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
return result
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default new ResultService();
|
export default new ResultService()
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { type Analytics } from '$lib/types/models';
|
import { type Analytics } from '$lib/types/models'
|
||||||
import { writable } from 'svelte/store';
|
import { writable } from 'svelte/store'
|
||||||
|
|
||||||
let analytics_data = {
|
const analytics_data = {
|
||||||
uptime: <number[]>[],
|
uptime: <number[]>[],
|
||||||
free_heap: <number[]>[],
|
free_heap: <number[]>[],
|
||||||
total_heap: <number[]>[],
|
total_heap: <number[]>[],
|
||||||
@@ -14,20 +14,22 @@ let analytics_data = {
|
|||||||
cpu0_usage: <number[]>[],
|
cpu0_usage: <number[]>[],
|
||||||
cpu1_usage: <number[]>[],
|
cpu1_usage: <number[]>[],
|
||||||
cpu_usage: <number[]>[]
|
cpu_usage: <number[]>[]
|
||||||
};
|
}
|
||||||
|
|
||||||
const maxAnalyticsData = 100;
|
const maxAnalyticsData = 100
|
||||||
|
|
||||||
function createAnalytics() {
|
function createAnalytics() {
|
||||||
const { subscribe, update } = writable(analytics_data);
|
const { subscribe, update } = writable(analytics_data)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
subscribe,
|
subscribe,
|
||||||
addData: (content: Analytics) => {
|
addData: (content: Analytics) => {
|
||||||
update((analytics_data) => ({
|
update(analytics_data => ({
|
||||||
...analytics_data,
|
...analytics_data,
|
||||||
uptime: [...analytics_data.uptime, content.uptime].slice(-maxAnalyticsData),
|
uptime: [...analytics_data.uptime, content.uptime].slice(-maxAnalyticsData),
|
||||||
free_heap: [...analytics_data.free_heap, content.free_heap / 1000].slice(-maxAnalyticsData),
|
free_heap: [...analytics_data.free_heap, content.free_heap / 1000].slice(
|
||||||
|
-maxAnalyticsData
|
||||||
|
),
|
||||||
total_heap: [...analytics_data.total_heap, content.total_heap / 1000].slice(
|
total_heap: [...analytics_data.total_heap, content.total_heap / 1000].slice(
|
||||||
-maxAnalyticsData
|
-maxAnalyticsData
|
||||||
),
|
),
|
||||||
@@ -35,21 +37,33 @@ function createAnalytics() {
|
|||||||
...analytics_data.used_heap,
|
...analytics_data.used_heap,
|
||||||
(content.total_heap - content.free_heap) / 1000
|
(content.total_heap - content.free_heap) / 1000
|
||||||
].slice(-maxAnalyticsData),
|
].slice(-maxAnalyticsData),
|
||||||
min_free_heap: [...analytics_data.min_free_heap, content.min_free_heap / 1000].slice(
|
min_free_heap: [
|
||||||
|
...analytics_data.min_free_heap,
|
||||||
|
content.min_free_heap / 1000
|
||||||
|
].slice(-maxAnalyticsData),
|
||||||
|
max_alloc_heap: [
|
||||||
|
...analytics_data.max_alloc_heap,
|
||||||
|
content.max_alloc_heap / 1000
|
||||||
|
].slice(-maxAnalyticsData),
|
||||||
|
fs_used: [...analytics_data.fs_used, content.fs_used / 1000].slice(
|
||||||
-maxAnalyticsData
|
-maxAnalyticsData
|
||||||
),
|
),
|
||||||
max_alloc_heap: [...analytics_data.max_alloc_heap, content.max_alloc_heap / 1000].slice(
|
fs_total: [...analytics_data.fs_total, content.fs_total / 1000].slice(
|
||||||
|
-maxAnalyticsData
|
||||||
|
),
|
||||||
|
core_temp: [...analytics_data.core_temp, content.core_temp].slice(
|
||||||
|
-maxAnalyticsData
|
||||||
|
),
|
||||||
|
cpu0_usage: [...analytics_data.cpu0_usage, content.cpu0_usage].slice(
|
||||||
|
-maxAnalyticsData
|
||||||
|
),
|
||||||
|
cpu1_usage: [...analytics_data.cpu1_usage, content.cpu1_usage].slice(
|
||||||
-maxAnalyticsData
|
-maxAnalyticsData
|
||||||
),
|
),
|
||||||
fs_used: [...analytics_data.fs_used, content.fs_used / 1000].slice(-maxAnalyticsData),
|
|
||||||
fs_total: [...analytics_data.fs_total, content.fs_total / 1000].slice(-maxAnalyticsData),
|
|
||||||
core_temp: [...analytics_data.core_temp, content.core_temp].slice(-maxAnalyticsData),
|
|
||||||
cpu0_usage: [...analytics_data.cpu0_usage, content.cpu0_usage].slice(-maxAnalyticsData),
|
|
||||||
cpu1_usage: [...analytics_data.cpu1_usage, content.cpu1_usage].slice(-maxAnalyticsData),
|
|
||||||
cpu_usage: [...analytics_data.cpu_usage, content.cpu_usage].slice(-maxAnalyticsData)
|
cpu_usage: [...analytics_data.cpu_usage, content.cpu_usage].slice(-maxAnalyticsData)
|
||||||
}));
|
}))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const analytics = createAnalytics();
|
export const analytics = createAnalytics()
|
||||||
|
|||||||
@@ -1,47 +1,39 @@
|
|||||||
import { persistentStore } from '$lib/utilities';
|
import { persistentStore } from '$lib/utilities'
|
||||||
import { get, type Writable } from 'svelte/store';
|
import { get, type Writable } from 'svelte/store'
|
||||||
|
|
||||||
import Visualization from '$lib/components/Visualization.svelte';
|
import Visualization from '$lib/components/Visualization.svelte'
|
||||||
import Stream from '$lib/components/Stream.svelte';
|
import Stream from '$lib/components/Stream.svelte'
|
||||||
import ChartWidget from '$lib/components/widget/ChartWidget.svelte';
|
import ChartWidget from '$lib/components/widget/ChartWidget.svelte'
|
||||||
|
|
||||||
export interface WidgetConfig {
|
export interface WidgetConfig {
|
||||||
id: string | number;
|
id: string | number
|
||||||
component: keyof typeof WidgetComponents;
|
component: keyof typeof WidgetComponents
|
||||||
props?: Record<string, any>;
|
props?: Record<string, unknown>
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface WidgetContainerConfig {
|
export interface WidgetContainerConfig {
|
||||||
id: string | number;
|
id: string | number
|
||||||
layout?: 'row' | 'column' | 'wrap';
|
layout?: 'row' | 'column' | 'wrap'
|
||||||
header?: string;
|
header?: string
|
||||||
widgets: Array<WidgetConfig | WidgetContainerConfig>;
|
widgets: Array<WidgetConfig | WidgetContainerConfig>
|
||||||
}
|
}
|
||||||
|
|
||||||
export const isWidgetConfig = (
|
export const isWidgetConfig = (
|
||||||
widget: WidgetConfig | WidgetContainerConfig
|
widget: WidgetConfig | WidgetContainerConfig
|
||||||
): widget is WidgetConfig => 'component' in widget;
|
): widget is WidgetConfig => 'component' in widget
|
||||||
|
|
||||||
export const WidgetComponents = {
|
export const WidgetComponents = {
|
||||||
Visualization,
|
Visualization,
|
||||||
Stream,
|
Stream,
|
||||||
ChartWidget
|
ChartWidget
|
||||||
};
|
}
|
||||||
|
|
||||||
interface View {
|
interface View {
|
||||||
name: string;
|
name: string
|
||||||
content: WidgetContainerConfig;
|
content: WidgetContainerConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
const defaultViews: View[] = [
|
const defaultViews: View[] = [
|
||||||
{
|
|
||||||
name: 'Stream',
|
|
||||||
content: {
|
|
||||||
id: 'root',
|
|
||||||
layout: 'column',
|
|
||||||
widgets: [{ id: 2, component: 'Stream' }]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
name: '3D representation',
|
name: '3D representation',
|
||||||
content: {
|
content: {
|
||||||
@@ -50,6 +42,14 @@ const defaultViews: View[] = [
|
|||||||
widgets: [{ id: 2, component: 'Visualization', props: { debug: true } }]
|
widgets: [{ id: 2, component: 'Visualization', props: { debug: true } }]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: 'Stream',
|
||||||
|
content: {
|
||||||
|
id: 'root',
|
||||||
|
layout: 'column',
|
||||||
|
widgets: [{ id: 2, component: 'Stream' }]
|
||||||
|
}
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: 'Split screen',
|
name: 'Split screen',
|
||||||
content: {
|
content: {
|
||||||
@@ -60,8 +60,8 @@ const defaultViews: View[] = [
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
];
|
]
|
||||||
|
|
||||||
export const views: Writable<View[]> = persistentStore('views', defaultViews);
|
export const views: Writable<View[]> = persistentStore('views', defaultViews)
|
||||||
|
|
||||||
export const selectedView = persistentStore('selected_view', get(views)[0].name);
|
export const selectedView = persistentStore('selected_view', get(views)[0].name)
|
||||||
|
|||||||
@@ -1,20 +1,64 @@
|
|||||||
import { api } from '$lib/api';
|
import { api } from '$lib/api'
|
||||||
import { notifications } from '$lib/components/toasts/notifications';
|
import { notifications } from '$lib/components/toasts/notifications'
|
||||||
import { writable, type Writable } from 'svelte/store';
|
import Kinematic from '$lib/kinematic'
|
||||||
|
import { persistentStore } from '$lib/utilities'
|
||||||
|
import { derived, type Writable } from 'svelte/store'
|
||||||
|
import { resolve } from '$app/paths'
|
||||||
|
|
||||||
let featureFlagsStore: Writable<Record<string, boolean>>;
|
let featureFlagsStore: Writable<Record<string, boolean | string>>
|
||||||
|
|
||||||
export function useFeatureFlags() {
|
export function useFeatureFlags() {
|
||||||
if (!featureFlagsStore) {
|
if (!featureFlagsStore) {
|
||||||
featureFlagsStore = writable<Record<string, boolean>>({});
|
featureFlagsStore = persistentStore<Record<string, boolean | string>>('FeatureFlags', {})
|
||||||
|
|
||||||
api.get<Record<string, boolean>>('/api/features').then((result) => {
|
api.get<Record<string, boolean>>('/api/features').then(result => {
|
||||||
if (result.isOk()) featureFlagsStore.set(result.inner);
|
if (result.isOk()) featureFlagsStore.set(result.inner)
|
||||||
else {
|
else {
|
||||||
notifications.error('Feature flag could not be fetched', 2500);
|
notifications.error('Feature flag could not be fetched', 2500)
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
return featureFlagsStore;
|
return featureFlagsStore
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const base = resolve('/')
|
||||||
|
|
||||||
|
export const variants = {
|
||||||
|
SPOTMICRO_ESP32: {
|
||||||
|
model: `${base}spot_micro.urdf.xacro`,
|
||||||
|
stl: `${base}stl.zip`,
|
||||||
|
kinematics: {
|
||||||
|
coxa: 60.5 / 100,
|
||||||
|
coxa_offset: 10 / 100,
|
||||||
|
femur: 111.7 / 100,
|
||||||
|
tibia: 118.5 / 100,
|
||||||
|
L: 207.5 / 100,
|
||||||
|
W: 78 / 100
|
||||||
|
}
|
||||||
|
},
|
||||||
|
SPOTMICRO_YERTLE: {
|
||||||
|
model: `${base}yertle.URDF`,
|
||||||
|
stl: `${base}URDF.zip`,
|
||||||
|
kinematics: {
|
||||||
|
coxa: 35 / 100,
|
||||||
|
coxa_offset: 0 / 100,
|
||||||
|
femur: 130 / 100,
|
||||||
|
tibia: 130 / 100,
|
||||||
|
L: 240 / 100,
|
||||||
|
W: 78 / 100
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const currentVariant = derived(useFeatureFlags(), $flagStore => {
|
||||||
|
const variantFlag = $flagStore['variant'] as string
|
||||||
|
return variantFlag && variants[variantFlag as keyof typeof variants] ?
|
||||||
|
variants[variantFlag as keyof typeof variants]
|
||||||
|
: variants.SPOTMICRO_ESP32
|
||||||
|
})
|
||||||
|
|
||||||
|
export const currentKinematic = derived(
|
||||||
|
currentVariant,
|
||||||
|
$variant => new Kinematic($variant.kinematics)
|
||||||
|
)
|
||||||
|
|||||||
@@ -1,24 +1,24 @@
|
|||||||
import { writable } from 'svelte/store';
|
import { writable } from 'svelte/store'
|
||||||
|
|
||||||
export const isFullscreen = writable(false);
|
export const isFullscreen = writable(false)
|
||||||
|
|
||||||
export function toggleFullscreen() {
|
export function toggleFullscreen() {
|
||||||
isFullscreen.update((state) => {
|
isFullscreen.update(state => {
|
||||||
!state ? document.documentElement.requestFullscreen() : document.exitFullscreen();
|
!state ? document.documentElement.requestFullscreen() : document.exitFullscreen()
|
||||||
return !state;
|
return !state
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
export function enterFullscreen() {
|
export function enterFullscreen() {
|
||||||
if (!document.fullscreenElement) {
|
if (!document.fullscreenElement) {
|
||||||
document.documentElement.requestFullscreen();
|
document.documentElement.requestFullscreen()
|
||||||
isFullscreen.set(true);
|
isFullscreen.set(true)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function exitFullscreen() {
|
export function exitFullscreen() {
|
||||||
if (document.fullscreenElement) {
|
if (document.fullscreenElement) {
|
||||||
document.exitFullscreen();
|
document.exitFullscreen()
|
||||||
isFullscreen.set(false);
|
isFullscreen.set(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import { readable, derived } from 'svelte/store'
|
||||||
|
|
||||||
|
export type GamepadState = {
|
||||||
|
available: boolean
|
||||||
|
gamepads: Gamepad[]
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEADZONE = 0.15
|
||||||
|
const dz = (x: number) => {
|
||||||
|
const a = Math.abs(x)
|
||||||
|
if (a < DEADZONE) return 0
|
||||||
|
return ((a - DEADZONE) / (1 - DEADZONE)) * Math.sign(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
let raf = 0
|
||||||
|
let running = false
|
||||||
|
|
||||||
|
export const gamepads = readable<GamepadState>({ available: false, gamepads: [] }, set => {
|
||||||
|
const update = () => {
|
||||||
|
const pads = navigator.getGamepads?.() ?? []
|
||||||
|
const list = Array.from(pads)
|
||||||
|
.map(p => p || null)
|
||||||
|
.filter(Boolean) as Gamepad[]
|
||||||
|
set({ available: 'getGamepads' in navigator, gamepads: list })
|
||||||
|
raf = requestAnimationFrame(update)
|
||||||
|
}
|
||||||
|
|
||||||
|
const onConnect = () => update()
|
||||||
|
const onDisconnect = () => update()
|
||||||
|
const onVis = () => {
|
||||||
|
if (document.hidden) {
|
||||||
|
running = false
|
||||||
|
cancelAnimationFrame(raf)
|
||||||
|
} else if (!running) {
|
||||||
|
running = true
|
||||||
|
raf = requestAnimationFrame(update)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener('gamepadconnected', onConnect)
|
||||||
|
window.addEventListener('gamepaddisconnected', onDisconnect)
|
||||||
|
document.addEventListener('visibilitychange', onVis)
|
||||||
|
|
||||||
|
running = true
|
||||||
|
raf = requestAnimationFrame(update)
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
running = false
|
||||||
|
cancelAnimationFrame(raf)
|
||||||
|
window.removeEventListener('gamepadconnected', onConnect)
|
||||||
|
window.removeEventListener('gamepaddisconnected', onDisconnect)
|
||||||
|
document.removeEventListener('visibilitychange', onVis)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
export const gamepad = derived(gamepads, s =>
|
||||||
|
s.available && s.gamepads.length ? s.gamepads[0] : null
|
||||||
|
)
|
||||||
|
|
||||||
|
export const hasGamepad = derived(gamepads, s => s.available && s.gamepads.length > 0)
|
||||||
|
|
||||||
|
export const gamepadAxes = derived(gamepad, g => (g ? g.axes.map(dz) : [0, 0, 0, 0]))
|
||||||
|
|
||||||
|
type ButtonEdge = { pressed: boolean; value: number; justPressed: boolean; justReleased: boolean }
|
||||||
|
const prev = new Map<number, { pressed: boolean; value: number }[]>()
|
||||||
|
|
||||||
|
export const gamepadButtons = derived(gamepad, g => g?.buttons ?? [])
|
||||||
|
|
||||||
|
export const gamepadButtonsEdges = derived(gamepad, g => {
|
||||||
|
if (!g) return [] as ButtonEdge[]
|
||||||
|
const p = prev.get(g.index) || []
|
||||||
|
const out = g.buttons.map((b, i): ButtonEdge => {
|
||||||
|
const pr = p[i] || { pressed: false, value: 0 }
|
||||||
|
const pressed = !!b.pressed || b.value > 0.5
|
||||||
|
return {
|
||||||
|
pressed,
|
||||||
|
value: b.value,
|
||||||
|
justPressed: pressed && !pr.pressed,
|
||||||
|
justReleased: !pressed && pr.pressed
|
||||||
|
}
|
||||||
|
})
|
||||||
|
prev.set(
|
||||||
|
g.index,
|
||||||
|
out.map(x => ({ pressed: x.pressed, value: x.value }))
|
||||||
|
)
|
||||||
|
return out
|
||||||
|
})
|
||||||
+12
-12
@@ -1,7 +1,7 @@
|
|||||||
import { writable } from 'svelte/store';
|
import { writable } from 'svelte/store'
|
||||||
import type { IMU } from '$lib/types/models';
|
import type { IMU } from '$lib/types/models'
|
||||||
|
|
||||||
const maxIMUData = 100;
|
const maxIMUData = 100
|
||||||
|
|
||||||
export const imu = (() => {
|
export const imu = (() => {
|
||||||
const { subscribe, update } = writable({
|
const { subscribe, update } = writable({
|
||||||
@@ -12,16 +12,16 @@ export const imu = (() => {
|
|||||||
altitude: [] as number[],
|
altitude: [] as number[],
|
||||||
pressure: [] as number[],
|
pressure: [] as number[],
|
||||||
bmp_temp: [] as number[]
|
bmp_temp: [] as number[]
|
||||||
});
|
})
|
||||||
|
|
||||||
const addData = (content: IMU) => {
|
const addData = (content: IMU) => {
|
||||||
update(data => {
|
update(data => {
|
||||||
(Object.keys(content) as (keyof IMU)[]).forEach(key => {
|
;(Object.keys(content) as (keyof IMU)[]).forEach(key => {
|
||||||
data[key] = [...data[key], content[key]].slice(-maxIMUData);
|
data[key] = [...data[key], content[key]].slice(-maxIMUData)
|
||||||
});
|
})
|
||||||
return data;
|
return data
|
||||||
});
|
})
|
||||||
};
|
}
|
||||||
|
|
||||||
return { subscribe, addData };
|
return { subscribe, addData }
|
||||||
})();
|
})()
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
export * from './socket-store';
|
export * from './socket-store'
|
||||||
export * from './logging-store';
|
export * from './logging-store'
|
||||||
export * from './model-store';
|
export * from './model-store'
|
||||||
export * from './socket';
|
export * from './socket'
|
||||||
export * from './fullscreen';
|
export * from './fullscreen'
|
||||||
export * from './telemetry';
|
export * from './telemetry'
|
||||||
export * from './analytics';
|
export * from './analytics'
|
||||||
export * from './featureFlags';
|
export * from './featureFlags'
|
||||||
export * from './location-store';
|
export * from './location-store'
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { persistentStore } from '$lib/utilities';
|
import { persistentStore } from '$lib/utilities'
|
||||||
import { writable } from 'svelte/store';
|
import { writable } from 'svelte/store'
|
||||||
import appEnv from 'app-env';
|
import { PUBLIC_VITE_USE_HOST_NAME } from '$env/static/public'
|
||||||
|
|
||||||
export const location = appEnv.VITE_USE_HOST_NAME ? writable('') : persistentStore('location', '');
|
export const apiLocation =
|
||||||
|
PUBLIC_VITE_USE_HOST_NAME ? writable('') : persistentStore('location', '')
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
import { writable, type Writable } from 'svelte/store';
|
import { writable, type Writable } from 'svelte/store'
|
||||||
|
|
||||||
export interface errorLog {
|
export interface errorLog {
|
||||||
message: unknown;
|
message: unknown
|
||||||
tag?: string;
|
tag?: string
|
||||||
exception?: unknown;
|
exception?: unknown
|
||||||
}
|
}
|
||||||
|
|
||||||
export const latestErrorLog: Writable<errorLog> = writable();
|
export const latestErrorLog: Writable<errorLog> = writable()
|
||||||
|
|
||||||
export const errorLogs: Writable<errorLog[]> = writable([]);
|
export const errorLogs: Writable<errorLog[]> = writable([])
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
import type { ControllerInput } from '$lib/types/models';
|
import type { ControllerInput } from '$lib/types/models'
|
||||||
import { persistentStore } from '$lib/utilities/svelte-utilities';
|
import { persistentStore } from '$lib/utilities/svelte-utilities'
|
||||||
import { writable, type Writable } from 'svelte/store';
|
import { writable, type Writable } from 'svelte/store'
|
||||||
|
|
||||||
export const emulateModel = writable(true);
|
export const emulateModel = writable(true)
|
||||||
|
|
||||||
export const jointNames = persistentStore('joint_names', <string[]>[]);
|
export const jointNames = persistentStore('joint_names', <string[]>[])
|
||||||
|
|
||||||
export const model = writable();
|
export const model = writable()
|
||||||
|
|
||||||
export const modes = [
|
export const modes = [
|
||||||
'deactivated',
|
'deactivated',
|
||||||
@@ -14,32 +14,50 @@ export const modes = [
|
|||||||
'calibration',
|
'calibration',
|
||||||
'rest',
|
'rest',
|
||||||
'stand',
|
'stand',
|
||||||
'crawl',
|
'walk',
|
||||||
'walk'
|
'animate'
|
||||||
] as const;
|
] as const
|
||||||
|
|
||||||
export type Modes = (typeof modes)[number];
|
export type Modes = (typeof modes)[number]
|
||||||
|
|
||||||
export enum ModesEnum {
|
export enum ModesEnum {
|
||||||
Deactivated,
|
Deactivated = 0,
|
||||||
Idle,
|
Idle = 1,
|
||||||
Calibration,
|
Calibration = 2,
|
||||||
Rest,
|
Rest = 3,
|
||||||
Stand,
|
Stand = 4,
|
||||||
Crawl,
|
Walk = 5,
|
||||||
Walk
|
Animate = 6
|
||||||
}
|
}
|
||||||
|
|
||||||
export const mode: Writable<ModesEnum> = writable(ModesEnum.Deactivated);
|
export enum WalkGaits {
|
||||||
|
Trot = 0,
|
||||||
|
Crawl = 1
|
||||||
|
}
|
||||||
|
|
||||||
export const outControllerData = writable([0, 0, 0, 0, 0, 1, 0]);
|
export const walkGaits = ['trot', 'crawl'] as const
|
||||||
|
|
||||||
export const kinematicData = writable([0, 0, 0, 0, 1, 0]);
|
export const walkGaitLabels: Record<WalkGaits, string> = {
|
||||||
|
[WalkGaits.Trot]: 'Trot',
|
||||||
|
[WalkGaits.Crawl]: 'Crawl'
|
||||||
|
}
|
||||||
|
|
||||||
|
export const walkGaitToMode = (gait: WalkGaits): 'trot' | 'crawl' => {
|
||||||
|
return gait === WalkGaits.Trot ? 'trot' : 'crawl'
|
||||||
|
}
|
||||||
|
|
||||||
|
export const mode: Writable<ModesEnum> = writable(ModesEnum.Deactivated)
|
||||||
|
|
||||||
|
export const walkGait: Writable<WalkGaits> = writable(WalkGaits.Trot)
|
||||||
|
|
||||||
|
export const outControllerData = writable([0, 0, 0, 0, 0, 1, 0])
|
||||||
|
|
||||||
|
export const kinematicData = writable([0, 0, 0, 0, 1, 0])
|
||||||
|
|
||||||
export const input: Writable<ControllerInput> = writable({
|
export const input: Writable<ControllerInput> = writable({
|
||||||
left: { x: 0, y: 0 },
|
left: { x: 0, y: 0 },
|
||||||
right: { x: 0, y: 0 },
|
right: { x: 0, y: 0 },
|
||||||
height: 50,
|
height: 0.5,
|
||||||
speed: 50,
|
speed: 0.5,
|
||||||
s1: 50
|
s1: 0.05
|
||||||
});
|
})
|
||||||
|
|||||||
@@ -1,27 +0,0 @@
|
|||||||
import { readable } from 'svelte/store';
|
|
||||||
|
|
||||||
export const heading = readable(0, (set) => {
|
|
||||||
const updateHeading = (e: any) => {
|
|
||||||
let alpha;
|
|
||||||
if (e.webkitCompassHeading) alpha = e.webkitCompassHeading;
|
|
||||||
else if (e.alpha) alpha = e.alpha;
|
|
||||||
else {
|
|
||||||
let q = e.target.quaternion;
|
|
||||||
alpha =
|
|
||||||
Math.atan2(2 * q[0] * q[1] + 2 * q[2] * q[3], 1 - 2 * q[1] * q[1] - 2 * q[2] * q[2]) *
|
|
||||||
(180 / Math.PI);
|
|
||||||
if (alpha < 0) alpha += 360;
|
|
||||||
}
|
|
||||||
set(alpha);
|
|
||||||
};
|
|
||||||
if ('AbsoluteOrientationSensor' in window) {
|
|
||||||
var sensor = new window.AbsoluteOrientationSensor({ frequency: 60 }) as any;
|
|
||||||
sensor.addEventListener('reading', updateHeading);
|
|
||||||
sensor.start();
|
|
||||||
} else if (window.DeviceMotionEvent) window.addEventListener('deviceorientation', updateHeading);
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
if ('AbsoluteOrientationSensor' in window) sensor.removeEventListener('reading', updateHeading);
|
|
||||||
window.addEventListener('deviceorientation', updateHeading);
|
|
||||||
};
|
|
||||||
});
|
|
||||||
@@ -1,22 +1,22 @@
|
|||||||
import { writable, type Writable } from 'svelte/store';
|
import { writable, type Writable } from 'svelte/store'
|
||||||
import { type angles } from '$lib/types/models';
|
import { type angles } from '$lib/types/models'
|
||||||
|
|
||||||
export const servoAnglesOut: Writable<number[]> = writable([
|
export const servoAnglesOut: Writable<number[]> = writable([
|
||||||
0, 45, -90, 0, 45, -90, 0, 45, -90, 0, 45, -90
|
0, 45, -90, 0, 45, -90, 0, 45, -90, 0, 45, -90
|
||||||
]);
|
])
|
||||||
export const servoAngles: Writable<number[]> = writable([
|
export const servoAngles: Writable<number[]> = writable([
|
||||||
0, 45, -90, 0, 45, -90, 0, 45, -90, 0, 45, -90
|
0, 45, -90, 0, 45, -90, 0, 45, -90, 0, 45, -90
|
||||||
]);
|
])
|
||||||
export const logs = writable([] as string[]);
|
export const logs = writable([] as string[])
|
||||||
export const mpu = writable({ heading: 0 });
|
export const mpu = writable({ heading: 0 })
|
||||||
export const sonar = writable([0, 0]);
|
export const sonar = writable([0, 0])
|
||||||
export const distances = writable({});
|
export const distances = writable({})
|
||||||
|
|
||||||
export interface socketDataCollection {
|
export interface socketDataCollection {
|
||||||
angles: Writable<angles>;
|
angles: Writable<angles>
|
||||||
logs: Writable<string[]>;
|
logs: Writable<string[]>
|
||||||
mpu: Writable<unknown>;
|
mpu: Writable<unknown>
|
||||||
distances: Writable<unknown>;
|
distances: Writable<unknown>
|
||||||
}
|
}
|
||||||
|
|
||||||
export const socketData = {
|
export const socketData = {
|
||||||
@@ -24,4 +24,4 @@ export const socketData = {
|
|||||||
logs,
|
logs,
|
||||||
mpu,
|
mpu,
|
||||||
distances
|
distances
|
||||||
};
|
}
|
||||||
|
|||||||
+110
-72
@@ -1,97 +1,135 @@
|
|||||||
import { writable } from 'svelte/store';
|
import { writable } from 'svelte/store'
|
||||||
|
import { encode, decode } from '@msgpack/msgpack'
|
||||||
|
|
||||||
const socketEvents = ['open', 'close', 'error', 'message', 'unresponsive'] as const;
|
const socketEvents = ['open', 'close', 'error', 'message', 'unresponsive'] as const
|
||||||
type SocketEvent = (typeof socketEvents)[number];
|
type SocketEvent = (typeof socketEvents)[number]
|
||||||
|
|
||||||
|
type SocketMessage = [number, string?, unknown?]
|
||||||
|
|
||||||
|
let useBinary = false
|
||||||
|
|
||||||
|
const decodeMessage = (data: string | ArrayBuffer): SocketMessage | null => {
|
||||||
|
useBinary = data instanceof ArrayBuffer
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (useBinary) {
|
||||||
|
return decode(new Uint8Array(data as ArrayBuffer)) as SocketMessage
|
||||||
|
}
|
||||||
|
return JSON.parse(data as string)
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Could not decode data: ${new Uint8Array(data as ArrayBuffer)} - ${error}`)
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
const encodeMessage = (data: unknown) => {
|
||||||
|
try {
|
||||||
|
return useBinary ? encode(data) : JSON.stringify(data)
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Could not encode data: ${data} - ${error}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function createWebSocket() {
|
function createWebSocket() {
|
||||||
let listeners = new Map<string, Set<(data?: unknown) => void>>();
|
const listeners = new Map<string, Set<(data?: unknown) => void>>()
|
||||||
const { subscribe, set } = writable(false);
|
const { subscribe, set } = writable(false)
|
||||||
const reconnectTimeoutTime = 5000;
|
const reconnectTimeoutTime = 5000
|
||||||
let unresponsiveTimeoutId: number;
|
let unresponsiveTimeoutId: ReturnType<typeof setTimeout>
|
||||||
let reconnectTimeoutId: number;
|
let reconnectTimeoutId: ReturnType<typeof setTimeout>
|
||||||
let ws: WebSocket;
|
let ws: WebSocket
|
||||||
let socketUrl: string | URL;
|
let socketUrl: string | URL
|
||||||
|
|
||||||
function init(url: string | URL) {
|
function init(url: string | URL) {
|
||||||
socketUrl = url;
|
socketUrl = url
|
||||||
connect();
|
connect()
|
||||||
}
|
}
|
||||||
|
|
||||||
function disconnect(reason: SocketEvent, event?: Event) {
|
function disconnect(reason: SocketEvent, event?: Event) {
|
||||||
ws.close();
|
ws.close()
|
||||||
set(false);
|
set(false)
|
||||||
clearTimeout(unresponsiveTimeoutId);
|
clearTimeout(unresponsiveTimeoutId)
|
||||||
clearTimeout(reconnectTimeoutId);
|
clearTimeout(reconnectTimeoutId)
|
||||||
listeners.get(reason)?.forEach((listener) => listener(event));
|
listeners.get(reason)?.forEach(listener => listener(event))
|
||||||
reconnectTimeoutId = setTimeout(connect, reconnectTimeoutTime);
|
reconnectTimeoutId = setTimeout(connect, reconnectTimeoutTime)
|
||||||
}
|
}
|
||||||
|
|
||||||
function connect() {
|
function connect() {
|
||||||
ws = new WebSocket(socketUrl);
|
ws = new WebSocket(socketUrl)
|
||||||
ws.onopen = (ev) => {
|
ws.binaryType = 'arraybuffer'
|
||||||
set(true);
|
ws.onopen = ev => {
|
||||||
clearTimeout(reconnectTimeoutId);
|
ping()
|
||||||
listeners.get('open')?.forEach((listener) => listener(ev));
|
useBinary = true
|
||||||
|
ping()
|
||||||
|
set(true)
|
||||||
|
clearTimeout(reconnectTimeoutId)
|
||||||
|
listeners.get('open')?.forEach(listener => listener(ev))
|
||||||
for (const event of listeners.keys()) {
|
for (const event of listeners.keys()) {
|
||||||
if (socketEvents.includes(event as SocketEvent)) continue;
|
if (socketEvents.includes(event as SocketEvent)) continue
|
||||||
subscribeToEvent(event);
|
subscribeToEvent(event)
|
||||||
}
|
}
|
||||||
};
|
|
||||||
ws.onmessage = (message) => {
|
|
||||||
resetUnresponsiveCheck();
|
|
||||||
let data = message.data;
|
|
||||||
if (data instanceof ArrayBuffer) {
|
|
||||||
listeners.get('binary')?.forEach((listener) => listener(data));
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
data = data.substring(1);
|
ws.onmessage = frame => {
|
||||||
|
resetUnresponsiveCheck()
|
||||||
if (!data) return;
|
const message = decodeMessage(frame.data)
|
||||||
|
if (!message) return
|
||||||
let event = data.substring(data.indexOf('/') + 1, data.indexOf('['));
|
const [, event, payload = undefined] = message
|
||||||
let payload = data.substring(data.indexOf('[') + 1, data.lastIndexOf(']'));
|
if (event) listeners.get(event)?.forEach(listener => listener(payload))
|
||||||
|
}
|
||||||
try {
|
ws.onerror = ev => disconnect('error', ev)
|
||||||
payload = JSON.parse(payload);
|
ws.onclose = ev => disconnect('close', ev)
|
||||||
} catch (error) {}
|
|
||||||
if (event) listeners.get(event)?.forEach((listener) => listener(payload));
|
|
||||||
};
|
|
||||||
ws.onerror = (ev) => disconnect('error', ev);
|
|
||||||
ws.onclose = (ev) => disconnect('close', ev);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function unsubscribe(event: string, listener?: (data: any) => void) {
|
function unsubscribe(event: string, listener?: (data: unknown) => void) {
|
||||||
let eventListeners = listeners.get(event);
|
const eventListeners = listeners.get(event)
|
||||||
if (!eventListeners) return;
|
if (!eventListeners) return
|
||||||
|
|
||||||
if (!eventListeners.size) {
|
if (!eventListeners.size) {
|
||||||
unsubscribeToEvent(event);
|
unsubscribeToEvent(event)
|
||||||
}
|
}
|
||||||
if (listener) {
|
if (listener) {
|
||||||
eventListeners?.delete(listener);
|
eventListeners?.delete(listener)
|
||||||
} else {
|
} else {
|
||||||
listeners.delete(event);
|
listeners.delete(event)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function resetUnresponsiveCheck() {
|
function resetUnresponsiveCheck() {
|
||||||
clearTimeout(unresponsiveTimeoutId);
|
clearTimeout(unresponsiveTimeoutId)
|
||||||
unresponsiveTimeoutId = setTimeout(() => disconnect('unresponsive'), reconnectTimeoutTime);
|
unresponsiveTimeoutId = setTimeout(() => disconnect('unresponsive'), reconnectTimeoutTime)
|
||||||
}
|
}
|
||||||
|
|
||||||
function sendEvent(event: string, data: unknown) {
|
function sendEvent(event: string, data: unknown) {
|
||||||
if (!ws || ws.readyState !== WebSocket.OPEN) return;
|
if (!ws || ws.readyState !== WebSocket.OPEN) return
|
||||||
ws.send(`2/${event}[${JSON.stringify(data)}]`);
|
send([2, event, data])
|
||||||
}
|
}
|
||||||
|
|
||||||
function unsubscribeToEvent(event: string) {
|
function unsubscribeToEvent(event: string) {
|
||||||
if (!ws || ws.readyState !== WebSocket.OPEN) return;
|
if (!ws || ws.readyState !== WebSocket.OPEN) return
|
||||||
ws.send('1/' + event);
|
send([1, event])
|
||||||
}
|
}
|
||||||
|
|
||||||
function subscribeToEvent(event: string) {
|
function subscribeToEvent(event: string) {
|
||||||
if (!ws || ws.readyState !== WebSocket.OPEN) return;
|
if (!ws || ws.readyState !== WebSocket.OPEN) return
|
||||||
ws.send('0/' + event);
|
send([0, event])
|
||||||
|
}
|
||||||
|
|
||||||
|
function send(data: unknown) {
|
||||||
|
if (!ws || ws.readyState !== WebSocket.OPEN) return
|
||||||
|
const serialized = encodeMessage(data)
|
||||||
|
if (!serialized) {
|
||||||
|
console.error('Could not serialize data:', data)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ws.send(serialized)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ping() {
|
||||||
|
const serialized = encodeMessage([4])
|
||||||
|
if (!serialized) {
|
||||||
|
console.error('Could not serialize message')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ws.send(serialized)
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -99,24 +137,24 @@ function createWebSocket() {
|
|||||||
sendEvent,
|
sendEvent,
|
||||||
init,
|
init,
|
||||||
on: <T>(event: string, listener: (data: T) => void): (() => void) => {
|
on: <T>(event: string, listener: (data: T) => void): (() => void) => {
|
||||||
let eventListeners = listeners.get(event);
|
let eventListeners = listeners.get(event)
|
||||||
if (!eventListeners) {
|
if (!eventListeners) {
|
||||||
if (!socketEvents.includes(event as SocketEvent)) {
|
if (!socketEvents.includes(event as SocketEvent)) {
|
||||||
subscribeToEvent(event);
|
subscribeToEvent(event)
|
||||||
}
|
}
|
||||||
eventListeners = new Set();
|
eventListeners = new Set()
|
||||||
listeners.set(event, eventListeners);
|
listeners.set(event, eventListeners)
|
||||||
}
|
}
|
||||||
eventListeners.add(listener as (data: any) => void);
|
eventListeners.add(listener as (data: unknown) => void)
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
unsubscribe(event, listener);
|
unsubscribe(event, listener as (data: unknown) => void)
|
||||||
};
|
}
|
||||||
},
|
},
|
||||||
off: (event: string, listener?: (data: any) => void) => {
|
off: <T>(event: string, listener?: (data: T) => void) => {
|
||||||
unsubscribe(event, listener);
|
unsubscribe(event, listener as (data: unknown) => void)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const socket = createWebSocket();
|
export const socket = createWebSocket()
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import type { DownloadOTA } from '$lib/types/models';
|
import type { DownloadOTA } from '$lib/types/models'
|
||||||
import { writable } from 'svelte/store';
|
import { writable } from 'svelte/store'
|
||||||
|
|
||||||
let telemetry_data = {
|
const telemetry_data = {
|
||||||
rssi: {
|
rssi: {
|
||||||
rssi: 0
|
rssi: 0
|
||||||
},
|
},
|
||||||
@@ -10,10 +10,10 @@ let telemetry_data = {
|
|||||||
progress: 0,
|
progress: 0,
|
||||||
error: ''
|
error: ''
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
function createTelemetry() {
|
function createTelemetry() {
|
||||||
const { subscribe, set, update } = writable(telemetry_data);
|
const { subscribe, update } = writable(telemetry_data)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
subscribe,
|
subscribe,
|
||||||
@@ -21,15 +21,15 @@ function createTelemetry() {
|
|||||||
update(telemetry_data => ({
|
update(telemetry_data => ({
|
||||||
...telemetry_data,
|
...telemetry_data,
|
||||||
rssi: { rssi: data }
|
rssi: { rssi: data }
|
||||||
}));
|
}))
|
||||||
},
|
},
|
||||||
setDownloadOTA: (data: DownloadOTA) => {
|
setDownloadOTA: (data: DownloadOTA) => {
|
||||||
update(telemetry_data => ({
|
update(telemetry_data => ({
|
||||||
...telemetry_data,
|
...telemetry_data,
|
||||||
download_ota: { status: data.status, progress: data.progress, error: data.error }
|
download_ota: { status: data.status, progress: data.progress, error: data.error }
|
||||||
}));
|
}))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const telemetry = createTelemetry();
|
export const telemetry = createTelemetry()
|
||||||
|
|||||||
Vendored
+15
-15
@@ -1,17 +1,17 @@
|
|||||||
declare module 'three/src/math/MathUtils' {
|
declare module 'three/src/math/MathUtils' {
|
||||||
export function generateUUID(): string;
|
export function generateUUID(): string
|
||||||
export function clamp(value: number, min: number, max: number): number;
|
export function clamp(value: number, min: number, max: number): number
|
||||||
export function euclideanModulo(n: number, m: number): number;
|
export function euclideanModulo(n: number, m: number): number
|
||||||
export function mapLinear(x: number, a1: number, a2: number, b1: number, b2: number): number;
|
export function mapLinear(x: number, a1: number, a2: number, b1: number, b2: number): number
|
||||||
export function lerp(x: number, y: number, t: number): number;
|
export function lerp(x: number, y: number, t: number): number
|
||||||
export function smoothstep(x: number, min: number, max: number): number;
|
export function smoothstep(x: number, min: number, max: number): number
|
||||||
export function smootherstep(x: number, min: number, max: number): number;
|
export function smootherstep(x: number, min: number, max: number): number
|
||||||
export function randInt(low: number, high: number): number;
|
export function randInt(low: number, high: number): number
|
||||||
export function randFloat(low: number, high: number): number;
|
export function randFloat(low: number, high: number): number
|
||||||
export function randFloatSpread(range: number): number;
|
export function randFloatSpread(range: number): number
|
||||||
export function degToRad(degrees: number): number;
|
export function degToRad(degrees: number): number
|
||||||
export function radToDeg(radians: number): number;
|
export function radToDeg(radians: number): number
|
||||||
export function isPowerOfTwo(value: number): boolean;
|
export function isPowerOfTwo(value: number): boolean
|
||||||
export function ceilPowerOfTwo(value: number): number;
|
export function ceilPowerOfTwo(value: number): number
|
||||||
export function floorPowerOfTwo(value: number): number;
|
export function floorPowerOfTwo(value: number): number
|
||||||
}
|
}
|
||||||
|
|||||||
+194
-133
@@ -1,178 +1,239 @@
|
|||||||
export type vector = { x: number; y: number };
|
export enum MessageTopic {
|
||||||
|
imu = 'imu',
|
||||||
|
mode = 'mode',
|
||||||
|
input = 'input',
|
||||||
|
analytics = 'analytics',
|
||||||
|
position = 'position',
|
||||||
|
angles = 'angles',
|
||||||
|
i2cScan = 'i2cScan',
|
||||||
|
peripheralSettings = 'peripheralSettings',
|
||||||
|
otastatus = 'otastatus',
|
||||||
|
gait = 'walk_gait',
|
||||||
|
servoState = 'servoState',
|
||||||
|
servoPWM = 'servoPWM',
|
||||||
|
WiFiSettings = 'WiFiSettings',
|
||||||
|
sonar = 'sonar',
|
||||||
|
rssi = 'rssi'
|
||||||
|
}
|
||||||
|
|
||||||
|
export type vector = { x: number; y: number }
|
||||||
|
|
||||||
export interface ControllerInput {
|
export interface ControllerInput {
|
||||||
left: vector;
|
left: vector
|
||||||
right: vector;
|
right: vector
|
||||||
height: number;
|
height: number
|
||||||
speed: number;
|
speed: number
|
||||||
s1: number;
|
s1: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export type GithubRelease = {
|
export type GithubRelease = {
|
||||||
message: string;
|
message: string
|
||||||
tag_name: string;
|
tag_name: string
|
||||||
assets: Array<{
|
assets: Array<{
|
||||||
name: string;
|
name: string
|
||||||
browser_download_url: string;
|
browser_download_url: string
|
||||||
}>;
|
}>
|
||||||
};
|
}
|
||||||
|
|
||||||
export type angles = number[] | Int16Array;
|
export type angles = number[] | Int16Array
|
||||||
|
|
||||||
export type WifiStatus = {
|
export type WifiStatus = {
|
||||||
status: number;
|
status: number
|
||||||
local_ip: string;
|
local_ip: string
|
||||||
mac_address: string;
|
mac_address: string
|
||||||
rssi: number;
|
rssi: number
|
||||||
ssid: string;
|
ssid: string
|
||||||
bssid: string;
|
bssid: string
|
||||||
channel: number;
|
channel: number
|
||||||
subnet_mask: string;
|
subnet_mask: string
|
||||||
gateway_ip: string;
|
gateway_ip: string
|
||||||
dns_ip_1: string;
|
dns_ip_1: string
|
||||||
dns_ip_2?: string;
|
dns_ip_2?: string
|
||||||
};
|
}
|
||||||
|
|
||||||
export type WifiSettings = {
|
export type WifiSettings = {
|
||||||
hostname: string;
|
hostname: string
|
||||||
priority_RSSI: boolean;
|
priority_RSSI: boolean
|
||||||
wifi_networks: KnownNetworkItem[];
|
wifi_networks: KnownNetworkItem[]
|
||||||
};
|
}
|
||||||
|
|
||||||
export type NetworkList = {
|
export type NetworkList = {
|
||||||
networks: NetworkItem[];
|
networks: NetworkItem[]
|
||||||
};
|
}
|
||||||
|
|
||||||
export type KnownNetworkItem = {
|
export type KnownNetworkItem = {
|
||||||
ssid: string;
|
ssid: string
|
||||||
password: string;
|
password: string
|
||||||
static_ip_config: boolean;
|
static_ip_config: boolean
|
||||||
local_ip?: string;
|
local_ip?: string
|
||||||
subnet_mask?: string;
|
subnet_mask?: string
|
||||||
gateway_ip?: string;
|
gateway_ip?: string
|
||||||
dns_ip_1?: string;
|
dns_ip_1?: string
|
||||||
dns_ip_2?: string;
|
dns_ip_2?: string
|
||||||
};
|
}
|
||||||
|
|
||||||
export type NetworkItem = {
|
export type NetworkItem = {
|
||||||
rssi: number;
|
rssi: number
|
||||||
ssid: string;
|
ssid: string
|
||||||
bssid: string;
|
bssid: string
|
||||||
channel: number;
|
channel: number
|
||||||
encryption_type: number;
|
encryption_type: number
|
||||||
};
|
}
|
||||||
|
|
||||||
export type ApStatus = {
|
export type ApStatus = {
|
||||||
status: number;
|
status: number
|
||||||
ip_address: string;
|
ip_address: string
|
||||||
mac_address: string;
|
mac_address: string
|
||||||
station_num: number;
|
station_num: number
|
||||||
};
|
}
|
||||||
|
|
||||||
export type ApSettings = {
|
export type ApSettings = {
|
||||||
provision_mode: number;
|
provision_mode: number
|
||||||
ssid: string;
|
ssid: string
|
||||||
password: string;
|
password: string
|
||||||
channel: number;
|
channel: number
|
||||||
ssid_hidden: boolean;
|
ssid_hidden: boolean
|
||||||
max_clients: number;
|
max_clients: number
|
||||||
local_ip: string;
|
local_ip: string
|
||||||
gateway_ip: string;
|
gateway_ip: string
|
||||||
subnet_mask: string;
|
subnet_mask: string
|
||||||
};
|
}
|
||||||
|
|
||||||
export type DownloadOTA = {
|
export type DownloadOTA = {
|
||||||
status: string;
|
status: string
|
||||||
progress: number;
|
progress: number
|
||||||
error: string;
|
error: string
|
||||||
};
|
}
|
||||||
|
|
||||||
export type Analytics = {
|
export type Analytics = {
|
||||||
max_alloc_heap: number;
|
max_alloc_heap: number
|
||||||
psram_size: number;
|
psram_size: number
|
||||||
free_psram: number;
|
free_psram: number
|
||||||
free_heap: number;
|
free_heap: number
|
||||||
total_heap: number;
|
total_heap: number
|
||||||
min_free_heap: number;
|
min_free_heap: number
|
||||||
core_temp: number;
|
core_temp: number
|
||||||
fs_total: number;
|
fs_total: number
|
||||||
fs_used: number;
|
fs_used: number
|
||||||
uptime: number;
|
uptime: number
|
||||||
cpu0_usage: number;
|
cpu0_usage: number
|
||||||
cpu1_usage: number;
|
cpu1_usage: number
|
||||||
cpu_usage: number;
|
cpu_usage: number
|
||||||
};
|
}
|
||||||
|
|
||||||
export type Rssi = {
|
export type Rssi = {
|
||||||
rssi: number;
|
rssi: number
|
||||||
ssid: string;
|
ssid: string
|
||||||
};
|
}
|
||||||
|
|
||||||
export type StaticSystemInformation = {
|
export type StaticSystemInformation = {
|
||||||
esp_platform: string;
|
esp_platform: string
|
||||||
firmware_version: string;
|
firmware_version: string
|
||||||
cpu_freq_mhz: number;
|
cpu_freq_mhz: number
|
||||||
cpu_type: string;
|
cpu_type: string
|
||||||
cpu_rev: number;
|
cpu_rev: number
|
||||||
cpu_cores: number;
|
cpu_cores: number
|
||||||
sketch_size: number;
|
sketch_size: number
|
||||||
free_sketch_space: number;
|
free_sketch_space: number
|
||||||
sdk_version: string;
|
sdk_version: string
|
||||||
arduino_version: string;
|
arduino_version: string
|
||||||
flash_chip_size: number;
|
flash_chip_size: number
|
||||||
flash_chip_speed: number;
|
flash_chip_speed: number
|
||||||
cpu_reset_reason: string;
|
cpu_reset_reason: string
|
||||||
};
|
}
|
||||||
|
|
||||||
export type SystemInformation = Analytics & StaticSystemInformation;
|
export type SystemInformation = Analytics & StaticSystemInformation
|
||||||
|
|
||||||
export type IMU = {
|
export type IMU = {
|
||||||
x: number;
|
x: number
|
||||||
y: number;
|
y: number
|
||||||
z: number;
|
z: number
|
||||||
heading: number;
|
heading: number
|
||||||
altitude: number;
|
altitude: number
|
||||||
bmp_temp: number;
|
bmp_temp: number
|
||||||
pressure: number;
|
pressure: number
|
||||||
};
|
}
|
||||||
|
|
||||||
export interface I2CDevice {
|
export interface I2CDevice {
|
||||||
address: number;
|
address: number
|
||||||
part_number: string;
|
part_number: string
|
||||||
name: string;
|
name: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PinConfig = {
|
||||||
|
pin: number
|
||||||
|
mode: string
|
||||||
|
type: string
|
||||||
|
role: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PeripheralsConfiguration = {
|
||||||
|
sda: number
|
||||||
|
scl: number
|
||||||
|
frequency: number
|
||||||
|
pins: PinConfig[]
|
||||||
}
|
}
|
||||||
|
|
||||||
export type CameraSettings = {
|
export type CameraSettings = {
|
||||||
framesize: number;
|
framesize: number
|
||||||
quality: number;
|
quality: number
|
||||||
brightness: number;
|
brightness: number
|
||||||
contrast: number;
|
contrast: number
|
||||||
saturation: number;
|
saturation: number
|
||||||
sharpness: number;
|
sharpness: number
|
||||||
denoise: number;
|
denoise: number
|
||||||
special_effect: number;
|
special_effect: number
|
||||||
wb_mode: number;
|
wb_mode: number
|
||||||
vflip: boolean;
|
vflip: boolean
|
||||||
hmirror: boolean;
|
hmirror: boolean
|
||||||
};
|
}
|
||||||
|
|
||||||
export type File = number;
|
export type File = number
|
||||||
|
|
||||||
export interface Directory {
|
export interface Directory {
|
||||||
[key: string]: File | Directory;
|
[key: string]: File | Directory
|
||||||
}
|
}
|
||||||
|
|
||||||
export type Servo = {
|
export type Servo = {
|
||||||
name: string;
|
name: string
|
||||||
channel: number;
|
channel: number
|
||||||
inverted: boolean;
|
inverted: boolean
|
||||||
angle: number;
|
angle: number
|
||||||
center_angle: number;
|
center_angle: number
|
||||||
};
|
}
|
||||||
|
|
||||||
export type ServoConfiguration = {
|
export type ServoConfiguration = {
|
||||||
is_active: boolean;
|
is_active: boolean
|
||||||
servo_pwm_frequency: number;
|
servo_pwm_frequency: number
|
||||||
servo_oscillator_frequency: number;
|
servo_oscillator_frequency: number
|
||||||
servos: Servo[];
|
servos: Servo[]
|
||||||
};
|
}
|
||||||
|
|
||||||
|
export interface MDNSServiceQuery {
|
||||||
|
services: MDNSServiceItem[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MDNSServiceItem {
|
||||||
|
ip: string
|
||||||
|
port: number
|
||||||
|
name: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MDNSService {
|
||||||
|
service: string
|
||||||
|
protocol: string
|
||||||
|
port: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MDNSTxtRecord {
|
||||||
|
key: string
|
||||||
|
value: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MDNSStatus {
|
||||||
|
started: boolean
|
||||||
|
hostname: string
|
||||||
|
instance: string
|
||||||
|
services: MDNSService[]
|
||||||
|
global_txt_records: MDNSTxtRecord[]
|
||||||
|
}
|
||||||
|
|||||||
Vendored
+9
-9
@@ -1,14 +1,14 @@
|
|||||||
declare module 'uzip' {
|
declare module 'uzip' {
|
||||||
interface UZIP {
|
interface UZIP {
|
||||||
parse(data: Uint8Array | ArrayBuffer): any;
|
parse(data: Uint8Array | ArrayBuffer): Record<string, Uint8Array>
|
||||||
compress(data: any): Uint8Array | ArrayBuffer;
|
compress(data: Record<string, Uint8Array>): Uint8Array | ArrayBuffer
|
||||||
compressRaw(data: Uint8Array | ArrayBuffer): Uint8Array | ArrayBuffer;
|
compressRaw(data: Uint8Array | ArrayBuffer): Uint8Array | ArrayBuffer
|
||||||
decompress(data: Uint8Array | ArrayBuffer): any;
|
decompress(data: Uint8Array | ArrayBuffer): Record<string, Uint8Array>
|
||||||
decompressRaw(data: Uint8Array | ArrayBuffer): Uint8Array | ArrayBuffer;
|
decompressRaw(data: Uint8Array | ArrayBuffer): Uint8Array | ArrayBuffer
|
||||||
encode(data: any): Uint8Array | ArrayBuffer;
|
encode(data: Record<string, Uint8Array>): Uint8Array | ArrayBuffer
|
||||||
decode(data: Uint8Array | ArrayBuffer): any;
|
decode(data: Uint8Array | ArrayBuffer): Record<string, Uint8Array>
|
||||||
}
|
}
|
||||||
|
|
||||||
const uzip: UZIP;
|
const uzip: UZIP
|
||||||
export default uzip;
|
export default uzip
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,15 @@
|
|||||||
export class throttler {
|
export class throttler {
|
||||||
private _throttlePause: boolean;
|
private _throttlePause: boolean
|
||||||
constructor() {
|
constructor() {
|
||||||
this._throttlePause = false;
|
this._throttlePause = false
|
||||||
}
|
}
|
||||||
throttle = (callback: Function, time: number) => {
|
throttle = (callback: () => void, time: number) => {
|
||||||
if (this._throttlePause) return;
|
if (this._throttlePause) return
|
||||||
|
|
||||||
this._throttlePause = true;
|
this._throttlePause = true
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
callback();
|
callback()
|
||||||
this._throttlePause = false;
|
this._throttlePause = false
|
||||||
}, time);
|
}, time)
|
||||||
};
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
export const daisyColor = (name: string, opacity: number = 100) => {
|
export const daisyColor = (name: string, opacity: number = 100) => {
|
||||||
const color = getComputedStyle(document.documentElement).getPropertyValue(name);
|
const color = getComputedStyle(document.documentElement).getPropertyValue(name).trim()
|
||||||
return `oklch(${color} / ${opacity}%)`;
|
if (opacity >= 100) return color
|
||||||
};
|
const alpha = Math.min(Math.max(opacity, 0), 100) / 100
|
||||||
|
return `${color.replace(/(\/\s*\d+(\.\d+)?\))|\)$/, '')} / ${alpha})`
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
export * from './result';
|
export * from './result'
|
||||||
export * from './string-utilities';
|
export * from './string-utilities'
|
||||||
export * from './svelte-utilities';
|
export * from './svelte-utilities'
|
||||||
export * from './math-utilities';
|
export * from './math-utilities'
|
||||||
export * from './buffer-utilities';
|
export * from './buffer-utilities'
|
||||||
export * from './model-utilities';
|
export * from './model-utilities'
|
||||||
export * from './position-utilities';
|
export * from './position-utilities'
|
||||||
export * from './string-utilities';
|
export * from './string-utilities'
|
||||||
export * from './color-utilities';
|
export * from './color-utilities'
|
||||||
|
|||||||
@@ -1,18 +1,18 @@
|
|||||||
export const toUint8 = (number: number, min: number, max: number) => {
|
export const toUint8 = (number: number, min: number, max: number) => {
|
||||||
number = Math.max(min, Math.min(max, number));
|
number = Math.max(min, Math.min(max, number))
|
||||||
let scaled = ((number - min) / (max - min)) * 255;
|
const scaled = ((number - min) / (max - min)) * 255
|
||||||
return Math.round(scaled) & 0xff;
|
return Math.round(scaled) & 0xff
|
||||||
};
|
}
|
||||||
|
|
||||||
export const toInt8 = (number: number, min: number, max: number) => {
|
export const toInt8 = (number: number, min: number, max: number) => {
|
||||||
number = Math.max(min, Math.min(max, number));
|
number = Math.max(min, Math.min(max, number))
|
||||||
let scaled = ((number - min) / (max - min)) * 255 - 128;
|
const scaled = ((number - min) / (max - min)) * 255 - 128
|
||||||
return Math.max(-128, Math.min(127, Math.round(scaled))) | 0;
|
return Math.max(-128, Math.min(127, Math.round(scaled))) | 0
|
||||||
};
|
}
|
||||||
|
|
||||||
export const fromInt8 = (int8: number, min: number, max: number) => {
|
export const fromInt8 = (int8: number, min: number, max: number) => {
|
||||||
int8 = Math.max(-128, Math.min(127, int8));
|
int8 = Math.max(-128, Math.min(127, int8))
|
||||||
const scaled = (int8 + 128) / 255;
|
const scaled = (int8 + 128) / 255
|
||||||
const number = scaled * (max - min) + min;
|
const number = scaled * (max - min) + min
|
||||||
return number;
|
return number
|
||||||
};
|
}
|
||||||
|
|||||||
@@ -1,89 +1,96 @@
|
|||||||
import { Color, LoaderUtils, Vector3 } from 'three';
|
import { Color, LoaderUtils, Vector3 } from 'three'
|
||||||
import URDFLoader, { type URDFRobot } from 'urdf-loader';
|
import URDFLoader, { type URDFRobot } from 'urdf-loader'
|
||||||
import { XacroLoader } from 'xacro-parser';
|
import { XacroLoader } from 'xacro-parser'
|
||||||
import { Result } from '$lib/utilities';
|
import { Result } from '$lib/utilities'
|
||||||
import { jointNames, model } from '$lib/stores';
|
import { currentVariant, jointNames, model } from '$lib/stores'
|
||||||
import uzip from 'uzip';
|
import uzip from 'uzip'
|
||||||
import { fileService } from '$lib/services';
|
import { fileService } from '$lib/services'
|
||||||
|
import { get } from 'svelte/store'
|
||||||
|
import { resolve } from '$app/paths'
|
||||||
|
|
||||||
let model_xml: XMLDocument;
|
let model_xml: XMLDocument
|
||||||
|
|
||||||
export const populateModelCache = async () => {
|
export const populateModelCache = async () => {
|
||||||
await cacheModelFiles();
|
await cacheModelFiles()
|
||||||
const modelRes = await loadModelAsync('/spot_micro.urdf.xacro');
|
const modelRes = await loadModel(get(currentVariant).model)
|
||||||
if (modelRes.isOk()) {
|
if (modelRes.isOk()) {
|
||||||
const [urdf, JOINT_NAME] = modelRes.inner;
|
const [urdf, JOINT_NAME] = modelRes.inner
|
||||||
jointNames.set(JOINT_NAME);
|
jointNames.set(JOINT_NAME)
|
||||||
model.set(urdf);
|
model.set(urdf)
|
||||||
} else {
|
} else {
|
||||||
console.error(modelRes.inner, { exception: modelRes.exception });
|
console.error(modelRes.inner, { exception: modelRes.exception })
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
export const cacheModelFiles = async () => {
|
export const cacheModelFiles = async () => {
|
||||||
let data = await fetch('/stl.zip');
|
const data = await fetch(get(currentVariant).stl)
|
||||||
|
|
||||||
var files = uzip.parse(await data.arrayBuffer());
|
const files = uzip.parse(await data.arrayBuffer())
|
||||||
|
|
||||||
for (const [path, data] of Object.entries(files) as [path: string, data: Uint8Array][]) {
|
for (const [path, data] of Object.entries(files) as [path: string, data: Uint8Array][]) {
|
||||||
const url = new URL(path, window.location.href);
|
const normalizedPath = path.startsWith('/') ? path : '/' + path
|
||||||
fileService.saveFile(url.toString(), data);
|
const resolvedUrl = resolve(normalizedPath as any)
|
||||||
|
fileService?.saveFile(resolvedUrl, data)
|
||||||
|
fileService?.saveFile(normalizedPath, data)
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
export const loadModelAsync = async (
|
export const loadModel = async (url: string): Promise<Result<[URDFRobot, string[]], string>> => {
|
||||||
url: string
|
const urdfLoader = new URDFLoader()
|
||||||
): Promise<Result<[URDFRobot, string[]], string>> => {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
const xacroLoader = new XacroLoader();
|
|
||||||
const urdfLoader = new URDFLoader();
|
|
||||||
urdfLoader.workingPath = LoaderUtils.extractUrlBase(url);
|
|
||||||
|
|
||||||
xacroLoader.load(
|
let xml =
|
||||||
url,
|
url.endsWith('.xacro') ? await loadXacro(url) : await fetch(url).then(res => res.text())
|
||||||
async (xml) => {
|
|
||||||
model_xml = xml;
|
if (typeof xml === 'string') {
|
||||||
|
xml = new window.DOMParser().parseFromString(xml, 'text/xml')
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Promise(resolve => {
|
||||||
|
model_xml = xml
|
||||||
try {
|
try {
|
||||||
const model = urdfLoader.parse(xml);
|
const model = urdfLoader.parse(xml)
|
||||||
model.rotation.x = -Math.PI / 2;
|
setupRobot(model)
|
||||||
model.rotation.z = Math.PI / 2;
|
|
||||||
model.traverse((c) => (c.castShadow = true));
|
|
||||||
model.updateMatrixWorld(true);
|
|
||||||
model.scale.setScalar(10);
|
|
||||||
const joints = Object.entries(model.joints)
|
const joints = Object.entries(model.joints)
|
||||||
.filter((joint) => joint[1].jointType !== 'fixed')
|
.filter(joint => joint[1].jointType !== 'fixed')
|
||||||
.map((joint) => joint[0]);
|
.map(joint => joint[0])
|
||||||
|
|
||||||
resolve(Result.ok([model, joints]));
|
resolve(Result.ok([model, joints]))
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
resolve(Result.err('Failed to load model', error));
|
resolve(Result.err('Failed to load model', error))
|
||||||
}
|
}
|
||||||
},
|
})
|
||||||
(error) => resolve(Result.err('Failed to load model', error))
|
}
|
||||||
);
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
export const toeWorldPositions = (robot: URDFRobot) => {
|
const loadXacro = async (url: string): Promise<XMLDocument> =>
|
||||||
const toe_positions: Vector3[] = [];
|
new Promise((resolve, reject) => {
|
||||||
robot.traverse((child) => {
|
new XacroLoader().load(url, resolve, reject)
|
||||||
if (child.name.includes('toe') && !child.name.includes('_link')) {
|
})
|
||||||
const worldPosition = new Vector3();
|
|
||||||
child.getWorldPosition(worldPosition);
|
|
||||||
toe_positions.push(worldPosition);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
return toe_positions;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const footColor = () => {
|
function setupRobot(robot: URDFRobot) {
|
||||||
const colorElem = model_xml.querySelector('material[name=foot_color] > color') as Element;
|
robot.rotation.x = -Math.PI / 2
|
||||||
const colorAttrStr = colorElem.getAttribute('rgba') as string;
|
robot.rotation.z = Math.PI / 2
|
||||||
|
robot.scale.setScalar(10)
|
||||||
|
robot.traverse(c => (c.castShadow = true))
|
||||||
|
robot.updateMatrixWorld(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getToeWorldPositions(robot: URDFRobot): Vector3[] {
|
||||||
|
const toes: Vector3[] = []
|
||||||
|
robot.traverse(c => {
|
||||||
|
if (c.name.includes('toe') && !c.name.includes('_link'))
|
||||||
|
toes.push(c.getWorldPosition(new Vector3()))
|
||||||
|
})
|
||||||
|
return toes
|
||||||
|
}
|
||||||
|
|
||||||
|
export const extractFootColor = () => {
|
||||||
|
const colorElem = model_xml.querySelector('material[name=foot_color] > color') as Element
|
||||||
|
const colorAttrStr = colorElem.getAttribute('rgba') as string
|
||||||
const colorStr = colorAttrStr
|
const colorStr = colorAttrStr
|
||||||
.split(' ')
|
.split(' ')
|
||||||
.slice(0, 3)
|
.slice(0, 3)
|
||||||
.map((val) => Math.floor(+val * 255))
|
.map(val => Math.floor(+val * 255))
|
||||||
.join(', ');
|
.join(', ')
|
||||||
|
|
||||||
return new Color(`rgb(${colorStr})`);
|
return new Color(`rgb(${colorStr})`)
|
||||||
};
|
}
|
||||||
|
|||||||
@@ -1,30 +1,32 @@
|
|||||||
class SunCalculator {
|
class SunCalculator {
|
||||||
calculateSunElevation(lat: number = 55, lon: number = 12) {
|
calculateSunElevation(lat: number = 55, lon: number = 12) {
|
||||||
const now = new Date();
|
const now = new Date()
|
||||||
const JD = this.getJulianDate(now);
|
const JD = this.getJulianDate(now)
|
||||||
const solarDec = this.getSolarDeclination(JD);
|
const solarDec = this.getSolarDeclination(JD)
|
||||||
const solarTime = this.getSolarTime(now, lon);
|
const solarTime = this.getSolarTime(now, lon)
|
||||||
|
|
||||||
const hourAngle = (solarTime - 12) * 15;
|
const hourAngle = (solarTime - 12) * 15
|
||||||
const elevation = Math.asin(
|
const elevation = Math.asin(
|
||||||
Math.sin(this.degToRad(lat)) * Math.sin(solarDec) +
|
Math.sin(this.degToRad(lat)) * Math.sin(solarDec) +
|
||||||
Math.cos(this.degToRad(lat)) * Math.cos(solarDec) * Math.cos(this.degToRad(hourAngle))
|
Math.cos(this.degToRad(lat)) *
|
||||||
);
|
Math.cos(solarDec) *
|
||||||
|
Math.cos(this.degToRad(hourAngle))
|
||||||
|
)
|
||||||
|
|
||||||
return this.radToDeg(elevation);
|
return this.radToDeg(elevation)
|
||||||
}
|
}
|
||||||
|
|
||||||
getJulianDate(date: Date) {
|
getJulianDate(date: Date) {
|
||||||
const Y = date.getUTCFullYear();
|
const Y = date.getUTCFullYear()
|
||||||
const M = date.getUTCMonth() + 1;
|
const M = date.getUTCMonth() + 1
|
||||||
const D =
|
const D =
|
||||||
date.getUTCDate() +
|
date.getUTCDate() +
|
||||||
date.getUTCHours() / 24 +
|
date.getUTCHours() / 24 +
|
||||||
date.getUTCMinutes() / 1440 +
|
date.getUTCMinutes() / 1440 +
|
||||||
date.getUTCSeconds() / 86400;
|
date.getUTCSeconds() / 86400
|
||||||
const A = Math.floor((14 - M) / 12);
|
const A = Math.floor((14 - M) / 12)
|
||||||
const Y1 = Y + 4800 - A;
|
const Y1 = Y + 4800 - A
|
||||||
const M1 = M + 12 * A - 3;
|
const M1 = M + 12 * A - 3
|
||||||
return (
|
return (
|
||||||
D +
|
D +
|
||||||
Math.floor((153 * M1 + 2) / 5) +
|
Math.floor((153 * M1 + 2) / 5) +
|
||||||
@@ -33,33 +35,33 @@ class SunCalculator {
|
|||||||
Math.floor(Y1 / 100) +
|
Math.floor(Y1 / 100) +
|
||||||
Math.floor(Y1 / 400) -
|
Math.floor(Y1 / 400) -
|
||||||
32045
|
32045
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
getSolarDeclination(JulianDate: number) {
|
getSolarDeclination(JulianDate: number) {
|
||||||
const n = JulianDate - 2451545;
|
const n = JulianDate - 2451545
|
||||||
const L = (280.46 + 0.9856474 * n) % 360;
|
const L = (280.46 + 0.9856474 * n) % 360
|
||||||
const g = this.degToRad((357.528 + 0.9856003 * n) % 360);
|
const g = this.degToRad((357.528 + 0.9856003 * n) % 360)
|
||||||
const lambda = this.degToRad(L + 1.915 * Math.sin(g) + 0.02 * Math.sin(2 * g));
|
const lambda = this.degToRad(L + 1.915 * Math.sin(g) + 0.02 * Math.sin(2 * g))
|
||||||
return Math.asin(Math.sin(lambda) * Math.sin(this.degToRad(23.44)));
|
return Math.asin(Math.sin(lambda) * Math.sin(this.degToRad(23.44)))
|
||||||
}
|
}
|
||||||
|
|
||||||
getSolarTime(date: Date, lon: number) {
|
getSolarTime(date: Date, lon: number) {
|
||||||
const EoT = this.getEquationOfTime(date);
|
const EoT = this.getEquationOfTime(date)
|
||||||
const offset = date.getTimezoneOffset() / 60;
|
const offset = date.getTimezoneOffset() / 60
|
||||||
const standardMeridian = Math.round(lon / 15) * 15;
|
const standardMeridian = Math.round(lon / 15) * 15
|
||||||
const solarTime =
|
const solarTime =
|
||||||
date.getUTCHours() +
|
date.getUTCHours() +
|
||||||
(date.getUTCMinutes() + (4 * (standardMeridian - lon) + EoT)) / 60 -
|
(date.getUTCMinutes() + (4 * (standardMeridian - lon) + EoT)) / 60 -
|
||||||
offset;
|
offset
|
||||||
return (solarTime + 24) % 24;
|
return (solarTime + 24) % 24
|
||||||
}
|
}
|
||||||
|
|
||||||
getEquationOfTime(date: Date) {
|
getEquationOfTime(date: Date) {
|
||||||
const JD = this.getJulianDate(date);
|
const JD = this.getJulianDate(date)
|
||||||
const n = JD - 2451545;
|
const n = JD - 2451545
|
||||||
const g = this.degToRad((357.528 + 0.9856003 * n) % 360);
|
const g = this.degToRad((357.528 + 0.9856003 * n) % 360)
|
||||||
const q = this.degToRad((280.46 + 0.9856474 * n) % 360);
|
const q = this.degToRad((280.46 + 0.9856474 * n) % 360)
|
||||||
return (
|
return (
|
||||||
4 *
|
4 *
|
||||||
this.radToDeg(
|
this.radToDeg(
|
||||||
@@ -69,16 +71,16 @@ class SunCalculator {
|
|||||||
0.014615 * Math.cos(2 * q) -
|
0.014615 * Math.cos(2 * q) -
|
||||||
0.040849 * Math.sin(2 * g)
|
0.040849 * Math.sin(2 * g)
|
||||||
)
|
)
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
degToRad(deg: number) {
|
degToRad(deg: number) {
|
||||||
return deg * (Math.PI / 180);
|
return deg * (Math.PI / 180)
|
||||||
}
|
}
|
||||||
|
|
||||||
radToDeg(rad: number) {
|
radToDeg(rad: number) {
|
||||||
return rad * (180 / Math.PI);
|
return rad * (180 / Math.PI)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const sunCalculator = new SunCalculator();
|
export const sunCalculator = new SunCalculator()
|
||||||
|
|||||||
@@ -1,18 +1,18 @@
|
|||||||
export class Err<T, U> {
|
export class Err<T, U> {
|
||||||
#inner: T;
|
#inner: T
|
||||||
#exception?: U;
|
#exception?: U
|
||||||
|
|
||||||
constructor(inner: T, exception?: U) {
|
constructor(inner: T, exception?: U) {
|
||||||
this.#inner = inner;
|
this.#inner = inner
|
||||||
this.#exception = exception;
|
this.#exception = exception
|
||||||
}
|
}
|
||||||
|
|
||||||
get inner(): T {
|
get inner(): T {
|
||||||
return this.#inner;
|
return this.#inner
|
||||||
}
|
}
|
||||||
|
|
||||||
get exception(): U | undefined {
|
get exception(): U | undefined {
|
||||||
return this.#exception;
|
return this.#exception
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -20,7 +20,7 @@ export class Err<T, U> {
|
|||||||
* @returns `true` if `Ok`; `false` if `Err`
|
* @returns `true` if `Ok`; `false` if `Err`
|
||||||
*/
|
*/
|
||||||
isOk(): false {
|
isOk(): false {
|
||||||
return false;
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -28,7 +28,7 @@ export class Err<T, U> {
|
|||||||
* @returns `true` if `Err`; `false` if `Ok`
|
* @returns `true` if `Err`; `false` if `Ok`
|
||||||
*/
|
*/
|
||||||
isErr(): this is Err<T, U> {
|
isErr(): this is Err<T, U> {
|
||||||
return true;
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -37,6 +37,6 @@ export class Err<T, U> {
|
|||||||
* @returns `Err(inner)`
|
* @returns `Err(inner)`
|
||||||
*/
|
*/
|
||||||
static new<E, F>(inner: E, exception: F): Err<E, F> {
|
static new<E, F>(inner: E, exception: F): Err<E, F> {
|
||||||
return new Err<E, F>(inner, exception);
|
return new Err<E, F>(inner, exception)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
export * from './err';
|
export * from './err'
|
||||||
export * from './ok';
|
export * from './ok'
|
||||||
export * from './result';
|
export * from './result'
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
export class Ok<T> {
|
export class Ok<T> {
|
||||||
#inner: T;
|
#inner: T
|
||||||
|
|
||||||
constructor(inner: T) {
|
constructor(inner: T) {
|
||||||
this.#inner = inner;
|
this.#inner = inner
|
||||||
}
|
}
|
||||||
|
|
||||||
get inner(): T {
|
get inner(): T {
|
||||||
return this.#inner;
|
return this.#inner
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -14,7 +14,7 @@ export class Ok<T> {
|
|||||||
* @returns `true` if `Ok`; `false` if `Err`
|
* @returns `true` if `Ok`; `false` if `Err`
|
||||||
*/
|
*/
|
||||||
isOk(): this is Ok<T> {
|
isOk(): this is Ok<T> {
|
||||||
return true;
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -22,7 +22,7 @@ export class Ok<T> {
|
|||||||
* @returns `true` if `Err`; `false` if `Ok`
|
* @returns `true` if `Err`; `false` if `Ok`
|
||||||
*/
|
*/
|
||||||
isErr(): false {
|
isErr(): false {
|
||||||
return false;
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -31,7 +31,7 @@ export class Ok<T> {
|
|||||||
* @returns `Ok(inner)`
|
* @returns `Ok(inner)`
|
||||||
*/
|
*/
|
||||||
static new<T>(inner: T): Ok<T> {
|
static new<T>(inner: T): Ok<T> {
|
||||||
return new Ok<T>(inner);
|
return new Ok<T>(inner)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -39,6 +39,6 @@ export class Ok<T> {
|
|||||||
* @returns `Ok(void)`
|
* @returns `Ok(void)`
|
||||||
*/
|
*/
|
||||||
static void(): Ok<void> {
|
static void(): Ok<void> {
|
||||||
return new Ok(undefined);
|
return new Ok(undefined)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,20 @@
|
|||||||
import { Err } from './err';
|
import { Err } from './err'
|
||||||
import { Ok } from './ok';
|
import { Ok } from './ok'
|
||||||
|
|
||||||
export type Result<T = unknown, E = unknown, F = unknown> = Ok<T> | Err<E, F>;
|
export type Result<T = unknown, E = unknown, F = unknown> = Ok<T> | Err<E, F>
|
||||||
|
|
||||||
export namespace Result {
|
export const Result = {
|
||||||
/**
|
/**
|
||||||
* @returns `Ok<T>`
|
* @returns `Ok<T>`
|
||||||
*/
|
*/
|
||||||
export function ok<T = unknown>(value: T) {
|
ok<T = unknown>(value: T) {
|
||||||
return Ok.new(value);
|
return Ok.new(value)
|
||||||
}
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @returns `Err<E, F>`
|
* @returns `Err<E, F>`
|
||||||
*/
|
*/
|
||||||
export function err<E = unknown, F = unknown>(error: E, exception?: F) {
|
err<E = unknown, F = unknown>(error: E, exception?: F) {
|
||||||
return Err.new(error, exception);
|
return Err.new(error, exception)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,36 +1,47 @@
|
|||||||
export const humanFileSize = (size: number): string => {
|
export const humanFileSize = (size: number): string => {
|
||||||
const units = ['B', 'kB', 'MB', 'GB', 'TB'];
|
const units = ['B', 'kB', 'MB', 'GB', 'TB']
|
||||||
var i = size == 0 ? 0 : Math.floor(Math.log(size) / Math.log(1024));
|
const i = size == 0 ? 0 : Math.floor(Math.log(size) / Math.log(1024))
|
||||||
return Number((size / Math.pow(1024, i)).toFixed(2)) * 1 + units[i];
|
return Number((size / Math.pow(1024, i)).toFixed(2)) * 1 + units[i]
|
||||||
};
|
}
|
||||||
|
|
||||||
export const capitalize = (str: string): string => {
|
export const capitalize = (str: string): string => {
|
||||||
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
|
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase()
|
||||||
};
|
}
|
||||||
|
|
||||||
export const convertSeconds = (seconds: number) => {
|
export const convertSeconds = (seconds: number) => {
|
||||||
// Calculate the number of seconds, minutes, hours, and days
|
// Calculate the number of seconds, minutes, hours, and days
|
||||||
let minutes = Math.floor(seconds / 60);
|
let minutes = Math.floor(seconds / 60)
|
||||||
let hours = Math.floor(minutes / 60);
|
let hours = Math.floor(minutes / 60)
|
||||||
let days = Math.floor(hours / 24);
|
const days = Math.floor(hours / 24)
|
||||||
|
|
||||||
// Calculate the remaining hours, minutes, and seconds
|
// Calculate the remaining hours, minutes, and seconds
|
||||||
hours = hours % 24;
|
hours = hours % 24
|
||||||
minutes = minutes % 60;
|
minutes = minutes % 60
|
||||||
seconds = seconds % 60;
|
seconds = seconds % 60
|
||||||
|
|
||||||
// Create the formatted string
|
// Create the formatted string
|
||||||
let result = '';
|
let result = ''
|
||||||
if (days > 0) {
|
if (days > 0) {
|
||||||
result += days + ' day' + (days > 1 ? 's' : '') + ' ';
|
result += days + ' day' + (days > 1 ? 's' : '') + ' '
|
||||||
}
|
}
|
||||||
if (hours > 0) {
|
if (hours > 0) {
|
||||||
result += hours + ' hour' + (hours > 1 ? 's' : '') + ' ';
|
result += hours + ' hour' + (hours > 1 ? 's' : '') + ' '
|
||||||
}
|
}
|
||||||
if (minutes > 0) {
|
if (minutes > 0) {
|
||||||
result += minutes + ' minute' + (minutes > 1 ? 's' : '') + ' ';
|
result += minutes + ' minute' + (minutes > 1 ? 's' : '') + ' '
|
||||||
}
|
}
|
||||||
result += seconds + ' second' + (seconds > 1 ? 's' : '');
|
result += seconds + ' second' + (seconds > 1 ? 's' : '')
|
||||||
|
|
||||||
return result;
|
return result
|
||||||
};
|
}
|
||||||
|
|
||||||
|
export const compareIp = (ip1: string, ip2: string) => {
|
||||||
|
const ip1Parts = ip1.split('.').map(Number)
|
||||||
|
const ip2Parts = ip2.split('.').map(Number)
|
||||||
|
for (let i = 0; i < 4; i++) {
|
||||||
|
if (ip1Parts[i] !== ip2Parts[i]) {
|
||||||
|
return ip1Parts[i] > ip2Parts[i] ? 1 : -1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,16 +1,16 @@
|
|||||||
import { writable } from 'svelte/store';
|
import { writable } from 'svelte/store'
|
||||||
import { browser } from '$app/environment';
|
import { browser } from '$app/environment'
|
||||||
|
|
||||||
export const persistentStore = <T>(key: string, initialValue: T) => {
|
export const persistentStore = <T>(key: string, initialValue: T) => {
|
||||||
const savedValue = browser ? localStorage.getItem(key) : null;
|
const savedValue = browser ? localStorage.getItem(key) : null
|
||||||
const data: T = savedValue !== null ? JSON.parse(savedValue) : initialValue;
|
const data: T = savedValue !== null ? JSON.parse(savedValue) : initialValue
|
||||||
const store = writable<T>();
|
const store = writable<T>()
|
||||||
|
|
||||||
store.subscribe(value => {
|
store.subscribe(value => {
|
||||||
if (browser) localStorage.setItem(key, JSON.stringify(value));
|
if (browser) localStorage.setItem(key, JSON.stringify(value))
|
||||||
});
|
})
|
||||||
|
|
||||||
store.set(data);
|
store.set(data)
|
||||||
|
|
||||||
return store;
|
return store
|
||||||
};
|
}
|
||||||
|
|||||||
@@ -1,15 +1,9 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { goto } from '$app/navigation';
|
import { page } from '$app/state'
|
||||||
import { onMount } from 'svelte';
|
import { resolve } from '$app/paths'
|
||||||
|
|
||||||
onMount(() => {
|
|
||||||
setTimeout(() => {
|
|
||||||
goto('/');
|
|
||||||
}, 3000);
|
|
||||||
});
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="flex justify-center items-center w-full h-full">
|
<div class="flex justify-center items-center w-full h-full">
|
||||||
<h1 class="text-4xl">404 - Page not found</h1>
|
<h1>{page.status} {page.error?.message}</h1>
|
||||||
<p>You will be redirected to the home page in 3 seconds</p>
|
<span>Go to <a class="btn btn-primary" href={resolve('/')}>Home page</a></span>
|
||||||
</div>
|
</div>
|
||||||
@@ -18,10 +18,13 @@
|
|||||||
servoAngles,
|
servoAngles,
|
||||||
servoAnglesOut,
|
servoAnglesOut,
|
||||||
socket,
|
socket,
|
||||||
location,
|
apiLocation,
|
||||||
useFeatureFlags
|
useFeatureFlags,
|
||||||
|
walkGait
|
||||||
} from '$lib/stores'
|
} from '$lib/stores'
|
||||||
import type { Analytics, DownloadOTA } from '$lib/types/models'
|
import { type Analytics, type DownloadOTA } from '$lib/types/models'
|
||||||
|
import { MessageTopic } from '$lib/types/models'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
children?: import('svelte').Snippet
|
children?: import('svelte').Snippet
|
||||||
}
|
}
|
||||||
@@ -31,15 +34,16 @@
|
|||||||
const features = useFeatureFlags()
|
const features = useFeatureFlags()
|
||||||
|
|
||||||
onMount(async () => {
|
onMount(async () => {
|
||||||
const ws = $location ? $location : window.location.host
|
const ws = $apiLocation ? $apiLocation : window.location.host
|
||||||
socket.init(`ws://${ws}/api/ws/events`)
|
socket.init(`ws://${ws}/api/ws`)
|
||||||
|
|
||||||
addEventListeners()
|
addEventListeners()
|
||||||
|
|
||||||
outControllerData.subscribe(data => socket.sendEvent('input', { data }))
|
outControllerData.subscribe(data => socket.sendEvent(MessageTopic.input, data))
|
||||||
mode.subscribe(data => socket.sendEvent('mode', { data }))
|
mode.subscribe(data => socket.sendEvent(MessageTopic.mode, data))
|
||||||
servoAnglesOut.subscribe(data => socket.sendEvent('angles', { data }))
|
walkGait.subscribe(data => socket.sendEvent(MessageTopic.gait, data))
|
||||||
kinematicData.subscribe(data => socket.sendEvent('position', { data }))
|
servoAnglesOut.subscribe(data => socket.sendEvent(MessageTopic.angles, data))
|
||||||
|
kinematicData.subscribe(data => socket.sendEvent(MessageTopic.position, data))
|
||||||
})
|
})
|
||||||
|
|
||||||
onDestroy(() => {
|
onDestroy(() => {
|
||||||
@@ -50,24 +54,24 @@
|
|||||||
socket.on('open', handleOpen)
|
socket.on('open', handleOpen)
|
||||||
socket.on('close', handleClose)
|
socket.on('close', handleClose)
|
||||||
socket.on('error', handleError)
|
socket.on('error', handleError)
|
||||||
socket.on('rssi', handleNetworkStatus)
|
socket.on(MessageTopic.rssi, handleNetworkStatus)
|
||||||
socket.on('mode', (data: ModesEnum) => mode.set(data))
|
socket.on(MessageTopic.mode, (data: ModesEnum) => mode.set(data))
|
||||||
socket.on('analytics', handleAnalytics)
|
socket.on(MessageTopic.analytics, handleAnalytics)
|
||||||
socket.on('angles', (angles: number[]) => {
|
socket.on(MessageTopic.angles, (angles: number[]) => {
|
||||||
if (angles.length) servoAngles.set(angles)
|
if (angles.length) servoAngles.set(angles)
|
||||||
})
|
})
|
||||||
features.subscribe(data => {
|
features.subscribe(data => {
|
||||||
if (data?.download_firmware) socket.on('otastatus', handleOAT)
|
if (data?.download_firmware) socket.on(MessageTopic.otastatus, handleOAT)
|
||||||
if (data?.sonar) socket.on('sonar', data => console.log(data))
|
if (data?.sonar) socket.on(MessageTopic.sonar, data => console.log(data))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const removeEventListeners = () => {
|
const removeEventListeners = () => {
|
||||||
socket.off('analytics', handleAnalytics)
|
socket.off(MessageTopic.analytics, handleAnalytics)
|
||||||
socket.off('open', handleOpen)
|
socket.off('open', handleOpen)
|
||||||
socket.off('close', handleClose)
|
socket.off('close', handleClose)
|
||||||
socket.off('rssi', handleNetworkStatus)
|
socket.off(MessageTopic.rssi, handleNetworkStatus)
|
||||||
socket.off('otastatus', handleOAT)
|
socket.off(MessageTopic.otastatus, handleOAT)
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleOpen = () => {
|
const handleOpen = () => {
|
||||||
@@ -79,7 +83,7 @@
|
|||||||
telemetry.setRSSI(0)
|
telemetry.setRSSI(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleError = (data: any) => console.error(data)
|
const handleError = (data: unknown) => console.error(data)
|
||||||
|
|
||||||
const handleAnalytics = (data: Analytics) => analytics.addData(data)
|
const handleAnalytics = (data: Analytics) => analytics.addData(data)
|
||||||
|
|
||||||
@@ -94,7 +98,7 @@
|
|||||||
<title>{page.data.title}</title>
|
<title>{page.data.title}</title>
|
||||||
</svelte:head>
|
</svelte:head>
|
||||||
|
|
||||||
<div class="drawer h-screen">
|
<div class="drawer">
|
||||||
<input id="main-menu" type="checkbox" class="drawer-toggle" bind:checked={menuOpen} />
|
<input id="main-menu" type="checkbox" class="drawer-toggle" bind:checked={menuOpen} />
|
||||||
<div class="drawer-content flex flex-col">
|
<div class="drawer-content flex flex-col">
|
||||||
<!-- Status bar content here -->
|
<!-- Status bar content here -->
|
||||||
@@ -111,14 +115,15 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Modals>
|
<Modals>
|
||||||
<!-- svelte-ignore a11y_click_events_have_key_events -->
|
|
||||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
|
||||||
{#snippet backdrop()}
|
{#snippet backdrop()}
|
||||||
<div
|
<div
|
||||||
class="fixed inset-0 z-40 max-h-full max-w-full bg-black/20 backdrop-blur-sm"
|
class="fixed inset-0 z-40 max-h-full max-w-full bg-black/20 backdrop-blur-sm"
|
||||||
transition:fade
|
transition:fade
|
||||||
onclick={modals.closeAll}>
|
onclick={modals.closeAll}
|
||||||
</div>
|
onkeydown={e => e.key === 'Escape' && modals.closeAll()}
|
||||||
|
role="button"
|
||||||
|
tabindex="0"
|
||||||
|
></div>
|
||||||
{/snippet}
|
{/snippet}
|
||||||
</Modals>
|
</Modals>
|
||||||
|
|
||||||
|
|||||||
+25
-13
@@ -1,22 +1,34 @@
|
|||||||
export const prerender = false;
|
export const prerender = true
|
||||||
export const ssr = false;
|
export const ssr = false
|
||||||
|
|
||||||
const registerFetchIntercept = async () => {
|
const registerFetchIntercept = async () => {
|
||||||
const { fetch: originalFetch } = window;
|
const { fetch: originalFetch } = window
|
||||||
const fileService = (await import('$lib/services/file-service')).default;
|
const fileService = (await import('$lib/services/file-service')).default
|
||||||
window.fetch = async (resource, config) => {
|
window.fetch = async (resource, config) => {
|
||||||
let url = resource instanceof Request ? resource.url : resource.toString();
|
const url = resource instanceof Request ? resource.url : resource.toString()
|
||||||
let file = await fileService.getFile(url);
|
|
||||||
return file.isOk() ? new Response(file.inner) : originalFetch(resource, config);
|
let file = await fileService?.getFile(url)
|
||||||
};
|
if (file?.isOk() && file.inner) return new Response(new Uint8Array(file.inner))
|
||||||
};
|
|
||||||
|
if (url.startsWith('http')) {
|
||||||
|
try {
|
||||||
|
const urlObj = new URL(url)
|
||||||
|
const pathOnly = urlObj.pathname
|
||||||
|
file = await fileService?.getFile(pathOnly)
|
||||||
|
if (file?.isOk() && file.inner) return new Response(new Uint8Array(file.inner))
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
|
||||||
|
return originalFetch(resource, config)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export const load = async () => {
|
export const load = async () => {
|
||||||
await registerFetchIntercept();
|
await registerFetchIntercept()
|
||||||
return {
|
return {
|
||||||
title: 'Spot micro controller',
|
title: 'Spot micro controller',
|
||||||
github: 'runeharlyk/SpotMicroESP32-Leika',
|
github: 'runeharlyk/SpotMicroESP32-Leika',
|
||||||
app_name: 'Spot Micro Controller',
|
app_name: 'Spot Micro Controller',
|
||||||
copyright: '2024 Rune Harlyk'
|
copyright: '2025 Rune Harlyk'
|
||||||
};
|
}
|
||||||
};
|
}
|
||||||
|
|||||||
@@ -3,25 +3,26 @@
|
|||||||
import Visualization from '$lib/components/Visualization.svelte'
|
import Visualization from '$lib/components/Visualization.svelte'
|
||||||
import { socket } from '$lib/stores'
|
import { socket } from '$lib/stores'
|
||||||
import { onMount } from 'svelte'
|
import { onMount } from 'svelte'
|
||||||
|
import { resolve } from '$app/paths'
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
socket.subscribe(isConnected => {
|
socket.subscribe(isConnected => {
|
||||||
if (isConnected) {
|
if (isConnected) {
|
||||||
goto('/controller')
|
goto(resolve('/controller'))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="w-full h-full flex justify-center items-center">
|
<div class="hero bg-base-100 h-screen">
|
||||||
<div class="h-full flex flex-col">
|
<div class="card md:card-side bg-base-200 shadow-2xl flex justify-center items-center">
|
||||||
<div class="grow-3 w-80 relative">
|
<div class="w-64 h-64">
|
||||||
<Visualization sky={false} orbit panel={false} ground={false} zoom={8} />
|
<Visualization sky={false} orbit panel={false} ground={false} />
|
||||||
<div class="absolute bottom-0 w-full h-40 bg-gradient-to-t from-base-100 to-transparent">
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
<div class="card-body w-80">
|
||||||
<div class="grow-3 flex justify-center">
|
<h2 class="card-title text-center text-2xl">Begin you journey</h2>
|
||||||
<a class="btn btn-primary rounded-full" href={$socket ? '/controller' : '/connection'}>
|
<p class="py-6 text-center"></p>
|
||||||
|
<a class="btn btn-primary" href={resolve($socket ? '/controller' : '/connection')}>
|
||||||
Add Robot Dog
|
Add Robot Dog
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import Connection from './Connection.svelte';
|
import Connection from './Connection.svelte'
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="mx-0 my-1 flex flex-col space-y-4 sm:mx-8 sm:my-8">
|
<div class="mx-0 my-1 flex flex-col space-y-4 sm:mx-8 sm:my-8">
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import type { PageLoad } from './$types';
|
import type { PageLoad } from './$types'
|
||||||
|
|
||||||
export const load = (async () => {
|
export const load = (async () => {
|
||||||
return {
|
return {
|
||||||
title: 'Connection'
|
title: 'Connection'
|
||||||
};
|
}
|
||||||
}) satisfies PageLoad;
|
}) satisfies PageLoad
|
||||||
|
|||||||
@@ -1,14 +1,12 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import SettingsCard from '$lib/components/SettingsCard.svelte';
|
import SettingsCard from '$lib/components/SettingsCard.svelte'
|
||||||
import { WiFi } from '$lib/components/icons';
|
import { WiFi } from '$lib/components/icons'
|
||||||
import { location, socket, useFeatureFlags } from '$lib/stores';
|
import { apiLocation, socket } from '$lib/stores'
|
||||||
|
|
||||||
const features = useFeatureFlags();
|
|
||||||
|
|
||||||
const update = () => {
|
const update = () => {
|
||||||
const ws = $location ? $location : window.location.host;
|
const ws = $apiLocation ? $apiLocation : window.location.host
|
||||||
socket.init(`ws://${ws}/api/ws/events`);
|
socket.init(`ws://${ws}/api/ws/events`)
|
||||||
};
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<SettingsCard collapsible={false}>
|
<SettingsCard collapsible={false}>
|
||||||
@@ -16,12 +14,12 @@
|
|||||||
<WiFi class="lex-shrink-0 mr-2 h-6 w-6 self-end" />
|
<WiFi class="lex-shrink-0 mr-2 h-6 w-6 self-end" />
|
||||||
{/snippet}
|
{/snippet}
|
||||||
{#snippet title()}
|
{#snippet title()}
|
||||||
<span >Connection</span>
|
<span>Connection</span>
|
||||||
{/snippet}
|
{/snippet}
|
||||||
|
|
||||||
<div class="flex">
|
<div class="flex">
|
||||||
<label class="label w-32" for="server">Address:</label>
|
<label class="label w-32" for="server">Address:</label>
|
||||||
<input class="input" bind:value={$location} />
|
<input class="input" bind:value={$apiLocation} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<button class="btn btn-primary" onclick={update}>Update</button>
|
<button class="btn btn-primary" onclick={update}>Update</button>
|
||||||
|
|||||||
@@ -1,26 +1,26 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import Controls from './Controls.svelte';
|
import Controls from './Controls.svelte'
|
||||||
import WidgetContainer from '$lib/components/layout/WidgetContainer.svelte';
|
import WidgetContainer from '$lib/components/layout/WidgetContainer.svelte'
|
||||||
import { selectedView, views } from '$lib/stores/application';
|
import { selectedView, views } from '$lib/stores/application'
|
||||||
import { onMount } from 'svelte';
|
import { onMount } from 'svelte'
|
||||||
import { mpu, socket } from '$lib/stores';
|
import { mpu, socket } from '$lib/stores'
|
||||||
import { imu } from '$lib/stores/imu';
|
import { imu } from '$lib/stores/imu'
|
||||||
import type { IMU } from '$lib/types/models';
|
import { MessageTopic, type IMU } from '$lib/types/models'
|
||||||
|
|
||||||
let layout = $derived($views.find(v => v.name === $selectedView)!);
|
let layout = $derived($views.find(v => v.name === $selectedView)!)
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
socket.on('imu', (data: IMU) => {
|
socket.on(MessageTopic.imu, (data: IMU) => {
|
||||||
imu.addData(data);
|
imu.addData(data)
|
||||||
if (data.heading)
|
if (data.heading)
|
||||||
mpu.update(mpuData => {
|
mpu.update(mpuData => {
|
||||||
mpuData.heading = data.heading;
|
mpuData.heading = data.heading
|
||||||
console.log(data.heading);
|
console.log(data.heading)
|
||||||
|
|
||||||
return mpuData;
|
return mpuData
|
||||||
});
|
})
|
||||||
});
|
})
|
||||||
});
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="absolute top-0 select-none w-screen h-screen">
|
<div class="absolute top-0 select-none w-screen h-screen">
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
export const load = async () => {
|
export const load = async () => {
|
||||||
return { title: 'Controller' };
|
return { title: 'Controller' }
|
||||||
};
|
}
|
||||||
|
|||||||
@@ -1,17 +1,60 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import nipplejs from 'nipplejs'
|
import nipplejs from 'nipplejs'
|
||||||
import { onMount } from 'svelte'
|
import { onMount } from 'svelte'
|
||||||
import { capitalize, throttler, toInt8 } from '$lib/utilities'
|
import { capitalize, throttler } from '$lib/utilities'
|
||||||
import { input, outControllerData, mode, modes, type Modes, ModesEnum } from '$lib/stores'
|
import {
|
||||||
|
input,
|
||||||
|
outControllerData,
|
||||||
|
mode,
|
||||||
|
modes,
|
||||||
|
type Modes,
|
||||||
|
ModesEnum,
|
||||||
|
WalkGaits,
|
||||||
|
walkGait,
|
||||||
|
walkGaitLabels
|
||||||
|
} from '$lib/stores'
|
||||||
import type { vector } from '$lib/types/models'
|
import type { vector } from '$lib/types/models'
|
||||||
import { VerticalSlider } from '$lib/components/input'
|
import { VerticalSlider } from '$lib/components/input'
|
||||||
|
import { gamepadAxes, gamepadButtonsEdges, hasGamepad } from '$lib/stores/gamepad'
|
||||||
|
import { notifications } from '$lib/components/toasts/notifications'
|
||||||
|
|
||||||
let throttle = new throttler()
|
let throttle = new throttler()
|
||||||
let left: nipplejs.JoystickManager
|
let left: nipplejs.JoystickManager
|
||||||
let right: nipplejs.JoystickManager
|
let right: nipplejs.JoystickManager
|
||||||
|
|
||||||
let throttle_timing = 40
|
let throttle_timing = 40
|
||||||
let data = new Array(8)
|
let data = new Array(7)
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
if ($hasGamepad) {
|
||||||
|
notifications.success('🎮 Gamepad connected', 3000)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
handleJoyMove('left', { x: $gamepadAxes[0], y: -$gamepadAxes[1] })
|
||||||
|
handleJoyMove('right', { x: $gamepadAxes[2], y: $gamepadAxes[3] })
|
||||||
|
})
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
if (!$hasGamepad) return
|
||||||
|
const b = $gamepadButtonsEdges
|
||||||
|
if (!b.length) return
|
||||||
|
if (b[0]?.justPressed) mode.set(5)
|
||||||
|
if (b[1]?.justPressed) mode.set(4)
|
||||||
|
if (b[2]?.justPressed) mode.set(3)
|
||||||
|
if (b[3]?.justPressed) mode.set(0)
|
||||||
|
if (b[12]?.justPressed)
|
||||||
|
input.update(inputData => {
|
||||||
|
inputData['height'] = Math.min(inputData.height + 0.1, 1)
|
||||||
|
return inputData
|
||||||
|
})
|
||||||
|
if (b[13]?.justPressed)
|
||||||
|
input.update(inputData => {
|
||||||
|
inputData['height'] = Math.min(inputData.height - 0.1, 1)
|
||||||
|
return inputData
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
left = nipplejs.create({
|
left = nipplejs.create({
|
||||||
@@ -31,9 +74,9 @@
|
|||||||
})
|
})
|
||||||
|
|
||||||
left.on('move', (_, data) => handleJoyMove('left', data.vector))
|
left.on('move', (_, data) => handleJoyMove('left', data.vector))
|
||||||
left.on('end', (_, __) => handleJoyMove('left', { x: 0, y: 0 }))
|
left.on('end', () => handleJoyMove('left', { x: 0, y: 0 }))
|
||||||
right.on('move', (_, data) => handleJoyMove('right', data.vector))
|
right.on('move', (_, data) => handleJoyMove('right', data.vector))
|
||||||
right.on('end', (_, __) => handleJoyMove('right', { x: 0, y: 0 }))
|
right.on('end', () => handleJoyMove('right', { x: 0, y: 0 }))
|
||||||
})
|
})
|
||||||
|
|
||||||
const handleJoyMove = (key: 'left' | 'right', data: vector) => {
|
const handleJoyMove = (key: 'left' | 'right', data: vector) => {
|
||||||
@@ -45,14 +88,13 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
const updateData = () => {
|
const updateData = () => {
|
||||||
data[0] = 0
|
data[0] = $input.left.x
|
||||||
data[1] = toInt8($input.left.x, -1, 1)
|
data[1] = $input.left.y
|
||||||
data[2] = toInt8($input.left.y, -1, 1)
|
data[2] = $input.right.x
|
||||||
data[3] = toInt8($input.right.x, -1, 1)
|
data[3] = $input.right.y
|
||||||
data[4] = toInt8($input.right.y, -1, 1)
|
data[4] = $input.height
|
||||||
data[5] = toInt8($input.height, 0, 100)
|
data[5] = $input.speed
|
||||||
data[6] = toInt8($input.speed, 0, 100)
|
data[6] = $input.s1
|
||||||
data[7] = toInt8($input.s1, 0, 100)
|
|
||||||
|
|
||||||
outControllerData.set(data)
|
outControllerData.set(data)
|
||||||
}
|
}
|
||||||
@@ -61,16 +103,18 @@
|
|||||||
const down = event.type === 'keydown'
|
const down = event.type === 'keydown'
|
||||||
input.update(data => {
|
input.update(data => {
|
||||||
if (event.key === 'w') data.left.y = down ? 1 : 0
|
if (event.key === 'w') data.left.y = down ? 1 : 0
|
||||||
if (event.key === 'a') data.left.x = down ? 1 : 0
|
if (event.key === 'a') data.left.x = down ? -1 : 0
|
||||||
if (event.key === 's') data.left.y = down ? -1 : 0
|
if (event.key === 's') data.left.y = down ? -1 : 0
|
||||||
if (event.key === 'd') data.left.x = down ? -1 : 0
|
if (event.key === 'd') data.left.x = down ? 1 : 0
|
||||||
|
if (event.key === 'ArrowLeft') data.right.x = down ? 1 : 0
|
||||||
|
if (event.key === 'ArrowRight') data.right.x = down ? -1 : 0
|
||||||
return data
|
return data
|
||||||
})
|
})
|
||||||
throttle.throttle(updateData, throttle_timing)
|
throttle.throttle(updateData, throttle_timing)
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleRange = (event: Event, key: 'speed' | 'height' | 's1') => {
|
const handleRange = (event: Event, key: 'speed' | 'height' | 's1') => {
|
||||||
const value: number = event.target?.value
|
const value: number = Number((event.target as HTMLInputElement).value)
|
||||||
|
|
||||||
input.update(inputData => {
|
input.update(inputData => {
|
||||||
inputData[key] = value
|
inputData[key] = value
|
||||||
@@ -82,6 +126,10 @@
|
|||||||
const changeMode = (modeValue: Modes) => {
|
const changeMode = (modeValue: Modes) => {
|
||||||
mode.set(modes.indexOf(modeValue))
|
mode.set(modes.indexOf(modeValue))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const changeWalkGait = (walkGaitValue: WalkGaits) => {
|
||||||
|
walkGait.set(walkGaitValue)
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="absolute top-0 left-0 w-screen h-screen">
|
<div class="absolute top-0 left-0 w-screen h-screen">
|
||||||
@@ -102,24 +150,47 @@
|
|||||||
<div class="flex justify-center w-full"></div>
|
<div class="flex justify-center w-full"></div>
|
||||||
</div>
|
</div>
|
||||||
<div class="absolute bottom-0 z-10 flex items-end">
|
<div class="absolute bottom-0 z-10 flex items-end">
|
||||||
<div class="flex items-center flex-col bg-base-300 bg-opacity-50 p-3 pb-2 gap-2 rounded-tr-xl">
|
<div
|
||||||
<VerticalSlider min={0} max={100} oninput={(e: Event) => handleRange(e, 'height')} />
|
class="flex items-center flex-col bg-base-300 bg-opacity-50 p-3 pb-2 gap-2 rounded-tr-xl"
|
||||||
|
>
|
||||||
|
<VerticalSlider
|
||||||
|
min={0}
|
||||||
|
max={1}
|
||||||
|
step={0.01}
|
||||||
|
oninput={(e: Event) => handleRange(e, 'height')}
|
||||||
|
/>
|
||||||
<label for="height">Ht</label>
|
<label for="height">Ht</label>
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
class="flex items-end gap-4 bg-base-300 bg-opacity-50 h-min rounded-tr-xl pl-0 p-3 portrait:hidden">
|
class="flex items-end gap-4 bg-base-300 bg-opacity-50 h-min rounded-tr-xl pl-0 p-3 portrait:hidden"
|
||||||
|
>
|
||||||
<div class="join">
|
<div class="join">
|
||||||
{#each modes as modeValue}
|
{#each modes as modeValue}
|
||||||
<button
|
<button
|
||||||
class="btn join-item"
|
class="btn join-item"
|
||||||
class:btn-primary={$mode === modes.indexOf(modeValue)}
|
class:btn-primary={$mode === modes.indexOf(modeValue)}
|
||||||
onclick={() => changeMode(modeValue)}>
|
onclick={() => changeMode(modeValue)}
|
||||||
|
>
|
||||||
{capitalize(modeValue)}
|
{capitalize(modeValue)}
|
||||||
</button>
|
</button>
|
||||||
{/each}
|
{/each}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{#if $mode === ModesEnum.Walk || $mode === ModesEnum.Crawl}
|
{#if $mode === ModesEnum.Walk}
|
||||||
|
<div class="join">
|
||||||
|
{#each Object.values(WalkGaits) as gaitValue}
|
||||||
|
{#if typeof gaitValue === 'number'}
|
||||||
|
<button
|
||||||
|
class="btn join-item btn-sm"
|
||||||
|
class:btn-secondary={$walkGait === gaitValue}
|
||||||
|
onclick={() => changeWalkGait(gaitValue)}
|
||||||
|
>
|
||||||
|
{walkGaitLabels[gaitValue]}
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="flex gap-4">
|
<div class="flex gap-4">
|
||||||
<div>
|
<div>
|
||||||
<label for="s1">S1</label>
|
<label for="s1">S1</label>
|
||||||
@@ -127,9 +198,11 @@
|
|||||||
type="range"
|
type="range"
|
||||||
name="s1"
|
name="s1"
|
||||||
min="0"
|
min="0"
|
||||||
max="100"
|
step="0.01"
|
||||||
|
max="1"
|
||||||
oninput={e => handleRange(e, 's1')}
|
oninput={e => handleRange(e, 's1')}
|
||||||
class="range range-sm range-primary" />
|
class="range range-sm range-primary"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<label for="speed">Speed</label>
|
<label for="speed">Speed</label>
|
||||||
@@ -137,9 +210,11 @@
|
|||||||
type="range"
|
type="range"
|
||||||
name="speed"
|
name="speed"
|
||||||
min="0"
|
min="0"
|
||||||
max="100"
|
step="0.01"
|
||||||
|
max="1"
|
||||||
oninput={e => handleRange(e, 'speed')}
|
oninput={e => handleRange(e, 'speed')}
|
||||||
class="range range-sm range-primary" />
|
class="range range-sm range-primary"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import type { PageLoad } from './$types';
|
import type { PageLoad } from './$types'
|
||||||
import { goto } from '$app/navigation';
|
import { goto } from '$app/navigation'
|
||||||
|
import { resolve } from '$app/paths'
|
||||||
|
|
||||||
export const load = (async () => {
|
export const load = (async () => {
|
||||||
goto('/');
|
goto(resolve('/'))
|
||||||
return;
|
return
|
||||||
}) satisfies PageLoad;
|
}) satisfies PageLoad
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import Camera from './Camera.svelte';
|
import Camera from './Camera.svelte'
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="mx-0 my-1 flex flex-col space-y-4 sm:mx-8 sm:my-8">
|
<div class="mx-0 my-1 flex flex-col space-y-4 sm:mx-8 sm:my-8">
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import type { PageLoad } from './$types';
|
import type { PageLoad } from './$types'
|
||||||
|
|
||||||
export const load = (async () => {
|
export const load = (async () => {
|
||||||
return {
|
return {
|
||||||
title: 'Camera'
|
title: 'Camera'
|
||||||
};
|
}
|
||||||
}) satisfies PageLoad;
|
}) satisfies PageLoad
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user