Initial webpage and backend

This commit is contained in:
2026-03-17 12:33:12 +01:00
parent 9010bac9a0
commit 28b120b88e
39 changed files with 153532 additions and 4 deletions

5
.gitignore vendored
View File

@@ -2,3 +2,8 @@
build
install
log
node_modules
dist
__pycache__

View File

@@ -25,9 +25,9 @@ source install/setup.bash
case $TARGET in
"na")
ros2 action send_goal /moveCoords toid_msgs/action/SimpleMoveCoords "
x: 0.0
y: 0.0
theta: 0.0
x: 1.325
y: 0.045
theta: -1.57079632679489661922
backwards: ${SMER:-0}"
;;
"pravo")

View File

@@ -33,9 +33,24 @@ def generate_launch_description():
parameters=[bt_params],
)
rosbridge_ws = Node(
package='rosbridge_server',
executable='rosbridge_websocket',
output='screen',
arguments=["--port", "3000"],
)
tf2_web_publisher = Node(
package='tf2_web_republisher',
executable='tf2_web_republisher_node',
output='screen'
)
return LaunchDescription([
visualize_arg,
use_mock_arg,
bt_executor,
rosbridge_ws,
tf2_web_publisher,
])

View File

@@ -21,6 +21,9 @@
<depend>toid_msgs</depend>
<depend>std_msgs</depend>
<depend>std_srvs</depend>
<depend>rosbridge_suite</depend>
<depend>tf2_web_republisher</depend>
<depend>tf2_web_republisher_interfaces</depend>
<test_depend>ament_lint_auto</test_depend>
<test_depend>ament_lint_common</test_depend>

16
toid_cli/package.xml Normal file
View File

@@ -0,0 +1,16 @@
<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>toid_cli</name>
<version>0.0.0</version>
<description>TODO: Package description</description>
<maintainer email="82343504+pimpest@users.noreply.github.com">petar</maintainer>
<license>MIT</license>
<depend>python3-fastapi</depend>
<depend>python3-pydantic</depend>
<export>
<build_type>ament_python</build_type>
</export>
</package>

View File

4
toid_cli/setup.cfg.old Normal file
View File

@@ -0,0 +1,4 @@
[develop]
script_dir=$base/lib/toid_cli
[install]
install_scripts=$base/lib/toid_cli

25
toid_cli/setup.py Normal file
View File

@@ -0,0 +1,25 @@
from setuptools import find_packages, setup
package_name = 'toid_cli'
setup(
name=package_name,
version='0.0.0',
packages=find_packages(exclude=['test']),
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
],
install_requires=['setuptools'],
zip_safe=True,
maintainer='pimpest',
maintainer_email='82343504+pimpest@users.noreply.github.com',
description='TODO: Package description',
license='MIT',
entry_points={
'console_scripts': [
'toid_cli = toid_cli.main:main'
],
},
)

View File

108
toid_cli/toid_cli/main.py Normal file
View File

@@ -0,0 +1,108 @@
import subprocess
import uuid
import os
import signal
from fastapi import FastAPI
from pydantic import BaseModel
import uvicorn
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=[
"*"
],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# store running launch processes
launch_processes = {}
class LaunchRequest(BaseModel):
package: str
launch_file: str
args: dict = {}
@app.post("/launch/start")
def start_launch(req: LaunchRequest):
launch_id = str(uuid.uuid4())
cmd = ["ros2", "launch", req.package, req.launch_file]
for k, v in req.args.items():
cmd.append(f"{k}:={v}")
log_dir = "log"
os.makedirs(log_dir, exist_ok=True)
stdout_file = open(f"{log_dir}/{launch_id}_stdout.log", "w")
stderr_file = open(f"{log_dir}/{launch_id}_stderr.log", "w")
proc = subprocess.Popen(
cmd,
stdout=stdout_file,
stderr=stderr_file,
preexec_fn=os.setsid
)
launch_processes[launch_id] = proc
return {
"launch_id": launch_id,
"pid": proc.pid,
"command": " ".join(cmd)
}
@app.get("/launch/list")
def list_launches():
running = {}
for lid, proc in launch_processes.items():
running[lid] = {
"pid": proc.pid,
"running": proc.poll() is None
}
return running
@app.post("/launch/stop/{launch_id}")
def stop_launch(launch_id: str):
if launch_id not in launch_processes:
return {"error": "launch id not found"}
proc = launch_processes[launch_id]
if proc.poll() is None:
os.killpg(os.getpgid(proc.pid), signal.SIGTERM)
return {"stopped": launch_id}
@app.post("/launch/stop_all")
def stop_all():
for proc in launch_processes.values():
if proc.poll() is None:
os.killpg(os.getpgid(proc.pid), signal.SIGTERM)
return {"status": "all stopped"}
def main():
uvicorn.run(
"toid_cli.main:app",
host="0.0.0.0",
port=8000,
reload=False
)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,8 @@
[*.{js,jsx,mjs,cjs,ts,tsx,mts,cts,vue,css,scss,sass,less,styl}]
charset = utf-8
indent_size = 2
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
end_of_line = lf
max_line_length = 100

1
toid_frontend/.gitattributes vendored Normal file
View File

@@ -0,0 +1 @@
* text=auto eol=lf

39
toid_frontend/.gitignore vendored Normal file
View File

@@ -0,0 +1,39 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
.DS_Store
dist
dist-ssr
coverage
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
*.tsbuildinfo
.eslintcache
# Cypress
/cypress/videos/
/cypress/screenshots/
# Vitest
__screenshots__/
# Vite
*.timestamp-*-*.mjs

View File

@@ -0,0 +1,10 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["eslint", "typescript", "unicorn", "oxc", "vue"],
"env": {
"browser": true
},
"categories": {
"correctness": "error"
}
}

View File

@@ -0,0 +1,6 @@
{
"$schema": "https://json.schemastore.org/prettierrc",
"semi": false,
"singleQuote": true,
"printWidth": 100
}

9
toid_frontend/.vscode/extensions.json vendored Normal file
View File

@@ -0,0 +1,9 @@
{
"recommendations": [
"Vue.volar",
"dbaeumer.vscode-eslint",
"EditorConfig.EditorConfig",
"oxc.oxc-vscode",
"esbenp.prettier-vscode"
]
}

View File

48
toid_frontend/README.md Normal file
View File

@@ -0,0 +1,48 @@
# .
This template should help get you started developing with Vue 3 in Vite.
## Recommended IDE Setup
[VS Code](https://code.visualstudio.com/) + [Vue (Official)](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur).
## Recommended Browser Setup
- Chromium-based browsers (Chrome, Edge, Brave, etc.):
- [Vue.js devtools](https://chromewebstore.google.com/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd)
- [Turn on Custom Object Formatter in Chrome DevTools](http://bit.ly/object-formatters)
- Firefox:
- [Vue.js devtools](https://addons.mozilla.org/en-US/firefox/addon/vue-js-devtools/)
- [Turn on Custom Object Formatter in Firefox DevTools](https://fxdx.dev/firefox-devtools-custom-object-formatters/)
## Type Support for `.vue` Imports in TS
TypeScript cannot handle type information for `.vue` imports by default, so we replace the `tsc` CLI with `vue-tsc` for type checking. In editors, we need [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) to make the TypeScript language service aware of `.vue` types.
## Customize configuration
See [Vite Configuration Reference](https://vite.dev/config/).
## Project Setup
```sh
npm install
```
### Compile and Hot-Reload for Development
```sh
npm run dev
```
### Type-Check, Compile and Minify for Production
```sh
npm run build
```
### Lint with [ESLint](https://eslint.org/)
```sh
npm run lint
```

1
toid_frontend/env.d.ts vendored Normal file
View File

@@ -0,0 +1 @@
/// <reference types="vite/client" />

View File

@@ -0,0 +1,26 @@
import { globalIgnores } from 'eslint/config'
import { defineConfigWithVueTs, vueTsConfigs } from '@vue/eslint-config-typescript'
import pluginVue from 'eslint-plugin-vue'
import pluginOxlint from 'eslint-plugin-oxlint'
import skipFormatting from 'eslint-config-prettier/flat'
// To allow more languages other than `ts` in `.vue` files, uncomment the following lines:
// import { configureVueProject } from '@vue/eslint-config-typescript'
// configureVueProject({ scriptLangs: ['ts', 'tsx'] })
// More info at https://github.com/vuejs/eslint-config-typescript/#advanced-setup
export default defineConfigWithVueTs(
{
name: 'app/files-to-lint',
files: ['**/*.{vue,ts,mts,tsx}'],
},
globalIgnores(['**/dist/**', '**/dist-ssr/**', '**/coverage/**']),
...pluginVue.configs['flat/essential'],
vueTsConfigs.recommended,
...pluginOxlint.buildFromOxlintConfigFile('.oxlintrc.json'),
skipFormatting,
)

13
toid_frontend/index.html Normal file
View File

@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="UTF-8">
<link rel="icon" href="/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vite App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

5990
toid_frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,48 @@
{
"name": "toid_frontend",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "run-p type-check \"build-only {@}\" --",
"preview": "vite preview",
"build-only": "vite build",
"type-check": "vue-tsc --build",
"lint": "run-s lint:*",
"lint:oxlint": "oxlint . --fix",
"lint:eslint": "eslint . --fix --cache",
"format": "prettier --write --experimental-cli src/"
},
"dependencies": {
"bootstrap": "^5.3.8",
"pinia": "^3.0.4",
"pixi-viewport": "^6.0.3",
"roslib": "^2.1.0",
"sass-embedded": "^1.97.3",
"vue": "^3.5.29",
"vue-router": "^5.0.3"
},
"devDependencies": {
"@tsconfig/node24": "^24.0.4",
"@types/node": "^24.11.0",
"@vitejs/plugin-vue": "^6.0.4",
"@vue/eslint-config-typescript": "^14.7.0",
"@vue/tsconfig": "^0.8.1",
"eslint": "^10.0.2",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-oxlint": "~1.50.0",
"eslint-plugin-vue": "~10.8.0",
"jiti": "^2.6.1",
"npm-run-all2": "^8.0.4",
"oxlint": "~1.50.0",
"prettier": "3.8.1",
"typescript": "~5.9.3",
"vite": "^7.3.1",
"vite-plugin-vue-devtools": "^8.0.6",
"vue-tsc": "^3.2.5"
},
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

57
toid_frontend/src/App.vue Normal file
View File

@@ -0,0 +1,57 @@
<script setup lang="ts">
import RobotViewport from './components/RobotViewport.vue'
</script>
<template>
<div class="container">
<div class="row-container">
<div class="box box1"></div>
<div class="box box2">
<RobotViewport />
</div>
<div class="box box3"></div>
</div>
</div>
</template>
<style scoped>
.container {
display: flex;
justify-content: stretch;
align-items: start;
width: 100vw;
height: calc(100vh - 1.5rem);
padding-top: 1.5rem;
}
.row-container {
width: 100vw;
max-height: 100%;
flex-shrink: 1;
display: flex;
margin: 0;
padding: 0;
justify-content: center;
flex-direction: row;
}
.box1 {
background-color: pink;
width: 3.5rem;
}
.box2 {
background-color: lightblue;
aspect-ratio: 3/2;
max-width: calc(150vh - 13.5rem);
max-height: calc((100vw - 13.5) * 2 / 3);
flex-grow: 2;
}
.box3 {
flex-grow: 1;
min-width: 10rem;
max-width: 20rem;
background-color: darkblue;
}
</style>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 MiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 17 MiB

View File

@@ -0,0 +1,9 @@
//@import 'bootstrap/scss/bootstrap';
body,
#app {
margin: 0;
min-height: 100vh;
max-width: 100vw;
background-color: #242130;
}

View File

@@ -0,0 +1,7 @@
<script lang="ts"></script>
<template>
<div>Banner</div>
</template>
<style scoped></style>

View File

@@ -0,0 +1,116 @@
<script setup lang="ts">
import * as PIXI from 'pixi.js'
import { Viewport } from 'pixi-viewport'
import { onMounted, onBeforeUnmount, ref } from 'vue'
import tableSvg from '@/assets/images/table.png'
const viewportArea = ref<HTMLDivElement | null>(null)
let app: PIXI.Application | null = null
let viewport: Viewport | null = null
let resizeObserver: ResizeObserver | null = null
onMounted(async () => {
if (!viewportArea.value) return
app = new PIXI.Application()
// 1. Initialize with resizeTo
await app.init({
resizeTo: viewportArea.value,
antialias: true,
backgroundColor: 0x222222,
roundPixels: true,
resolution: window.devicePixelRatio * 2,
autoDensity: true,
})
viewportArea.value.appendChild(app.canvas)
// 2. Create Viewport
viewport = new Viewport({
screenWidth: viewportArea.value.clientWidth,
screenHeight: viewportArea.value.clientHeight,
worldWidth: 3000,
worldHeight: 2000,
events: app.renderer.events,
})
app.stage.addChild(viewport)
// 3. Configure Behaviors & Clamping
viewport
.drag()
.pinch()
.wheel()
.decelerate({
friction: 0.95,
})
.clamp({ direction: 'all' }) // Don't let user pan outside 1000x1000
.clampZoom({
maxHeight: 2000, // Max zoom out (show whole world)
minWidth: 500, // Max zoom in (detail)
})
// Add visual markers
setupScene(viewport)
// 4. Handle Dynamic Resizing
resizeObserver = new ResizeObserver(() => {
if (viewport && viewportArea.value) {
const { clientWidth, clientHeight } = viewportArea.value
// Tell the viewport the "window" size changed
viewport.resize(clientWidth, clientHeight)
viewport.fitWorld()
}
})
resizeObserver.observe(viewportArea.value)
viewportArea.value.addEventListener(
'wheel',
(e) => {
e.preventDefault()
},
{ passive: false },
)
})
async function setupScene(v: Viewport) {
// Border
const svgTexture = await PIXI.Assets.load({
src: tableSvg,
data: {},
})
const background = new PIXI.Sprite({
texture: svgTexture,
width: v.worldWidth,
height: v.worldHeight,
})
v.addChild(background)
// Center Sprite
const sprite = v.addChild(new PIXI.Sprite(PIXI.Texture.WHITE))
sprite.tint = 0xff0000
sprite.setSize(100, 100)
sprite.position.set(450, 450)
}
onBeforeUnmount(() => {
resizeObserver?.disconnect()
app?.destroy(true, { children: true, texture: true })
})
</script>
<template>
<div class="viewport-wrapper" ref="viewportArea"></div>
</template>
<style scoped>
.viewport-wrapper {
overflow: hidden;
height: 100%;
aspect-ratio: 3/2;
}
</style>

36
toid_frontend/src/main.ts Normal file
View File

@@ -0,0 +1,36 @@
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
import { ros } from './ros_client'
import '@/assets/scss/global.scss'
const app = createApp(App)
app.use(createPinia())
app.use(router)
app.mount('#app')
ros.connect('http://localhost:3000')
ros.on('error', (error) => {
console.log(error)
setTimeout(() => {
ros.connect('http://localhost:3000').catch()
}, 1000)
})
ros.on('close', () => {
setTimeout(() => {
if (!ros.isConnected) {
ros.connect('http://localhost:3000').catch()
}
}, 1000)
})
ros.on('connection', () => {
console.log('Connection made!')
})

View File

@@ -0,0 +1,9 @@
import * as ROSLIB from 'roslib'
interface BehaviorTreeList {
tree_ids: Array<string>
}
const ros = new ROSLIB.Ros()
export { ros, type BehaviorTreeList }

View File

@@ -0,0 +1,8 @@
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [],
})
export default router

View File

@@ -0,0 +1,12 @@
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
return { count, doubleCount, increment }
})

View File

@@ -0,0 +1,123 @@
/**
* Utility functions to replicate NumPy behavior
*/
const clip = (val: number, min: number, max: number): number => Math.min(Math.max(val, min), max)
const wrapToPi = (angle: number): number => Math.atan2(Math.sin(angle), Math.cos(angle))
/**
* Calculates egocentric polar coordinates relative to a target
*/
const egocentricPolar = (
target: [number, number, number],
current: [number, number, number],
backward: boolean = false,
): [number, number, number] => {
const [tx, ty, tyaw] = target
const [x, y, yaw] = current
const dx = tx - x
const dy = ty - y
const r = Math.hypot(dx, dy)
// Inverting dy for atan2 to match Python logic
let los = Math.atan2(-dy, dx)
if (backward) los += Math.PI
const phi = wrapToPi(tyaw + los)
const delta = wrapToPi(yaw + los)
return [r, phi, delta]
}
class SmoothControlLaw {
// Controller gains and constraints
public k_phi: number
public k_delta: number
public beta: number
public lam: number
public slowdown_radius: number
public v_linear_min: number
public v_linear_max: number
public v_angular_max: number
constructor(
k_phi: number = 3.0,
k_delta: number = 3.0,
beta: number = 0.3,
lam: number = 1.0,
slowdown_radius: number = 0.1,
v_linear_min: number = 0.1,
v_linear_max: number = 0.2,
v_angular_max: number = 2.0,
) {
this.k_phi = k_phi
this.k_delta = k_delta
this.beta = beta
this.lam = lam
this.slowdown_radius = slowdown_radius
this.v_linear_min = v_linear_min
this.v_linear_max = v_linear_max
this.v_angular_max = v_angular_max
}
public curvature(r: number, phi: number, delta: number): number {
if (r < 1e-6) return 0.0
const prop = this.k_delta * (delta - Math.atan(-this.k_phi * phi))
const feedback = (1 + this.k_phi / (1 + Math.pow(this.k_phi * phi, 2))) * Math.sin(delta)
return (-1.0 / r) * (prop + feedback)
}
public velocity(
target: [number, number, number],
current: [number, number, number],
backward: boolean = false,
): { v: number; w: number; kappa: number } {
const [r, phi, delta] = egocentricPolar(target, current, backward)
let kappa = this.curvature(r, phi, delta)
if (backward) kappa = -kappa
// Calculate linear velocity based on curvature
let v = this.v_linear_max / (1 + this.beta * Math.pow(Math.abs(kappa), this.lam))
// Slow down as we approach target
v = Math.min(this.v_linear_max * (r / this.slowdown_radius), v)
v = clip(v, this.v_linear_min, this.v_linear_max)
if (backward) v = -v
// Calculate angular velocity
let w = kappa * v
w = clip(w, -this.v_angular_max, this.v_angular_max)
// Adjust v if w was clipped to maintain the path curvature
if (Math.abs(kappa) > 1e-6) {
v = w / kappa
}
return { v, w, kappa }
}
public step(
target: [number, number, number],
current: [number, number, number],
dt: number,
backward: boolean = false,
): [[number, number, number], number, number] {
const { v, w } = this.velocity(target, current, backward)
let [x, y, yaw] = current
x += v * dt * Math.cos(yaw)
y += v * dt * Math.sin(yaw)
yaw += w * dt
return [[x, y, yaw], v, w]
}
}
export { SmoothControlLaw }

View File

@@ -0,0 +1,18 @@
{
"extends": "@vue/tsconfig/tsconfig.dom.json",
"include": ["env.d.ts", "src/**/*", "src/**/*.vue"],
"exclude": ["src/**/__tests__/*"],
"compilerOptions": {
// Extra safety for array and object lookups, but may have false positives.
"noUncheckedIndexedAccess": true,
// Path mapping for cleaner imports.
"paths": {
"@/*": ["./src/*"]
},
// `vue-tsc --build` produces a .tsbuildinfo file for incremental type-checking.
// Specified here to keep it out of the root directory.
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo"
}
}

View File

@@ -0,0 +1,11 @@
{
"files": [],
"references": [
{
"path": "./tsconfig.node.json"
},
{
"path": "./tsconfig.app.json"
}
]
}

View File

@@ -0,0 +1,28 @@
// TSConfig for modules that run in Node.js environment via either transpilation or type-stripping.
{
"extends": "@tsconfig/node24/tsconfig.json",
"include": [
"vite.config.*",
"vitest.config.*",
"cypress.config.*",
"nightwatch.conf.*",
"playwright.config.*",
"eslint.config.*"
],
"compilerOptions": {
// Most tools use transpilation instead of Node.js's native type-stripping.
// Bundler mode provides a smoother developer experience.
"module": "preserve",
"moduleResolution": "bundler",
// Include Node.js types and avoid accidentally including other `@types/*` packages.
"types": ["node"],
// Disable emitting output during `vue-tsc --build`, which is used for type-checking only.
"noEmit": true,
// `vue-tsc --build` produces a .tsbuildinfo file for incremental type-checking.
// Specified here to keep it out of the root directory.
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo"
}
}

View File

@@ -0,0 +1,18 @@
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'
// https://vite.dev/config/
export default defineConfig({
plugins: [
vue(),
vueDevTools(),
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
},
},
})