From 24bbaefb00d311ca4388caf5876a258bee1bcd46 Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Fri, 25 Sep 2026 16:37:20 +0300 Subject: [PATCH 1/7] chore(repo): keep private evidence local and version rover assets with LFS --- .gitattributes | 1 + .gitignore | 7 +++++++ 2 files changed, 8 insertions(+) diff --git a/.gitattributes b/.gitattributes index ced284c..939b625 100644 --- a/.gitattributes +++ b/.gitattributes @@ -11,3 +11,4 @@ *.lcc binary apps/control-station/vendor/rerun-web-viewer-0.34.1/re_viewer_bg.nodedc.wasm filter=lfs diff=lfs merge=lfs -text apps/control-station/vendor/rerun-web-viewer-0.36.3/re_viewer_bg.nodedc.wasm filter=lfs diff=lfs merge=lfs -text +apps/control-station/public/rover-scene/*.glb filter=lfs diff=lfs merge=lfs -text diff --git a/.gitignore b/.gitignore index 307135a..f443432 100644 --- a/.gitignore +++ b/.gitignore @@ -49,3 +49,10 @@ mqtt.summary.json # Small synthetic/redacted fixtures under tests/fixtures are allowed. !tests/fixtures/**/*.pcap !tests/fixtures/**/*.pcapng + +# Dependency caches may be links into an existing local checkout. +.venv +node_modules + +# Private experiment evidence and generated build archives. +/outputs/ From 45fb14b20678a8bad69a253d9cbf71f39b237a1f Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Fri, 25 Sep 2026 16:37:56 +0300 Subject: [PATCH 2/7] feat(vesc): integrate native calibration diagnostics and configuration archives --- .../internal/node/pairing_transport.go | 5 + .../internal/node/sensor_archives.go | 88 + .../internal/node/sensor_archives_test.go | 25 + .../node-agent/internal/node/sensor_models.go | 25 +- .../internal/node/sensor_preparation.go | 14 +- .../internal/node/sensor_vesc_test.go | 141 + apps/node-agent/internal/node/sensors.go | 49 +- apps/node-agent/ui/src/NodeSensors.tsx | 11 +- packages/sensor-ui/src/SensorWorkspace.tsx | 11 +- packages/sensor-ui/src/contracts.ts | 6 + packages/sensor-ui/src/extensions.ts | 9 +- plugins/vesc/README.md | 253 ++ plugins/vesc/frontend/src/VescBackups.tsx | 51 + .../vesc/frontend/src/VescBoardSettings.tsx | 54 + plugins/vesc/frontend/src/VescCalibration.tsx | 56 + plugins/vesc/frontend/src/VescDetail.tsx | 80 + plugins/vesc/frontend/src/VescHall.tsx | 42 + plugins/vesc/frontend/src/VescLimits.tsx | 35 + plugins/vesc/frontend/src/VescLink.tsx | 42 + plugins/vesc/frontend/src/VescMotor.tsx | 89 + plugins/vesc/frontend/src/model.ts | 69 + plugins/vesc/frontend/src/plugin.ts | 9 + plugins/vesc/native/LICENSE | 674 +++ plugins/vesc/native/config_export.h | 97 + plugins/vesc/native/engine_main.cpp | 375 ++ plugins/vesc/native/offline_main.cpp | 94 + .../vesc/packaging/70-mission-core-vesc.rules | 2 + plugins/vesc/packaging/build_native_probe.py | 33 + plugins/vesc/packaging/clear_runtime_cache.py | 22 + .../mission-core-node-vesc-prepare.service | 8 + .../vesc/packaging/mission-core-vesc.service | 37 + plugins/vesc/packaging/native-runtime.json | 676 +++ plugins/vesc/packaging/native_bundle.py | 95 + plugins/vesc/packaging/native_check.py | 34 + plugins/vesc/packaging/native_probe.py | 188 + plugins/vesc/packaging/payload.py | 49 + plugins/vesc/packaging/prepare.py | 88 + plugins/vesc/packaging/tool_build.py | 188 + plugins/vesc/runtime/__init__.py | 5 + plugins/vesc/runtime/configuration.py | 46 + plugins/vesc/runtime/drive_profile.py | 54 + plugins/vesc/runtime/foc_calibration.py | 157 + plugins/vesc/runtime/group_test.py | 135 + plugins/vesc/runtime/hall_detection.py | 99 + plugins/vesc/runtime/limits_view.py | 18 + plugins/vesc/runtime/link_check.py | 99 + plugins/vesc/runtime/motor_test.py | 390 ++ plugins/vesc/runtime/native_link.py | 171 + plugins/vesc/runtime/protocol.py | 154 + plugins/vesc/runtime/receiver.py | 22 + plugins/vesc/runtime/remote_control.py | 343 ++ plugins/vesc/runtime/schemas/5.02/info.xml | 1008 +++++ .../schemas/5.02/parameters_appconf.xml | 3626 +++++++++++++++ .../schemas/5.02/parameters_mcconf.xml | 3911 +++++++++++++++++ plugins/vesc/runtime/schemas/NOTICE | 1 + .../vesc/runtime/schemas/VESC_TOOL_LICENSE | 674 +++ plugins/vesc/runtime/serial.py | 163 + plugins/vesc/runtime/server.py | 139 + plugins/vesc/runtime/service.py | 364 ++ plugins/vesc/runtime/speed_hold.py | 52 + plugins/vesc/runtime/temporary_limits.py | 88 + plugins/vesc/tests/test_attachment.py | 50 + plugins/vesc/tests/test_drive_profile.py | 74 + plugins/vesc/tests/test_foc_calibration.py | 180 + plugins/vesc/tests/test_group_test.py | 159 + plugins/vesc/tests/test_hall_standstill.py | 108 + plugins/vesc/tests/test_limits_view.py | 34 + plugins/vesc/tests/test_link_check.py | 107 + plugins/vesc/tests/test_motor_test.py | 352 ++ plugins/vesc/tests/test_native_link.py | 93 + plugins/vesc/tests/test_reader.py | 178 + plugins/vesc/tests/test_receiver.py | 75 + plugins/vesc/tests/test_remote_control.py | 307 ++ plugins/vesc/tests/test_reverse_speed.py | 136 + plugins/vesc/tests/test_speed_and_hall.py | 206 + plugins/vesc/tests/test_upgrade.py | 26 + src/k1link/device_plugins/vesc/__init__.py | 1 + src/k1link/device_plugins/vesc/archive.py | 131 + src/k1link/fleet/registry.py | 47 +- src/k1link/fleet/sensors.py | 2 + src/k1link/fleet/transport.py | 28 + src/k1link/web/app.py | 2 + src/k1link/web/fleet_api.py | 64 +- tests/fleet/test_pairing.py | 19 + tests/fleet/test_vesc_archive.py | 74 + 85 files changed, 17968 insertions(+), 28 deletions(-) create mode 100644 apps/node-agent/internal/node/sensor_archives.go create mode 100644 apps/node-agent/internal/node/sensor_archives_test.go create mode 100644 apps/node-agent/internal/node/sensor_vesc_test.go create mode 100644 plugins/vesc/README.md create mode 100644 plugins/vesc/frontend/src/VescBackups.tsx create mode 100644 plugins/vesc/frontend/src/VescBoardSettings.tsx create mode 100644 plugins/vesc/frontend/src/VescCalibration.tsx create mode 100644 plugins/vesc/frontend/src/VescDetail.tsx create mode 100644 plugins/vesc/frontend/src/VescHall.tsx create mode 100644 plugins/vesc/frontend/src/VescLimits.tsx create mode 100644 plugins/vesc/frontend/src/VescLink.tsx create mode 100644 plugins/vesc/frontend/src/VescMotor.tsx create mode 100644 plugins/vesc/frontend/src/model.ts create mode 100644 plugins/vesc/frontend/src/plugin.ts create mode 100644 plugins/vesc/native/LICENSE create mode 100644 plugins/vesc/native/config_export.h create mode 100644 plugins/vesc/native/engine_main.cpp create mode 100644 plugins/vesc/native/offline_main.cpp create mode 100644 plugins/vesc/packaging/70-mission-core-vesc.rules create mode 100644 plugins/vesc/packaging/build_native_probe.py create mode 100644 plugins/vesc/packaging/clear_runtime_cache.py create mode 100644 plugins/vesc/packaging/mission-core-node-vesc-prepare.service create mode 100644 plugins/vesc/packaging/mission-core-vesc.service create mode 100644 plugins/vesc/packaging/native-runtime.json create mode 100644 plugins/vesc/packaging/native_bundle.py create mode 100644 plugins/vesc/packaging/native_check.py create mode 100644 plugins/vesc/packaging/native_probe.py create mode 100644 plugins/vesc/packaging/payload.py create mode 100644 plugins/vesc/packaging/prepare.py create mode 100644 plugins/vesc/packaging/tool_build.py create mode 100644 plugins/vesc/runtime/__init__.py create mode 100644 plugins/vesc/runtime/configuration.py create mode 100644 plugins/vesc/runtime/drive_profile.py create mode 100644 plugins/vesc/runtime/foc_calibration.py create mode 100644 plugins/vesc/runtime/group_test.py create mode 100644 plugins/vesc/runtime/hall_detection.py create mode 100644 plugins/vesc/runtime/limits_view.py create mode 100644 plugins/vesc/runtime/link_check.py create mode 100644 plugins/vesc/runtime/motor_test.py create mode 100644 plugins/vesc/runtime/native_link.py create mode 100644 plugins/vesc/runtime/protocol.py create mode 100644 plugins/vesc/runtime/receiver.py create mode 100644 plugins/vesc/runtime/remote_control.py create mode 100644 plugins/vesc/runtime/schemas/5.02/info.xml create mode 100644 plugins/vesc/runtime/schemas/5.02/parameters_appconf.xml create mode 100644 plugins/vesc/runtime/schemas/5.02/parameters_mcconf.xml create mode 100644 plugins/vesc/runtime/schemas/NOTICE create mode 100644 plugins/vesc/runtime/schemas/VESC_TOOL_LICENSE create mode 100644 plugins/vesc/runtime/serial.py create mode 100644 plugins/vesc/runtime/server.py create mode 100644 plugins/vesc/runtime/service.py create mode 100644 plugins/vesc/runtime/speed_hold.py create mode 100644 plugins/vesc/runtime/temporary_limits.py create mode 100644 plugins/vesc/tests/test_attachment.py create mode 100644 plugins/vesc/tests/test_drive_profile.py create mode 100644 plugins/vesc/tests/test_foc_calibration.py create mode 100644 plugins/vesc/tests/test_group_test.py create mode 100644 plugins/vesc/tests/test_hall_standstill.py create mode 100644 plugins/vesc/tests/test_limits_view.py create mode 100644 plugins/vesc/tests/test_link_check.py create mode 100644 plugins/vesc/tests/test_motor_test.py create mode 100644 plugins/vesc/tests/test_native_link.py create mode 100644 plugins/vesc/tests/test_reader.py create mode 100644 plugins/vesc/tests/test_receiver.py create mode 100644 plugins/vesc/tests/test_remote_control.py create mode 100644 plugins/vesc/tests/test_reverse_speed.py create mode 100644 plugins/vesc/tests/test_speed_and_hall.py create mode 100644 plugins/vesc/tests/test_upgrade.py create mode 100644 src/k1link/device_plugins/vesc/__init__.py create mode 100644 src/k1link/device_plugins/vesc/archive.py create mode 100644 tests/fleet/test_vesc_archive.py diff --git a/apps/node-agent/internal/node/pairing_transport.go b/apps/node-agent/internal/node/pairing_transport.go index bf0022f..cc5007d 100644 --- a/apps/node-agent/internal/node/pairing_transport.go +++ b/apps/node-agent/internal/node/pairing_transport.go @@ -152,6 +152,7 @@ func (p *Pairing) remoteHandler() http.Handler { func (p *Pairing) Run(ctx context.Context) { go p.channel(ctx) + go p.roverChannel(ctx) var server *http.Server endpoint := "" serverIdentity := "" @@ -307,6 +308,9 @@ func (p *Pairing) channel(ctx context.Context) { payload["devices"] = inv["items"] payload["sensor_state"] = inv payload["sensor_results"] = p.Sensors.RemoteResults() + if batch := p.Sensors.ConfigurationBatch(binding.BindingID); batch != nil { + payload["vesc_configurations"] = batch + } } if p.DeviceEnrollment != nil { payload["device_enrollment"] = p.DeviceEnrollment.Status() @@ -337,6 +341,7 @@ func (p *Pairing) channel(ctx context.Context) { } } if p.Sensors != nil { + p.Sensors.AcknowledgeConfigurations(binding.BindingID, result["vesc_configurations_ack"], payload["vesc_configurations"]) var ack []string if json.Unmarshal(result["sensor_acknowledgements"], &ack) == nil { p.Sensors.Acknowledge(ack) diff --git a/apps/node-agent/internal/node/sensor_archives.go b/apps/node-agent/internal/node/sensor_archives.go new file mode 100644 index 0000000..0e62326 --- /dev/null +++ b/apps/node-agent/internal/node/sensor_archives.go @@ -0,0 +1,88 @@ +package node + +import ( + "context" + "encoding/json" + "net/http" + "net/url" + "os" + "path/filepath" + "strconv" + "time" +) + +func (s *Sensors) vescArchive(path string) (map[string]any, error) { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + for i := range sensorModels { + if sensorModels[i].ID == "vesc.controller" { + return s.modelDriver(ctx, &sensorModels[i], path, nil) + } + } + panic("shipped VESC model is missing") +} + +func archiveCursorName(binding string) string { + return "vesc-archive-" + digest(binding)[:24] + ".cursor" +} + +// Each pairing receives the complete immutable history, including backups +// made locally and while Core was offline. ACK follows durable Core storage. +func (s *Sensors) ConfigurationBatch(binding string) map[string]any { + var after int64 + data, _ := os.ReadFile(filepath.Join(s.root, archiveCursorName(binding))) + if json.Unmarshal(data, &after) != nil || after < 0 { + after = 0 + } + result, err := s.vescArchive("/archive-export?after=" + strconv.FormatInt(after, 10)) + if err != nil { + return nil + } + return result +} + +func (s *Sensors) AcknowledgeConfigurations(binding string, ack json.RawMessage, batch any) { + value, ok := batch.(map[string]any) + if !ok { + return + } + var sequence int64 + if json.Unmarshal(ack, &sequence) != nil || sequence < 0 { + return + } + next, ok := value["next"].(float64) + if !ok || next != float64(sequence) { + return + } + // A failed cursor write causes replay; immutable archive insertion deduplicates it. + _ = s.write(archiveCursorName(binding), sequence) +} + +func (s *Sensors) configurationRoutes(mux *http.ServeMux, server *Server) { + for _, route := range []string{"GET /api/device-configurations/{device}", "GET /api/device-configurations/{device}/{version}"} { + mux.HandleFunc(route, func(w http.ResponseWriter, r *http.Request) { + if !server.authorized(w, r) { + return + } + w.Header().Set("Cache-Control", "no-store") + device := r.PathValue("device") + model := modelForDevice(device) + if model == nil || model.ID != "vesc.controller" { + reply(w, 404, map[string]string{"error": "История не найдена"}) + return + } + path := "/archives/" + url.PathEscape(device) + if version := r.PathValue("version"); version != "" { + path += "/" + url.PathEscape(version) + } else { + path += "?before=" + url.QueryEscape(r.URL.Query().Get("before")) + } + result, err := s.vescArchive(path) + if err != nil { + reply(w, 503, map[string]string{"error": "Архив конфигураций недоступен"}) + return + } + reply(w, 200, result) + }) + } +} diff --git a/apps/node-agent/internal/node/sensor_archives_test.go b/apps/node-agent/internal/node/sensor_archives_test.go new file mode 100644 index 0000000..8debdd9 --- /dev/null +++ b/apps/node-agent/internal/node/sensor_archives_test.go @@ -0,0 +1,25 @@ +package node + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" +) + +func TestVESCArchiveAckRequiresExactBatchAndPairingScope(t *testing.T) { + s := isolatedSensors(t) + batch := map[string]any{"next": float64(9)} + s.AcknowledgeConfigurations("pair-a", json.RawMessage(`10`), batch) + if _, err := os.Stat(filepath.Join(s.root, archiveCursorName("pair-a"))); !os.IsNotExist(err) { + t.Fatal("incorrect ACK persisted") + } + s.AcknowledgeConfigurations("pair-a", json.RawMessage(`9`), batch) + data, err := os.ReadFile(filepath.Join(s.root, archiveCursorName("pair-a"))) + if err != nil || string(data) != "9" { + t.Fatalf("durable cursor: %q %v", data, err) + } + if _, err := os.Stat(filepath.Join(s.root, archiveCursorName("pair-b"))); !os.IsNotExist(err) { + t.Fatal("history skipped on another pairing") + } +} diff --git a/apps/node-agent/internal/node/sensor_models.go b/apps/node-agent/internal/node/sensor_models.go index 4f6ece5..251dce0 100644 --- a/apps/node-agent/internal/node/sensor_models.go +++ b/apps/node-agent/internal/node/sensor_models.go @@ -20,6 +20,8 @@ type sensorModel struct { Socket, PrepareUnit, Report string Actions map[string]bool ActionTimeouts map[string]time.Duration + // This model may prepare an attachment only to read its protocol identity. + ProtocolIdentity bool } func actions(names ...string) map[string]bool { @@ -44,6 +46,11 @@ var sensorModels = []sensorModel{ PrepareUnit: "mission-core-node-insta360-x4-profile.service", Report: "/var/lib/mission-core-node-profiles/insta360-x4/preparation.json", ActionTimeouts: map[string]time.Duration{"power.wake": 55 * time.Second}, Actions: actions("prepare", "details", "rename", "verify", "preview.start", "preview.stop", "record.start", "record.stop", "photo.capture", "settings.read", "settings.apply", "files.list", "offer", "close-peer", "recovery.configure", "power.wake")}, + {ID: "vesc.controller", Name: "VESC", Prefix: "vesc", Kind: "vesc.controller", Plugin: "missioncore.vesc", Version: "0.7.4", + Vendor: "0483", Product: "5740", USBName: "ChibiOS/RT Virtual COM Port", Socket: "/run/mission-core-vesc/driver.sock", + PrepareUnit: "mission-core-node-vesc-prepare.service", Report: "/var/lib/mission-core-node-profiles/vesc/preparation.json", + ActionTimeouts: map[string]time.Duration{"vesc.link.check": 45 * time.Second, "vesc.motor.run": 90 * time.Second, "vesc.drive.run": 120 * time.Second, "vesc.hall.measure": 60 * time.Second, "vesc.foc.calibrate": 300 * time.Second, "vesc.motor.pulse": 60 * time.Second, "vesc.control.release": 60 * time.Second}, + ProtocolIdentity: true, Actions: actions("prepare", "details", "rename", "verify", "vesc.link.check", "vesc.telemetry.read", "vesc.limits.read", "vesc.config.backup", "vesc.input.read", "vesc.can.read", "vesc.drive.assign", "vesc.drive.layout", "vesc.drive.unassign", "vesc.motor.pulse", "vesc.motor.run", "vesc.drive.run", "vesc.hall.measure", "vesc.foc.calibrate", "vesc.motor.stop", "vesc.control.release")}, } func modelForDevice(id string) *sensorModel { @@ -74,6 +81,22 @@ func modelDeviceID(model *sensorModel, serial string) string { return model.Prefix + "_" + hex.EncodeToString(h[:])[:32] } +func preparedDeviceID(command SensorCommand, result any) string { + model := modelForDevice(command.Session.DeviceID) + if model == nil { + return "" + } + if !model.ProtocolIdentity { + return command.Session.DeviceID + } + if value, ok := result.(map[string]any); ok { + if id, ok := value["device_id"].(string); ok && modelForDevice(id) == model { + return id + } + } + return "" +} + func sensorClient(socket string) *http.Client { return &http.Client{Timeout: 25 * time.Second, Transport: &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { return (&net.Dialer{}).DialContext(ctx, "unix", socket) @@ -110,7 +133,7 @@ func discoverSensors(root string) []usbSensor { } unique := []usbSensor{} for _, item := range items { - if !item.stable || counts[item.id] != 1 { + if item.model.ProtocolIdentity || !item.stable || counts[item.id] != 1 { item.stable = false item.id = modelDeviceID(item.model, "provisional:"+item.binding) } diff --git a/apps/node-agent/internal/node/sensor_preparation.go b/apps/node-agent/internal/node/sensor_preparation.go index 4c7a939..e63f8e1 100644 --- a/apps/node-agent/internal/node/sensor_preparation.go +++ b/apps/node-agent/internal/node/sensor_preparation.go @@ -77,7 +77,7 @@ func (s *Sensors) preparationPhase(c SensorCommand, model *sensorModel, job *pro } op.Preparation = &sensorPreparation{OperationID: c.ID, DeviceID: c.Session.DeviceID, ModelID: model.ID, StartedAt: float64(started.UnixMilli()) / 1000, ProfileStartedAt: job.started, State: state, Phase: phase, - Steps: []preparationStep{{ID: "profile", Label: "Подготовка драйвера", State: deploy}, {ID: "verify", Label: "Проверка выбранной камеры", State: verify}}} + Steps: []preparationStep{{ID: "profile", Label: "Подготовка драйвера", State: deploy}, {ID: "verify", Label: "Проверка выбранного устройства", State: verify}}} op.Updated = time.Now().Unix() err := s.write(c.ID+".json", op) s.events.notify() @@ -217,18 +217,20 @@ func (s *Sensors) prepare(c SensorCommand, selected map[string]any) (result any, binding := s.discoverySessions[c.Session.DeviceID].binding s.mu.Unlock() if initialBinding != "" && binding != initialBinding { - return nil, errors.New("Камера переподключена во время подготовки. Повторите проверку устройства.") + return nil, errors.New("Устройство переподключено во время подготовки. Повторите проверку устройства.") } for _, raw := range inventory["items"].([]any) { item := raw.(map[string]any) - if item["id"] != c.Session.DeviceID || item["online"] != true || item["prepared"] != true { + matches := item["id"] == c.Session.DeviceID || (model.ProtocolIdentity && item["attachment_id"] == c.Session.DeviceID) + if !matches || item["online"] != true || item["prepared"] != true || (model.ProtocolIdentity && item["verified"] != true) { continue } verify := c verify.Action = "verify" + verify.Session.DeviceID, _ = item["id"].(string) verify.Session.SessionID = sensorSessionID(item) if verify.Session.SessionID == "" { - return nil, errors.New("Драйвер не подтвердил сеанс камеры.") + return nil, errors.New("Драйвер не подтвердил сеанс устройства.") } response, e := s.modelDriver(ctx, model, "/operation", verify) if e != nil || response["state"] == "unknown" { @@ -237,7 +239,7 @@ func (s *Sensors) prepare(c SensorCommand, selected map[string]any) (result any, if response["state"] != "complete" { message, _ := response["error"].(string) if message == "" { - message = "Не удалось проверить изображение выбранной камеры." + message = "Не удалось проверить выбранное устройство." } return nil, errors.New(message) } @@ -249,7 +251,7 @@ func (s *Sensors) prepare(c SensorCommand, selected map[string]any) (result any, case <-time.After(time.Second): } } - return nil, errors.New("Драйвер установлен, но камера не открылась. Проверьте USB-подключение.") + return nil, errors.New("Драйвер установлен, но устройство не ответило. Проверьте питание и USB-подключение.") } // Project only the matching model run. A previous success or another model's diff --git a/apps/node-agent/internal/node/sensor_vesc_test.go b/apps/node-agent/internal/node/sensor_vesc_test.go new file mode 100644 index 0000000..5c3016a --- /dev/null +++ b/apps/node-agent/internal/node/sensor_vesc_test.go @@ -0,0 +1,141 @@ +package node + +import ( + "context" + "encoding/json" + "net/http" + "os" + "path/filepath" + "regexp" + "strings" + "sync/atomic" + "testing" +) + +func TestVESCDeclaredVersionMatchesBundledDriver(t *testing.T) { + model := modelForDevice("vesc_00000000000000000000000000000000") + root := filepath.Join("..", "..", "..", "..", "plugins", "vesc") + driver, err := os.ReadFile(filepath.Join(root, "runtime", "__init__.py")) + if err != nil { + t.Fatal(err) + } + match := regexp.MustCompile(`(?m)^VERSION = "([^"]+)"`).FindSubmatch(driver) + if model == nil || len(match) != 2 || model.Version != string(match[1]) { + t.Fatal("Node must admit the exact driver shipped in the same release", model, string(driver)) + } + preparation, err := os.ReadFile(filepath.Join(root, "packaging", "prepare.py")) + if err != nil || !strings.Contains(string(preparation), `"version": "`+model.Version+`"`) { + t.Fatal("VESC preparation must declare the bundled driver version", err) + } +} + +func fakeVESC(t *testing.T, s *Sensors, port, number string) { + t.Helper() + fakeUSB(t, s.usbRoot, port, "duplicate", "ChibiOS/RT Virtual COM Port", number) + for key, value := range map[string]string{"idVendor": "0483", "idProduct": "5740"} { + if err := os.WriteFile(filepath.Join(s.usbRoot, port, key), []byte(value), 0600); err != nil { + t.Fatal(err) + } + } +} + +func TestVESCProvisionalIdentityIsReadOnlyAndDoesNotWeakenCameras(t *testing.T) { + s := isolatedSensors(t) + fakeVESC(t, s, "1-2", "2") + fakeVESC(t, s, "1-3", "3") + items := s.Inventory()["items"].([]any) + if len(items) != 2 { + t.Fatal("both controllers must be visible") + } + for _, raw := range items { + item := raw.(map[string]any) + if item["initializable"] != true || item["prepared"] != false { + t.Fatal("identity bootstrap unavailable or falsely prepared") + } + c := sensorTestCommand() + c.Session.DeviceID = item["id"].(string) + for _, action := range []string{"start", "stop", "option", "settings.apply", "firmware.write"} { + c.Action = action + if _, err := s.Submit(c, false); err == nil { + t.Fatal("VESC acquired write authority", action) + } + } + } + if items[0].(map[string]any)["id"] == items[1].(map[string]any)["id"] { + t.Fatal("duplicate USB serial collapsed") + } + fakeUSB(t, s.usbRoot, "2-2", "same", "Insta360 X4", "4") + fakeUSB(t, s.usbRoot, "2-3", "same", "Insta360 X4", "5") + for _, raw := range s.Inventory()["items"].([]any) { + item := raw.(map[string]any) + if item["kind"] == "insta360.x4" && item["initializable"] != false { + t.Fatal("camera guard weakened") + } + } +} + +func TestVESCPreparePromotesAttachmentToProtocolUUID(t *testing.T) { + s := isolatedSensors(t) + fakeVESC(t, s, "1-2", "2") + first := s.Inventory()["items"].([]any)[0].(map[string]any) + attachment := first["id"].(string) + model := modelForDevice(attachment) + stable := modelDeviceID(model, "uuid:synthetic-controller") + var installed atomic.Bool + s.runPreparation = func(_ context.Context, unit string) error { + if unit != "mission-core-node-vesc-prepare.service" { + t.Error("wrong profile") + } + installed.Store(true) + return nil + } + s.clients[model.ID].Transport = sensorRoundTrip(func(r *http.Request) (*http.Response, error) { + if r.URL.Path == "/inventory" { + items := []any{} + if installed.Load() { + item := s.discovery(stable, "12", true) + item["prepared"] = true + item["verified"] = true + item["configured"] = true + item["attachment_id"] = attachment + item["snapshot"].(map[string]any)["context"].(map[string]any)["session_id"] = "protocol_session" + items = append(items, item) + } + return testSensorReply(map[string]any{"items": items}), nil + } + var command SensorCommand + _ = json.NewDecoder(r.Body).Decode(&command) + if command.Action != "verify" || command.Session.DeviceID != stable || command.Session.SessionID != "protocol_session" { + t.Error("verification did not follow protocol identity") + } + return testSensorReply(map[string]any{"state": "complete", "result": map[string]any{"device_id": stable}}), nil + }) + c := sensorTestCommand() + c.Action = "prepare" + c.Session = SensorSession{DeviceID: attachment, SessionID: sensorSessionID(first)} + if _, err := s.Submit(c, true); err != nil { + t.Fatal(err) + } + awaitSensor(t, func() bool { return s.Get(c.ID).State != "running" }) + if s.Get(c.ID).State != "complete" { + t.Fatal(s.Get(c.ID)) + } + items := s.Inventory()["items"].([]any) + if len(items) != 1 || items[0].(map[string]any)["id"] != stable { + t.Fatal("provisional row survived promotion") + } + s.mu.Lock() + a, b := s.initialized[stable], s.initialized[attachment] + s.mu.Unlock() + if !a || b { + t.Fatal("initialization persisted transport identity") + } + // A stale runtime attachment is never presented as a currently connected controller. + if err := os.RemoveAll(filepath.Join(s.usbRoot, "1-2")); err != nil { + t.Fatal(err) + } + items = s.Inventory()["items"].([]any) + if len(items) != 1 || items[0].(map[string]any)["online"] != false { + t.Fatal("unplugged driver observation accepted") + } +} diff --git a/apps/node-agent/internal/node/sensors.go b/apps/node-agent/internal/node/sensors.go index d54e56e..f2a6c69 100644 --- a/apps/node-agent/internal/node/sensors.go +++ b/apps/node-agent/internal/node/sensors.go @@ -106,7 +106,9 @@ func OpenSensors(root, nodeID string) (*Sensors, error) { } for _, op := range s.operations { if op.Command.Action == "prepare" && op.State == "complete" { - s.initialized[op.Command.Session.DeviceID] = true + if id := preparedDeviceID(op.Command, op.Result); id != "" { + s.initialized[id] = true + } } } if e := s.write("initialized.json", s.initialized); e != nil { @@ -192,7 +194,7 @@ func (s *Sensors) modelDriver(ctx context.Context, model *sensorModel, path stri } response, e := client.Do(req) if e != nil { - return nil, errors.New("Служба камеры недоступна. Подготовьте устройство.") + return nil, errors.New("Служба устройства недоступна. Подготовьте устройство.") } defer response.Body.Close() var result map[string]any @@ -241,8 +243,24 @@ func (s *Sensors) Inventory() map[string]any { unsafePreparation[id] = item["preparation_safe"] == false || snapshot["acquisition"] != "idle" continue } + if model.ProtocolIdentity { + if !currentCameraSnapshot(item, model) { + continue + } + attachment, _ := item["attachment_id"].(string) + matched := false + for _, candidate := range usb { + if candidate.model == model && candidate.id == attachment { + matched = true + } + } + if !matched { + continue + } + seen[attachment] = true + } s.mu.Lock() - if model.PrepareUnit != "" { + if model.PrepareUnit != "" && !model.ProtocolIdentity { item["configured"] = s.initialized[id] } if name := s.names[id]; name != "" { @@ -325,13 +343,18 @@ func (s *Sensors) discovery(id, speed string, online bool) map[string]any { if !initializable { stability, basis = "provisional", "transport-local" } + // VESC bootstrap grants only a fixed identity read on the selected attachment. + // This does not promote the attachment to stable identity or allow motor control. + if online && model.ProtocolIdentity { + initializable = true + } return map[string]any{"id": id, "name": name, "model": model.Name, "kind": model.Kind, "initializable": initializable, "configured": configured, "prepared": false, "verified": false, "online": online, "usb": speed, "layers": []any{}, "snapshot": map[string]any{ "context": map[string]any{"session_id": session, "device": map[string]any{"device_id": id, "model": map[string]string{"plugin_id": model.Plugin, "plugin_version": model.Version, "model_id": model.ID}, "stability": stability, "basis": basis}, "execution": map[string]string{"node_id": s.nodeID, "agent_instance_id": s.instance, "platform": "linux"}, "opened_at": now}, "revision": 0, "enrollment": enrollment, "connectivity": connectivity, "acquisition": "idle", "observed_at": now}} } func sensorViewAction(action string) bool { - return action == "details" || action == "offer" || action == "close-peer" || action == "settings.read" || action == "files.list" + return action == "details" || action == "offer" || action == "close-peer" || action == "settings.read" || action == "files.list" || action == "vesc.telemetry.read" || action == "vesc.limits.read" || action == "vesc.config.backup" } func (s *Sensors) Submit(c SensorCommand, remote bool) (*SensorOperation, error) { @@ -365,10 +388,10 @@ func (s *Sensors) Submit(c SensorCommand, remote bool) (*SensorOperation, error) return nil, errors.New("Срок команды истёк. Устройство не изменено.") } for _, v := range s.operations { - if v.State == "running" && v.Command.Action == "prepare" && (v.Preparation == nil || v.Preparation.Phase == "profile") && c.Action != "prepare" && !sensorViewAction(c.Action) && modelForDevice(v.Command.Session.DeviceID) == model { + if v.State == "running" && v.Command.Action == "prepare" && (v.Preparation == nil || v.Preparation.Phase == "profile") && c.Action != "prepare" && c.Action != "vesc.motor.stop" && !sensorViewAction(c.Action) && modelForDevice(v.Command.Session.DeviceID) == model { return nil, errors.New("Подготовка модели ещё выполняется.") } - if v.State == "running" && v.Command.Session.DeviceID == c.Session.DeviceID && !sensorViewAction(c.Action) && !sensorViewAction(v.Command.Action) { + if v.State == "running" && v.Command.Session.DeviceID == c.Session.DeviceID && c.Action != "vesc.motor.stop" && !sensorViewAction(c.Action) && !sensorViewAction(v.Command.Action) { return nil, errors.New("Другая операция устройства ещё выполняется.") } } @@ -411,11 +434,11 @@ func (s *Sensors) execute(c SensorCommand) { if !deadline.After(time.Now()) { err = errors.New("Срок команды истёк. Устройство не изменено.") } else if item == nil { - err = errors.New("Камера не обнаружена. Проверьте подключение.") + err = errors.New("Устройство не обнаружено. Проверьте подключение.") } else if c.Action == "prepare" && item["online"] != true { - err = errors.New("Камера отключена. Проверьте подключение.") + err = errors.New("Устройство отключено. Проверьте подключение.") } else if c.Action == "prepare" && item["initializable"] == false { - err = errors.New("Не удалось однозначно определить камеру. Проверьте её идентификатор и подключение.") + err = errors.New("Не удалось однозначно определить устройство. Проверьте его идентификатор и подключение.") } else if (c.Action == "prepare" || c.Action == "rename") && sensorSessionID(item) != c.Session.SessionID { err = errors.New("Сеанс устройства изменился. Обновите сведения.") } else if c.Action == "prepare" { @@ -451,7 +474,12 @@ func (s *Sensors) execute(c SensorCommand) { s.mu.Lock() defer s.mu.Unlock() if err == nil && c.Action == "prepare" { - s.initialized[c.Session.DeviceID] = true + initializedID := preparedDeviceID(c, result) + if initializedID == "" { + err = errors.New("Драйвер не подтвердил личность устройства.") + } else { + s.initialized[initializedID] = true + } if e := s.write("initialized.json", s.initialized); e != nil { err = e uncertain = true @@ -496,6 +524,7 @@ func (s *Sensors) RemoteResults() []any { return out } func (s *Sensors) Routes(mux *http.ServeMux, server *Server) { + s.configurationRoutes(mux, server) mux.HandleFunc("GET /api/devices/events", func(w http.ResponseWriter, r *http.Request) { s.stream(w, r, server) }) mux.HandleFunc("GET /api/devices", func(w http.ResponseWriter, r *http.Request) { if server.authorized(w, r) { diff --git a/apps/node-agent/ui/src/NodeSensors.tsx b/apps/node-agent/ui/src/NodeSensors.tsx index fa12520..97d9667 100644 --- a/apps/node-agent/ui/src/NodeSensors.tsx +++ b/apps/node-agent/ui/src/NodeSensors.tsx @@ -1,8 +1,13 @@ +import {vescSensorUi} from '../../../../plugins/vesc/frontend/src/plugin'; import {xgridsK1SensorUi} from '../../../../plugins/xgrids-k1/frontend/src/sensors/plugin'; import {insta360X4SensorUi} from '../../../../plugins/insta360-x4/frontend/src/plugin'; import {createIsolatedRerunHost} from '../../../control-station/src/components/rerun/isolatedRerunHost'; import {SensorWorkspace} from '../../../../packages/sensor-ui/src/SensorWorkspace'; import type {SensorTransport} from '../../../../packages/sensor-ui/src/contracts'; -import {request} from './api'; -const transport:SensorTransport={localPreview:{open:(command,signal)=>fetch("/api/devices/preview",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify(command),signal}),read:(peer,after,signal)=>fetch("/api/devices/preview/read",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({peer_id:peer,after}),signal})},enrollment:{state:()=>request("/api/devices/enrollment"),submit:value=>request("/api/devices/enrollment/operations","POST",value),operation:id=>request("/api/devices/enrollment/operations/"+encodeURIComponent(id))},subscribe:(receive,unavailable)=>{const events=new EventSource('/api/devices/events');events.onmessage=e=>{try{receive(JSON.parse(e.data));}catch{unavailable();}};events.onerror=unavailable;return()=>events.close();},inventory:()=>request('/api/devices'),submit:value=>request('/api/devices/operations','POST',value),operation:id=>request('/api/devices/operations/'+encodeURIComponent(id))}; -export function NodeSensors(){return ;} +import {request,type Status} from './api'; +import {Button,Icon,SettingsCard} from '@nodedc/ui-react'; +import {createBoardLayoutStore} from '../../../../packages/sensor-ui/src/boardLayout'; +const layout=createBoardLayoutStore({read:()=>request('/api/presentation/board-layout'),patch:(section,open)=>request('/api/presentation/board-layout','PATCH',{section,open})}); +const configurationArchive:NonNullable={list:(device,before)=>request(`/api/device-configurations/${encodeURIComponent(device)}${before?'?before='+encodeURIComponent(before):''}`),read:(device,version)=>request(`/api/device-configurations/${encodeURIComponent(device)}/${encodeURIComponent(version)}`)}; +const transport:SensorTransport={configurationArchive,localPreview:{open:(command,signal)=>fetch("/api/devices/preview",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify(command),signal}),read:(peer,after,signal)=>fetch("/api/devices/preview/read",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({peer_id:peer,after}),signal})},enrollment:{state:()=>request("/api/devices/enrollment"),submit:value=>request("/api/devices/enrollment/operations","POST",value),operation:id=>request("/api/devices/enrollment/operations/"+encodeURIComponent(id))},subscribe:(receive,unavailable)=>{const events=new EventSource('/api/devices/events');events.onmessage=e=>{try{receive(JSON.parse(e.data));}catch{unavailable();}};events.onerror=unavailable;return()=>events.close();},inventory:()=>request('/api/devices'),submit:value=>request('/api/devices/operations','POST',value),operation:id=>request('/api/devices/operations/'+encodeURIComponent(id))}; +export function NodeSensors({value,openSettings}:{value:Status;openSettings:()=>void}){return
Бортовой компьютер
{value.node_id}
Операционная система
{value.host.os}
Архитектура
{value.host.architecture}
Процессоры
{value.host.cpus}
Память
{value.host.memory_kib?`${(value.host.memory_kib/1048576).toFixed(1)} ГиБ`:"Нет сведений"}
Mission Core Node
{value.version}
}} contributions={[xgridsK1SensorUi,insta360X4SensorUi,vescSensorUi]} createRerunHost={createIsolatedRerunHost} transport={transport}/>;} diff --git a/packages/sensor-ui/src/SensorWorkspace.tsx b/packages/sensor-ui/src/SensorWorkspace.tsx index 0c82e6b..d04c392 100644 --- a/packages/sensor-ui/src/SensorWorkspace.tsx +++ b/packages/sensor-ui/src/SensorWorkspace.tsx @@ -9,8 +9,9 @@ import {sensorStatus} from './sensorStatus'; import {sensorContribution,type SensorUiContribution,wirelessContributions} from './extensions'; import type {RerunHostFactory} from './rerunHost'; import './sensors.css'; +import {BoardSections,type BoardSectionsProps} from './BoardSections'; import {WirelessEnrollmentWindow} from './WirelessEnrollmentWindow'; -export function SensorWorkspace({transport,enabled=true,onDetailChange,createRerunHost,contributions=[]}:{transport:SensorTransport;enabled?:boolean;onDetailChange?:(open:boolean)=>void;createRerunHost?:RerunHostFactory;contributions?:readonly SensorUiContribution[]}){ +export function SensorWorkspace({transport,enabled=true,onDetailChange,createRerunHost,contributions=[],board}:{transport:SensorTransport;enabled?:boolean;onDetailChange?:(open:boolean)=>void;createRerunHost?:RerunHostFactory;contributions?:readonly SensorUiContribution[];board?:BoardSectionsProps}){ const [adding,setAdding]=useState(false); const [inventory,setInventory]=useState(null);const [selected,setSelected]=useState(null);const [editing,setEditing]=useState(null);const [name,setName]=useState('');const [localBusy,setBusy]=useState>(()=>new Map());const activeActions=useRef(new Map());const [error,setError]=useState('');const [fresh,setFresh]=useState(false); const failure=useCallback((e:unknown)=>{setError(e===null?'':e instanceof Error?e.message:'Не удалось выполнить действие устройства.');},[]); @@ -44,7 +45,7 @@ export function SensorWorkspace({transport,enabled=true,onDetailChange,createRer const editingCurrent=inventory?.items.find(v=>v.id===editing?.id); useEffect(()=>{onDetailChange?.(!!device);},[!!device,onDetailChange]); const Detail=device?(sensorContribution(contributions,device)?.Detail??(device.kind?null:SensorDetail)):null; - return
{device?Detail?setSelected(null)} refresh={refresh} failure={failure} createRerunHost={createRerunHost} reconnect={transport.enrollment?()=>setAdding(true):undefined}/>:
:<> + const inventoryView=<>
{!enabled?'БК недоступен':fresh?'Сведения с БК':'Нет свежих сведений'}
{transport.enrollment&&wirelessContributions(contributions).length>0&&setAdding(true)}>}{void refresh();}}>
{!inventory?:connected.length===0?:{connected.map(item=>{ const operation=inventory.operations?.find(v=>v.device_id===item.id&&['queued','running'].includes(v.state));const busy=!!operation||localBusy.has(item.id); @@ -52,9 +53,11 @@ export function SensorWorkspace({transport,enabled=true,onDetailChange,createRer const configured=item.configured??item.snapshot.enrollment==='enrolled'; const prep=devicePreparation(inventory,item); const status=(sensorContribution(contributions,item)?.status??sensorStatus)(item,enabled&&fresh);const label=busy?(operation?.action_id==='prepare'?'Подготовка устройства':'Выполняется команда'):status.label; - return
  • } title={item.name} description={item.model} metadata={{item.connection_label||`USB ${item.usb}`}} statusPlacement={configured?'leading':'trailing'} aria-busy={busy} progress={busy&&pending==='prepare'?preparationProgress(prep,label):undefined} status={{configured?null:label}} actions={<>void action(item,name,parameters)}/>{!configured&&sensorContribution(contributions,item)?.supportsPreparation!==false&&void action(item,'prepare')}>}{sensorContribution(contributions,item)?.supportsRenaming!==false&&{setEditing(item);setName(item.name);}}>}setSelected(item.id)}>}/>
  • ;})}
    } + return
  • } title={item.name} description={item.model} metadata={{item.connection_label||`USB ${item.usb}`}} statusPlacement={configured?'leading':'trailing'} aria-busy={busy} progress={busy&&pending==='prepare'?preparationProgress(prep,label):undefined} status={{configured?null:label}} actions={<>void action(item,name,parameters)}/>{!configured&&sensorContribution(contributions,item)?.supportsPreparation!==false&&void action(item,'prepare')}>}{sensorContribution(contributions,item)?.supportsRenaming!==false&&{setEditing(item);setName(item.name);}}>}{sensorContribution(contributions,item)?.detailLabel?:setSelected(item.id)}>}}/>
  • ;})}} - } + ; + const boardSettings=contributions.filter(value=>value.BoardSettings&&contributions.filter(other=>other.kind===value.kind).length===1); + return
    {device?Detail?setSelected(null)} refresh={refresh} failure={failure} createRerunHost={createRerunHost} reconnect={transport.enrollment?()=>setAdding(true):undefined}/>:
    :(board?{boardSettings.map(contribution=>{const View=contribution.BoardSettings!;return ;})}{!boardSettings.length&&

    Для подключённых устройств общие настройки пока недоступны.

    }
    } devices={inventoryView}/>:inventoryView)} setEditing(null)} footer={}>
    setName(e.target.value)} disabled={localBusy.has(editing?.id??'')}/>{editing&&sensorContribution(contributions,editing)?.supportsPreparation!==false&&(editing.configured??editing.snapshot.enrollment==='enrolled')&&{const target=editing;setEditing(null);void action(target,'prepare');}}>Обновить}/>}
    {adding&&transport.enrollment&&wirelessContributions(contributions).length>0&&setAdding(false)} onChange={()=>{void refresh();}} onComplete={completeEnrollment}/>} setError('')}/> diff --git a/packages/sensor-ui/src/contracts.ts b/packages/sensor-ui/src/contracts.ts index 8ec2a22..e26668d 100644 --- a/packages/sensor-ui/src/contracts.ts +++ b/packages/sensor-ui/src/contracts.ts @@ -4,6 +4,7 @@ export interface Sensor { kind?:string; connection_label?:string; control?:{generation:number;revision:number;phase:string;can_start:boolean;can_stop?:boolean;can_verify?:boolean;network_applied?:boolean;reason_code?:string|null;acquisition_id:string|null;acquisition_phase?:string}; live_settings?: Record; camera_status?: Record; + vesc_status?: Record; id: string; name: string; model: string; initializable?:boolean; preparation_safe?:boolean; prepared: boolean; configured?: boolean; verified: boolean; online: boolean; usb: string; firmware?: string; playback_id?: string | null; snapshot: {context: {session_id: string; device: {device_id: string}; execution: {node_id: string}}; acquisition: string; enrollment: string; message?: string}; profiles?: SensorProfile[]; defaults?: string[]; options?: SensorOption[]; layers: string[]; @@ -33,6 +34,10 @@ export interface SensorCommand { } export interface SensorOperation {state:string;error?:string;result?:unknown} export interface SensorTransport { + configurationArchive?: { + list:(deviceId:string,before?:string)=>Promise<{items:ConfigurationVersion[];next:string|null}>; + read:(deviceId:string,versionId:string)=>Promise>; + }; localPreview?: { open: (command:SensorCommand, signal:AbortSignal) => Promise; read: (peer:string, after:number, signal:AbortSignal) => Promise; @@ -43,6 +48,7 @@ export interface SensorTransport { submit: (value:SensorCommand) => Promise; operation: (id:string) => Promise; } +export interface ConfigurationVersion {id:string;sequence:number;device_id:string;observed_at:string;firmware:string;configs:Record} export function command(device:Sensor,action:string,parameters:Record={},timeoutMs=60000):SensorCommand { const id='op_'+crypto.randomUUID().replaceAll('-','');const now=Date.now(); return {api_version:'missioncore.nodedc/plugin-sdk/v0alpha2',kind:'OperationRequest',operation_id:id,idempotency_key:id, diff --git a/packages/sensor-ui/src/extensions.ts b/packages/sensor-ui/src/extensions.ts index 492950b..393f93d 100644 --- a/packages/sensor-ui/src/extensions.ts +++ b/packages/sensor-ui/src/extensions.ts @@ -1,6 +1,6 @@ import type {ComponentType,ReactNode} from 'react'; import type {IconName} from '@nodedc/ui-react'; -import type {Sensor, SensorTransport} from './contracts'; +import type {Sensor, SensorInventory, SensorTransport} from './contracts'; import type {EnrollmentTransport} from './enrollment'; import type {RerunHostFactory} from './rerunHost'; @@ -15,6 +15,7 @@ export interface SensorEnrollmentProps { renderWindow:(view:{content:ReactNode;actions?:ReactNode;busy?:boolean})=>ReactNode; } export interface SensorUiContribution { + BoardSettings?:ComponentType; observation?:import('./observation').SensorObservationContribution; kind:string; Detail:ComponentType; @@ -22,11 +23,17 @@ export interface SensorUiContribution { retainOffline:boolean; supportsPreparation:boolean; supportsRenaming?:boolean; + detailLabel?:string; rowActions?:(device:Sensor)=>readonly SensorRowAction[]; status?:(device:Sensor,fresh:boolean)=>{label:string;tone:'neutral'|'success'|'warning'|'danger'}; wirelessEnrollment?:{label:string;View:ComponentType}; } +export interface SensorBoardSettingsProps { + inventory:SensorInventory|null;transport:SensorTransport;enabled:boolean; + refresh:()=>Promise;failure:(error:unknown)=>void;openDevice:(id:string)=>void; +} + export interface SensorRowAction { actionId:string; label:string; description?:string; disabled?:boolean; parameters?:Record; diff --git a/plugins/vesc/README.md b/plugins/vesc/README.md new file mode 100644 index 0000000..dc70141 --- /dev/null +++ b/plugins/vesc/README.md @@ -0,0 +1,253 @@ +# VESC onboard plugin — profile 0.4.0 + +**Native release in preparation:** 0.4.0 / Node 0.8.30-1 uses the actual VESC Tool 7.00 C++ engine for USB ownership, commands, configuration codecs and Hall measurement. Installation and physical qualification are still pending. + +**Previous release status, 2026-09-23:** 0.3.0 / Node 0.8.29-1 is an uninstalled, +withheld experiment. The owner requires the actual upstream VESC Tool as the +onboard engine behind Mission Core controls. Do not deploy the separate Python +Hall workflow below as the intended calibration backend. Hardware currently +runs 0.2.5 / Node 0.8.28-1. The verified native adapter and canonical procedure +are documented in [the native engine plan](../../docs/node/18_VESC_TOOL_NATIVE_BACKEND.md). + +This increment discovers USB candidates, reads protocol identity and telemetry, +saves opaque motor/application configuration backups and provides bounded +identification pulses and user-assigned drive positions. It is not complete +VESC Tool functional parity and does not implement continuous driving, +configuration writes, calibration, CAN forwarding, custom configuration, +firmware update or script execution. + +## Placement and ownership + +One `mission-core-vesc` service owns the serial descriptors. The Node model +registry admits only its Unix socket and explicit domain operations. Local Node UI +and paired Core use the same `SensorUiContribution` and operation journal. +`VESC Tool` is a text action in the existing device row, opening the existing +Detail slot. No workspace, root, visual control or motor icon was added. + +Candidates must match `0483:5740` and `ChibiOS/RT Virtual COM Port`. USB serial +is never their durable identity: every candidate starts with a transport-local +attachment including USB devnum. Only a valid firmware reply with a nonzero +12-byte UUID establishes a stable ID. Duplicate protocol UUIDs remain separate +provisional rows and cannot receive read operations. Replug renews the session. +Names and physical Left/Right roles must not be inferred from tty numbering. + +The read-only serial path admits command bytes 0, 4, 14, 17, 31 and 62, with no +arguments: identity, values, motor config, application config, decoded PPM and +CAN discovery. The separate fixed test commands are described below. No +keepalive, detect, config write, terminal or arbitrary packet API exists. Firmware identity is checked again before each operation; +backup verifies it at the end as well. CRC/framing/length and response limits +are enforced. Every port is held with flock/TIOCEXCL; an already running external +tool must release it before this service is prepared. + +## Compatibility and backup + +Wire reference is the official [VESC Tool source](https://github.com/vedderb/vesc_tool/tree/dc53c658cbb89a947246034f7a00149cf79abdfc), +specifically packet.cpp, commands.cpp and datatypes.h. The reference identifies +itself as test version 7.01; it is not installed by this profile. The first +reader implements the common values prefix for motor firmware major 5–7 and +hardware type 0 (or an older reply without hardware type). Exact board/firmware +qualification remains a hardware acceptance result, not a claim from a version +number alone. Unknown layouts may identify themselves but are not decoded. + +Config replies are preserved as received, including command byte and signature, +with SHA-256 and identity/version metadata. Their fields are not decoded without +the exact firmware schema. The backups are not XML files importable into Tool, +and this profile provides no restore action. Motor and application reads are +sequential, not an atomic snapshot against other controller interfaces. + +Read receipts and backups live privately in `/var/lib/mission-core-vesc`. +Operation IDs bind the exact request; retries retrieve receipts. An interrupted +request remains unknown rather than being silently replayed. This service's +host storage is bounded and does not delete backups to make space. GUI telemetry +is an explicitly requested timestamped snapshot, not a control loop or a +waveform recorder. ERPM is not mechanical shaft RPM. + +## Packaging and first preparation + +Node 0.8.22-1 carries this plugin from `packaging/payload.py`; no ad-hoc files, +global Python packages or separate Qt installation are required. The source +build pin is Design Guideline `8dd9190573d6616024ef01b9b34bf90b72960f44`. +The existing versioned owner installer installs Node. Its local Ubuntu sudo +prompt belongs to the owner; no password is handled by Core or an agent. + +The device's Prepare action starts only +`mission-core-node-vesc-prepare.service`, via the existing Node polkit rule. +The shipped profile creates the dedicated account, installs the exact-candidate +udev rule, applies it to matching attached ttys and starts the read service. +It does not add the operator or Node to dialout or disable ModemManager globally. +Node retains PrivateDevices. The adapter has no capabilities, private network, +read-only system files, bounded memory/tasks and a cdc_acm device cgroup rule. +`modprobe@cdc_acm` ensures the named ttyACM group exists before cgroup resolution +on cold boot; [systemd DeviceAllow](https://www.freedesktop.org/software/systemd/man/latest/systemd.resource-control.html#DeviceAllow=) +uses group names from `/proc/devices`, not `char-`. + +Before package replacement, the installer refuses an active preparation and +stops the reader. A prepared profile restarts through its shipped job afterward. +Removal stops/disables the service and removes only a byte-matching owned udev +rule. Private backups and account identity are retained. Rolling Node back to +0.8.21-3 disables VESC support; do not claim an older package can restore the new +UI or firmware configuration. No VESC firmware was changed by this profile. + +## Validation + +Synthetic tests cover every denied transmit byte, fragmented/coalesced/corrupt +frames, missing identities, scales, duplicate IDs, two independent attachments, +replug sessions, receipts, config hashes and denied write actions. Node tests +cover UUID promotion and preservation of camera guards. Full Node and Core +checks are required alongside Linux package qualification and actual hardware +reads. Test success is not clean-Ubuntu or motor calibration acceptance. + +On the Mini, `qmake`, `qmake6` and `cmake` were absent in the read-only build +inventory. This first increment therefore uses the bounded reader fallback from +the implementation plan. Headless extraction of the full upstream engine has +not been demonstrated; it remains a separate build/compatibility task for the +remaining Tool feature matrix. + + +## 0.2.1 — per-controller identification pulse and immutable archive + +Node 0.8.24-1 adds a fixed 2 A pulse on one selected VESC, with a duration +chosen from 1.5, 5 or 10 seconds. Discovery and session validation accept up +to 128 directly attached controllers per board; there is no two-motor role enum. +Names are the existing UUID-bound device names, scoped to their board. +Synthetic 1/6/10-controller tests do not establish physical USB capacity. +This is not a vehicle drive controller, completed RC arbiter, or calibration. +All attached UUID sessions, firmware 5.02 / 75_300_R2, FOC, PPM Duty Cycle, +neutral input for one second and a zero-current failsafe are mandatory. +Official 5.02 schemas are included unchanged with their upstream license. +Before any torque, motor and application configurations of every attached +controller are archived durably, and each CAN segment is checked for unmanaged +peers. Attachments are rechecked throughout the pulse. Each +controller receives its own 250 ms volatile app-output lease (CAN-forward +flag false). Other controllers receive zero current; the target receives only 2 A. +A receiver command, serial fault, telemetry limit or local Stop ends the test. +No config/firmware write, arbitrary current, arbitrary packet or CAN broadcast +is exposed. Replaying an operation ID never repeats physical work. + +Firmware PPM pulses reset the global timeout even during app-output pause; +therefore the design relies on the expiring local app-output lease returning +to the existing PPM neutral/missing-pulse behavior, not solely on USB timeout. +RC activity latches further test requests until an explicit neutral release. +This is a test-session guard, not continuous production RC takeover monitoring. +Neutral PPM alone cannot prove transmitter/link availability. Host-independent +lease behavior follows the pinned firmware source; real stop/failsafe +qualification is still required and must not be claimed from synthetic tests. + +Versions live in a private SQLite archive, are replicated via existing pairing +with ACK after durable Core storage, and remain downloadable when a controller +is offline. The Node and Core use the same detail component. The native VESC +Tool 7.00 engineering build is separate: it has not acquired serial ownership +or been integrated for calibration. + +Package upgrades remove only generated bytecode below the installed VESC +payload before preparation starts. Deterministic source mtimes can otherwise +validate stale same-size `.pyc` files even with `python -B`; a regression test +reproduces the failed 0.8.23-1 upgrade and verifies this installer-owned fix. + +## 0.2.2 — entered test values and drive positions + +Node 0.8.25-1 carries numeric current and duration fields. The board advertises +and independently enforces 0.5–5 A and 0.5–10 seconds for this identification +mode. These are software bounds, not controller or motor nameplate +ratings. Existing 60 A motor / 55 A battery configuration is not evidence that +the rig can safely sustain those currents. Above 2 A the test coasts at +400 electrical RPM and resumes current below 250, with a separate 800 ERPM +abort threshold. Requested current is also bounded by the read configuration. +Receipts distinguish successfully sent current commands from sampled cycles +that ended before transmission. These bounds do not admit maximum-power tests. + +The existing VESC detail offers one board-wide drive profile: 1×1 means left +and right (two motors); 2×2 means left front, left rear, right front and right +rear (four motors). Directions are relative to forward vehicle motion. Position +is manually assigned after physical identification and persists by controller +UUID, not USB address. The same component is used on Node and paired Core. +Revision checks prevent stale updates; an occupied position cannot be stolen, +and rear assignments must be explicitly removed before shrinking to 1×1. +Changing profile/position is local metadata and sends no VESC command. +Discovery itself remains independent of these two admitted layout presets. + +## 0.2.3 — explain blocked tests and retain stop evidence + +Numeric fields show validation errors beside invalid values. The action area +explains why Start is unavailable, including confirmation reset after a test. +A telemetry-bound stop retains the triggering sample and its field, measured +value and unchanged bounds. A completed current pulse never proves physical +rotation; the owner must observe the motor before assigning its position. + +## 0.2.4 — gradual current in identification mode + +The confirmed right motor crossed800ERPM within0.245s of a5A step. The next +profile starts and resumes at0.5A, increasing by approximately1A/s toward the +entered ceiling. Soft coasting triggers at200ERPM or4%PWM and only resumes +below100ERPM and2%PWM. It applies to every allowed current, while the hard +abort thresholds remain unchanged. This is an identification pulse governor, +not a vehicle speed controller. Command receipts record actual requested +current per sample, including ramp/coasting;5A input is a ceiling. + + +## 0.2.5 — entered current up to 30 A and time up to 30 seconds + +At the owner's request the raised-rig test accepts 0.5–30 A and 0.5–30 s. +These are software admission bounds, not motor/controller nameplate ratings. +The selected controller's configured motor and input current limits still bind. +Positive current starts at0.5A and ramps by2A/s; the entered value is a current +ceiling, not a speed request. No configuration or firmware write is performed. + +The former200ERPM/4%PWM coast/restart loop was causing the observed right-motor +steps and pauses. This increment removes that automatic cycling. Current is +maintained until time expires, Stop/RC/link interruption, or a telemetry limit. +The test ends at6000ERPM or25%PWM (or a lower configured speed/duty limit), +without automatic re-acceleration. A no-load motor can reach a speed limit +before the entered time:30seconds is the maximum duration, not a promise of +constant-speed rotation. Current feedback has bounded overshoot tolerance, +capped by the configured motor current limit. Fault, voltage, temperature, +identity/topology, neutral RC, expiring per-device leases and release checks +remain active. + +Above5A, a2-second interval without at least three net electrical tachometer +steps at60ERPM ends the test. This uses the existing Hall/FOC estimate; it is +not independent mechanical feedback or certified thermal protection, especially +with a damaged sensor connection. It prevents continuing to raise commanded +current while the reported rotor remains stationary. Sustained vehicle control, +calibration and native VESC Tool parity remain separate unfinished work. + +The owner clarified the diagnostic roles: LEFT is the problematic motor; +RIGHT works normally from RC and is physically assigned right.1. Short steps +in the earlier Core test must not be recorded as a right-motor defect. Every +powered engineering experiment is coordinated with the owner at launch time. + + +## 0.3.0 — measured speed hold and native Hall measurement + +`vesc.motor.run` calls firmware speed PID (`COMM_SET_RPM`), ramps the setpoint +at 600 ERPM/s and counts time only after one second within 15% of the requested +speed with a changing VESC tachometer. The UI exposes speed 300–3000 ERPM, +motor-current ceiling 0.5–30 A and **rotation time** 0.5–30 s. Startup is bounded +by 15 s; losing speed for 2 s ends the run. No automatic restart. FOC telemetry +is not an independent physical encoder; the operator compares visible motion. +The old `vesc.motor.pulse` action remains compatible but is not used by this UI. + +Before a speed command, `COMM_SET_MCCONF_TEMP` applies current scaling to both +positive and braking motor current. Store/CAN/divide flags are false. ACK and +full configuration readback precede torque. A durable UUID-bound journal exists +before the first write. Cleanup restores the exact original configuration, +verified byte-for-byte. A lost ACK, disconnection or process interruption leaves +the journal pending; discovery retries restoration only with a matching identity, +zero current, neutral receiver and unchanged unrelated configuration. An external +configuration change is never overwritten. No flash or application write is used. +The operation transport permits 90 s, including preflight and acceleration. + +`vesc.hall.measure` is the native FW 5.02 `COMM_DETECT_HALL_FOC` procedure also +used by VESC Tool. It uses fixed 5 A, sweeps three electrical turns forward and +three backwards, returns the observed table and restores its prior configuration. +The table is **not automatically applied**. The firmware locks `mc_interface` +during this approximately 12 s cycle; USB current-zero and receiver input cannot +interrupt it. The UI requires a separate observed-rig/physical-power-cut +acknowledgement and explicitly describes this limitation. Unknown completion +latches authority and blocks another powered operation. Measurement, samples and +backup references remain in the receipt. + +These operations do not constitute the full VESC Tool desktop UI. The product +entry is labelled “Настройка VESC” until complete native application session +integration is shipped. Full R/L/flux calibration, table application and +configuration restore remain separate unimplemented work. diff --git a/plugins/vesc/frontend/src/VescBackups.tsx b/plugins/vesc/frontend/src/VescBackups.tsx new file mode 100644 index 0000000..0ada10e --- /dev/null +++ b/plugins/vesc/frontend/src/VescBackups.tsx @@ -0,0 +1,51 @@ +import {useEffect,useState} from 'react'; +import {Button,LoadingRegion,ResourceList,ResourceRow,SettingsCard} from '@nodedc/ui-react'; +import type {ConfigurationVersion,SensorTransport} from '../../../../packages/sensor-ui/src/contracts'; + +export function VescBackups({deviceId,archive,revision}: {deviceId:string;archive:SensorTransport['configurationArchive'];revision:string|null}) { + const [reload,setReload]=useState(0); + const [items,setItems]=useState([]); + const [next,setNext]=useState(null); + const [loading,setLoading]=useState(false); + const [error,setError]=useState(null); + const [download,setDownload]=useState(null); + useEffect(()=>{ + let active=true; + setItems([]);setNext(null);setError(null); + if(!archive)return; + setLoading(true); + archive.list(deviceId).then(result=>{if(active){setItems(result.items);setNext(result.next);}}) + .catch(()=>{if(active)setError('Не удалось загрузить историю конфигураций.');}) + .finally(()=>{if(active)setLoading(false);}); + return()=>{active=false;}; + },[deviceId,archive,revision,reload]); + async function more(){ + if(!archive||!next||loading)return; + setLoading(true);setError(null); + try{const result=await archive.list(deviceId,next);setItems(current=>[...current,...result.items.filter(item=>!current.some(old=>old.id===item.id))]);setNext(result.next);} + catch{setError('Не удалось загрузить следующие версии.');} + finally{setLoading(false);} + } + async function save(id:string){ + if(!archive||download)return; + setDownload(id);setError(null); + try{ + const value=await archive.read(deviceId,id); + const url=URL.createObjectURL(new Blob([JSON.stringify(value,null,2)+'\n'],{type:'application/json'})); + const link=document.createElement('a');link.href=url;link.download=`${deviceId}-${id}.json`;link.click(); + setTimeout(()=>URL.revokeObjectURL(url),1000); + }catch{setError('Не удалось скачать выбранную версию.');} + finally{setDownload(null);} + } + return setReload(value=>value+1)}>Обновить историю}> + + {error&&

    {error}

    } + {!loading&&!items.length&&!error&&

    Сохранённых версий пока нет.

    } + {items.map(item=>
  • + void save(item.id)}>Скачать}/> +
  • )}
    +
    + {next&&} +
    ; +} diff --git a/plugins/vesc/frontend/src/VescBoardSettings.tsx b/plugins/vesc/frontend/src/VescBoardSettings.tsx new file mode 100644 index 0000000..0d6327e --- /dev/null +++ b/plugins/vesc/frontend/src/VescBoardSettings.tsx @@ -0,0 +1,54 @@ +import {useRef,useState} from 'react'; +import {Button,InspectorSelectField,ResourceList,ResourceRow,SettingsCard} from '@nodedc/ui-react'; +import type {SensorBoardSettingsProps} from '../../../../packages/sensor-ui/src/extensions'; +import {perform,type Sensor} from '../../../../packages/sensor-ui/src/contracts'; +import {drivePositions,vescStatus,type DriveProfile} from './model'; +import {VescLimits} from './VescLimits'; + +export function VescBoardSettings({inventory,transport,enabled,refresh,failure,openDevice}:SensorBoardSettingsProps){ + const controllers=inventory?.items.filter(device=>device.kind==='vesc.controller')??[]; + const profile=controllers.map(device=>vescStatus(device).drive_profile).filter((value):value is DriveProfile=>!!value).sort((a,b)=>b.revision-a.revision)[0]; + const anchor=controllers.find(device=>device.online&&device.verified&&vescStatus(device).board_settings_supported); + const [busy,setBusy]=useState(false);const running=useRef(false); + const active=inventory?.operations?.some(value=>['queued','running'].includes(value.state)&&controllers.some(device=>device.id===value.device_id)); + const blocked=!enabled||!anchor||busy||active||!profile; + const positions=drivePositions(profile?.layout??null); + async function change(device:Sensor,action:string,parameters:Record){ + if(blocked||running.current||!profile)return; + running.current=true;setBusy(true);failure(null); + try{await perform(transport,device,action,{revision:profile.revision,...parameters});await refresh();} + catch(error){failure(error);await refresh();}finally{running.current=false;setBusy(false);} + } + return
    + + {if(anchor)void change(anchor,'vesc.drive.layout',{layout});}}/> + {!profile&&

    {inventory?'Подключите VESC, чтобы получить профиль привода с борта.':'Получение профиля привода…'}

    } + {profile&&!anchor&&

    Профиль показан по последним сведениям с борта. Для изменения нужна связь с VESC и актуальное бортовое приложение.

    } + {profile?.layout&&<> +

    Стороны — по направлению движения вперёд. Назначения сохраняются автоматически и остаются с контроллером при смене USB-порта.

    + {Object.entries(positions).map(([slot,label])=>{ + const bound=profile.bindings[slot]; + const missing=bound&&!controllers.some(device=>device.id===bound.device_id); + return ({value:device.id,label:device.name+(!device.online?' · нет связи':''),disabled:!device.online||!device.verified||Object.entries(profile.bindings).some(([other,binding])=>other!==slot&&binding.device_id===device.id)})), + ...(missing?[{value:bound.device_id,label:`VESC ${bound.uuid.slice(0,6).toUpperCase()} · нет связи`,disabled:true}]:[]), + ]} onChange={id=>{ + const target=id?controllers.find(device=>device.id===id):anchor; + if(!target)return; + void change(target,id?'vesc.drive.assign':'vesc.drive.unassign',id?{layout:profile.layout,slot}:{slot}); + }}/>; + })} + {Object.entries(profile.bindings).map(([slot,binding])=>{ + const target=controllers.find(device=>device.id===binding.device_id); + return
  • openDevice(binding.device_id)}>Настройка мотора}/>
  • ; + })}
    + } +
    + +
    ; +} diff --git a/plugins/vesc/frontend/src/VescCalibration.tsx b/plugins/vesc/frontend/src/VescCalibration.tsx new file mode 100644 index 0000000..5ee193c --- /dev/null +++ b/plugins/vesc/frontend/src/VescCalibration.tsx @@ -0,0 +1,56 @@ +import {useRef,useState} from 'react'; +import {Button,Checker,ResourceList,ResourceRow,SettingsCard,TextField} from '@nodedc/ui-react'; +import type {SensorDetailProps} from '../../../../packages/sensor-ui/src/extensions'; +import {perform} from '../../../../packages/sensor-ui/src/contracts'; +import {vescStatus} from './model'; + +interface CalibrationResult { + completed:boolean;success:boolean;configuration_verified:boolean;release_confirmed:boolean; + native:{success?:boolean;code?:number;sensor_mode?:number;parameters?:Record}; +} + +export function VescCalibration({device,transport,enabled,refresh,failure,blocked,onBusyChange}:SensorDetailProps&{blocked:boolean;onBusyChange:(busy:boolean)=>void}){ + const [loss,setLoss]=useState('50'); + const [confirmed,setConfirmed]=useState(false); + const [busy,setBusy]=useState(false); + const [result,setResult]=useState(null); + const running=useRef(false); + const limits=vescStatus(device).foc_calibration; + const power=Number(loss); + const valid=!!limits&&loss.trim()!==''&&Number.isFinite(power)&&power>=limits.min_power_loss_w&&power<=limits.max_power_loss_w; + const available=enabled&&device.online&&device.verified&&device.vesc_status?.test_supported===true&&!!limits; + async function calibrate(){ + if(running.current||blocked||!available||!confirmed||!valid)return; + running.current=true;setBusy(true);onBusyChange(true);setResult(null);failure(null); + try{ + const inventory=await transport.inventory(); + const controllers=inventory.items.filter(item=>item.kind==='vesc.controller'&&item.online); + const target=controllers.find(item=>item.id===device.id); + if(inventory.fresh===false||!target||controllers.some(item=>!item.verified))throw new Error('Нужна свежая связь со всеми VESC борта.'); + setResult(await perform(transport,target,'vesc.foc.calibrate',{ + rig_clear:true,native_cycle_confirmed:true,max_power_loss_w:power, + sessions:Object.fromEntries(controllers.map(item=>[item.id,item.snapshot.context.session_id])), + },300000)); + }catch(error){failure(error);} + finally{running.current=false;setBusy(false);onBusyChange(false);setConfirmed(false);await refresh();} + } + const parameters=result?.native.parameters; + const calibrated=result?.native.success===true&&result.configuration_verified; + return +

    Мастер измеряет сопротивление, индуктивность и магнитный поток, определяет датчики и записывает параметры выбранного мотора. Версии до и после сохраняются в истории; настройки аккумулятора и пульта сохраняются.

    + setLoss(event.target.value)} disabled={busy||blocked||!limits} min={limits?.min_power_loss_w} max={limits?.max_power_loss_w} step="5" aria-invalid={!valid} description="Параметр нагрева для мастера VESC Tool, не номинальная мощность мотора. По нему мастер выбирает токи измерения; предел тока проверки вращения здесь не применяется."/> +

    Мотор будет двигаться и разгоняться. На прошивке 5.02 процедуру нельзя прервать кнопкой или пультом — только отключением силового питания. Оставьте пульт выключенным и приводы вывешенными до завершения; цикл может занять до трёх минут.

    + + + {busy&&

    Подготовка и калибровка VESC Tool. Дождитесь результата и снятия тока.

    } + {result&&<> +

    {calibrated?'Параметры мотора измерены, записаны и проверены.':result.completed?`Калибровка не принята. Код VESC: ${result.native.code??'не получен'}.`:'Завершение калибровки не подтверждено. Проверьте состояние мотора и питание.'} {result.release_confirmed?'Снятие тока подтверждено.':'Снятие тока пока не подтверждено. Перед следующей проверкой верните управление после нейтрали.'} {!result.configuration_verified&&' Проверка конфигурации не завершена; новое движение заблокировано.'}

    + {calibrated&&<> +

    {result.native.sensor_mode===0?'Выбран режим без датчиков. Холлы не определились; качество запуска нужно проверить вращением.':result.native.sensor_mode===2?'Определены датчики Холла.':'Определён энкодер.'}

    + {parameters&& + {([['foc_motor_r','Сопротивление',1000,'мОм'],['foc_motor_l','Индуктивность',1e6,'мкГн'],['foc_motor_flux_linkage','Магнитный поток',1000,'мВб'],['l_current_max','Предел тока мотора',1,'А']] as const).map(([key,title,scale,unit])=>
  • )} +
    } + } + } +
    ; +} diff --git a/plugins/vesc/frontend/src/VescDetail.tsx b/plugins/vesc/frontend/src/VescDetail.tsx new file mode 100644 index 0000000..8b90e6b --- /dev/null +++ b/plugins/vesc/frontend/src/VescDetail.tsx @@ -0,0 +1,80 @@ +import {useEffect,useRef,useState} from 'react'; +import {Button,LoadingRegion,ResourceList,ResourceRow,SettingsCard,StatusBadge} from '@nodedc/ui-react'; +import type {SensorDetailProps} from '../../../../packages/sensor-ui/src/extensions'; +import {perform} from '../../../../packages/sensor-ui/src/contracts'; +import {vescLabel,vescStatus,type VescTelemetry} from './model'; +import {VescBackups} from './VescBackups'; +import {VescMotor} from './VescMotor'; +import {VescHall} from './VescHall'; +import {VescCalibration} from './VescCalibration'; +import {VescLink} from './VescLink'; + +const fields=[['input_voltage_v','Напряжение питания','В'],['input_current_a','Ток питания','А'], + ['motor_current_a','Ток мотора','А'],['erpm','Электрические обороты','ERPM'],['duty','Заполнение PWM',''], + ['mos_temperature_c','Температура контроллера','°C'],['motor_temperature_c','Температура мотора','°C'], + ['fault_code','Код ошибки',''],['can_id','CAN ID',''],['timeout','Тайм-аут управления',''], + ['kill_switch','Вход аварийного останова','']] as const; + +export function VescDetail(props:SensorDetailProps){ + const {device,transport,enabled,back,refresh,failure}=props; + const status=vescStatus(device);const label=vescLabel(device,enabled); + const [telemetry,setTelemetry]=useState(status.telemetry); + const [pending,setPending]=useState(null); + const [saved,setSaved]=useState(null); + const [motorBusy,setMotorBusy]=useState(false); + const [hallBusy,setHallBusy]=useState(false); + const [calibrationBusy,setCalibrationBusy]=useState(false); + const [linkBusy,setLinkBusy]=useState(false); + const poweredBusy=motorBusy||hallBusy||calibrationBusy||linkBusy; + const running=useRef(false);const mounted=useRef(true); + const available=enabled&&device.online&&device.verified&&status.readable; + useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]); + async function read(action:'vesc.telemetry.read'|'vesc.config.backup'){ + if(running.current||poweredBusy||!available)return; + running.current=true;setPending(action);failure(null); + try{ + const result=await perform>(transport,device,action); + if(!mounted.current)return; + if(action==='vesc.telemetry.read')setTelemetry(result as unknown as VescTelemetry); + else { + setSaved(String(result.observed_at)); + } + await refresh(); + }catch(error){if(mounted.current)failure(error);} + finally{running.current=false;if(mounted.current)setPending(null);} + } + const backupAt=saved??status.backup?.observed_at; + return
    +
    + {label.label}}> + {!enabled||!device.online?

    Нет свежей связи с контроллером.

    :status.message?

    {status.message}

    :null} + {status.identity? +
  • +
  • +
  • + {status.identity.test_firmware!==null&&status.identity.test_firmware>0&&
  • } +
    :

    Аппаратный идентификатор ещё не подтверждён.

    } +
    + void read('vesc.telemetry.read')}>Обновить показания}> + + {telemetry?{fields.map(([key,title,unit])=>{ + const value=telemetry.values[key];if(value===undefined)return null; + return
  • ; + })}
    :

    Показания ещё не прочитаны.

    } +
    +

    ERPM — электрические обороты. Обороты вала зависят от числа пар полюсов мотора.

    +
    + void read('vesc.config.backup')}>Сохранить версию}> + {backupAt&&

    Последняя копия: {new Date(backupAt).toLocaleString()}

    } +

    Копия привязана к UUID и прошивке. Версии до и после калибровки остаются в истории.

    +
    + + + + + +
    ; +} diff --git a/plugins/vesc/frontend/src/VescHall.tsx b/plugins/vesc/frontend/src/VescHall.tsx new file mode 100644 index 0000000..870102d --- /dev/null +++ b/plugins/vesc/frontend/src/VescHall.tsx @@ -0,0 +1,42 @@ +import {useRef,useState} from 'react'; +import {Button,Checker,SettingsCard} from '@nodedc/ui-react'; +import type {SensorDetailProps} from '../../../../packages/sensor-ui/src/extensions'; +import {perform} from '../../../../packages/sensor-ui/src/contracts'; +import {vescStatus} from './model'; + +interface HallResult { + completed:boolean;configuration_restored:boolean;release_confirmed:boolean; + measurement:null|{valid_six_states:boolean;observed_states:number[];hall_table:number[]}; +} + +export function VescHall({device,transport,enabled,refresh,failure,blocked,onBusyChange}:SensorDetailProps&{blocked:boolean;onBusyChange:(busy:boolean)=>void}){ + const [confirmed,setConfirmed]=useState(false); + const [busy,setBusy]=useState(false); + const [result,setResult]=useState(null); + const running=useRef(false); + const available=enabled&&device.online&&device.verified&&device.vesc_status?.test_supported===true&&!!vescStatus(device).hall_measurement; + async function measure(){ + if(running.current||blocked||!available||!confirmed)return; + running.current=true;setBusy(true);onBusyChange(true);setResult(null);failure(null); + try{ + const inventory=await transport.inventory(); + const controllers=inventory.items.filter(item=>item.kind==='vesc.controller'&&item.online); + const target=controllers.find(item=>item.id===device.id); + if(inventory.fresh===false||!target||controllers.some(item=>!item.verified))throw new Error('Нужна свежая связь со всеми VESC борта.'); + setResult(await perform(transport,target,'vesc.hall.measure',{ + rig_clear:true,native_cycle_confirmed:true, + ...(vescStatus(target).hall_measurement?.standstill_confirmation_required?{standstill_confirmed:true}:{}), + sessions:Object.fromEntries(controllers.map(item=>[item.id,item.snapshot.context.session_id])), + },60000)); + }catch(error){failure(error);} + finally{running.current=false;setBusy(false);onBusyChange(false);setConfirmed(false);await refresh();} + } + return +

    Мотор медленно смещается в обе стороны около 12 секунд. Измерение проверяет состояния датчиков и получает таблицу их положения; новая таблица автоматически не записывается.

    +

    На прошивке 5.02 этот цикл нельзя прервать кнопкой или пультом. Для немедленной остановки нужно отключить силовое питание. Пульт должен оставаться выключенным, все приводы — вывешенными. Перед запуском убедитесь, что все моторы полностью остановились: в бессенсорном режиме показание оборотов на остановленном моторе может быть ненулевым.

    + + + {busy&&

    Подготовка и штатное измерение датчиков. Дождитесь результата.

    } + {result&&

    {!result.completed?'Завершение измерения не подтверждено. Проверьте мотор и питание.':result.measurement?.valid_six_states?'Измерение получило шесть состояний Холла.':'Не удалось получить полную таблицу Холла. Возможны отсутствие движения или неисправность датчиков/соединения.'} {result.release_confirmed?'Снятие тока подтверждено.':'Снятие тока не подтверждено.'} {result.configuration_restored?'Исходная конфигурация сохранена.':'Возврат исходной конфигурации не подтверждён.'}

    } +
    ; +} diff --git a/plugins/vesc/frontend/src/VescLimits.tsx b/plugins/vesc/frontend/src/VescLimits.tsx new file mode 100644 index 0000000..dfb4adb --- /dev/null +++ b/plugins/vesc/frontend/src/VescLimits.tsx @@ -0,0 +1,35 @@ +import {useRef,useState} from 'react'; +import {Button,ResourceList,ResourceRow,SettingsCard} from '@nodedc/ui-react'; +import {perform,type Sensor,type SensorTransport} from '../../../../packages/sensor-ui/src/contracts'; +import {vescStatus} from './model'; + +interface Limits {observed_at:string;identity?:{uuid:string};parameters:Record} +const number=(value:number|undefined)=>value===undefined?'—':value.toLocaleString('ru-RU',{maximumFractionDigits:2}); +export function VescLimits({controllers,transport,enabled,failure}:{controllers:Sensor[];transport:SensorTransport;enabled:boolean;failure:(error:unknown)=>void}){ + const [values,setValues]=useState>({}); + const [busy,setBusy]=useState(false);const running=useRef(false); + const readable=controllers.filter(device=>device.online&&device.verified&&vescStatus(device).readable&&vescStatus(device).board_settings_supported); + async function read(){ + if(!enabled||running.current||!readable.length)return; + running.current=true;setBusy(true);failure(null);setValues({}); + try{for(const device of readable){const value=await perform(transport,device,'vesc.limits.read');setValues(current=>({...current,[device.id]:value}));}} + catch(error){failure(error);}finally{running.current=false;setBusy(false);} + } + return void read()}>Прочитать ограничения}> +

    Ток мотора задаёт тягу; ток батареи ограничивает потребление. Эти настройки действуют и при управлении с пульта. Паспортные пределы моторов, контроллеров и батареи проверяются отдельно.

    + {controllers.map(device=>{ + const value=values[device.id];if(!value)return null; + const p=value.parameters; + const fields=[ + ['Ток мотора · разгон / торможение',`${number(p.l_current_max)} / ${number(p.l_current_min)} А`], + ['Масштаб тока · разгон / торможение',`${number(p.l_current_max_scale*100)} / ${number(p.l_current_min_scale*100)} %`], + ['Ток батареи · потребление / рекуперация',`${number(p.l_in_current_max)} / ${number(p.l_in_current_min)} А`], + ['Диапазон электрических оборотов',`${number(p.l_min_erpm)} … ${number(p.l_max_erpm)} ERPM`], + ['Максимальная мощность',p.l_watt_max>=1500000?'Отдельный предел не задан':`${number(p.l_watt_max)} Вт`], + ['Максимальный duty cycle',`${number(p.l_max_duty*100)} %`], + ]; + return {fields.map(([title,description])=>
  • )}
    ; + })} + {!Object.keys(values).length&&

    Прочитайте значения для подключённых контроллеров.

    } +
    ; +} diff --git a/plugins/vesc/frontend/src/VescLink.tsx b/plugins/vesc/frontend/src/VescLink.tsx new file mode 100644 index 0000000..1317b63 --- /dev/null +++ b/plugins/vesc/frontend/src/VescLink.tsx @@ -0,0 +1,42 @@ +import {useEffect,useRef,useState} from 'react'; +import {Button,ResourceList,ResourceRow,SettingsCard} from '@nodedc/ui-react'; +import type {SensorDetailProps} from '../../../../packages/sensor-ui/src/extensions'; +import {perform} from '../../../../packages/sensor-ui/src/contracts'; +import {vescStatus} from './model'; + +interface LinkResult { + outcome:string;duration_s:number; + devices:Record; +} +export function VescLink({device,transport,enabled,failure,refresh,blocked,onBusyChange}:SensorDetailProps&{blocked:boolean;onBusyChange:(busy:boolean)=>void}){ + const [busy,setBusy]=useState(false);const [result,setResult]=useState(null); + const running=useRef(false);const mounted=useRef(true); + useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]); + const available=enabled&&device.online&&device.verified&&vescStatus(device).link_check_supported; + async function check(){ + if(running.current||blocked||!available)return; + running.current=true;setBusy(true);onBusyChange(true);failure(null);setResult(null); + try{ + const inventory=await transport.inventory(); + const peers=inventory.items.filter(item=>item.kind==='vesc.controller'); + const selected=peers.find(item=>item.id===device.id); + if(inventory.fresh===false||!selected||peers.some(item=>!item.online||!item.verified))throw new Error('Обновите связь со всеми VESC борта.'); + const sessions=Object.fromEntries(peers.map(item=>[item.id,item.snapshot.context.session_id])); + const value=await perform(transport,selected,'vesc.link.check',{sessions},45000); + if(mounted.current)setResult(value); + await refresh(); + }catch(error){if(mounted.current)failure(error);} + finally{running.current=false;if(mounted.current){setBusy(false);onBusyChange(false);}} + } + if(!vescStatus(device).link_check_supported)return null; + const text=result?.outcome==='complete'?'Все ответы получены. Эта проверка не подтверждает связь во время вращения.': + result?.outcome==='not_idle'?'Измерение прекращено: есть команда с пульта или движение мотора.': + result?.outcome==='read_failed'?'Ответ контроллера не получен. Проверка прервана.': + 'Измерение не завершено.'; + return void check()}>Проверить связь}> + {busy&&

    Измеряется время ответа контроллеров.

    } + {result&&<>

    {text}

    {Object.entries(result.devices).map(([id,item])=>
  • )}
    } +
    ; +} diff --git a/plugins/vesc/frontend/src/VescMotor.tsx b/plugins/vesc/frontend/src/VescMotor.tsx new file mode 100644 index 0000000..a5a94dd --- /dev/null +++ b/plugins/vesc/frontend/src/VescMotor.tsx @@ -0,0 +1,89 @@ +import {useEffect,useRef,useState} from 'react'; +import {Button,Checker,Select,TextField,SettingsCard} from '@nodedc/ui-react'; +import type {SensorDetailProps} from '../../../../packages/sensor-ui/src/extensions'; +import {perform} from '../../../../packages/sensor-ui/src/contracts'; +import {testInput,speedInput,rotationResult,vescStatus,driveTestIds,drivePositions} from './model'; + +export function VescMotor({device,transport,enabled,refresh,failure,blocked=false,onBusyChange}:SensorDetailProps&{blocked?:boolean;onBusyChange?:(busy:boolean)=>void}){ + const [duration,setDuration]=useState('30'); + const [current,setCurrent]=useState('30'); + const [speed,setSpeed]=useState('2000'); + const [direction,setDirection]=useState('forward'); + const [scope,setScope]=useState('single'); + const status=vescStatus(device),profile=status.drive_profile; + const driveIds=driveTestIds(profile,device.id); + const group=scope==='profile'; + const groupAvailable=status.group_test_supported===true&&driveIds.length>1; + const [clear,setClear]=useState(false);const [busy,setBusy]=useState(false); + const [result,setResult]=useState(null);const [stopping,setStopping]=useState(false); + const [rc,setRc]=useState(device.vesc_status?.rc_latched===true); + const running=useRef(false);const mounted=useRef(true); + useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]); + const limits=vescStatus(device).test_limits; + const speedLimits=vescStatus(device).speed_limits; + const speedValue=speedInput(speed,speedLimits); + const input=testInput(current,duration,limits); + const available=!!limits&&!!speedLimits&&enabled&&!blocked&&device.online&&device.verified&&device.vesc_status?.test_supported===true; + const valid=input.valid&&!speedValue.error&&(direction==='forward'||speedLimits?.reverse_supported===true)&&(!group||groupAvailable); + const blockedReason=busy?'Подготовка и проверка выполняются. Дождитесь результата или остановите проверку.': + !enabled||!device.online?'Для запуска нужна свежая связь с бортом и VESC.': + !device.verified?'Контроллер ещё не определён. Обновите устройства.': + !available?'Проверка вращения для этого VESC сейчас недоступна на борту.': + !valid?'Исправьте значения в отмеченных полях.': + !clear?'Для запуска подтвердите, что все приводы остановлены, вывешены и вращение свободно.':null; + async function execute(release=false){ + if(running.current||!available||!clear||!valid)return; + running.current=true;setBusy(true);onBusyChange?.(true);setResult(null);failure(null); + try{ + const inventory=await transport.inventory(); + const controllers=inventory.items.filter(item=>item.kind==='vesc.controller'&&item.online); + const target=controllers.find(item=>item.id===device.id); + if(inventory.fresh===false||!target||controllers.some(item=>!item.verified))throw new Error('Нужна свежая связь со всеми подключёнными VESC этого борта.'); + if(group&&!release&&(vescStatus(target).drive_profile?.revision!==profile?.revision||driveIds.some(id=>!controllers.some(item=>item.id===id))))throw new Error('Профиль или состав моторов изменился. Обновите карточку.'); + const value=await perform<{outcome?:string;rotation_s?:number;release_confirmed?:boolean;limits_restored?:boolean}>(transport,target,release?'vesc.control.release':group?'vesc.drive.run':'vesc.motor.run',{ + rig_clear:true,duration_s:input.durationS,current_a:input.currentA, + ...(release?{}:{erpm:speedValue.erpm*(direction==='reverse'?-1:1)}), + ...(vescStatus(target).speed_limits?.standstill_confirmation_required?{standstill_confirmed:true}:{}), + ...(!release&&group?{profile_revision:profile?.revision,device_ids:driveIds}:{}), + sessions:Object.fromEntries(controllers.map(item=>[item.id,item.snapshot.context.session_id])), + },group&&!release?120000:90000); + if(mounted.current){ + setResult(release?'Управление возвращено для проверки.':rotationResult(value)); + if(release)setRc(false); + } + }catch(error){if(mounted.current)failure(error);} + finally{ + running.current=false; + onBusyChange?.(false); + if(mounted.current){setBusy(false);setClear(false);await refresh();} + } + } + async function stop(){ + if(stopping)return;setStopping(true); + try{const value=await perform<{interruptible?:boolean}>(transport,device,'vesc.motor.stop',{},15000);if(mounted.current)setResult(value.interruptible===false?'Идёт штатный цикл измерения VESC. Немедленная остановка возможна отключением питания.':'Остановка запрошена. Ожидаем результат проверки.');} + catch(error){if(mounted.current)failure(error);} + finally{if(mounted.current)setStopping(false);} + } + useEffect(()=>setRc(device.vesc_status?.rc_latched===true),[device.vesc_status?.rc_latched]); + return +

    Для вывешенных колёс без нагрузки. При команде с приёмника проверка прекращается; повторный запуск требует явного возврата управления.

    + {setDirection(value);setClear(false);}}/> +

    Направление относительно настроек VESC. Перед обратным запуском дождитесь полной остановки всех моторов и подтвердите её.

    + setSpeed(event.target.value)} disabled={busy||!speedLimits} min={speedLimits?.min_erpm} max={speedLimits?.max_erpm} step="100" aria-invalid={!!speedValue.error} description={speedValue.error??'Электрические обороты в минуту. VESC плавно разгоняет мотор и удерживает заданную скорость.'}/> + setCurrent(event.target.value)} disabled={busy||!limits} min={limits?.min_current_a} max={limits?.max_current_a} step="0.1" aria-invalid={!!input.currentError} hint={limits?`${limits.min_current_a}–${limits.max_current_a} А`:undefined} description={input.currentError??'Максимальный ток разгона и удержания скорости. Прежние пределы сохраняются перед тестом и восстанавливаются после него.'}/> + setDuration(event.target.value)} disabled={busy||!limits} min={limits?.min_duration_s} max={limits?.max_duration_s} step="0.1" aria-invalid={!!input.durationError} hint={limits?`${limits.min_duration_s}–${limits.max_duration_s} с`:undefined} description={input.durationError??'Отсчёт начинается после разгона и стабилизации скорости. Подготовка, разгон и остановки не входят в это время.'}/> +

    Время считается по скорости и тахометру VESC. Если мотор не разгонится за 15 секунд, потеряет скорость или сработает ограничение, результат покажет фактическое время и причину остановки. Показания контроллера нужно сопоставить с видимым вращением.

    + {limits?.stall_timeout_s&&

    При токе выше {limits.stall_current_a} А и отсутствии подтверждённого движения в течение {limits.stall_timeout_s} секунд проверка остановится.

    } +

    Все приводы должны быть вывешены, вращение свободно. Подтверждение требуется перед каждым запуском.

    + + {blockedReason&&

    {blockedReason}

    } +
    + {rc?: + } + +
    + {result&&

    {result}

    } +
    ; +} diff --git a/plugins/vesc/frontend/src/model.ts b/plugins/vesc/frontend/src/model.ts new file mode 100644 index 0000000..eeaa024 --- /dev/null +++ b/plugins/vesc/frontend/src/model.ts @@ -0,0 +1,69 @@ +import type {Sensor} from '../../../../packages/sensor-ui/src/contracts'; + +export interface VescIdentity {uuid:string;hardware:string;version:string;test_firmware:number|null;hardware_type:number|null} +export interface VescTelemetry {observed_at:string;values:Record} +export interface DriveProfile {layout:null|'1x1'|'2x2';revision:number;bindings:Record} +export function drivePositions(layout:DriveProfile['layout']):Record { + return layout==='2x2' + ? {'left.1':'Левый передний','left.2':'Левый задний','right.1':'Правый передний','right.2':'Правый задний'} + : {'left.1':'Левый','right.1':'Правый'}; +} +export interface VescStatus { + board_settings_supported?:boolean; + group_test_supported?:boolean; + link_check_supported?:boolean; + foc_calibration?:{min_power_loss_w:number;max_power_loss_w:number;interruptible:boolean}; + speed_limits?:{min_erpm:number;max_erpm:number;duration_basis:string;reverse_supported?:boolean;standstill_confirmation_required?:boolean}; + hall_measurement?:{current_a:number;interruptible:boolean;standstill_confirmation_required?:boolean}; + drive_profile?:DriveProfile; + test_limits?:{min_current_a:number;max_current_a:number;min_duration_s:number;max_duration_s:number;current_ramp_a_per_s?:number;continuous_current?:boolean;max_erpm?:number;max_duty?:number;stall_current_a?:number;stall_timeout_s?:number}; + identity:VescIdentity|null; readable:boolean; message:string|null; telemetry:VescTelemetry|null; + backup:{observed_at:string;operation_id:string;configs:Record}|null; +} + +export function driveTestIds(profile:DriveProfile|undefined,selected:string):string[] { + if(!profile?.layout)return []; + const slots=Object.keys(drivePositions(profile.layout)); + if(Object.keys(profile.bindings).length!==slots.length||slots.some(slot=>!profile.bindings[slot]))return []; + const ids=slots.map(slot=>profile.bindings[slot].device_id); + return new Set(ids).size===ids.length&&ids.includes(selected)?ids:[]; +} + +export function speedInput(speed:string,limits:VescStatus['speed_limits']) { + const erpm=Number(speed); + const error=!limits?'Для удержания скорости требуется обновление профиля VESC на борту.': + speed.trim()===''||!Number.isFinite(erpm)?'Введите скорость.': + erpmlimits.max_erpm?`Скорость должна быть от ${limits.min_erpm} до ${limits.max_erpm} ERPM.`:null; + return {erpm,error}; +} + +export function rotationResult(value:{outcome?:string;rotation_s?:number;release_confirmed?:boolean;limits_restored?:boolean}) { + const time=(value.rotation_s??0).toLocaleString('ru-RU',{maximumFractionDigits:1}); + const outcome=value.outcome==='duration'?'Заданное время вращения набрано.':value.outcome==='stopped'?'Проверка остановлена.':String(value.outcome); + return `${outcome} Вращение на заданной скорости по данным VESC: ${time} с. ${value.release_confirmed?'Снятие тока подтверждено.':'Снятие тока не подтверждено.'}${value.limits_restored?' Исходные токовые пределы восстановлены.':''}`; +} +export function vescStatus(device:Sensor):VescStatus { + return {identity:null,readable:false,message:null,telemetry:null,backup:null,...device.vesc_status} as VescStatus; +} +export function vescLabel(device:Sensor,fresh:boolean):{label:string;tone:'neutral'|'success'|'warning'|'danger'} { + const status=vescStatus(device); + if(!fresh||!device.online)return {label:'Нет связи',tone:'neutral'}; + if(!device.prepared)return {label:'Требуется подготовка',tone:'neutral'}; + if(!status.identity)return {label:'Не определён',tone:'warning'}; + if(!status.readable)return {label:'Прошивка не поддерживается',tone:'warning'}; + return {label:'Готов к чтению',tone:'success'}; +} + +export function testInput(current:string,duration:string,limits:VescStatus['test_limits']) { + const currentA=Number(current),durationS=Number(duration); + const number=(value:number)=>value.toLocaleString('ru-RU'); + const currentError=!limits?null:current.trim()===''||!Number.isFinite(currentA) + ? 'Введите ток мотора.' + : currentAlimits.max_current_a + ? `Ток должен быть от ${number(limits.min_current_a)} до ${number(limits.max_current_a)} А.`:null; + const durationError=!limits?null:duration.trim()===''||!Number.isFinite(durationS) + ? 'Введите длительность проверки.' + : durationSlimits.max_duration_s + ? `Длительность должна быть от ${number(limits.min_duration_s)} до ${number(limits.max_duration_s)} с.`:null; + return {currentA,durationS,currentError,durationError,valid:!!limits&&!currentError&&!durationError}; +} diff --git a/plugins/vesc/frontend/src/plugin.ts b/plugins/vesc/frontend/src/plugin.ts new file mode 100644 index 0000000..93dddcd --- /dev/null +++ b/plugins/vesc/frontend/src/plugin.ts @@ -0,0 +1,9 @@ +import type {SensorUiContribution} from '../../../../packages/sensor-ui/src/extensions'; +import {VescDetail} from './VescDetail'; +import {VescBoardSettings} from './VescBoardSettings'; +import {vescLabel} from './model'; + +export const vescSensorUi:SensorUiContribution={ + kind:'vesc.controller',Detail:VescDetail,BoardSettings:VescBoardSettings,icon:'activity',retainOffline:true, + supportsPreparation:true,supportsRenaming:true,detailLabel:'Настройка VESC',status:vescLabel, +}; diff --git a/plugins/vesc/native/LICENSE b/plugins/vesc/native/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/plugins/vesc/native/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/plugins/vesc/native/config_export.h b/plugins/vesc/native/config_export.h new file mode 100644 index 0000000..17e9076 --- /dev/null +++ b/plugins/vesc/native/config_export.h @@ -0,0 +1,97 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "vescinterface.h" +#include "utility.h" + +static QString sha256(const QByteArray &data) { + return QCryptographicHash::hash(data, QCryptographicHash::Sha256).toHex(); +} + +static void require(bool condition, const char *message) { + if (!condition) throw std::runtime_error(message); +} + +static QJsonObject exportConfig(ConfigParams *config, const QByteArray &packet, + const QString &xmlName) { + VByteArray roundTrip; + config->serialize(roundTrip); + require(roundTrip == packet.mid(1), "Native configuration round-trip differs from archive"); + QJsonArray parameters; + for (const auto &name : config->getParamOrder()) { + const auto p = config->getParamCopy(name); + QJsonObject item{{"name", name}, {"title", p.longName}, + {"description", p.description}, {"suffix", p.suffix}, + {"transmittable", p.transmittable}, {"editor_scale", p.editorScale}}; + switch (p.type) { + case CFG_T_DOUBLE: + item.insert("type", "number"); item.insert("value", p.valDouble); + item.insert("min", p.minDouble); item.insert("max", p.maxDouble); + item.insert("step", p.stepDouble); item.insert("decimals", p.editorDecimalsDouble); + break; + case CFG_T_INT: case CFG_T_BITFIELD: + item.insert("type", p.type == CFG_T_INT ? "integer" : "bitfield"); + item.insert("value", p.valInt); item.insert("min", p.minInt); + item.insert("max", p.maxInt); item.insert("step", p.stepInt); + break; + case CFG_T_ENUM: + item.insert("type", "enum"); item.insert("value", p.valInt); + item.insert("options", QJsonArray::fromStringList(p.enumNames)); break; + case CFG_T_BOOL: + item.insert("type", "boolean"); item.insert("value", bool(p.valInt)); break; + case CFG_T_QSTRING: + item.insert("type", "string"); item.insert("value", p.valString); + item.insert("max_length", p.maxLen); break; + default: item.insert("type", "undefined"); + } + parameters.append(item); + } + QJsonArray groups; + for (const auto &group : config->getParamGroups()) { + QJsonArray subgroups; + for (const auto &subgroup : config->getParamSubgroups(group)) { + subgroups.append(QJsonObject{{"name", subgroup}, {"parameters", + QJsonArray::fromStringList(config->getParamsFromSubgroup(group, subgroup))}}); + } + groups.append(QJsonObject{{"name", group}, {"subgroups", subgroups}}); + } + QString xml; + QXmlStreamWriter writer(&xml); + writer.setAutoFormatting(true); + config->getXML(writer, xmlName); + // Validate Tool's own XML load as well as its binary codec. No output file, + // motor configuration write, custom schema, or custom parameter parser. + ConfigParams loaded; + loaded = *config; + QXmlStreamReader reader(xml); + require(loaded.setXML(reader, xmlName), "Native XML round-trip failed"); + VByteArray xmlRoundTrip; loaded.serialize(xmlRoundTrip); + const auto differences = config->checkDifference(&loaded); + require(differences.isEmpty(), "Native XML differs beyond upstream comparison tolerance"); + return QJsonObject{{"parameters", parameters}, {"groups", groups}, {"xml", xml}, + {"packet_sha256", sha256(packet)}, {"round_trip_exact", true}, + {"xml_round_trip_exact", xmlRoundTrip == roundTrip}, + {"xml_equivalent_by_upstream_comparison", true}, + {"signature", double(config->getSignature())}}; +} + +static QByteArray archivePacket(const QJsonObject &archive, const QString &key, int command) { + auto entry = archive.value("configs").toObject().value(key).toObject(); + auto encoded = entry.value("payload").toString().toLatin1(); + auto packet = QByteArray::fromBase64(encoded, QByteArray::AbortOnBase64DecodingErrors); + require(entry.value("encoding") == "base64" && !packet.isEmpty() && packet.size() <= 16384, + "Invalid archived configuration encoding"); + require(packet.toBase64() == encoded && packet.size() == entry.value("bytes").toInt(), + "Invalid archived configuration length"); + require(quint8(packet.at(0)) == command && sha256(packet) == entry.value("sha256").toString(), + "Archived configuration hash or command mismatch"); + return packet; +} diff --git a/plugins/vesc/native/engine_main.cpp b/plugins/vesc/native/engine_main.cpp new file mode 100644 index 0000000..9f7d2f5 --- /dev/null +++ b/plugins/vesc/native/engine_main.cpp @@ -0,0 +1,375 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Private per-device JSON process adapter. Every wire operation is upstream. +#include "config_export.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class ExchangeFailure : public std::runtime_error { +public: + QJsonObject diagnostics; + explicit ExchangeFailure(const QJsonObject &value) + : std::runtime_error("Native query timed out or disconnected"), diagnostics(value) {} +}; + +class Engine { +public: + VescInterface vesc; + Packet *packet; + FW_RX_PARAMS identity; + bool procedureRunning = false; + bool procedureUncertain = false; + QJsonObject procedure; + bool queryRunning = false; + bool allowHardware = false; + QByteArray lastMotor, lastApplication, lastHall; + QTimer outputWatchdog; + + Engine() { + outputWatchdog.setSingleShot(true); + QObject::connect(&outputWatchdog, &QTimer::timeout, [&] { + if (allowHardware && vesc.isPortConnected() && !procedureRunning) { + vesc.commands()->setCurrent(0); + try { flush(); } catch (...) {} + } + }); + require(Utility::configLoadLatest(&vesc), "Upstream resources missing"); + packet = vesc.findChild(); + require(packet, "Upstream packet transport missing"); + QObject::connect(vesc.commands(), &Commands::fwVersionReceived, + [&](FW_RX_PARAMS value) { identity = value; }); + QObject::connect(packet, &Packet::packetReceived, [&](QByteArray &raw) { + if (!raw.isEmpty() && quint8(raw[0]) == COMM_GET_MCCONF) lastMotor = raw; + if (!raw.isEmpty() && quint8(raw[0]) == COMM_GET_APPCONF) lastApplication = raw; + if (!raw.isEmpty() && quint8(raw[0]) == COMM_DETECT_HALL_FOC) lastHall = raw; + }); + } + + void open(const QString &port) { + require(QRegularExpression("^/dev/ttyACM[0-9]+$").match(port).hasMatch(), "Unsupported USB path"); + struct stat st; + require(lstat(port.toLocal8Bit(), &st) == 0 && S_ISCHR(st.st_mode) && major(st.st_rdev) == 166, + "Not a CDC ACM device"); + require(vesc.connectSerial(port, 115200), "Native serial connection failed"); + auto serial = vesc.findChild(); + require(serial && serial->isOpen() && "/dev/" + serial->portName() == port, + "Native serial path mismatch"); + require(flock(serial->handle(), LOCK_EX | LOCK_NB) == 0 && ioctl(serial->handle(), TIOCEXCL) == 0, + "Serial port is already owned"); + allowHardware = true; + query(COMM_FW_VERSION, 3000); + require(identity.major == 5 && identity.minor == 2 && identity.hwType == HW_TYPE_VESC + && identity.isTestFw == 0 && identity.customConfigNum == 0, + "Native hardware acceptance currently admits stable FW 5.02 only"); + } + + QByteArray exchange(int command, int timeoutMs, const std::function &send) { + require(allowHardware && vesc.isPortConnected(), "Device disconnected"); + require(!queryRunning, "A native query is already pending"); + queryRunning = true; + struct PendingReset { bool &pending; ~PendingReset() { pending = false; } } reset{queryRunning}; + QEventLoop loop; + QTimer timeout; timeout.setSingleShot(true); + QObject observer; + QElapsedTimer elapsed; elapsed.start(); + QJsonArray events; + bool emitted = false; + int packetsSent = 0, packetsReceived = 0; + qint64 bytesWritten = 0; + auto serial = vesc.findChild(); + auto record = [&](const QString &kind, int code, qint64 bytes) { + if (events.size() == 24) events.removeFirst(); + events.append(QJsonObject{{"event", kind}, {"command", code}, + {"bytes", double(bytes)}, {"at_ms", elapsed.nsecsElapsed() / 1e6}}); + }; + QObject::connect(vesc.commands(), &Commands::dataToSend, &observer, [&](QByteArray &raw) { + const int code = raw.isEmpty() ? -1 : quint8(raw[0]); + if (code == command) emitted = true; + record("command_emitted", code, raw.size()); + }); + QObject::connect(packet, &Packet::dataToSend, &observer, [&](QByteArray &raw) { + ++packetsSent; record("packet_sent", -1, raw.size()); + }); + if (serial) { + QObject::connect(serial, &QSerialPort::bytesWritten, &observer, [&](qint64 bytes) { + bytesWritten += bytes; record("serial_written", -1, bytes); + }); + QObject::connect(serial, &QSerialPort::errorOccurred, &observer, [&](QSerialPort::SerialPortError error) { + if (error != QSerialPort::NoError) record("serial_error", int(error), 0); + }); + } + QByteArray answer; + QObject::connect(packet, &Packet::packetReceived, &observer, [&](QByteArray &raw) { + ++packetsReceived; + record("packet_received", raw.isEmpty() ? -1 : quint8(raw[0]), raw.size()); + if (!raw.isEmpty() && quint8(raw[0]) == command) { answer = raw; loop.quit(); } + }); + QObject::connect(&timeout, &QTimer::timeout, &loop, &QEventLoop::quit); + timeout.start(timeoutMs); + send(); + if (answer.isEmpty()) loop.exec(); + if (answer.isEmpty() || !vesc.isPortConnected()) { + throw ExchangeFailure({{"requested_command", command}, {"timeout_ms", timeoutMs}, + {"elapsed_ms", elapsed.nsecsElapsed() / 1e6}, {"request_emitted", emitted}, + {"packets_sent", packetsSent}, {"packets_received", packetsReceived}, + {"serial_bytes_written", double(bytesWritten)}, {"port_connected", vesc.isPortConnected()}, + {"serial_open", serial && serial->isOpen()}, {"serial_error", serial ? int(serial->error()) : -1}, + {"serial_bytes_pending", serial ? double(serial->bytesToWrite()) : -1}, {"events", events}}); + } + return answer; + } + + QByteArray query(int code, int timeoutMs, bool internal = false) { + auto cmd = vesc.commands(); + require(internal || !procedureRunning || code == COMM_GET_VALUES || code == COMM_GET_DECODED_PPM, + "Configuration reads are unavailable during native measurement"); + std::function send; + switch (code) { + case COMM_FW_VERSION: send = [=] { cmd->getFwVersion(); }; break; + case COMM_GET_VALUES: send = [=] { cmd->getValues(); }; break; + case COMM_GET_MCCONF: send = [=] { cmd->getMcconf(); }; break; + case COMM_GET_APPCONF: send = [=] { cmd->getAppConf(); }; break; + case COMM_GET_DECODED_PPM: send = [=] { cmd->getDecodedPpm(); }; break; + case COMM_PING_CAN: send = [=] { cmd->pingCan(); }; break; + default: throw std::runtime_error("Native read command is not admitted"); + } + auto raw = exchange(code, timeoutMs, send); + if (code == COMM_GET_MCCONF || code == COMM_GET_APPCONF) { + VByteArray serialized; + auto config = code == COMM_GET_MCCONF ? vesc.mcConfig() : vesc.appConfig(); + config->serialize(serialized); + require(serialized == raw.mid(1), "Native configuration decode is not byte-exact"); + } + return raw; + } + + QByteArray configurationPacket(ConfigParams *config, int code) { + VByteArray raw; raw.vbAppendInt8(code); config->serialize(raw); return raw; + } + + void calibrate(double loss) { + ConfigParams beforeMotor, beforeApp; + beforeMotor = *vesc.mcConfig(); beforeApp = *vesc.appConfig(); + bool received = false, validated = false; + int code = -1000; + QString report, error; + QJsonArray changed; + auto connection = QObject::connect(vesc.commands(), &Commands::detectAllFocReceived, + [&](int result) { received = true; code = result; }); + try { + // The actual upstream wizard motor procedure, including its FW 5.02 + // power-loss correction. Do not infer a battery profile from Ah/voltage. + report = Utility::detectAllFoc(&vesc, false, loss, + beforeMotor.getParamDouble("l_in_current_min"), beforeMotor.getParamDouble("l_in_current_max"), + beforeMotor.getParamDouble("foc_openloop_rpm"), beforeMotor.getParamDouble("foc_sl_erpm")); + require(received, "Native calibration completion was not received"); + query(COMM_GET_MCCONF, 3000, true); + query(COMM_GET_APPCONF, 3000, true); + auto mc = vesc.mcConfig(); auto app = vesc.appConfig(); + const QStringList admitted = {"l_current_max", "l_current_min", "motor_type", "foc_motor_r", + "foc_motor_l", "foc_motor_flux_linkage", "foc_current_kp", "foc_current_ki", "foc_observer_gain", + "foc_sensor_mode", "m_sensor_port_mode", "foc_encoder_offset", "foc_encoder_ratio", "foc_encoder_inverted", + "foc_hall_table__0", "foc_hall_table__1", "foc_hall_table__2", "foc_hall_table__3", + "foc_hall_table__4", "foc_hall_table__5", "foc_hall_table__6", "foc_hall_table__7"}; + for (const auto &key : beforeMotor.checkDifference(mc)) { + require(admitted.contains(key), "Calibration changed a protected motor parameter"); + changed.append(key); + } + for (const auto &key : beforeApp.checkDifference(app)) + require(key == "send_can_status", "Calibration changed a protected receiver parameter"); + // Native FW 5.02 enables CAN status as a side effect. Restore the + // original application exactly; retain existing PPM and CAN identity. + if (!beforeApp.checkDifference(app).isEmpty()) { + *app = beforeApp; + const auto expected = configurationPacket(app, COMM_GET_APPCONF); + require(exchange(COMM_SET_APPCONF, 3000, [&] { vesc.commands()->setAppConf(); }).size() == 1, + "Application write ACK invalid"); + require(query(COMM_GET_APPCONF, 3000, true) == expected, "Application restore not byte-exact"); + } + if (code < 0) { + // A completed failed detection can leave partial RAM changes. + // Only the known calibration fields passed the guard above. + *mc = beforeMotor; + } else { + for (const auto &key : {"foc_motor_r", "foc_motor_l", "foc_motor_flux_linkage"}) + require(std::isfinite(mc->getParamDouble(key)) && mc->getParamDouble(key) > 0, + "Invalid detected motor parameter"); + require(mc->getParamDouble("l_current_max") > 0 && mc->getParamDouble("l_current_min") < 0, + "Invalid detected current limits"); + // Calibration must not silently increase the owner's existing + // current limits. The separate spin test applies its own 30 A cap. + mc->updateParamDouble("l_current_max", qMin(mc->getParamDouble("l_current_max"), beforeMotor.getParamDouble("l_current_max"))); + mc->updateParamDouble("l_current_min", qMax(mc->getParamDouble("l_current_min"), beforeMotor.getParamDouble("l_current_min"))); + } + const auto expected = configurationPacket(mc, COMM_GET_MCCONF); + if (expected != lastMotor) { + require(exchange(COMM_SET_MCCONF, 3000, [&] { vesc.commands()->setMcconf(false); }).size() == 1, + "Motor write ACK invalid"); + require(query(COMM_GET_MCCONF, 3000, true) == expected, "Motor write not byte-exact"); + } + validated = true; + } catch (const std::exception &e) { error = e.what(); } + QObject::disconnect(connection); + QJsonObject parameters; + for (const auto &key : {"l_current_max", "l_current_min", "foc_motor_r", "foc_motor_l", "foc_motor_flux_linkage"}) + parameters.insert(key, vesc.mcConfig()->getParamDouble(key)); + procedure = {{"kind", "foc"}, {"completed", received}, {"success", received && code >= 0 && validated}, + {"validated", validated}, {"code", code}, {"report", report}, {"error", error}, + {"sensor_mode", vesc.mcConfig()->getParamEnum("foc_sensor_mode")}, {"parameters", parameters}, + {"changed", changed}, {"upstream", "Utility::detectAllFoc"}}; + procedureUncertain = !validated; + procedureRunning = false; + } + + double number(const QJsonObject &request, const QString &name, double min, double max) { + auto v = request.value(name); + require(v.isDouble() && std::isfinite(v.toDouble()) && v.toDouble() >= min && v.toDouble() <= max, + "Numeric argument is outside operation bounds"); + return v.toDouble(); + } + + void flush() { + auto serial = vesc.findChild(); + require(serial && serial->isOpen(), "Serial transport closed"); + serial->flush(); + if (serial->bytesToWrite() > 0) require(serial->waitForBytesWritten(40), "Serial write not confirmed"); + require(serial->bytesToWrite() == 0, "Serial write is incomplete"); + } + + QJsonObject dispatch(const QJsonObject &request) { + const auto method = request.value("method").toString(); + if (method == "engine") return {{"version", "7.00"}, {"commit", "01d5f10901116c311e3fb84d5a1541f663d3ce20"}, + {"connected", vesc.isPortConnected()}, {"hardware_enabled", allowHardware}, + {"legacy_power_loss_correction", vesc.commands()->getMaxPowerLossBug()}}; + require(allowHardware && vesc.isPortConnected(), "Native device is not connected"); + if (method == "query") return {{"payload", QString::fromLatin1(query( + int(number(request, "command", 0, 255)), int(number(request, "timeout_ms", 20, 8000))).toBase64())}}; + if (method == "procedure_result") return {{"running", procedureRunning}, {"uncertain", procedureUncertain}, {"result", procedure}}; + if (method == "lease") { + require(!procedureRunning && !procedureUncertain, "Native procedure owns this controller"); + vesc.commands()->disableAppOutput(250, false); flush(); outputWatchdog.start(200); return {}; + } + if (method == "release") { vesc.commands()->setCurrent(0); flush(); return {}; } + require(!procedureRunning && !procedureUncertain, "Native procedure owns this controller"); + if (method == "current") { + require(outputWatchdog.isActive(), "Output lease expired"); + auto current = number(request, "current_a", 0, 30); + require(current <= vesc.mcConfig()->getParamDouble("l_current_max"), "Configured current limit exceeded"); + vesc.commands()->setCurrent(current); flush(); return {}; + } + if (method == "rpm") { require(outputWatchdog.isActive(), "Output lease expired"); vesc.commands()->setRpm(int(number(request, "erpm", -3000, 3000))); flush(); return {}; } + if (method == "limits") { + auto p = request.value("parameters").toObject(); + MCCONF_TEMP conf; + conf.current_min_scale = number(p, "l_current_min_scale", 0, 1); + conf.current_max_scale = number(p, "l_current_max_scale", 0, 1); + // Restore/application may only change current scales. All other + // values must equal the last native read, including battery limits. + auto mc = vesc.mcConfig(); + for (const auto &key : {"l_min_erpm", "l_max_erpm", "l_min_duty", "l_max_duty", "l_watt_min", "l_watt_max", "l_in_current_min", "l_in_current_max"}) + require(p.value(key).isDouble() && p.value(key).toDouble() == mc->getParamDouble(key), "Only volatile current scales may change"); + conf.erpm_or_speed_min = mc->getParamDouble("l_min_erpm"); + conf.erpm_or_speed_max = mc->getParamDouble("l_max_erpm"); + conf.duty_min = mc->getParamDouble("l_min_duty"); conf.duty_max = mc->getParamDouble("l_max_duty"); + conf.watt_min = mc->getParamDouble("l_watt_min"); conf.watt_max = mc->getParamDouble("l_watt_max"); + auto ack = exchange(COMM_SET_MCCONF_TEMP, 2000, [&] { + vesc.commands()->setMcconfTemp(conf, false, false, false, false, true); + }); + require(ack.size() == 1, "Invalid native limits ACK"); return {}; + } + if (method == "configuration") { + auto motor = query(COMM_GET_MCCONF, 2000); + auto application = query(COMM_GET_APPCONF, 2000); + return {{"motor", exportConfig(vesc.mcConfig(), motor, "MCConfiguration")}, + {"application", exportConfig(vesc.appConfig(), application, "APPConfiguration")}}; + } + if (method == "foc_start") { + const auto loss = number(request, "max_power_loss_w", 10, 150); + require(!lastMotor.isEmpty() && !lastApplication.isEmpty(), "Read configurations before calibration"); + for (const auto &key : {"l_in_current_min", "l_in_current_max", "foc_openloop_rpm", "foc_sl_erpm"}) + require(std::isfinite(vesc.mcConfig()->getParamDouble(key)) && std::abs(vesc.mcConfig()->getParamDouble(key)) > 0.001, + "Zero-valued detection inputs require an explicit equipment profile"); + procedureRunning = true; procedure = {{"kind", "foc"}}; + QTimer::singleShot(0, [this, loss] { calibrate(loss); }); + return {{"started", true}, {"interruptible", false}}; + } + if (method == "hall_start") { + require(request.value("current_a") == 5, "This Hall profile uses 5 A"); + procedureRunning = true; procedure = {}; lastHall.clear(); + QTimer::singleShot(0, [&] { + auto measured = Utility::measureHallFocBlocking(&vesc, 5.0); + QJsonArray table; + for (int i = 1; i < measured.size(); ++i) table.append(measured[i]); + const bool completed = measured.size() == 9 && measured.first() != -10; + procedure = {{"kind", "hall"}, {"completed", completed}, + {"status", measured.isEmpty() ? -10 : measured.first()}, {"table", table}, + {"payload", QString::fromLatin1(lastHall.toBase64())}, + {"upstream", "Utility::measureHallFocBlocking"}}; + procedureUncertain = !completed; + procedureRunning = false; + }); + return {{"started", true}, {"interruptible", false}}; + } + throw std::runtime_error("Native operation is not admitted"); + } +}; + +int main(int argc, char **argv) { + qputenv("QT_QPA_PLATFORM", "offscreen"); + QApplication application(argc, argv); + QCoreApplication::setOrganizationName("MissionCore"); + QCoreApplication::setApplicationName("VescToolEngine"); + try { + require(argc == 2, "One exact serial port or --offline argument is required"); + Engine engine; + const QString port = QString::fromLocal8Bit(argv[1]); + if (port != "--offline") engine.open(port); + QFile output; output.open(stdout, QIODevice::WriteOnly); + auto write = [&](const QJsonObject &value) { + output.write(QJsonDocument(value).toJson(QJsonDocument::Compact) + '\n'); output.flush(); + }; + write({{"ready", true}, {"engine", engine.dispatch({{"method", "engine"}})}}); + QByteArray buffer; + fcntl(STDIN_FILENO, F_SETFL, fcntl(STDIN_FILENO, F_GETFL) | O_NONBLOCK); + QSocketNotifier input(STDIN_FILENO, QSocketNotifier::Read); + QObject::connect(&input, &QSocketNotifier::activated, [&] { + char chunk[4096]; const auto size = ::read(STDIN_FILENO, chunk, sizeof(chunk)); + if (size == 0) { application.quit(); return; } + if (size < 0) return; + buffer.append(chunk, int(size)); + if (buffer.size() > 65536) { application.exit(2); return; } + int end; + while ((end = buffer.indexOf('\n')) >= 0) { + auto raw = buffer.left(end); buffer.remove(0, end + 1); + QJsonParseError error; + auto document = QJsonDocument::fromJson(raw, &error); + auto request = document.object(); + QJsonObject response{{"id", request.value("id")}}; + try { + require(error.error == QJsonParseError::NoError && document.isObject(), "Invalid JSON request"); + response.insert("result", engine.dispatch(request)); response.insert("ok", true); + } catch (const ExchangeFailure &e) { + response.insert("ok", false); response.insert("error", e.what()); + response.insert("diagnostics", e.diagnostics); + } catch (const std::exception &e) { response.insert("ok", false); response.insert("error", e.what()); } + write(response); + } + }); + return application.exec(); + } catch (const std::exception &error) { + fprintf(stderr, "Native engine startup failed: %s\n", error.what()); + return 1; + } +} diff --git a/plugins/vesc/native/offline_main.cpp b/plugins/vesc/native/offline_main.cpp new file mode 100644 index 0000000..91a7cd2 --- /dev/null +++ b/plugins/vesc/native/offline_main.cpp @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Mission Core adapter to the unmodified VESC Tool engine. No hardware transport +// is admitted by this executable. Input is one archived snapshot on stdin. +#include "config_export.h" + +int main(int argc, char **argv) { + // This application never calls connectSerial/connectTcp/connectBle or starts + // a Qt event loop. Upstream timers therefore cannot reconnect or poll. + qputenv("QT_QPA_PLATFORM", "offscreen"); + QApplication app(argc, argv); + QCoreApplication::setOrganizationName("MissionCore"); + QCoreApplication::setApplicationName("VescToolOfflineAdapter"); + QJsonObject result{{"schema", "missioncore.vesc.native-offline/v1"}, + {"upstream_commit", "01d5f10901116c311e3fb84d5a1541f663d3ce20"}, + {"upstream_version", QString::number(VT_VERSION, 'f', 2)}, + {"hardware_access", false}}; + try { + require(argc == 1, "No command-line transport or operation arguments are accepted"); + QFile input; require(input.open(stdin, QIODevice::ReadOnly), "Cannot read input"); + const auto raw = input.read(1024 * 1024 + 1); + require(!raw.isEmpty() && raw.size() <= 1024 * 1024, "Archive input is empty or too large"); + QJsonParseError parse; + auto document = QJsonDocument::fromJson(raw, &parse); + require(parse.error == QJsonParseError::NoError && document.isObject(), "Invalid archive JSON"); + const auto archive = document.object(); + const auto identity = archive.value("identity").toObject(); + FW_RX_PARAMS fw; + fw.major = identity.value("major").toInt(-1); + fw.minor = identity.value("minor").toInt(-1); + fw.hw = identity.value("hardware").toString(); + fw.isTestFw = identity.value("test_firmware").toInt(-1); + fw.customConfigNum = identity.value("custom_configs").toInt(-1); + const auto uuid = identity.value("uuid").toString(); + require(QRegularExpression("^[0-9a-fA-F]{24}$").match(uuid).hasMatch(), "Invalid archived UUID"); + fw.uuid = QByteArray::fromHex(uuid.toLatin1()); + require(fw.major == 5 && fw.minor == 2 && fw.isTestFw == 0 && fw.customConfigNum == 0 + && identity.value("hardware_type").toInt(-1) == 0, + "Offline acceptance currently admits stable firmware 5.02 only"); + VescInterface vesc; + require(Utility::configLoadLatest(&vesc), "Bundled upstream configuration resources missing"); + auto *commands = vesc.commands(); + // Replay the archived identity through the real firmware negotiation + // signal. The real engine selects bundled schemas and compatibility. + commands->fwVersionReceived(fw); + require(!vesc.isPortConnected(), "Offline adapter unexpectedly connected"); + require(vesc.mcConfig()->getSerializeOrder().size() > 0, "Native schema not selected"); + bool failed = false; + QObject::connect(commands, &Commands::deserializeConfigFailed, + [&](bool, bool) { failed = true; }); + auto motor = archivePacket(archive, "motor", COMM_GET_MCCONF); + auto application = archivePacket(archive, "application", COMM_GET_APPCONF); + // FW 5.02 has fixed-size configurations. Obtain their size through the + // public native serializer; do not reproduce the private schema walker. + VByteArray motorShape, applicationShape; + vesc.mcConfig()->serialize(motorShape); + vesc.appConfig()->serialize(applicationShape); + require(motor.size() == motorShape.size() + 1 && application.size() == applicationShape.size() + 1, + "Archive length differs from the native firmware schema"); + commands->processPacket(motor); + commands->processPacket(application); + require(!failed, "Upstream rejected archived configuration"); + result.insert("motor", exportConfig(vesc.mcConfig(), motor, "MCConfiguration")); + result.insert("application", exportConfig(vesc.appConfig(), application, "APPConfiguration")); + // A disconnected serializer-only probe demonstrates that FW-specific + // detect corrections execute upstream. This byte array goes nowhere. + QByteArray encodedDetect; + QObject::connect(commands, &Commands::dataToSend, [&](QByteArray &data) { + if (!data.isEmpty() && quint8(data.at(0)) == COMM_DETECT_APPLY_ALL_FOC) encodedDetect = data; + }); + commands->detectAllFoc(false, 100.0, 0.0, 0.0, 0.0, 0.0); + require(!encodedDetect.isEmpty() && !vesc.isPortConnected(), "Offline serialization failed"); + result.insert("compatibility", QJsonObject{ + {"legacy_power_loss_correction", commands->getMaxPowerLossBug()}, + {"offline_detect_example_base64", QString::fromLatin1(encodedDetect.toBase64())}, + {"example_requested_power_loss_w", 100.0}, {"transmitted_to_hardware", false}}); + QJsonArray rpmExamples; + QObject::connect(commands, &Commands::dataToSend, [&](QByteArray &data) { + if (!data.isEmpty() && quint8(data.at(0)) == COMM_SET_RPM) + rpmExamples.append(QString::fromLatin1(data.toBase64())); + }); + commands->setRpm(3000); + commands->setRpm(-3000); + require(rpmExamples.size() == 2 && !vesc.isPortConnected(), "Offline signed RPM serialization failed"); + result.insert("offline_signed_rpm_examples_base64", rpmExamples); + result.insert("archive_sha256", sha256(raw)); + result.insert("ok", true); + } catch (const std::exception &error) { + result = QJsonObject{{"schema", "missioncore.vesc.native-offline/v1"}, + {"ok", false}, {"hardware_access", false}, {"error", error.what()}}; + } + QFile output; output.open(stdout, QIODevice::WriteOnly); + output.write(QJsonDocument(result).toJson(QJsonDocument::Compact) + '\n'); + return result.value("ok").toBool() ? 0 : 1; +} diff --git a/plugins/vesc/packaging/70-mission-core-vesc.rules b/plugins/vesc/packaging/70-mission-core-vesc.rules new file mode 100644 index 0000000..faf267d --- /dev/null +++ b/plugins/vesc/packaging/70-mission-core-vesc.rules @@ -0,0 +1,2 @@ +# Exact observed candidate descriptor. Firmware identity is verified by the reader. +SUBSYSTEM=="tty", ATTRS{idVendor}=="0483", ATTRS{idProduct}=="5740", ATTRS{product}=="ChibiOS/RT Virtual COM Port", GROUP="mission-core-vesc", MODE="0660", ENV{ID_MM_DEVICE_IGNORE}="1", ENV{ID_MM_PORT_IGNORE}="1" diff --git a/plugins/vesc/packaging/build_native_probe.py b/plugins/vesc/packaging/build_native_probe.py new file mode 100644 index 0000000..5e5c0e4 --- /dev/null +++ b/plugins/vesc/packaging/build_native_probe.py @@ -0,0 +1,33 @@ +"""Create the deterministic, self-contained native-engine qualification job.""" +import argparse +import hashlib +import json +from pathlib import Path +import zipfile + + +def build(output): + root = Path(__file__).resolve().parents[1] + files = {"__main__.py": (root / "packaging/native_probe.py").read_bytes(), + "offline_main.cpp": (root / "native/offline_main.cpp").read_bytes(), + "config_export.h": (root / "native/config_export.h").read_bytes(), + "engine_main.cpp": (root / "native/engine_main.cpp").read_bytes(), + "native_bundle.py": (root / "packaging/native_bundle.py").read_bytes()} + identity = hashlib.sha256(b"".join(k.encode() + v for k, v in sorted(files.items()))).hexdigest()[:24] + output.mkdir(parents=True, exist_ok=True) + path = output / ("mission-core-vesc-native-probe-" + identity + ".pyz") + with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as bundle: + for name, data in files.items(): + entry = zipfile.ZipInfo(name, (2026, 9, 23, 0, 0, 0)) + entry.external_attr = 0o600 << 16 + bundle.writestr(entry, data) + result = {"id": identity, "artifact": str(path.resolve()), + "sha256": hashlib.sha256(path.read_bytes()).hexdigest(), "bytes": path.stat().st_size} + (output / "current-artifact.json").write_text(json.dumps(result, indent=2) + "\n") + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + print(json.dumps(build(parser.parse_args().output))) diff --git a/plugins/vesc/packaging/clear_runtime_cache.py b/plugins/vesc/packaging/clear_runtime_cache.py new file mode 100644 index 0000000..2031f47 --- /dev/null +++ b/plugins/vesc/packaging/clear_runtime_cache.py @@ -0,0 +1,22 @@ +"""Discard only generated VESC bytecode before starting an upgraded profile. + +Deterministic packages reuse file mtimes; a same-size Python source update +can otherwise validate an old timestamp-based pyc, even with python -B. +""" +from pathlib import Path +import shutil +import sys + + +def clear(root): + for cache in root.rglob("__pycache__"): + if cache.is_symlink(): + cache.unlink() + elif cache.is_dir(): + shutil.rmtree(cache) + + +if __name__ == "__main__": + if sys.argv[1:]: + raise ValueError("This installer step accepts no paths or arguments") + clear(Path("/usr/lib/mission-core-vesc")) diff --git a/plugins/vesc/packaging/mission-core-node-vesc-prepare.service b/plugins/vesc/packaging/mission-core-node-vesc-prepare.service new file mode 100644 index 0000000..5460994 --- /dev/null +++ b/plugins/vesc/packaging/mission-core-node-vesc-prepare.service @@ -0,0 +1,8 @@ +[Unit] +Description=Prepare the versioned VESC read profile + +[Service] +Type=oneshot +ExecStart=/usr/bin/python3 -I -B /usr/lib/mission-core-vesc/prepare.py +TimeoutStartSec=90 +UMask=0022 diff --git a/plugins/vesc/packaging/mission-core-vesc.service b/plugins/vesc/packaging/mission-core-vesc.service new file mode 100644 index 0000000..9a04177 --- /dev/null +++ b/plugins/vesc/packaging/mission-core-vesc.service @@ -0,0 +1,37 @@ +[Unit] +Description=Mission Core VESC Tool service +Wants=modprobe@cdc_acm.service +After=systemd-udev-settle.service modprobe@cdc_acm.service + +[Service] +Type=simple +User=mission-core-vesc +Group=mission-core-node +SupplementaryGroups=mission-core-vesc +WorkingDirectory=/usr/lib/mission-core-vesc +ExecStart=/usr/bin/python3 -B -m runtime.server +RuntimeDirectory=mission-core-vesc +RuntimeDirectoryMode=0750 +StateDirectory=mission-core-vesc +StateDirectoryMode=0700 +UMask=0007 +Restart=on-failure +RestartSec=5 +NoNewPrivileges=yes +CapabilityBoundingSet= +AmbientCapabilities= +PrivateNetwork=yes +ProtectSystem=strict +ProtectHome=yes +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectControlGroups=yes +RestrictSUIDSGID=yes +RestrictAddressFamilies=AF_UNIX +DevicePolicy=closed +DeviceAllow=char-ttyACM rw +MemoryMax=512M +TasksMax=64 + +[Install] +WantedBy=multi-user.target diff --git a/plugins/vesc/packaging/native-runtime.json b/plugins/vesc/packaging/native-runtime.json new file mode 100644 index 0000000..e155f7f --- /dev/null +++ b/plugins/vesc/packaging/native-runtime.json @@ -0,0 +1,676 @@ +{ + "schema": "missioncore.vesc.native-runtime/v1", + "upstream_version": "7.00", + "upstream_commit": "01d5f10901116c311e3fb84d5a1541f663d3ce20", + "os": "ubuntu-24.04-amd64", + "file": "mission-core-vesc-native-runtime.tar.gz", + "bytes": 50354000, + "sha256": "4473819387682089a814a6c558065e3e6a4c2fe67266c0ed82ad49cea1444aad", + "engine_sha256": "10cfe14cd0eff561a06f0da33c940861b314de077de489908c90204904e4e590", + "files": { + "bin/mission-core-vesc-engine": { + "sha256": "10cfe14cd0eff561a06f0da33c940861b314de077de489908c90204904e4e590", + "bytes": 24801840 + }, + "lib/libGL.so.1": { + "sha256": "67f471213576d225d38347a0b6d2a08a231980685301ff6461bd74d3994e5027", + "bytes": 547136 + }, + "lib/libGLX.so.0": { + "sha256": "16fc8a37eea9210dc83c57eeff5aedc10ab4c6673f2f97e8bb6ee103df657b40", + "bytes": 137792 + }, + "lib/libGLdispatch.so.0": { + "sha256": "ca01a91104c8887b3d8e59499b58cbb8f604cc285666b50d9ec888eb0c915182", + "bytes": 719304 + }, + "lib/libQt5Bluetooth.so.5": { + "sha256": "7e409c8ba1153801671343a454a3aee4943504f2d7a9d1077c67ff46dc7a9831", + "bytes": 915320 + }, + "lib/libQt5Core.so.5": { + "sha256": "f3a46b3517fdcd82d70b9a2c01ba707499860e2eab328bb98445d8afce59ca37", + "bytes": 5699976 + }, + "lib/libQt5DBus.so.5": { + "sha256": "1122d2c92c03fca880e2e8e7de4eaf15fc577f75012362e8f3a76a38a3ce07ab", + "bytes": 595528 + }, + "lib/libQt5Gamepad.so.5": { + "sha256": "364e27bb1a7dd64ff974ab6442a844beb729006da53912581674c478ac5dc4d7", + "bytes": 130144 + }, + "lib/libQt5Gui.so.5": { + "sha256": "75b66a3edcbc7f3013b4180b76919b49c22ce652372eba45ead8aac9121625e0", + "bytes": 7256408 + }, + "lib/libQt5Network.so.5": { + "sha256": "8b3062321c31ddb2c0d96f2c7a7761e086fc4ef2d0d52dbf1119a03d0079ec64", + "bytes": 1749216 + }, + "lib/libQt5Positioning.so.5": { + "sha256": "267929ff49f2ecfbfed7951f3a2cd50985dc2d96f1d8f5ca689615bb6ee5f2b6", + "bytes": 590448 + }, + "lib/libQt5PrintSupport.so.5": { + "sha256": "818b07d6b46ede7e935f97c523231c97b79b44004723b8c1a17e40739337767d", + "bytes": 486696 + }, + "lib/libQt5Qml.so.5": { + "sha256": "e57364d9d0d366824064539a49f4cb3d8fdd284a15db9e3d164ca1ac9a1f64f3", + "bytes": 4729856 + }, + "lib/libQt5QmlModels.so.5": { + "sha256": "68bebbb6db95909aa2262aa2fa6cfd23547565faaa5bb72c49cfe027ac9caf0b", + "bytes": 567600 + }, + "lib/libQt5Quick.so.5": { + "sha256": "a2d2e45f415baa2c9a251844dd45f67d1d10cf6f15c6270dd49c0d348a431260", + "bytes": 5737928 + }, + "lib/libQt5QuickWidgets.so.5": { + "sha256": "8e3947729ac17448ed59a0a0a74960d9f09244a2d084c976b1c4af342f87d82e", + "bytes": 92384 + }, + "lib/libQt5SerialPort.so.5": { + "sha256": "67305251921c0a1d737b90d72b365cc937ca665c6ee218575e2555e85c63dcdb", + "bytes": 97680 + }, + "lib/libQt5Widgets.so.5": { + "sha256": "8e03815f581781fc8b0ef931335493f8f2fcb48ee855f0be2258bbfbd06e62ee", + "bytes": 7057536 + }, + "lib/libX11.so.6": { + "sha256": "c5b5d782bd9cab3420a62df88f5c991507edf3331a89f98464ddbc538c37b879", + "bytes": 1298088 + }, + "lib/libXau.so.6": { + "sha256": "8040da3f8516c1acfe39f04ff022480cdb273705ba5e7a4ca70bbdb1527cd67a", + "bytes": 18696 + }, + "lib/libXdmcp.so.6": { + "sha256": "667d97d6da16016400ab10de9f83ef4ab209ceb6adf68ff9650225ec13e723b0", + "bytes": 26776 + }, + "lib/libbrotlicommon.so.1": { + "sha256": "a91ead095d2c80520c55a89057bbe10b031a075340442e63f44b310f93883a1b", + "bytes": 141640 + }, + "lib/libbrotlidec.so.1": { + "sha256": "64d8a5019d4c294b89fde1193343ea324bbd8603652554e5545f0a01595fa2c5", + "bytes": 51512 + }, + "lib/libbsd.so.0": { + "sha256": "e86cd4f0019f42c2ba5e60602e0edc8694d2948377d98c3654d0f6bddb5254bb", + "bytes": 80888 + }, + "lib/libbz2.so.1.0": { + "sha256": "cc08c9f50a8009ffd6391e0116a100369b11ca9238fa52392c019e6645b122a1", + "bytes": 78944 + }, + "lib/libcap.so.2": { + "sha256": "6ac6abc86ac891c6e13486470e26f1d939f47fda9e6b5d5508a7f5ec881adc84", + "bytes": 51536 + }, + "lib/libcom_err.so.2": { + "sha256": "022943b3b11c860b049bce41342f1c2594941b7b401d95dfdf235521099fee08", + "bytes": 18504 + }, + "lib/libdbus-1.so.3": { + "sha256": "a6ae7b4ef48562b40d7b9ba8efd2e49f6528b7cc6364bea382dcee4b473b5413", + "bytes": 317752 + }, + "lib/libdouble-conversion.so.3": { + "sha256": "d1c9583dc7c1fce6f0a0701dd4356448425e45afe15c0946c23edeaf93d9397c", + "bytes": 79952 + }, + "lib/libexpat.so.1": { + "sha256": "ec6c12d33bb8f9d0e90804121adf19930f36b1b2a4aeb6e1a454b89c7a50c801", + "bytes": 186624 + }, + "lib/libfontconfig.so.1": { + "sha256": "a94b4059b27766f563894c8f7e61762b6f6b2e25c59ef36b730164d4b75c6c98", + "bytes": 325712 + }, + "lib/libfreetype.so.6": { + "sha256": "c14c53c5baff12afafb610c6312fb879e9bb77e80dd42e27504d52d6d8bcd059", + "bytes": 833608 + }, + "lib/libgcc_s.so.1": { + "sha256": "d93224d2b0dab4247598be683adca02f5cf00586f99c187579cd7e92058fb7cb", + "bytes": 183024 + }, + "lib/libgcrypt.so.20": { + "sha256": "6ad6d7007ee1ad8319eb18ba9a512cf09dda49396a303774c68b47477020bad4", + "bytes": 1345072 + }, + "lib/libglib-2.0.so.0": { + "sha256": "96ef9163aee942bdc09e6f4a1acd2fd6b178c03af824c569741440d63ac9f4f4", + "bytes": 1343056 + }, + "lib/libgpg-error.so.0": { + "sha256": "6cb18a007bfcb623029f4528a36b46578fea7dc34c2b505b8e6e0d99e6348cd1", + "bytes": 149760 + }, + "lib/libgraphite2.so.3": { + "sha256": "fcfaf843b25b58b88319ced52f826fc8213a661f3693c916f88641eddffe05b8", + "bytes": 149776 + }, + "lib/libgssapi_krb5.so.2": { + "sha256": "6c1b81696044d79a47d6f0f494ee60aaf641c525c46a11da0c6e4a041a782d3c", + "bytes": 338696 + }, + "lib/libharfbuzz.so.0": { + "sha256": "4562cfcfd18935324ba3ac74a944898b867ab87a56e925ab3e351ba773f1513e", + "bytes": 1101752 + }, + "lib/libicudata.so.74": { + "sha256": "ddbb3718b8bd9cbd780e5ab08b4503c30a6c4fa0706ebe5d074ed6b596c1714e", + "bytes": 30795392 + }, + "lib/libicui18n.so.74": { + "sha256": "3550b194eb2cf2e6f798f033eb9ca279d498c21296b4a18790ce158d2023e47b", + "bytes": 3455304 + }, + "lib/libicuuc.so.74": { + "sha256": "7560aadde38e5f4237a47a1ddd5891f9b36768a77a60faae30beee003ac01901", + "bytes": 2140336 + }, + "lib/libk5crypto.so.3": { + "sha256": "73bc9d72c0c684d6149a3c38f96aab891d178375415c05954fdda587685936f5", + "bytes": 178648 + }, + "lib/libkeyutils.so.1": { + "sha256": "f48214417757f18793ed6e180cc14ee1d6f04252a518fc7270e8ca1d0b4260fe", + "bytes": 22600 + }, + "lib/libkrb5.so.3": { + "sha256": "9615a2841f0783c410eec7fae005a951282551cfedd377737ad8431c8c8cde64", + "bytes": 823488 + }, + "lib/libkrb5support.so.0": { + "sha256": "0aa43578471faecbd642ed2ee6ab92b6682a2b676644193e956fc59d18ca24bb", + "bytes": 47904 + }, + "lib/liblz4.so.1": { + "sha256": "40bffd0a098387368b16b992abd5f7cf43c0fa2f05cabe5a6d483719554adfda", + "bytes": 137440 + }, + "lib/liblzma.so.5": { + "sha256": "696e868dd0700a19a6d65fc01608ec2d70d3cb91f65710e89180cd2e688f30cb", + "bytes": 202904 + }, + "lib/libmd.so.0": { + "sha256": "423e18586b6ea740f4465afd64f7a9a4cb7264ed979c8e7256f9085af5345fef", + "bytes": 55536 + }, + "lib/libmd4c.so.0": { + "sha256": "d5f418d0ea9aec6b41efbb924580a1fb61e9113bcae36d5ad3f322269822d1b3", + "bytes": 67656 + }, + "lib/libpcre2-16.so.0": { + "sha256": "4dfa8a4023270763b8ca1654dc4f59f835393b1ae78085a19369228f8109a671", + "bytes": 572064 + }, + "lib/libpcre2-8.so.0": { + "sha256": "e00576d71d81d3ba0cfa4903c835a44a8723aac96f72f79ff75200b4cff9071b", + "bytes": 625344 + }, + "lib/libpng16.so.16": { + "sha256": "eac265b3506df0d9110dd9143e1d0503e2daabafe1d98b23fac8ca17b71d1f6b", + "bytes": 223304 + }, + "lib/libstdc++.so.6": { + "sha256": "1fd75fe70354a416d75aef22bcae68c47bd25d20e2d0568c30b1a9838cf62f11", + "bytes": 2592224 + }, + "lib/libsystemd.so.0": { + "sha256": "bdf59c828b547bcdbe7b3576c0810d9d9d2e982d8b61b365812542da6a4c4a99", + "bytes": 910592 + }, + "lib/libudev.so.1": { + "sha256": "4298228175fa62a36af88b1afd4406cdd8b1bf166621f957d0dbbde45a698fe5", + "bytes": 207288 + }, + "lib/libxcb.so.1": { + "sha256": "7958a0136b121bdc4c708968569ad152a9ed208ab026e2537b1005dde64ca440", + "bytes": 162392 + }, + "lib/libz.so.1": { + "sha256": "86200da370f20476a2507e9097a789b5ef97269b4ca8d5e164ad82dab9d99892", + "bytes": 113000 + }, + "lib/libzstd.so.1": { + "sha256": "0a2128bc10841fb29e76d08d945864dfb0b6a66da5df6df5d8299197439e54bb", + "bytes": 755864 + }, + "licenses/UPSTREAM-SOURCE.txt": { + "sha256": "ff2fbc975e47bffd1e3c488e14f1fbe417c83db82fb5ab41e16a9c1da96edb2a", + "bytes": 293 + }, + "licenses/VESC-Tool-LICENSE": { + "sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986", + "bytes": 35149 + }, + "licenses/config_export.h": { + "sha256": "f0c483aa27b9910bab1bff4f7baf66fe4077461e65a1d3e11169c4a722212756", + "bytes": 4724 + }, + "licenses/engine_main.cpp": { + "sha256": "e4b32dc5c9def71208d8daad830d5c47852f39f85a321713abc45dc15173b4fc", + "bytes": 21539 + }, + "licenses/gir1.2-glib-2.0.copyright": { + "sha256": "b52574b109fb876dfa71dea7a98b8aee1bb583f6aa90c327d1e4dc0a1d59f211", + "bytes": 54957 + }, + "licenses/gir1.2-gudev-1.0.copyright": { + "sha256": "e8208610819fd05fca6ea4776156858bb934e29c408ae9bdac4a8266a53178e3", + "bytes": 1056 + }, + "licenses/libblkid-dev.copyright": { + "sha256": "3492fb92cb56cf517d9a899828b4f989038421a38736e49e5525ffbd33196eab", + "bytes": 23160 + }, + "licenses/libbrotli-dev.copyright": { + "sha256": "24a64e5bb83d0960d1835696a1e23c0896ad6055b0ca47c66ab0eb9a766324b1", + "bytes": 1354 + }, + "licenses/libdouble-conversion3.copyright": { + "sha256": "1cc0b36cdfe5a674e11cb9907a88291c7602d3805bddd334cc07d57231a0cd00", + "bytes": 1999 + }, + "licenses/libegl-dev.copyright": { + "sha256": "37920f219f60efa2fde5d003c51be0608b2159cc74c5eb6d70d630907db2d9a3", + "bytes": 4422 + }, + "licenses/libevdev-dev.copyright": { + "sha256": "01d0da4919f92dd06e7ec73fee6cf5dccac3c6e475917b9dc57cb22800b732de", + "bytes": 5460 + }, + "licenses/libexpat1-dev.copyright": { + "sha256": "60919fe1a156395ff14511bb6ff79756c50ade2fff59ac60c9bae1d8a7fe6292", + "bytes": 1756 + }, + "licenses/libexpat1.copyright": { + "sha256": "60919fe1a156395ff14511bb6ff79756c50ade2fff59ac60c9bae1d8a7fe6292", + "bytes": 1756 + }, + "licenses/libfontconfig-dev.copyright": { + "sha256": "b215a61cdd3e62b5b17cc28b1852c78acb3dd38be0fb30706f7efc050dba91db", + "bytes": 1301 + }, + "licenses/libfreetype-dev.copyright": { + "sha256": "ce6d766883ea111e7f47acc09e9d49be8827daa6a03f2c2707243a425d41f0e9", + "bytes": 31209 + }, + "licenses/libgirepository-2.0-0.copyright": { + "sha256": "b52574b109fb876dfa71dea7a98b8aee1bb583f6aa90c327d1e4dc0a1d59f211", + "bytes": 54957 + }, + "licenses/libgl-dev.copyright": { + "sha256": "37920f219f60efa2fde5d003c51be0608b2159cc74c5eb6d70d630907db2d9a3", + "bytes": 4422 + }, + "licenses/libglib2.0-0t64.copyright": { + "sha256": "b52574b109fb876dfa71dea7a98b8aee1bb583f6aa90c327d1e4dc0a1d59f211", + "bytes": 54957 + }, + "licenses/libglib2.0-bin.copyright": { + "sha256": "b52574b109fb876dfa71dea7a98b8aee1bb583f6aa90c327d1e4dc0a1d59f211", + "bytes": 54957 + }, + "licenses/libglib2.0-data.copyright": { + "sha256": "b52574b109fb876dfa71dea7a98b8aee1bb583f6aa90c327d1e4dc0a1d59f211", + "bytes": 54957 + }, + "licenses/libglib2.0-dev-bin.copyright": { + "sha256": "b52574b109fb876dfa71dea7a98b8aee1bb583f6aa90c327d1e4dc0a1d59f211", + "bytes": 54957 + }, + "licenses/libglib2.0-dev.copyright": { + "sha256": "b52574b109fb876dfa71dea7a98b8aee1bb583f6aa90c327d1e4dc0a1d59f211", + "bytes": 54957 + }, + "licenses/libglu1-mesa-dev.copyright": { + "sha256": "7802232600641c113e2948fbc2feae6de45f26af59a43c28836e0ef846f8dd94", + "bytes": 4055 + }, + "licenses/libglx-dev.copyright": { + "sha256": "37920f219f60efa2fde5d003c51be0608b2159cc74c5eb6d70d630907db2d9a3", + "bytes": 4422 + }, + "licenses/libgudev-1.0-dev.copyright": { + "sha256": "e8208610819fd05fca6ea4776156858bb934e29c408ae9bdac4a8266a53178e3", + "bytes": 1056 + }, + "licenses/libinput-bin.copyright": { + "sha256": "f075af6e7319a471289bc1908aae04e44ba954ea53b11fcf42ee8d5422f40363", + "bytes": 2292 + }, + "licenses/libinput-dev.copyright": { + "sha256": "f075af6e7319a471289bc1908aae04e44ba954ea53b11fcf42ee8d5422f40363", + "bytes": 2292 + }, + "licenses/libinput10.copyright": { + "sha256": "f075af6e7319a471289bc1908aae04e44ba954ea53b11fcf42ee8d5422f40363", + "bytes": 2292 + }, + "licenses/libmd4c0.copyright": { + "sha256": "68e5ce452a6fc2bee44279ca61a7064950d146481e325eeaece6c9bea095fd2f", + "bytes": 23273 + }, + "licenses/libmount-dev.copyright": { + "sha256": "3492fb92cb56cf517d9a899828b4f989038421a38736e49e5525ffbd33196eab", + "bytes": 23160 + }, + "licenses/libmtdev-dev.copyright": { + "sha256": "7ca89f7e6e0ab15b9941aa80def7c50b22a7bd6356dd1eacf28ca4382f72a6de", + "bytes": 1628 + }, + "licenses/libopengl-dev.copyright": { + "sha256": "37920f219f60efa2fde5d003c51be0608b2159cc74c5eb6d70d630907db2d9a3", + "bytes": 4422 + }, + "licenses/libpcre2-16-0.copyright": { + "sha256": "030511beb4d9d620ad09914c369c36ec0528dcf301d1923cc643c948ee7c6a38", + "bytes": 6626 + }, + "licenses/libpcre2-dev.copyright": { + "sha256": "030511beb4d9d620ad09914c369c36ec0528dcf301d1923cc643c948ee7c6a38", + "bytes": 6626 + }, + "licenses/libpcre2-posix3.copyright": { + "sha256": "030511beb4d9d620ad09914c369c36ec0528dcf301d1923cc643c948ee7c6a38", + "bytes": 6626 + }, + "licenses/libpkgconf3.copyright": { + "sha256": "676c75e54ff7e3b9892940fbf1b31763cb6f2a6527a5607a3640ac59a2441fba", + "bytes": 7501 + }, + "licenses/libpng-dev.copyright": { + "sha256": "4620d402b97601a910946acccbbe2e15bdffac11615bf9046520990d3b00f2b9", + "bytes": 13051 + }, + "licenses/libpthread-stubs0-dev.copyright": { + "sha256": "e45b85577d0f6883300ccfb004ab79e1a4f2cf3777b64eb989525115af400b5a", + "bytes": 1849 + }, + "licenses/libqt5bluetooth5-bin.copyright": { + "sha256": "937c1479a92f32fbd29957b9339b35e9edb7c85be3be6543c8c7495ea799933e", + "bytes": 7982 + }, + "licenses/libqt5bluetooth5.copyright": { + "sha256": "937c1479a92f32fbd29957b9339b35e9edb7c85be3be6543c8c7495ea799933e", + "bytes": 7982 + }, + "licenses/libqt5concurrent5t64.copyright": { + "sha256": "4839c591405c069c6daad29f578f0e9d09580d15571b4c1e6bb7bbc0902b8c08", + "bytes": 131975 + }, + "licenses/libqt5core5t64.copyright": { + "sha256": "4839c591405c069c6daad29f578f0e9d09580d15571b4c1e6bb7bbc0902b8c08", + "bytes": 131975 + }, + "licenses/libqt5dbus5t64.copyright": { + "sha256": "4839c591405c069c6daad29f578f0e9d09580d15571b4c1e6bb7bbc0902b8c08", + "bytes": 131975 + }, + "licenses/libqt5gamepad5-dev.copyright": { + "sha256": "eb1b57f89c6b2c7e25472e1e59c796ed6bc7ff5c5eb08845a95fe9653f781c5b", + "bytes": 3446 + }, + "licenses/libqt5gamepad5.copyright": { + "sha256": "eb1b57f89c6b2c7e25472e1e59c796ed6bc7ff5c5eb08845a95fe9653f781c5b", + "bytes": 3446 + }, + "licenses/libqt5gui5t64.copyright": { + "sha256": "4839c591405c069c6daad29f578f0e9d09580d15571b4c1e6bb7bbc0902b8c08", + "bytes": 131975 + }, + "licenses/libqt5network5t64.copyright": { + "sha256": "4839c591405c069c6daad29f578f0e9d09580d15571b4c1e6bb7bbc0902b8c08", + "bytes": 131975 + }, + "licenses/libqt5nfc5.copyright": { + "sha256": "937c1479a92f32fbd29957b9339b35e9edb7c85be3be6543c8c7495ea799933e", + "bytes": 7982 + }, + "licenses/libqt5positioning5-plugins.copyright": { + "sha256": "2d54a4f412d1a2c1f5138b06a94a6cdd445e267227fb0526fc376ab2e7d9b63f", + "bytes": 18782 + }, + "licenses/libqt5positioning5.copyright": { + "sha256": "2d54a4f412d1a2c1f5138b06a94a6cdd445e267227fb0526fc376ab2e7d9b63f", + "bytes": 18782 + }, + "licenses/libqt5positioningquick5.copyright": { + "sha256": "2d54a4f412d1a2c1f5138b06a94a6cdd445e267227fb0526fc376ab2e7d9b63f", + "bytes": 18782 + }, + "licenses/libqt5printsupport5t64.copyright": { + "sha256": "4839c591405c069c6daad29f578f0e9d09580d15571b4c1e6bb7bbc0902b8c08", + "bytes": 131975 + }, + "licenses/libqt5qml5.copyright": { + "sha256": "5efc270a798372057f7ee88c14cf4a7cb41289607f2a15a5c5aa7d26809eddd0", + "bytes": 44601 + }, + "licenses/libqt5qmlmodels5.copyright": { + "sha256": "5efc270a798372057f7ee88c14cf4a7cb41289607f2a15a5c5aa7d26809eddd0", + "bytes": 44601 + }, + "licenses/libqt5qmlworkerscript5.copyright": { + "sha256": "5efc270a798372057f7ee88c14cf4a7cb41289607f2a15a5c5aa7d26809eddd0", + "bytes": 44601 + }, + "licenses/libqt5quick5.copyright": { + "sha256": "5efc270a798372057f7ee88c14cf4a7cb41289607f2a15a5c5aa7d26809eddd0", + "bytes": 44601 + }, + "licenses/libqt5quickcontrols2-5.copyright": { + "sha256": "334854f9488a33d1211ded54478a35071369a4addaf86d2581820025b244ae03", + "bytes": 10979 + }, + "licenses/libqt5quickparticles5.copyright": { + "sha256": "5efc270a798372057f7ee88c14cf4a7cb41289607f2a15a5c5aa7d26809eddd0", + "bytes": 44601 + }, + "licenses/libqt5quickshapes5.copyright": { + "sha256": "5efc270a798372057f7ee88c14cf4a7cb41289607f2a15a5c5aa7d26809eddd0", + "bytes": 44601 + }, + "licenses/libqt5quicktemplates2-5.copyright": { + "sha256": "334854f9488a33d1211ded54478a35071369a4addaf86d2581820025b244ae03", + "bytes": 10979 + }, + "licenses/libqt5quicktest5.copyright": { + "sha256": "5efc270a798372057f7ee88c14cf4a7cb41289607f2a15a5c5aa7d26809eddd0", + "bytes": 44601 + }, + "licenses/libqt5quickwidgets5.copyright": { + "sha256": "5efc270a798372057f7ee88c14cf4a7cb41289607f2a15a5c5aa7d26809eddd0", + "bytes": 44601 + }, + "licenses/libqt5serialport5-dev.copyright": { + "sha256": "679e7d434baaf5b3b80e3f7764d6e57a7a971f11693f8d0420f1de5dc7696a6b", + "bytes": 6220 + }, + "licenses/libqt5serialport5.copyright": { + "sha256": "679e7d434baaf5b3b80e3f7764d6e57a7a971f11693f8d0420f1de5dc7696a6b", + "bytes": 6220 + }, + "licenses/libqt5sql5t64.copyright": { + "sha256": "4839c591405c069c6daad29f578f0e9d09580d15571b4c1e6bb7bbc0902b8c08", + "bytes": 131975 + }, + "licenses/libqt5svg5-dev.copyright": { + "sha256": "71bc825205f218db925d601e2c4cee8f1cdd36ae07ece4e63736bfb0afe0453f", + "bytes": 8476 + }, + "licenses/libqt5svg5.copyright": { + "sha256": "71bc825205f218db925d601e2c4cee8f1cdd36ae07ece4e63736bfb0afe0453f", + "bytes": 8476 + }, + "licenses/libqt5test5t64.copyright": { + "sha256": "4839c591405c069c6daad29f578f0e9d09580d15571b4c1e6bb7bbc0902b8c08", + "bytes": 131975 + }, + "licenses/libqt5widgets5t64.copyright": { + "sha256": "4839c591405c069c6daad29f578f0e9d09580d15571b4c1e6bb7bbc0902b8c08", + "bytes": 131975 + }, + "licenses/libqt5xml5t64.copyright": { + "sha256": "4839c591405c069c6daad29f578f0e9d09580d15571b4c1e6bb7bbc0902b8c08", + "bytes": 131975 + }, + "licenses/libselinux1-dev.copyright": { + "sha256": "864f1bb189f609075d580b8c4aada16d85a44546884f1687989e1cacc8c56751", + "bytes": 1957 + }, + "licenses/libsepol-dev.copyright": { + "sha256": "78d2a34606a0302057ec499a3b3c07bcbc43ca334064ce4c80891a0f69c8f6c6", + "bytes": 3750 + }, + "licenses/libudev-dev.copyright": { + "sha256": "a7d06854714a1ca99f6dbd1a1641dde5bcf28635be149f6554449618f8f427f3", + "bytes": 12776 + }, + "licenses/libvulkan-dev.copyright": { + "sha256": "c579213e28f67944a7e407816b8a8e1d2d2406b3d820e420aa923807c450dc07", + "bytes": 1964 + }, + "licenses/libwacom-dev.copyright": { + "sha256": "5026eb61394922e821cfea069fe9740141b1d6abd3ea900e79655ad45ea1cb8a", + "bytes": 1624 + }, + "licenses/libx11-dev.copyright": { + "sha256": "0b380a7fd5b2228f26e9585e56f14812efd3350f3df307507d2bc055dfd8de3e", + "bytes": 47102 + }, + "licenses/libxau-dev.copyright": { + "sha256": "118dd263a7b91c8f21c489f949bf13281dff9e766deea92b829dac4dce66601a", + "bytes": 1224 + }, + "licenses/libxcb-xinerama0.copyright": { + "sha256": "4f7cb9db6bf6542f5417e3d674c780d3a5fd12291a54d63054fb576ee0cfae80", + "bytes": 1781 + }, + "licenses/libxcb-xinput0.copyright": { + "sha256": "4f7cb9db6bf6542f5417e3d674c780d3a5fd12291a54d63054fb576ee0cfae80", + "bytes": 1781 + }, + "licenses/libxcb1-dev.copyright": { + "sha256": "4f7cb9db6bf6542f5417e3d674c780d3a5fd12291a54d63054fb576ee0cfae80", + "bytes": 1781 + }, + "licenses/libxdmcp-dev.copyright": { + "sha256": "1bcbb50f8603fe8b86d330bfa460b772ea04fbd3c70e4499f0768b5340b9fd6e", + "bytes": 1265 + }, + "licenses/libxext-dev.copyright": { + "sha256": "bc57e445ca1d9fe082c8d54189dd411ff26caa8552c9c63d44ea06a982f32124", + "bytes": 10421 + }, + "licenses/libxkbcommon-dev.copyright": { + "sha256": "5eeaeb1b6e029a0274e1573765bb0bae2926ef96a3679203faa4fd00fdaeaa88", + "bytes": 3566 + }, + "licenses/pkgconf-bin.copyright": { + "sha256": "676c75e54ff7e3b9892940fbf1b31763cb6f2a6527a5607a3640ac59a2441fba", + "bytes": 7501 + }, + "licenses/pkgconf.copyright": { + "sha256": "676c75e54ff7e3b9892940fbf1b31763cb6f2a6527a5607a3640ac59a2441fba", + "bytes": 7501 + }, + "licenses/python3-packaging.copyright": { + "sha256": "51fe4bbadf841c4e4d02ad97ba375bcde0ae11a51da62ae16fdcbe723d3cdad2", + "bytes": 2444 + }, + "licenses/qt5-qmake-bin.copyright": { + "sha256": "4839c591405c069c6daad29f578f0e9d09580d15571b4c1e6bb7bbc0902b8c08", + "bytes": 131975 + }, + "licenses/qt5-qmake.copyright": { + "sha256": "4839c591405c069c6daad29f578f0e9d09580d15571b4c1e6bb7bbc0902b8c08", + "bytes": 131975 + }, + "licenses/qt5-qmltooling-plugins.copyright": { + "sha256": "5efc270a798372057f7ee88c14cf4a7cb41289607f2a15a5c5aa7d26809eddd0", + "bytes": 44601 + }, + "licenses/qtbase5-dev-tools.copyright": { + "sha256": "4839c591405c069c6daad29f578f0e9d09580d15571b4c1e6bb7bbc0902b8c08", + "bytes": 131975 + }, + "licenses/qtbase5-dev.copyright": { + "sha256": "4839c591405c069c6daad29f578f0e9d09580d15571b4c1e6bb7bbc0902b8c08", + "bytes": 131975 + }, + "licenses/qtbase5-private-dev.copyright": { + "sha256": "4839c591405c069c6daad29f578f0e9d09580d15571b4c1e6bb7bbc0902b8c08", + "bytes": 131975 + }, + "licenses/qtchooser.copyright": { + "sha256": "0b3fa692b33acfbb5b9539335c66938c957350b2a24d2fec35de89e09198738e", + "bytes": 5193 + }, + "licenses/qtconnectivity5-dev.copyright": { + "sha256": "937c1479a92f32fbd29957b9339b35e9edb7c85be3be6543c8c7495ea799933e", + "bytes": 7982 + }, + "licenses/qtdeclarative5-dev-tools.copyright": { + "sha256": "5efc270a798372057f7ee88c14cf4a7cb41289607f2a15a5c5aa7d26809eddd0", + "bytes": 44601 + }, + "licenses/qtdeclarative5-dev.copyright": { + "sha256": "5efc270a798372057f7ee88c14cf4a7cb41289607f2a15a5c5aa7d26809eddd0", + "bytes": 44601 + }, + "licenses/qtpositioning5-dev.copyright": { + "sha256": "2d54a4f412d1a2c1f5138b06a94a6cdd445e267227fb0526fc376ab2e7d9b63f", + "bytes": 18782 + }, + "licenses/qtquickcontrols2-5-dev.copyright": { + "sha256": "334854f9488a33d1211ded54478a35071369a4addaf86d2581820025b244ae03", + "bytes": 10979 + }, + "licenses/uuid-dev.copyright": { + "sha256": "3492fb92cb56cf517d9a899828b4f989038421a38736e49e5525ffbd33196eab", + "bytes": 23160 + }, + "licenses/x11proto-dev.copyright": { + "sha256": "7b40446cf2035abc6836c7a7f411ec79153dbf4530bce209e26aa2fd7c4dd55a", + "bytes": 3963 + }, + "licenses/xorg-sgml-doctools.copyright": { + "sha256": "f8f02d5cfd7d4ed0eb6c46deacb3a64c1fa5bc60e06db10ecbf202e6fe1d5a89", + "bytes": 2271 + }, + "licenses/xtrans-dev.copyright": { + "sha256": "29e6f06b1dcd85f1bc4b3e9374b92967cb2a274abde00169784f1dd1c7c95431", + "bytes": 6364 + }, + "licenses/zlib1g-dev.copyright": { + "sha256": "9e5b96d63773a5d177ba264254390f792be07e41748ebd94730981c6cac31cc6", + "bytes": 2927 + }, + "plugins/platforms/libqoffscreen.so": { + "sha256": "f2f19a29e816c7e5c60fd52b9d3c1a214634c38e06cd2ffdf9fc88e9f0c49ffd", + "bytes": 193880 + } + }, + "host_libraries": [ + "ld-linux-x86-64.so.2", + "libc.so.6", + "libdl.so.2", + "libm.so.6", + "libpthread.so.0", + "libresolv.so.2", + "librt.so.1" + ], + "offline_verified": true, + "hardware_qualified": false, + "clean_os_qualified": false +} diff --git a/plugins/vesc/packaging/native_bundle.py b/plugins/vesc/packaging/native_bundle.py new file mode 100644 index 0000000..a0c3b26 --- /dev/null +++ b/plugins/vesc/packaging/native_bundle.py @@ -0,0 +1,95 @@ +"""Bundle an admitted native engine and the actual ELF dependency closure. + +Private, installer-owned Qt runtime; never installs packages on the build host. +The target is Ubuntu 24.04 amd64. Only its glibc family stays a host prerequisite. +""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import tarfile + +SYSTEM = {"libc.so.6", "libm.so.6", "libpthread.so.0", "libdl.so.2", "librt.so.1", "libresolv.so.2", "ld-linux-x86-64.so.2"} + + +def build(engine, sysroot, source, output): + output.mkdir(mode=0o700, exist_ok=False) + staging = output / "payload" + (staging / "bin").mkdir(parents=True) + (staging / "lib").mkdir() + (staging / "plugins/platforms").mkdir(parents=True) + binary = staging / "bin/mission-core-vesc-engine" + shutil.copyfile(engine, binary); binary.chmod(0o755) + qtlib = sysroot / "usr/lib/x86_64-linux-gnu" + plugin = qtlib / "qt5/plugins/platforms/libqoffscreen.so" + shutil.copyfile(plugin, staging / "plugins/platforms/libqoffscreen.so") + env = dict(os.environ, LD_LIBRARY_PATH=str(qtlib), LC_ALL="C") + sources = {} + for executable in (engine, plugin): + result = subprocess.run(["/usr/bin/ldd", str(executable)], env=env, capture_output=True, text=True, check=True).stdout + if "not found" in result: raise RuntimeError("Native runtime dependency missing") + for name, path in re.findall(r"^\s*(\S+) => (/[\S]+) \(", result, re.MULTILINE): + if name in SYSTEM: continue + library = Path(path) + if name in sources and sources[name] != library: raise RuntimeError("Conflicting dependency") + sources[name] = library + for name, library in sources.items(): shutil.copyfile(library, staging / "lib" / name) + env.update(LD_LIBRARY_PATH=str(staging / "lib"), QT_PLUGIN_PATH=str(staging / "plugins"), + QT_QPA_PLATFORM="offscreen", XDG_CONFIG_HOME=str(output / "config"), XDG_CACHE_HOME=str(output / "cache")) + # All non-glibc ELF dependencies must now resolve inside the shipped payload. + for executable in (binary, staging / "plugins/platforms/libqoffscreen.so"): + result = subprocess.run(["/usr/bin/ldd", str(executable)], env=env, capture_output=True, text=True, check=True).stdout + if "not found" in result: raise RuntimeError("Bundled native closure incomplete") + for name, path in re.findall(r"^\s*(\S+) => (/[\S]+) \(", result, re.MULTILINE): + if name not in SYSTEM and not Path(path).resolve().is_relative_to(staging): + raise RuntimeError("Undeclared host dependency: " + name) + proc = subprocess.run([str(binary), "--offline"], env=env, input=b'{"id":1,"method":"engine"}\n', + capture_output=True, timeout=15, check=True) + responses = [json.loads(line) for line in proc.stdout.splitlines()] + if len(responses) != 2 or not responses[0]["ready"] or responses[1]["result"]["connected"]: + raise RuntimeError("Bundled engine acceptance failed") + (output / "offline.stdout").write_bytes(proc.stdout) + (output / "offline.stderr").write_bytes(proc.stderr) + (staging / "licenses").mkdir() + shutil.copyfile(source / "LICENSE", staging / "licenses/VESC-Tool-LICENSE") + (staging / "licenses/UPSTREAM-SOURCE.txt").write_text( + "VESC Tool 7.00, unmodified upstream sources and resources:\n" + "https://github.com/vedderb/vesc_tool/tree/01d5f10901116c311e3fb84d5a1541f663d3ce20\n" + "Source archive SHA-256: 4565ecec4e41e094bcc43127a51970e810aa9080a9d7c025af64632bfd4c0189\n" + "The process adapter source is included alongside this notice.\n") + for name in ("engine_main.cpp", "config_export.h"): + shutil.copyfile(engine.parent / name, staging / "licenses" / name) + # Preserve dependency notices available in the private signed-package sysroot. + for index, path in enumerate(sorted((sysroot / "usr/share/doc").glob("*/copyright"))): + shutil.copyfile(path, staging / "licenses" / (path.parent.name + ".copyright")) + # Host libraries copied into the closure retain their distribution notices. + for library in sources.values(): + if library.resolve().is_relative_to(sysroot): continue + owner = subprocess.run(["dpkg-query", "-S", str(library)], capture_output=True, text=True) + if owner.returncode: continue + package = owner.stdout.split(": ", 1)[0].split(":", 1)[0] + notice = Path("/usr/share/doc") / package / "copyright" + if notice.is_file(): shutil.copyfile(notice, staging / "licenses" / (package + ".copyright")) + metadata = {str(p.relative_to(staging)): {"sha256": hashlib.sha256(p.read_bytes()).hexdigest(), "bytes":p.stat().st_size} + for p in sorted(staging.rglob("*")) if p.is_file()} + archive = output / "mission-core-vesc-native-runtime.tar.gz" + with tarfile.open(archive, "w:gz") as stream: + for path in sorted(staging.rglob("*")): + if path.is_file(): stream.add(path, arcname=str(path.relative_to(staging))) + report = {"schema":"missioncore.vesc.native-runtime/v1", "upstream_version":"7.00", + "upstream_commit":"01d5f10901116c311e3fb84d5a1541f663d3ce20", "os":"ubuntu-24.04-amd64", + "file":archive.name, "bytes":archive.stat().st_size, "sha256":hashlib.sha256(archive.read_bytes()).hexdigest(), + "engine_sha256":hashlib.sha256(binary.read_bytes()).hexdigest(), "files":metadata, + "host_libraries":sorted(SYSTEM), "offline_verified":True, "hardware_qualified":False, + "clean_os_qualified":False} + (output / "bundle.json").write_text(json.dumps(report,indent=2)+"\n") + + +if __name__ == "__main__": + parser=argparse.ArgumentParser() + for name in ("engine","sysroot","source","output"):parser.add_argument("--"+name,type=Path,required=True) + args=parser.parse_args();build(args.engine,args.sysroot,args.source,args.output) diff --git a/plugins/vesc/packaging/native_check.py b/plugins/vesc/packaging/native_check.py new file mode 100644 index 0000000..da34918 --- /dev/null +++ b/plugins/vesc/packaging/native_check.py @@ -0,0 +1,34 @@ +"""Installer acceptance under the service account; never opens a USB device.""" +import hashlib +import json +import os +from pathlib import Path +import subprocess +import tempfile + + +def check(root): + manifest = json.loads((root / "manifest.json").read_text()) + for name, expected in manifest["files"].items(): + path = root / name + if path.is_symlink() or not path.resolve().is_relative_to(root.resolve()): + raise RuntimeError("Untrusted native runtime path") + if path.stat().st_size != expected["bytes"] or hashlib.sha256(path.read_bytes()).hexdigest() != expected["sha256"]: + raise RuntimeError("Native runtime integrity check failed") + with tempfile.TemporaryDirectory(prefix="mission-core-vesc-check-") as temporary: + env = {"PATH":"/usr/bin:/bin", "LANG":"C.UTF-8", "QT_QPA_PLATFORM":"offscreen", + "LD_LIBRARY_PATH":str(root / "lib"), "QT_PLUGIN_PATH":str(root / "plugins"), + "XDG_CONFIG_HOME":temporary, "XDG_CACHE_HOME":temporary} + result = subprocess.run([str(root / "bin/mission-core-vesc-engine"), "--offline"], + env=env, input=b'{"id":1,"method":"engine"}\n', capture_output=True, timeout=15, check=True) + replies = [json.loads(line) for line in result.stdout.splitlines()] + if (len(replies) != 2 or not replies[0]["ready"] or not replies[1]["ok"] + or replies[1]["result"]["hardware_enabled"] or replies[1]["result"]["connected"] + or replies[1]["result"]["commit"] != manifest["upstream_commit"]): + raise RuntimeError("Native engine offline check failed") + print(json.dumps({"ok":True, "upstream_commit":manifest["upstream_commit"], "hardware_access":False})) + + +if __name__ == "__main__": + if os.geteuid() == 0: raise RuntimeError("Run as the VESC service account") + check(Path(__file__).resolve().parent / "native") diff --git a/plugins/vesc/packaging/native_probe.py b/plugins/vesc/packaging/native_probe.py new file mode 100644 index 0000000..c006fc1 --- /dev/null +++ b/plugins/vesc/packaging/native_probe.py @@ -0,0 +1,188 @@ +"""Versioned offline qualification artifact, not a runtime installer. + +Reuse an attested upstream Tool build's object files unchanged. Only the adapter +entry point is compiled. The previous staging, packages and services are untouched. +All inputs, link objects, outputs and checks are hashed in the private report. +""" +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +import platform +import re +import subprocess +import time +import zipfile + +COMMIT = "01d5f10901116c311e3fb84d5a1541f663d3ce20" +UPSTREAM_SHA256 = "4565ecec4e41e094bcc43127a51970e810aa9080a9d7c025af64632bfd4c0189" + + +def digest(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def run(args): + release = platform.freedesktop_os_release() + if os.geteuid() == 0 or (release.get("ID"), release.get("VERSION_ID"), platform.machine()) != ("ubuntu", "24.04", "x86_64"): + raise RuntimeError("Unprivileged Ubuntu 24.04 amd64 required") + group = Path("/sys/fs/cgroup") / Path("/proc/self/cgroup").read_text().strip().split("::", 1)[1].lstrip("/") + limit = (group / "memory.max").read_text().strip() + if limit == "max" or int(limit) > 3 * 1024**3: + raise RuntimeError("A bounded user scope with MemoryMax <= 3G is required") + previous = json.loads(args.upstream_report.read_text()) + if previous.get("state") != "complete" or previous.get("source_sha256") != UPSTREAM_SHA256: + raise RuntimeError("Unqualified upstream build") + upstream = Path(previous["binary"]) + if digest(upstream) != previous["binary_sha256"]: + raise RuntimeError("Upstream binary changed") + source = upstream.parents[2] + if source.name != "vesc_tool-" + COMMIT: + raise RuntimeError("Upstream source path mismatch") + os.umask(0o077) + root = args.output.resolve() + root.mkdir(parents=True, mode=0o700, exist_ok=False) + # Paths enter a generated makefile, never a shell command assembled from JSON. + if any(not re.fullmatch(r"[A-Za-z0-9_./-]+", str(p)) for p in (root, source)): + raise RuntimeError("Build paths must be make-safe") + with zipfile.ZipFile(args.artifact) as bundle: + for name in ("offline_main.cpp", "config_export.h", "engine_main.cpp", "native_bundle.py"): + (root / name).write_bytes(bundle.read(name)) + report = {"schema": "missioncore.vesc.native-probe/v1", "state": "running", + "started_at": datetime.now(timezone.utc).isoformat(), "monotonic_started": time.monotonic(), + "source_commit": COMMIT, "artifact_sha256": digest(args.artifact), + "upstream_report_sha256": digest(args.upstream_report), + "adapter_sha256": digest(root / "offline_main.cpp"), + "hardware_access": False, "runtime_installed": False, "system_packages_installed": False, + "jobs": [], "checks": []} + + def publish(): + (root / "report.json").write_text(json.dumps(report, indent=2) + "\n") + + staging = source.parents[1] + qtbase = staging / "sysroot/usr" + env = dict(os.environ, LC_ALL="C", QT_QPA_PLATFORM="offscreen", + LD_LIBRARY_PATH=str(qtbase / "lib/x86_64-linux-gnu"), + QT_PLUGIN_PATH=str(qtbase / "lib/x86_64-linux-gnu/qt5/plugins"), + XDG_CONFIG_HOME=str(root / "config"), XDG_CACHE_HOME=str(root / "cache")) + + def execute(name, command, data=None, expected=0, timeout=60): + start = time.monotonic() + proc = subprocess.run(command, cwd=source, env=env, input=data, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout) + (root / (name + ".stdout")).write_bytes(proc.stdout) + (root / (name + ".stderr")).write_bytes(proc.stderr) + report["jobs"].append({"id": name, "exit_code": proc.returncode, + "duration_seconds": time.monotonic() - start, + "stdout_sha256": hashlib.sha256(proc.stdout).hexdigest(), + "stderr_sha256": hashlib.sha256(proc.stderr).hexdigest()}) + publish() + if proc.returncode != expected: + raise RuntimeError("Native probe step failed: " + name) + return proc.stdout + + try: + makefile = (source / "Makefile").read_text().replace("\\\n", " ") + match = re.search(r"^OBJECTS\s*=\s*(.+)$", makefile, re.MULTILINE) + if not match: + raise RuntimeError("Upstream link objects missing") + objects = [source / name for name in match.group(1).split() if name != "build/lin/obj/main.o"] + if not 100 < len(objects) < 1000 or any(not p.is_file() for p in objects): + raise RuntimeError("Upstream object inventory incomplete") + report["link_objects"] = [{"file": str(p.relative_to(source)), "sha256": digest(p)} for p in objects] + report["upstream_makefile_sha256"] = digest(source / "Makefile") + target = root / "mission-core-vesc-offline" + wrapper = root / "Makefile.native" + wrapper.write_text( + "include " + str(source / "Makefile") + "\n" + ".PHONY: mission-core-native-probe\n" + "mission-core-native-probe:\n" + "\t$(CXX) -c $(CXXFLAGS) $(INCPATH) -o " + str(root / "offline_main.o") + " " + str(root / "offline_main.cpp") + "\n" + "\t$(LINK) $(LFLAGS) -o " + str(target) + " " + str(root / "offline_main.o") + + " $(filter-out build/lin/obj/main.o,$(OBJECTS)) $(OBJCOMP) $(LIBS)\n") + execute("compile-link", ["/usr/bin/make", "-f", str(wrapper), "mission-core-native-probe"], timeout=180) + report["binary_sha256"] = digest(target) + for index, archive in enumerate(args.archives): + raw = archive.read_bytes() + native = json.loads(execute("archive-%d" % index, [str(target)], raw)) + if not native["ok"] or not native["compatibility"]["legacy_power_loss_correction"]: + raise RuntimeError("Upstream compatibility check failed") + import base64 + packet = base64.b64decode(native["compatibility"]["offline_detect_example_base64"]) + if packet[:2] != bytes([58, 0]) or int.from_bytes(packet[2:6], "big", signed=True) != 50000: + raise RuntimeError("Expected native 5.02 detect correction was not applied") + rpm_packets = [base64.b64decode(p) for p in native["offline_signed_rpm_examples_base64"]] + if (len(rpm_packets) != 2 or any(len(p) != 5 or p[0] != 8 for p in rpm_packets) + or [int.from_bytes(p[1:], "big", signed=True) for p in rpm_packets] != [3000, -3000]): + raise RuntimeError("Upstream signed RPM serialization mismatch") + report["checks"].append({"id": "signed-rpm-serialization-%d" % index, "ok": True}) + report["checks"].append({"id": "native-archive-%d" % index, "ok": True, + "archive_sha256": hashlib.sha256(raw).hexdigest(), + "motor_parameter_count": len(native["motor"]["parameters"]), + "application_parameter_count": len(native["application"]["parameters"]), + "binary_round_trip_exact": True, + "xml_equivalent_by_upstream_comparison": True, + "xml_binary_exact": all(native[k]["xml_round_trip_exact"] for k in ("motor", "application")), + "legacy_power_loss_correction": True}) + # Fail closed on archive corruption and unsupported firmware instead + # of silently presenting the bundled defaults as actual settings. + original = json.loads(raw) + damaged = json.loads(raw); damaged["configs"]["motor"]["sha256"] = "0" * 64 + unknown = json.loads(raw); unknown["identity"]["major"] = 99 + wrong_signature = json.loads(raw) + payload = bytearray(base64.b64decode(original["configs"]["motor"]["payload"])); payload[1] ^= 1 + wrong_signature["configs"]["motor"]["payload"] = base64.b64encode(payload).decode() + wrong_signature["configs"]["motor"]["sha256"] = hashlib.sha256(payload).hexdigest() + truncated = json.loads(raw) + payload = base64.b64decode(original["configs"]["motor"]["payload"])[:-1] + truncated["configs"]["motor"].update(payload=base64.b64encode(payload).decode(), + sha256=hashlib.sha256(payload).hexdigest(), bytes=len(payload)) + for name, value in (("corrupt", damaged), ("unsupported", unknown), ("signature", wrong_signature), ("truncated", truncated)): + rejected = json.loads(execute("%s-%d" % (name, index), [str(target)], json.dumps(value).encode(), expected=1)) + if rejected["ok"] or rejected["hardware_access"]: + raise RuntimeError("Invalid archive was not rejected") + report["checks"].append({"id": "%s-%d" % (name, index), "ok": True}) + for item in report["link_objects"]: + if digest(source / item["file"]) != item["sha256"]: + raise RuntimeError("Upstream objects were modified") + engine = root / "mission-core-vesc-engine" + wrapper.write_text(wrapper.read_text() + + "\n.PHONY: mission-core-native-engine\nmission-core-native-engine:\n" + "\t$(CXX) -c $(CXXFLAGS) $(INCPATH) -o " + str(root / "engine_main.o") + " " + str(root / "engine_main.cpp") + "\n" + "\t$(LINK) $(LFLAGS) -o " + str(engine) + " " + str(root / "engine_main.o") + + " $(filter-out build/lin/obj/main.o,$(OBJECTS)) $(OBJCOMP) $(LIBS)\n") + execute("engine-compile", ["/usr/bin/make", "-f", str(wrapper), "mission-core-native-engine"], timeout=180) + requests = [{"id": 1, "method": "engine"}, {"id": 2, "method": "current", "current_a": 30}, + {"id": 3, "method": "hall_start", "current_a": 5}, {"id": 4, "method": "arbitrary_packet"}] + responses = [json.loads(line) for line in execute("engine-offline", [str(engine), "--offline"], + b"".join(json.dumps(r).encode()+b"\n" for r in requests)).splitlines()] + if (len(responses) != 5 or not responses[0]["ready"] or not responses[1]["ok"] + or any(r["ok"] for r in responses[2:]) or responses[1]["result"]["hardware_enabled"]): + raise RuntimeError("Native engine offline boundary failed") + report["checks"].append({"id": "engine-offline-denies-hardware", "ok": True}) + execute("runtime-bundle", ["/usr/bin/python3", str(root / "native_bundle.py"), + "--engine", str(engine), "--sysroot", str(staging / "sysroot"), "--source", str(source), "--output", str(root / "runtime")], timeout=180) + report["native_runtime"] = json.loads((root / "runtime/bundle.json").read_text()) + report.update(state="complete", binary=str(target), upstream_objects_unchanged=True) + except Exception as error: + report.update(state="error", error=str(error)) + raise + finally: + report["finished_at"] = datetime.now(timezone.utc).isoformat() + report["duration_seconds"] = time.monotonic() - report["monotonic_started"] + publish() + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--artifact", type=Path, required=True) + parser.add_argument("--upstream-report", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--archives", type=Path, nargs="+", required=True) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/plugins/vesc/packaging/payload.py b/plugins/vesc/packaging/payload.py new file mode 100644 index 0000000..c589475 --- /dev/null +++ b/plugins/vesc/packaging/payload.py @@ -0,0 +1,49 @@ +"""The Node release carries this model profile from the first hardware use.""" +from pathlib import Path, PurePosixPath +import hashlib +import json +import tarfile + + +def payload(): + root = Path(__file__).resolve().parents[1] + files = [("usr/lib/mission-core-vesc/runtime/" + p.name, p.read_bytes(), 0o644) + for p in sorted((root / "runtime").glob("*.py"))] + files.extend(("usr/lib/mission-core-vesc/runtime/" + str(p.relative_to(root / "runtime")), p.read_bytes(), 0o644) + for p in sorted((root / "runtime/schemas").rglob("*")) if p.is_file()) + files.append(("usr/lib/mission-core-vesc/runtime/archive.py", + (root.parents[1] / "src/k1link/device_plugins/vesc/archive.py").read_bytes(), 0o644)) + for name in ("mission-core-vesc.service", "mission-core-node-vesc-prepare.service"): + files.append(("usr/lib/systemd/system/" + name, (root / "packaging" / name).read_bytes(), 0o644)) + files.append(("usr/lib/mission-core-vesc/prepare.py", (root / "packaging/prepare.py").read_bytes(), 0o644)) + files.append(("usr/lib/mission-core-vesc/clear_runtime_cache.py", (root / "packaging/clear_runtime_cache.py").read_bytes(), 0o644)) + files.append(("usr/share/mission-core-node/profiles/vesc/70-mission-core-vesc.rules", + (root / "packaging/70-mission-core-vesc.rules").read_bytes(), 0o644)) + manifest = json.loads((root / "packaging/native-runtime.json").read_text()) + bundle = root / "build/native-runtime" / manifest["file"] + data = bundle.read_bytes() + if len(data) != manifest["bytes"] or hashlib.sha256(data).hexdigest() != manifest["sha256"]: + raise ValueError("Native VESC Tool bundle changed") + seen = set() + with tarfile.open(bundle, "r:gz") as archive: + for member in archive.getmembers(): + path = PurePosixPath(member.name) + if (not member.isfile() or path.is_absolute() or ".." in path.parts + or path.as_posix() != member.name or member.name in seen + or member.name not in manifest["files"]): + raise ValueError("Unexpected native payload member") + seen.add(member.name) + expected = manifest["files"][member.name] + if member.size != expected["bytes"] or member.size > 128 * 1024**2: + raise ValueError("Native member size mismatch") + content = archive.extractfile(member).read() + if hashlib.sha256(content).hexdigest() != expected["sha256"]: + raise ValueError("Native member hash mismatch") + mode = 0o755 if member.name.startswith("bin/") else 0o644 + files.append(("usr/lib/mission-core-vesc/native/" + member.name, content, mode)) + if seen != set(manifest["files"]): raise ValueError("Incomplete native payload") + files.append(("usr/lib/mission-core-vesc/native/manifest.json", + (root / "packaging/native-runtime.json").read_bytes(), 0o644)) + files.append(("usr/lib/mission-core-vesc/native_check.py", + (root / "packaging/native_check.py").read_bytes(), 0o644)) + return files diff --git a/plugins/vesc/packaging/prepare.py b/plugins/vesc/packaging/prepare.py new file mode 100644 index 0000000..ebae100 --- /dev/null +++ b/plugins/vesc/packaging/prepare.py @@ -0,0 +1,88 @@ +"""Versioned, idempotent VESC profile; no packages downloaded and no motor I/O.""" + +import fcntl +import hashlib +import json +import os +from pathlib import Path +import platform +import subprocess +import sys +import time +import uuid + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from runtime.serial import discover +from runtime.service import atomic + +STATE = Path("/var/lib/mission-core-node-profiles/vesc") + + +def prepare(): + if os.geteuid() != 0 or sys.argv[1:]: + raise RuntimeError("Fixed system profile only") + release = platform.freedesktop_os_release() + if (release.get("ID"), release.get("VERSION_ID"), platform.machine()) != ("ubuntu", "24.04", "x86_64"): + raise RuntimeError("Ubuntu 24.04 amd64 required") + STATE.mkdir(mode=0o755, parents=True, exist_ok=True) + for directory in (STATE.parent, STATE): + info = directory.lstat() + if directory.is_symlink() or info.st_uid != 0 or info.st_mode & 0o022: + raise RuntimeError("Untrusted profile state") + lock = os.open(STATE / "prepare.lock", os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600) + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + report = {"schema": "missioncore.node.device-preparation/v1", "model_id": "vesc.controller", + "version": "0.7.4", "run_id": uuid.uuid4().hex, "started_at": time.time(), + "monotonic_started": time.monotonic(), "state": "running", "steps": []} + + def publish(): + atomic(STATE / "preparation.json", report) + os.chmod(STATE / "preparation.json", 0o644) + + def run(name, label, args): + step = {"id": name, "label": label, "state": "running"} + report["steps"].append(step) + publish() + result = subprocess.run(args, capture_output=True, timeout=45, + env={"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LANG": "C.UTF-8"}) + step["state"] = "complete" if result.returncode == 0 else "error" + publish() + if result.returncode: + raise RuntimeError("Не завершён этап: " + label) + + try: + import pwd + try: + pwd.getpwnam("mission-core-vesc") + except KeyError: + run("account", "Подготовка доступа", ["/usr/sbin/adduser", "--system", "--group", "--home", + "/var/lib/mission-core-vesc", "--no-create-home", "--disabled-login", "mission-core-vesc"]) + run("native", "Проверка VESC Tool", ["/usr/sbin/runuser", "-u", "mission-core-vesc", "--", + "/usr/bin/python3", "-I", "/usr/lib/mission-core-vesc/native_check.py"]) + source = Path("/usr/share/mission-core-node/profiles/vesc/70-mission-core-vesc.rules") + rules = source.read_bytes() + report["udev_sha256"] = hashlib.sha256(rules).hexdigest() + target = Path("/etc/udev/rules.d/70-mission-core-vesc.rules") + if target.is_symlink(): + raise RuntimeError("Untrusted udev destination") + target.write_bytes(rules) + target.chmod(0o644) + run("rules", "Настройка USB-доступа", ["/usr/bin/udevadm", "control", "--reload-rules"]) + for i, device in enumerate(discover()): + run("usb" + str(i), "Применение USB-доступа", ["/usr/bin/udevadm", "trigger", "--action=change", + "/sys/class/tty/" + device.tty]) + run("settle", "Проверка USB-доступа", ["/usr/bin/udevadm", "settle", "--timeout=10"]) + run("enable", "Подготовка службы", ["/usr/bin/systemctl", "enable", "mission-core-vesc.service"]) + run("runtime", "Запуск чтения контроллеров", ["/usr/bin/systemctl", "restart", "mission-core-vesc.service"]) + report["state"] = "complete" + except (OSError, RuntimeError, subprocess.SubprocessError) as error: + report.update(state="error", message=str(error)[:300]) + finally: + report["duration_seconds"] = time.monotonic() - report["monotonic_started"] + publish() + os.close(lock) + return report["state"] == "complete" + + +if __name__ == "__main__": + sys.exit(0 if prepare() else 1) diff --git a/plugins/vesc/packaging/tool_build.py b/plugins/vesc/packaging/tool_build.py new file mode 100644 index 0000000..9b2f740 --- /dev/null +++ b/plugins/vesc/packaging/tool_build.py @@ -0,0 +1,188 @@ +"""Unprivileged VESC Tool build spike; never installs packages or opens a device. + +Run in a bounded user systemd scope on Ubuntu 24.04 amd64. APT resolves and +downloads signed Ubuntu packages into this job; dpkg-deb only extracts them. +The output is an engineering build, not an installed or qualified runtime. +""" + +import argparse +import hashlib +import json +import os +from pathlib import Path +import platform +import re +import shutil +import subprocess +import tarfile +import time +from datetime import datetime, timezone + +COMMIT = "01d5f10901116c311e3fb84d5a1541f663d3ce20" +ARCHIVE_SHA256 = "4565ecec4e41e094bcc43127a51970e810aa9080a9d7c025af64632bfd4c0189" +DEPS = ( + "qtbase5-dev", "qtbase5-private-dev", "qtdeclarative5-dev", + "qtquickcontrols2-5-dev", "libqt5serialport5-dev", "qtconnectivity5-dev", + "qtpositioning5-dev", "libqt5gamepad5-dev", "libqt5svg5-dev", +) + + +def build(archive, root, dependency_cache=None, resume=None): + if os.geteuid() == 0: + raise RuntimeError("This build must not run as root") + release = platform.freedesktop_os_release() + if (release.get("ID"), release.get("VERSION_ID"), platform.machine()) != ("ubuntu", "24.04", "x86_64"): + raise RuntimeError("Ubuntu 24.04 amd64 required") + assert hashlib.sha256(archive.read_bytes()).hexdigest() == ARCHIVE_SHA256 + group = Path("/sys/fs/cgroup") / Path("/proc/self/cgroup").read_text().strip().split("::", 1)[1].lstrip("/") + limit = (group / "memory.max").read_text().strip() + if limit == "max" or int(limit) > 3 * 1024**3: + raise RuntimeError("Run in a user scope with MemoryMax=3G") + os.umask(0o077) + root.mkdir(mode=0o700, parents=True, exist_ok=False) + root = root.resolve() + report = {"schema": "missioncore.vesc.tool-build/v1", "source_commit": COMMIT, + "source_sha256": ARCHIVE_SHA256, "state": "running", "jobs": [], + "started_at": datetime.now(timezone.utc).isoformat(), "monotonic_started": time.monotonic(), + "hardware_access": False, "system_packages_installed": False, "packages": []} + env = dict(os.environ, LC_ALL="C", DEBIAN_FRONTEND="noninteractive", QT_QPA_PLATFORM="offscreen") + + def publish(): + (root / "report.json").write_text(json.dumps(report, indent=2) + "\n") + + def run(name, args, cwd=None, timeout=600): + job = {"id": name, "state": "running"}; report["jobs"].append(job); publish() + started = time.monotonic() + with (root / (name + ".stdout")).open("wb") as out, (root / (name + ".stderr")).open("wb") as err: + result = subprocess.run(args, cwd=cwd or root, env=env, stdout=out, stderr=err, timeout=timeout) + job.update(state="complete" if result.returncode == 0 else "error", exit_code=result.returncode, + duration_seconds=time.monotonic() - started) + publish() + if result.returncode: + raise RuntimeError("Build step failed: " + name) + return (root / (name + ".stdout")).read_text() + + try: + staging = root + if resume is not None: + previous_raw = (resume / "report.json").read_bytes() + previous = json.loads(previous_raw) + if previous.get("source_sha256") != ARCHIVE_SHA256 or previous.get("error") != "Build step failed: compile": + raise RuntimeError("Only this source's failed compile may resume") + staging = resume.resolve() + report["resume_report_sha256"] = hashlib.sha256(previous_raw).hexdigest() + report["resumed_staging"] = str(staging) + downloads = staging / "packages" + if resume is None: downloads.mkdir() + sysroot = staging / "sysroot" + if resume is None: sysroot.mkdir() + if resume is not None: + report["packages"] = previous["packages"] + for item in report["packages"]: + if hashlib.sha256((downloads / item["file"]).read_bytes()).hexdigest() != item["sha256"]: + raise RuntimeError("Resumed dependency changed") + elif dependency_cache is not None: + previous = json.loads((dependency_cache / "report.json").read_text()) + if previous.get("source_sha256") != ARCHIVE_SHA256 or not previous.get("packages"): + raise RuntimeError("Unqualified dependency cache") + for item in previous["packages"]: + name = item["file"] + if Path(name).name != name or not name.endswith(".deb"): + raise RuntimeError("Invalid cached package name") + package = dependency_cache / "packages" / name + if hashlib.sha256(package.read_bytes()).hexdigest() != item["sha256"]: + raise RuntimeError("Cached dependency changed") + shutil.copyfile(package, downloads / name) + report["dependency_cache_report_sha256"] = hashlib.sha256((dependency_cache / "report.json").read_bytes()).hexdigest() + else: + # Host lists may refer to superseded security packages. Refresh only + # this job's signed Ubuntu indexes; never update /var/lib/apt or invoke + # the host's update hooks (Timescale and other sources are irrelevant). + aptdir = root / "apt"; aptdir.mkdir() + for name in ("lists", "lists/partial", "archives", "archives/partial"): + (aptdir / name).mkdir(exist_ok=True) + sources = aptdir / "sources.list" + sources.write_text("".join( + "deb [signed-by=/usr/share/keyrings/ubuntu-archive-keyring.gpg] " + url + " " + suite + " main universe\n" + for url, suite in (("https://archive.ubuntu.com/ubuntu", "noble"), + ("https://archive.ubuntu.com/ubuntu", "noble-updates"), + ("https://security.ubuntu.com/ubuntu", "noble-security")))) + config = aptdir / "apt.conf" + config.write_text( + 'Dir::Etc::Parts "-";\nDir::Etc::main "-";\n' + 'Dir::Etc::sourceparts "-";\nDir::Etc::sourcelist "' + str(sources) + '";\n' + 'Dir::State::lists "' + str(aptdir / "lists") + '";\n' + 'Dir::Cache::archives "' + str(aptdir / "archives") + '";\n' + 'Dir::Cache::pkgcache "";\nDir::Cache::srcpkgcache "";\n' + 'Acquire::Languages "none";\nDebug::NoLocking "true";\n' + '#clear APT::Update::Post-Invoke;\n#clear APT::Update::Post-Invoke-Success;\n') + env["APT_CONFIG"] = str(config) + apt = ["/usr/bin/apt-get"] + run("private-indexes", [*apt, "update"]) + plan = run("dependencies-plan", [*apt, "--simulate", "--no-install-recommends", "--no-remove", "install", *DEPS]) + packages = re.findall(r"^Inst (\S+)(?: \[[^\]]+\])? \((\S+)", plan, re.MULTILINE) + if not packages or len(packages) > 150: + raise RuntimeError("Unexpected dependency plan; inspect before changing profile") + for index, (name, version) in enumerate(packages): + # apt-get download verifies the archive against the host's trusted + # repository metadata. No maintainer script or package install runs. + run("download-%03d" % index, [*apt, "download", name + "=" + version], downloads) + for index, package in enumerate(sorted(downloads.glob("*.deb")) if resume is None else []): + report["packages"].append({"file": package.name, "sha256": hashlib.sha256(package.read_bytes()).hexdigest()}) + run("extract-%03d" % index, ["/usr/bin/dpkg-deb", "--extract", str(package), str(sysroot)]) + source = staging / "source" + if resume is None: + source.mkdir() + with tarfile.open(archive) as stream: + stream.extractall(source, filter="data") + source = source / ("vesc_tool-" + COMMIT) + qtbase = sysroot / "usr" + # APT omits already-installed runtime packages. Complete the private + # development symlinks from declared host libraries, recording provenance. + report["host_libraries"] = [] + for name in ("libGL.so.1", "libGLX.so.0", "libGLU.so.1"): + target = qtbase / "lib/x86_64-linux-gnu" / name + host = Path("/usr/lib/x86_64-linux-gnu") / name + if not target.exists() and host.exists(): + shutil.copyfile(host, target) + report["host_libraries"].append({"source": str(host.resolve()), "sha256": hashlib.sha256(host.read_bytes()).hexdigest()}) + qtarch = qtbase / "lib/x86_64-linux-gnu/qt5" + qtbin = qtbase / "lib/qt5/bin" + qtconfig = "[Paths]\nPrefix=" + str(qtbase) + "\n" + "\n".join( + name + "=" + str(path) for name, path in { + "Headers": qtbase / "include/x86_64-linux-gnu/qt5", + "Libraries": qtbase / "lib/x86_64-linux-gnu", "ArchData": qtarch, + "HostData": qtarch, "Binaries": qtbin, "HostBinaries": qtbin, + "Plugins": qtarch / "plugins", "Qml2Imports": qtarch / "qml", + "Data": qtbase / "share/qt5", + }.items()) + "\n" + (qtbin / "qt.conf").write_text(qtconfig) + env["LD_LIBRARY_PATH"] = str(qtbase / "lib/x86_64-linux-gnu") + env["QT_PLUGIN_PATH"] = str(qtarch / "plugins") + env["PKG_CONFIG_LIBDIR"] = str(qtbase / "lib/x86_64-linux-gnu/pkgconfig") + env["PKG_CONFIG_SYSROOT_DIR"] = str(sysroot) + run("qmake", [str(qtbin / "qmake"), "-config", "release", "CONFIG += release_lin build_original exclude_fw", + "VT_GIT_COMMIT=" + COMMIT[:8], "INCLUDEPATH += " + str(qtbase / "include") + " " + str(qtbase / "include/x86_64-linux-gnu"), + "QMAKE_LIBDIR += " + str(qtbase / "lib/x86_64-linux-gnu")], source) + run("compile", ["/usr/bin/make", "-j2"], source, timeout=1800) + binary = source / "build/lin/vesc_tool_7.00" + result = run("version", [str(binary), "--version"], source, timeout=30) + report.update(state="complete", binary=str(binary), binary_sha256=hashlib.sha256(binary.read_bytes()).hexdigest(), + version_output=result, runtime_installed=False, hardware_qualified=False) + except Exception as error: + report.update(state="error", error=str(error)) + raise + finally: + report["duration_seconds"] = time.monotonic() - report["monotonic_started"] + report["finished_at"] = datetime.now(timezone.utc).isoformat() + publish() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--source", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--dependencies", type=Path) + parser.add_argument("--resume", type=Path) + args = parser.parse_args() + build(args.source.resolve(), args.output, args.dependencies, args.resume) diff --git a/plugins/vesc/runtime/__init__.py b/plugins/vesc/runtime/__init__.py new file mode 100644 index 0000000..5cf8079 --- /dev/null +++ b/plugins/vesc/runtime/__init__.py @@ -0,0 +1,5 @@ +"""Onboard VESC discovery, archive and bounded motor identification service.""" + +VERSION = "0.7.4" +MODEL = "vesc.controller" +SCHEMA = "missioncore.nodedc/plugin-sdk/v0alpha2" diff --git a/plugins/vesc/runtime/configuration.py b/plugins/vesc/runtime/configuration.py new file mode 100644 index 0000000..68ccfab --- /dev/null +++ b/plugins/vesc/runtime/configuration.py @@ -0,0 +1,46 @@ +"""Exact, read-only firmware configuration decoder. Never serializes a write.""" +import math +from pathlib import Path +import struct +import xml.etree.ElementTree as ET + + +def crc32c(data): + value = 0xffffffff + for byte in data: + value ^= byte + for _ in range(8): + value = (value >> 1) ^ (0x82f63b78 if value & 1 else 0) + return value ^ 0xffffffff + + +def decode(data, kind): + code, name = {"motor": (14, "mcconf"), "application": (17, "appconf")}[kind] + xml = ET.parse(Path(__file__).parent / "schemas/5.02" / ("parameters_" + name + ".xml")).getroot() + params = {p.tag: p for p in xml.find("Params")} + order = [p.text for p in xml.find("SerOrder")] + signature = "".join(n + params[n].findtext("type", "0") + params[n].findtext("vTx", "0") + + "".join(x.text or "" for x in params[n].findall("enumNames")) for n in order) + if len(data) < 5 or data[0] != code or int.from_bytes(data[1:5], "big") != crc32c(signature.encode()): + raise ValueError("Configuration signature differs from firmware 5.02 schema") + offset, result = 5, {} + for name in order: + p = params[name]; kind = int(p.findtext("type")); tx = int(p.findtext("vTx", "0")) + if kind in (4, 5): fmt = "b" + elif kind == 6: fmt = "B" + elif kind == 2: fmt = {1: "B", 2: "b", 3: "H", 4: "h", 5: "I", 6: "i"}[tx] + elif kind == 1: fmt = {7: "h", 8: "i", 9: "I"}[tx] + else: raise ValueError("Unsupported configuration type") + size = struct.calcsize(">" + fmt) + if offset + size > len(data): raise ValueError("Truncated configuration") + value = struct.unpack_from(">" + fmt, data, offset)[0]; offset += size + if kind == 1: + if tx == 9: + exponent, fraction = (value >> 23) & 255, value & 0x7fffff + part = fraction / 16777216.0 + 0.5 if exponent or fraction else 0.0 + value = math.ldexp(-part if value & 0x80000000 else part, exponent - 126) + else: value /= float(p.findtext("vTxDoubleScale", "1")) + if not math.isfinite(value): raise ValueError("Non-finite parameter") + result[name] = value + if offset != len(data): raise ValueError("Unexpected configuration tail") + return result diff --git a/plugins/vesc/runtime/drive_profile.py b/plugins/vesc/runtime/drive_profile.py new file mode 100644 index 0000000..b2b8503 --- /dev/null +++ b/plugins/vesc/runtime/drive_profile.py @@ -0,0 +1,54 @@ +"""Owner-assigned drive slots, independent of USB addresses and motor commands.""" +import json + +LAYOUTS = {"1x1": ("left.1", "right.1"), "2x2": ("left.1", "left.2", "right.1", "right.2")} + +def slot_label(layout, slot): + side = "Левый" if slot.startswith("left.") else "Правый" + return side + ((" передний" if slot.endswith(".1") else " задний") if layout == "2x2" else "") + + +class DriveProfile: + def __init__(self, root, atomic): + self.path, self.atomic = root / "drive-profile.json", atomic + self.value = json.loads(self.path.read_text()) if self.path.exists() else {"layout": None, "revision": 0, "bindings": {}} + + def update(self, action, params, device): + current = self.value + if params["revision"] != current["revision"]: + raise ValueError("Профиль привода изменился. Обновите карточку.") + bindings = dict(current["bindings"]) + layout = current["layout"] + if action == "vesc.drive.layout": + layout = params["layout"] + if set(bindings) - set(LAYOUTS[layout]): + raise ValueError("Сначала снимите назначения задних моторов.") + elif action == "vesc.drive.assign": + layout, slot = params["layout"], params["slot"] + if set(bindings) - set(LAYOUTS[layout]): + raise ValueError("Сначала снимите назначения задних моторов.") + if slot and slot in bindings and bindings[slot]["device_id"] != device.id: + raise ValueError("Это место уже занято. Сначала снимите прежнее назначение.") + bindings = {key: value for key, value in bindings.items() if value["device_id"] != device.id} + if slot: + bindings[slot] = {"device_id": device.id, "uuid": device.identity["uuid"]} + else: + bindings.pop(params["slot"], None) + value = {"layout": layout, "revision": current["revision"] + 1, "bindings": bindings} + self.atomic(self.path, value) + self.value = value + return value + + +def validate(action, params): + keys = {"revision", "layout"} if action == "vesc.drive.layout" else ({"revision", "layout", "slot"} if action == "vesc.drive.assign" else {"revision", "slot"}) + if set(params) != keys or type(params["revision"]) is not int or params["revision"] < 0: + raise ValueError("Invalid drive profile revision") + if action == "vesc.drive.layout": + if params["layout"] not in LAYOUTS: + raise ValueError("Invalid drive layout") + elif action == "vesc.drive.assign": + if params["layout"] not in LAYOUTS or params["slot"] not in ("", *LAYOUTS[params["layout"]]): + raise ValueError("Invalid drive layout or slot") + elif params["slot"] not in LAYOUTS["2x2"]: + raise ValueError("Invalid drive slot") diff --git a/plugins/vesc/runtime/foc_calibration.py b/plugins/vesc/runtime/foc_calibration.py new file mode 100644 index 0000000..bd5e16e --- /dev/null +++ b/plugins/vesc/runtime/foc_calibration.py @@ -0,0 +1,157 @@ +"""Transaction lifecycle around unchanged upstream Utility::detectAllFoc. + +No FOC algorithm or wire writes here. Native firmware owns this non-interruptible +cycle; a pending marker survives any uncertain completion and prevents replay. +""" +import base64 +import hashlib +import json +import os +import re +import uuid + +from .protocol import firmware, values +from .configuration import decode +from .receiver import neutral_band + + +def fresh_values(owner, devices): + # FW 5.02 GET_VALUES reads AND resets accumulated average current. The + # first reply after a quiet 30 s calibration includes the entire cycle. + # Drain it, then measure a new bounded interval after the release command. + for device in devices: + values(device.link.query(4, timeout=0.2)) + owner.sleep(0.25) + return {device.id: values(device.link.query(4, timeout=0.2)) for device in devices} + + +def remove_pending(pending): + pending.unlink() + fd = os.open(pending.parent, os.O_RDONLY) + try: os.fsync(fd) + finally: os.close(fd) + + +def reconcile(owner, devices): + """Explicit neutral-return recovery, never calibration or config replay. + + Admits only a previously completed/verified native receipt, exact archived + post-configs for every peer, stable identity, neutral PPM and fresh idle + telemetry. Unknown native completion always remains blocked. + """ + if any(device.link is None for device in devices): raise ValueError("Controller disconnected") + pending = owner.service.root / "calibration-pending.json" + record = json.loads(pending.read_text()) + operation = record.get("operation_id", "") + if not re.fullmatch(r"op_[0-9a-f]{32}", operation): raise ValueError("Invalid pending operation") + receipt = json.loads((owner.service.root / (operation + ".json")).read_text())["receipt"] + result = receipt.get("result", {}) + native = result.get("native", {}) + if not (receipt.get("state") == "complete" and result.get("completed") is True + and result.get("configuration_verified") is True and native.get("validated") is True): + raise ValueError("Native completion/configuration is unconfirmed") + expected = {} + for identifier in result.get("after_backups", []): + if not re.fullmatch(r"op_[0-9a-f]{32}", identifier): raise ValueError("Invalid backup identity") + backup = json.loads((owner.service.root / ("backup_" + identifier + ".json")).read_text()) + if backup.get("parent_operation_id") != operation or backup["device_id"] in expected: + raise ValueError("Calibration backup ownership differs") + expected[backup["device_id"]] = backup + if set(expected) != {d.id for d in devices}: raise ValueError("Controller set changed") + for device in devices: + backup = expected[device.id] + if firmware(device.link.query(0)) != backup["identity"]: raise ValueError("Controller identity changed") + for kind, code in (("motor",14),("application",17)): + actual = device.link.query(code) + if actual != base64.b64decode(backup["configs"][kind]["payload"], validate=True): + raise ValueError("Post-calibration configuration changed") + if kind == "application": + owner.receiver_bands[device.id] = neutral_band(decode(actual, kind)) + owner.neutral(devices) + after = fresh_values(owner, devices) + if any(abs(v["motor_current_a"]) > 1 or abs(v["erpm"]) > 30 or abs(v["duty"]) > .01 or v["fault_code"] != 0 for v in after.values()): + raise ValueError("Fresh idle state unconfirmed") + evidence = {"operation_id": operation, "observed_at": owner.utc(), "after": after, + "configuration_verified": True, "release_confirmed": True, "calibration_replayed": False} + owner.atomic(owner.service.root / ("calibration_recovered_" + operation + ".json"), evidence) + remove_pending(pending) + return evidence + + +def archive_after(owner, command, device, configs): + identifier = "op_" + uuid.uuid4().hex + backup = {"schema": "missioncore.vesc.config-backup/v1", "device_id": device.id, + "identity": device.identity, "operation_id": identifier, + "parent_operation_id": command["operation_id"], "observed_at": owner.utc(), + "monotonic_at": owner.monotonic(), "decoded": False, + "configs": {kind: {"encoding": "base64", "payload": base64.b64encode(raw).decode(), + "bytes": len(raw), "sha256": hashlib.sha256(raw).hexdigest(), "signature_hex": raw[1:5].hex()} + for kind, raw in configs.items()}} + owner.atomic(owner.service.root / ("backup_" + identifier + ".json"), backup) + owner.service.archive.add("local", backup) + device.backup = {"observed_at": backup["observed_at"], "operation_id": identifier, + "configs": {k: {"bytes": v["bytes"], "sha256": v["sha256"]} for k, v in backup["configs"].items()}} + return identifier + + +def calibrate(owner, command, devices, target, originals, backups, unchanged): + pending = owner.service.root / "calibration-pending.json" + owner.atomic(pending, {"device_id": target.id, "identity": target.identity, + "started_at": owner.utc(), "operation_id": command["operation_id"], "backups": backups}) + owner.state("calibrating") + owner.active, owner.mode = True, "foc" + started = owner.monotonic() + native, after, issues, saved = {}, {}, [], [] + verified, attempted = False, False + try: + unchanged() + owner.neutral(devices) + if owner.stop.is_set(): raise ValueError("Cancelled before calibration") + # Do not renew a 250 ms lease over the upstream 180 s calibration lease. + # No host current/RPM or configuration command is sent while it runs. + for device in devices: device.link.test_command("release") + attempted = True + target.link.calibrate_foc(command["parameters"]["max_power_loss_w"]) + while owner.monotonic() - started < 225: + unchanged() + state = target.link.procedure_result() + if not state.get("running"): + native = state.get("result", {}) + if state.get("uncertain"): issues.append("native_postcondition_unconfirmed") + break + if owner.stop.is_set() and "stop_requested_during_native_cycle" not in issues: + issues.append("stop_requested_during_native_cycle") + owner.sleep(0.5) + if not native.get("completed"): issues.append("native_completion_unconfirmed") + except (OSError, ValueError, TimeoutError): + issues.append("communication_unconfirmed") + finally: + for device in devices: + try: device.link.test_command("release") + except (OSError, ValueError, TimeoutError): issues.append("release_unconfirmed") + owner.sleep(0.5) + try: after = fresh_values(owner, devices) + except (OSError, ValueError, TimeoutError): after = {device.id: None for device in devices} + released = all(v is not None and abs(v["motor_current_a"]) <= 1 and abs(v["duty"]) <= .01 for v in after.values()) + if not attempted or native.get("completed"): + try: + unchanged() + for device in devices: + if firmware(device.link.query(0)) != device.identity: raise ValueError("Identity changed") + configs = {kind: device.link.query(code) for kind, code in (("motor",14),("application",17))} + saved.append(archive_after(owner, command, device, configs)) + if configs["application"] != originals[device.id]["application"]: raise ValueError("Receiver config changed") + if (device is not target or not attempted or not native.get("success")) and configs["motor"] != originals[device.id]["motor"]: + raise ValueError("Unchanged/restored motor config differs") + verified = not attempted or native.get("validated") is True + except (OSError, ValueError, TimeoutError): issues.append("configuration_unconfirmed") + if verified and released: + remove_pending(pending) + if not owner.latched: owner.state("ready") + else: owner.state("rc") + owner.active, owner.mode = False, None + return {"observed_at": owner.utc(), "device_id": target.id, "procedure": "native_foc_calibration", + "elapsed_s": owner.monotonic() - started, "completed": native.get("completed", False), + "success": bool(native.get("success") and verified and released), "native": native, + "configuration_verified": verified, "release_confirmed": released, "after": after, + "issues": issues, "backups": backups, "after_backups": saved} diff --git a/plugins/vesc/runtime/group_test.py b/plugins/vesc/runtime/group_test.py new file mode 100644 index 0000000..618a8f6 --- /dev/null +++ b/plugins/vesc/runtime/group_test.py @@ -0,0 +1,135 @@ +"""One local, bounded speed test for the complete owner-assigned drive profile.""" +from concurrent.futures import ThreadPoolExecutor + +from .drive_profile import LAYOUTS +from .protocol import ppm, values, TEST_LIMITS +from .speed_hold import SpeedHold + + +def targets(service, params, devices, selected): + profile = service.drive.value + bindings = profile["bindings"] + slots = LAYOUTS.get(profile["layout"], ()) + if (not slots or params["profile_revision"] != profile["revision"] + or set(bindings) != set(slots)): + raise ValueError("Профиль изменился или не все моторы назначены.") + ids = [bindings[slot]["device_id"] for slot in slots] + if len(set(ids)) != len(ids) or set(params["device_ids"]) != set(ids) or selected.id not in ids: + raise ValueError("Состав проверяемого привода не совпадает с профилем.") + available = {device.id: device for device in devices} + if any(identifier not in available for identifier in ids): + raise ValueError("Один из назначенных моторов отключён.") + if any(available[b["device_id"]].identity["uuid"] != b["uuid"] for b in bindings.values()): + raise ValueError("Идентичность назначенного VESC изменилась.") + return [available[identifier] for identifier in ids] + + +def batch(pool, devices, function): + # Join every submitted call before propagating an error: no late worker may + # issue torque after the caller has already released the other controllers. + futures = [(device.id, pool.submit(function, device)) for device in devices] + result, errors = {}, [] + for identifier, future in futures: + try: result[identifier] = future.result() + except (OSError, ValueError, TimeoutError) as error: + error.device_id = identifier + errors.append(error) + if errors: raise errors[0] + return result + + +def run(owner, command, devices, moving, originals, backups, unchanged, preflight): + from .motor_test import Rejected, check_values + params = command["parameters"] + duration, erpm, current_a = (params[key] for key in ("duration_s", "erpm", "current_a")) + ids = {device.id for device in moving} + motors, samples, after, cleanup = {}, [], {}, {} + restored, failure, rotation, previous_good = True, None, 0.0, False + outcome, claimed, started, previous = "duration", False, owner.monotonic(), owner.monotonic() + stalls = {} + owner.state("testing") + owner.active, owner.mode = True, "group_speed" + with ThreadPoolExecutor(max_workers=min(16, len(devices)), thread_name_prefix="vesc-drive") as pool: + try: + for device in moving: + motors[device.id] = owner.limits.apply(device, originals[device.id]["motor"], current_a) + started = previous = owner.monotonic() + holds = {device.id: SpeedHold(erpm, duration, started) for device in moving} + while owner.monotonic() - started < duration + 20: + cycle = owner.monotonic() + if owner.stop.is_set(): outcome = "stopped"; break + unchanged() + def read(device): + level = ppm(device.link.query(31, timeout=.06))["level"] + value = values(device.link.query(4, timeout=.06)) if device.id in ids else None + return level, value + observed = batch(pool, devices, read) + if any(owner.receiver_active(identifier, level) for identifier, (level, _) in observed.items()): + owner.state("rc") + raise Rejected("Приёмник передаёт команду. Общая проверка остановлена; управление за пультом.") + now = owner.monotonic() + readings = {identifier: observed[identifier][1] for identifier in ids} + setpoint = None + for identifier, value in readings.items(): + check_values(value, moving=True, current_a=current_a, motor=motors[identifier]) + setpoint, _, error = holds[identifier].update(now, value) + if error: raise Rejected(error) + if abs(value["motor_current_a"]) > TEST_LIMITS["stall_current_a"]: + at, tacho = stalls.setdefault(identifier, (now, value["tachometer"])) + if abs(value["erpm"]) >= 60 and abs(value["tachometer"] - tacho) >= 3: + stalls[identifier] = (now, value["tachometer"]) + elif now - at >= TEST_LIMITS["stall_timeout_s"]: + raise Rejected("Один из моторов не движется при токе выше 5 А. Общая проверка остановлена.") + else: stalls.pop(identifier, None) + good = all(h.hold_started is not None and h.previous_good for h in holds.values()) + delta = now - previous + if good and previous_good and delta <= .25: rotation += delta + previous, previous_good = now, good + sample = {"at": now-started, "devices": readings, "rotation_s": rotation, + "phase": "holding" if good else "accelerating", "commanded_erpm": None} + samples.append(sample) + if rotation >= duration: break + if owner.monotonic()-cycle > .12: raise Rejected("Связь слишком медленная для общей проверки.") + claimed = True + batch(pool, devices, lambda d: d.link.test_command("claim")) + if owner.stop.is_set(): outcome = "stopped"; break + if owner.monotonic()-cycle > .16: raise Rejected("Связь слишком медленная для общей проверки.") + def send(device): + if owner.stop.is_set(): return + if device.id in ids: device.link.test_speed(setpoint) + else: device.link.test_command("release") + sent_at = owner.monotonic() + batch(pool, devices, send) + sample.update(commanded_erpm=setpoint, command_batch_s=owner.monotonic()-sent_at) + owner.sleep(max(0, .1-(owner.monotonic()-cycle))) + if outcome == "duration" and rotation < duration: + outcome = "Общий срок проверки истёк; заданное время совместного вращения не набрано." + except (OSError, ValueError, TimeoutError) as error: + failure = {"type": type(error).__name__, "message": str(error), "elapsed_s": owner.monotonic()-started} + failure["device_id"] = getattr(error, "device_id", None) + failure["native_rpc"] = getattr(error, "native_rpc", None) + failure["native_history"] = getattr(error, "native_history", []) + outcome = str(error) if isinstance(error, Rejected) else "Ответ одного из VESC не получен вовремя. Общая проверка остановлена." + finally: + def release(device): + try: + device.link.test_command("release") + return "zero_current_sent" + except (OSError, ValueError, TimeoutError): return "unconfirmed" + if claimed: cleanup = batch(pool, devices, release) + owner.sleep(.3) + for device in devices: + try: after[device.id] = values(device.link.query(4, timeout=.2)) + except (OSError, ValueError, TimeoutError): after[device.id] = None + confirmed = all(v is not None and abs(v["motor_current_a"]) <= 1 for v in after.values()) + for device in moving: + try: owner.limits.restore(device) + except (OSError, ValueError, TimeoutError): restored = False + if not confirmed or not restored: owner.state("rc") + elif not owner.latched: owner.state("ready") + owner.active, owner.mode = False, None + return {"observed_at": owner.utc(), "device_ids": [d.id for d in moving], "mode": "group_speed", + "preflight": preflight, "profile_revision": params["profile_revision"], "current_a": current_a, "erpm_target": erpm, + "duration_limit_s": duration, "rotation_s": rotation, "outcome": outcome, "failure": failure, + "samples": samples, "release": cleanup, "release_confirmed": confirmed, + "limits_restored": restored, "after": after, "backups": backups} diff --git a/plugins/vesc/runtime/hall_detection.py b/plugins/vesc/runtime/hall_detection.py new file mode 100644 index 0000000..c2b79e4 --- /dev/null +++ b/plugins/vesc/runtime/hall_detection.py @@ -0,0 +1,99 @@ +"""Native FW 5.02 Hall measurement used by VESC Tool (COMM_DETECT_HALL_FOC). + +This is a non-interruptible ~12 s firmware procedure: it locks mc_interface, +overrides phase, sweeps three electrical turns in each direction and restores +its prior RAM configuration. A host stop/current-zero cannot cancel the sweep. +No table is applied here; measurements are archived in the operation receipt. +""" +from .configuration import decode +from .protocol import values, ppm + + +def parse_result(raw): + if len(raw) != 10 or raw[0] != 28 or raw[9] not in (0, 1): + raise ValueError("Invalid Hall result") + table = list(raw[1:9]) + if any(v > 200 and v != 255 for v in table): raise ValueError("Invalid Hall angle") + observed = [i for i, v in enumerate(table) if v != 255] + return {"firmware_success": raw[9] == 0, "hall_table": table, + "observed_states": observed, "valid_six_states": raw[9] == 0 and len(observed) == 6} + + +def measure(owner, devices, target, original, backups, unchanged, preflight): + motor = decode(original, "motor") + if motor["m_sensor_port_mode"] != 0: + from .motor_test import Rejected + raise Rejected("Вход датчиков выбран не в режиме Холла.") + pending = owner.service.root / "hall-pending.json" + owner.atomic(pending, {"device_id": target.id, "identity": target.identity, + "started_at": owner.utc(), "backups": backups}) + owner.state("calibrating") + owner.active, owner.mode = True, "hall" + started = owner.monotonic() + samples, issues, result, after = [], [], None, {} + completed, restored, attempted = False, False, False + try: + unchanged() + owner.neutral(devices) + # Do not enter the native procedure if Stop arrived during preflight. + if owner.stop.is_set(): raise ValueError("Measurement cancelled before start") + for device in devices: device.link.test_command("claim") + attempted = True + target.link.detect_hall() + while owner.monotonic() - started < 30: + cycle = owner.monotonic() + try: + unchanged() + for device in devices: + incoming = ppm(device.link.query(31, timeout=0.06)) + if owner.receiver_active(device.id, incoming["level"]): + owner.state("rc") + if "rc_during_native_cycle" not in issues: issues.append("rc_during_native_cycle") + sample = values(target.link.query(4, timeout=0.06)) + samples.append({"at": owner.monotonic() - started, "values": sample}) + for device in devices: device.link.test_command("claim") + for device in devices: + if device is not target: device.link.test_command("release") + except (OSError, ValueError, TimeoutError): + if "communication_unconfirmed" not in issues: issues.append("communication_unconfirmed") + if owner.stop.is_set() and "stop_requested_during_native_cycle" not in issues: + issues.append("stop_requested_during_native_cycle") + reply = target.link.hall_result + if reply is not None: + result = parse_result(reply) + completed = True + break + owner.sleep(max(0, 0.1 - (owner.monotonic() - cycle))) + except (OSError, ValueError, TimeoutError): + issues.append("native_completion_unconfirmed") + finally: + # Zero is a release AFTER completion, never a claim that native detect + # is interruptible. Peers also receive release if the target disappears. + for device in devices: + try: device.link.test_command("release") + except (OSError, ValueError, TimeoutError): issues.append("release_unconfirmed") + owner.sleep(0.3) + for device in devices: + try: after[device.id] = values(device.link.query(4, timeout=0.1)) + except (OSError, ValueError, TimeoutError): after[device.id] = None + if completed or not attempted: + target.link.hall_pending = False + try: restored = target.link.query(14) == original + except (OSError, ValueError, TimeoutError): pass + released = all(v is not None and abs(v["motor_current_a"]) <= 1 for v in after.values()) + if (completed or not attempted) and restored and released: + pending.unlink() + import os + fd = os.open(pending.parent, os.O_RDONLY) + try: os.fsync(fd) + finally: os.close(fd) + if not owner.latched: owner.state("ready") + else: + owner.state("rc") + owner.active, owner.mode = False, None + return {"observed_at": owner.utc(), "device_id": target.id, "procedure": "native_foc_hall", + "preflight": preflight, + "current_a": 5, "elapsed_s": owner.monotonic() - started, + "completed": completed, "measurement": result, "issues": issues, + "configuration_restored": restored, "configuration_written": False, + "release_confirmed": released, "after": after, "samples": samples, "backups": backups} diff --git a/plugins/vesc/runtime/limits_view.py b/plugins/vesc/runtime/limits_view.py new file mode 100644 index 0000000..350682a --- /dev/null +++ b/plugins/vesc/runtime/limits_view.py @@ -0,0 +1,18 @@ +"""Read controller settings using the bundled upstream VESC Tool decoder.""" +import math + +FIELDS = frozenset({"l_current_max", "l_current_min", "l_current_max_scale", "l_current_min_scale", + "l_in_current_max", "l_in_current_min", "l_min_erpm", "l_max_erpm", "l_max_duty", + "l_watt_max", "l_watt_min", "si_motor_poles", "si_gear_ratio", "si_wheel_diameter"}) + + +def read_limits(link): + configuration = link.configuration() + result = {} + for parameter in configuration["motor"]["parameters"]: + name, value = parameter["name"], parameter.get("value") + if name in FIELDS and type(value) in (int, float) and math.isfinite(value): + result[name] = value + if set(result) != FIELDS: + raise ValueError("Native configuration is missing limit fields") + return result diff --git a/plugins/vesc/runtime/link_check.py b/plugins/vesc/runtime/link_check.py new file mode 100644 index 0000000..7ac3cf6 --- /dev/null +++ b/plugins/vesc/runtime/link_check.py @@ -0,0 +1,99 @@ +"""Bounded idle transport measurement through the installed native owners. + +Only application/PPM/telemetry reads, no leases, motor commands or configuration writes. +The 500 ms diagnostic deadline observes replies beyond the 60 ms motor budget; +it never relaxes the motor-control deadline or authorizes powered operation. +""" +from concurrent.futures import ThreadPoolExecutor +from contextlib import ExitStack +from datetime import datetime, timezone +import math +import time + +from .protocol import ppm, values +from .configuration import decode +from .receiver import active, neutral_band + + +def summary(samples): + times = sorted(s["elapsed_ms"] for s in samples) + if not times: return {"replies": 0} + def percentile(p): return times[max(0, math.ceil(len(times)*p)-1)] + return {"replies": len(times), "p50_ms": percentile(.5), "p95_ms": percentile(.95), + "p99_ms": percentile(.99), "max_ms": times[-1], + "over_60_ms": sum(t > 60 for t in times)} + + +def measure(service, command, devices, *, sleep=time.sleep, monotonic=time.monotonic): + started = monotonic() + observed = datetime.now(timezone.utc).isoformat() + deadline = datetime.fromisoformat(command["deadline_at"].replace("Z", "+00:00")) + ids = {d.id: d.session for d in devices} + if not devices or len(ids) != len(devices) or ids != command["parameters"]["sessions"]: + raise ValueError("Controller sessions changed") + samples = {d.id: [] for d in devices} + bands = {} + failure = None + stop_reason = "complete" + def interrupted(): + cancelled = service.motor.cancelled_at + if cancelled is not None and cancelled >= datetime.fromisoformat(command["requested_at"].replace("Z", "+00:00")): + return "stopped" + if monotonic()-started >= 25 or (deadline-datetime.now(timezone.utc)).total_seconds() < 2: + return "deadline" + return None + def failed(device, code, before, error): + return {"device_id": device.id, "command": code, "reason": "read_failed", "error": str(error), + "elapsed_ms": (monotonic()-before)*1000, + "native_rpc": getattr(error, "native_rpc", None), + "native_history": getattr(error, "native_history", [])} + def read(device): + for code in (31, 4): + before = monotonic() + try: + raw = device.link.query(code, timeout=.5) + reading = ppm(raw) if code == 31 else values(raw) + sample = {"command": code, "at_s": before-started, "elapsed_ms": (monotonic()-before)*1000, + "native_rpc": getattr(device.link, "last_rpc", None)} + if code == 31: + sample["ppm_level"] = reading["level"] + idle = not active(reading["level"], bands[device.id]) + else: + sample.update(erpm=reading["erpm"], current_a=reading["motor_current_a"], + duty=reading["duty"], fault_code=reading["fault_code"]) + idle = abs(reading["erpm"]) <= 30 and abs(reading["motor_current_a"]) <= 1 and abs(reading["duty"]) <= .01 + samples[device.id].append(sample) + if not idle: return {"device_id": device.id, "reason": "not_idle"} + except (OSError, ValueError, TimeoutError) as error: + return failed(device, code, before, error) + return None + with ExitStack() as locks: + for device in sorted(devices, key=lambda d: d.id): locks.enter_context(device.lock) + if any(d.link is None for d in devices): raise ValueError("Controller unavailable") + for device in devices: + if reason := interrupted(): + stop_reason = reason; break + before = monotonic() + try: + bands[device.id] = neutral_band(decode(device.link.query(17), "application")) + except (OSError, ValueError, TimeoutError) as error: + failure = [failed(device, 17, before, error)] + stop_reason = "read_failed"; break + # Same cadence and per-controller query order as group rotation, with a + # larger read-only deadline to expose latency instead of destroying it. + with ThreadPoolExecutor(max_workers=min(16, len(devices))) as pool: + for _ in range(100): + if stop_reason != "complete": break + cycle = monotonic() + if reason := interrupted(): + stop_reason = reason; break + futures = [pool.submit(read, d) for d in devices] + errors = [error for future in futures if (error := future.result()) is not None] + if errors: + failure = errors; stop_reason = errors[0]["reason"]; break + sleep(max(0, .1-(monotonic()-cycle))) + return {"observed_at": observed, "monotonic_started": started, "duration_s": monotonic()-started, + "outcome": stop_reason, "motor_commands_sent": False, "read_timeout_ms": 500, + "failure": failure, "devices": {d.id: {"name": "VESC "+d.identity["uuid"][:6].upper(), + "neutral_band": bands.get(d.id), "summary": summary(samples[d.id]), + "samples": samples[d.id]} for d in devices}} diff --git a/plugins/vesc/runtime/motor_test.py b/plugins/vesc/runtime/motor_test.py new file mode 100644 index 0000000..d6766df --- /dev/null +++ b/plugins/vesc/runtime/motor_test.py @@ -0,0 +1,390 @@ +"""A bounded 0.5–30 A raised-rig test for firmware 5.02, never a drive API. + +Firmware reference: vedderb/bldc 3f670137e27e6e383fa79c50cc6b1fa85aab1554, +commands.c, app_ppm.c, app.c and chvt.h. The admitted PPM applications are paused +with separate 250 ms leases, never broadcast. Firmware resumes PPM on expiry, +including its missing-pulse timeout. USB commands alone cannot rely on the +global timeout: receiver pulses reset it even while app output is disabled. +""" +import base64 +from contextlib import ExitStack +import hashlib +import math +import threading +import time +import uuid +from datetime import datetime, timezone + +from .configuration import decode +from .protocol import firmware, ppm, values, TEST_LIMITS, SPEED_LIMITS +from .speed_hold import SpeedHold +from .temporary_limits import TemporaryLimits +from .receiver import active as receiver_active, neutral_band + + +class Rejected(ValueError): + pass + + +class LimitExceeded(Rejected): + def __init__(self, field, value, low, high, label, unit, scale=1): + self.violation = {"field": field, "value": value, "minimum": low, "maximum": high} + number = lambda v: format(v * scale, ".3g").replace(".", ",") + super().__init__(f"Тест остановлен: {label} {number(value)} {unit}; диапазон проверки {number(low)}…{number(high)} {unit}.") + + +def check_configuration(identity, motor, app): + if (identity["version"], identity["hardware"], identity["test_firmware"], identity["hardware_type"]) != ("5.02", "75_300_R2", 0, 0): + raise Rejected("Тест поддерживает только проверенный профиль VESC 75_300_R2 / 5.02.") + if (motor["motor_type"] != 2 or app["app_to_use"] not in (1, 4) + or app["timeout_msec"] > 1000 or app["timeout_msec"] < 100 + or app["timeout_brake_current"] != 0 or app["app_ppm_conf.ctrl_type"] != 4 + or not 0.01 <= app["app_ppm_conf.hyst"] <= 0.3): + raise Rejected("Настройки FOC, PPM или тайм-аута не подходят для короткой проверки.") + if not 2 <= motor["l_current_max"] <= 100 or not 2 <= motor["l_in_current_max"] <= 100: + raise Rejected("Нужна проверка токовых ограничений.") + + +def check_values(value, moving=False, current_a=2, motor=None, *, standstill_confirmed=False): + current_limit = max(5, current_a * 1.2 + 2) if moving else 1 + speed_limit = TEST_LIMITS["max_erpm"] if moving else 30 + duty_limit = TEST_LIMITS["max_duty"] if moving else 0.01 + if moving and motor is not None: + current_limit = min(current_limit, motor["l_current_max"]) + speed_limit = min(speed_limit, motor["l_max_erpm"], -motor["l_min_erpm"]) + duty_limit = min(duty_limit, motor["l_max_duty"]) + # FW 5.02 continues its observer/PLL while undriven. Sensorless ERPM and + # tachometer share that estimate, so neither proves physical standstill. + # Only explicitly attended Hall/speed/release operations may substitute + # observation. Current, modulation bounds and sensored ERPM still apply. + observed_sensorless = (standstill_confirmed is True and not moving + and motor is not None and motor["motor_type"] == 2 + and motor["foc_sensor_mode"] == 0) + if observed_sensorless: + # FW 5.02 mcpwm_foc.c calculates duty_now from measured phase voltages + # even in the undriven branch. COMM_GET_VALUES quantizes it to 1/1000; + # one idle quantum is not proof that PWM is enabled. Permit at most + # that quantum only with fresh operator-confirmed physical standstill. + # Current/voltage/temperature/fault and neutral-window guards remain. + duty_limit = 0.001 + bounds = ( + ("fault_code", 0, 0, "код ошибки VESC", "", 1), + ("input_voltage_v", 20, 60, "напряжение питания", "В", 1), + ("mos_temperature_c", 0, 65, "температура контроллера", "°C", 1), + ("motor_current_a", -current_limit, current_limit, "ток мотора", "А", 1), + ("erpm", -speed_limit, speed_limit, "электрические обороты", "ERPM", 1), + ("duty", -duty_limit, duty_limit, "заполнение PWM", "%", 100), + ) + for field, low, high, label, unit, scale in bounds: + actual = value[field] + estimated_speed = field == "erpm" and observed_sensorless + if not math.isfinite(actual) or (not estimated_speed and not low <= actual <= high): + raise LimitExceeded(field, actual, low, high, label, unit, scale) + if standstill_confirmed: + actual = value["input_current_a"] + if not math.isfinite(actual) or abs(actual) > 1: + raise LimitExceeded("input_current_a", actual, -1, 1, "ток батареи", "А") + + +class MotorTest: + def __init__(self, service, atomic, utc, sleep=time.sleep, monotonic=time.monotonic): + self.service, self.atomic, self.utc = service, atomic, utc + self.sleep, self.monotonic = sleep, monotonic + self.stop = threading.Event() + self.stop_lock = threading.Lock() + self.cancelled_at = None + self.active = False + self.mode = None + self.receiver_bands = {} + self.limits = TemporaryLimits(service, atomic) + self.authority = service.root / "motor-authority.json" + # A process restart during a test cannot silently grant another pulse. + if self.authority.exists(): + import json + self.latched = json.loads(self.authority.read_text()).get("state") != "ready" + else: + self.latched = False + + def state(self, value): + self.atomic(self.authority, {"state": value, "observed_at": self.utc()}) + self.latched = value == "rc" + + def cancel(self): + with self.stop_lock: + self.cancelled_at = datetime.now(timezone.utc) + self.stop.set() + + def neutral(self, devices): + for device in devices: + value = ppm(device.link.query(31, timeout=0.06)) + if self.receiver_active(device.id, value["level"]): + self.state("rc") + raise Rejected("Приёмник передаёт команду. Управление удерживается за пультом.") + + def receiver_active(self, identifier, level): + if identifier not in self.receiver_bands: + raise Rejected("Нейтраль приёмника ещё не проверена по конфигурации VESC.") + return receiver_active(level, self.receiver_bands[identifier]) + + def run(self, command, devices, target, release=False, remote=None): + if not 1 <= len(devices) <= 128 or len({d.id for d in devices}) != len(devices): + raise Rejected("Для проверки нужны однозначно определённые VESC этого борта.") + duration = command["parameters"]["duration_s"] + current_a = command["parameters"]["current_a"] + group_mode = command["action_id"] == "vesc.drive.run" + speed_mode = command["action_id"] in ("vesc.motor.run", "vesc.drive.run") + moving = [target] + if group_mode: + from .group_test import targets + try: moving = targets(self.service, command["parameters"], devices, target) + except ValueError as error: raise Rejected(str(error)) from error + hall_mode = command["action_id"] == "vesc.hall.measure" + foc_mode = command["action_id"] == "vesc.foc.calibrate" + budget = duration + (20 if speed_mode else 0) + if self.latched and not release and remote is None: + raise Rejected("Управление удерживается за пультом. Верните его явно после нейтрали.") + requested = datetime.fromisoformat(command["requested_at"].replace("Z", "+00:00")) + if (datetime.now(timezone.utc) - requested).total_seconds() > 10: + raise Rejected("Команда устарела до начала проверки. Повторите запрос.") + deadline = datetime.fromisoformat(command["deadline_at"].replace("Z", "+00:00")) + def preflight(): + if remote is not None: remote.ensure_live() + if self.stop.is_set(): raise Rejected("Проверка отменена.") + if (deadline - datetime.now(timezone.utc)).total_seconds() < budget + 5: + raise Rejected("Не хватило времени для проверки всех контроллеров. Ток не подавался.") + attachments = {d.attachment for d in devices} + def unchanged(): + if set(self.service.discover_fn()) != attachments: + raise Rejected("Подключение VESC изменилось. Обновите устройства.") + with self.stop_lock: + if self.cancelled_at is not None and requested <= self.cancelled_at: + raise Rejected("Проверка отменена до начала исполнения.") + self.stop.clear() + with ExitStack() as stack: + # Never reuse an earlier operation's neutral configuration. + self.receiver_bands = {} + for device in sorted(devices, key=lambda d: d.id): + stack.enter_context(device.lock) + recovered = None + if release and (self.service.root / "calibration-pending.json").exists(): + from .foc_calibration import reconcile + unchanged() + try: recovered = reconcile(self, devices) + except (OSError, ValueError, TimeoutError, KeyError) as error: + raise Rejected("Возврат управления пока невозможен: итог калибровки, конфигурация или нулевой ток не подтверждены.") from error + identities, applications, backups, originals = {}, {}, [], {} + motors, idle_samples = {}, [] + observed_standstill = (hall_mode or speed_mode or release) and command["parameters"].get("standstill_confirmed") is True + target_motor, target_raw = None, None + for device in devices: + preflight() + if device.link is None: raise Rejected("Один из контроллеров отключён.") + if self.limits.pending(device): + raise Rejected("Восстановление временных токовых пределов ещё не подтверждено.") + if (self.service.root / "hall-pending.json").exists(): + raise Rejected("Завершение предыдущего измерения Холла не подтверждено. Нужна проверка состояния VESC.") + if (self.service.root / "calibration-pending.json").exists(): + raise Rejected("Завершение предыдущей калибровки не подтверждено. Новое движение заблокировано.") + identity = firmware(device.link.query(0)) + if identity != device.identity: raise Rejected("Идентичность контроллера изменилась.") + configs = {kind: device.link.query(code) for kind, code in (("motor", 14), ("application", 17))} + originals[device.id] = configs + motor, app = decode(configs["motor"], "motor"), decode(configs["application"], "application") + motors[device.id] = motor + check_configuration(identity, motor, app) + self.receiver_bands[device.id] = neutral_band(app) + if device in moving: + if not foc_mode and current_a > min(motor["l_current_max"], motor["l_in_current_max"]): + raise Rejected("Ток проверки превышает настроенный предел выбранного контроллера.") + if not (motor["l_max_erpm"] > 0 and motor["l_min_erpm"] < 0 and 0 < motor["l_max_duty"] <= 1): + raise Rejected("Нужна проверка настроенных пределов оборотов и PWM.") + target_motor = motor + target_raw = configs["motor"] + if foc_mode and any(abs(motor[key]) <= 0.001 for key in ("l_in_current_min", "l_in_current_max", "foc_openloop_rpm", "foc_sl_erpm")): + raise Rejected("Для калибровки нужны ненулевые сохранённые пределы питания и настройки запуска FOC.") + if speed_mode and abs(command["parameters"]["erpm"]) > min(SPEED_LIMITS["max_erpm"], + (motor["l_max_erpm"] if command["parameters"]["erpm"] > 0 else -motor["l_min_erpm"]) * 0.8): + raise Rejected("Заданная скорость превышает настроенный диапазон контроллера.") + if speed_mode and abs(command["parameters"]["erpm"]) < motor["s_pid_min_erpm"]: + raise Rejected(f"Минимальная скорость регулятора этого VESC: {motor['s_pid_min_erpm']:g} ERPM.") + check_values(values(device.link.query(4)), motor=motor, + standstill_confirmed=observed_standstill) + identities[device.id], applications[device.id] = identity, app + identifier = "op_" + uuid.uuid4().hex + backup = {"schema": "missioncore.vesc.config-backup/v1", "device_id": device.id, + "identity": identity, "operation_id": identifier, "parent_operation_id": command["operation_id"], + "observed_at": self.utc(), "monotonic_at": self.monotonic(), "decoded": False, + "configs": {kind: {"encoding": "base64", "payload": base64.b64encode(raw).decode(), + "bytes": len(raw), "sha256": hashlib.sha256(raw).hexdigest(), "signature_hex": raw[1:5].hex()} + for kind, raw in configs.items()}} + self.atomic(self.service.root / ("backup_" + identifier + ".json"), backup) + self.service.archive.add("local", backup) + device.backup = {"observed_at": backup["observed_at"], "operation_id": identifier, + "configs": {k: {"bytes": v["bytes"], "sha256": v["sha256"]} for k, v in backup["configs"].items()}} + backups.append(identifier) + ids = {int(app["controller_id"]) for app in applications.values()} + if len(ids) != len(devices): raise Rejected("У контроллеров совпали CAN ID. Нужна проверка схемы.") + for device in devices: + preflight() + # CAN ping includes up to 5 ms transmit wait plus 10 ms reply + # wait for every ID; scheduling can exceed the former 4 s cap. + try: + peers = device.link.query(62, timeout=8) + except TimeoutError as error: + raise Rejected("Проверка CAN не завершилась вовремя. Ток не подавался.") from error + if not peers or peers[0] != 62 or not set(peers[1:]).issubset(ids): + raise Rejected("На CAN обнаружено другое устройство. Нужна проверка схемы.") + if foc_mode and len(peers) != 1: + raise Rejected("Этот профиль калибрует VESC по отдельным USB без CAN-соседей. Требуется профиль связанного CAN-борта.") + for _ in range(10): + preflight() + unchanged() + self.neutral(devices) + if observed_standstill: + for device in devices: + sample = values(device.link.query(4, timeout=0.06)) + check_values(sample, motor=motors[device.id], + standstill_confirmed=observed_standstill) + idle_samples.append({"device_id": device.id, "at": self.monotonic(), + "sensor_mode": motors[device.id]["foc_sensor_mode"], "values": sample}) + self.sleep(0.1) + preflight_record = {"standstill_confirmed": observed_standstill, "samples": idle_samples} + if release: + self.state("ready") + return {"authority": "ready", "observed_at": self.utc(), "backups": backups, "calibration_recovered": recovered, "preflight": preflight_record} + if hall_mode: + from .hall_detection import measure + return measure(self, devices, target, target_raw, backups, unchanged, + preflight_record) + if foc_mode: + from .foc_calibration import calibrate + return calibrate(self, command, devices, target, originals, backups, unchanged) + now = datetime.now(timezone.utc) + if (deadline - now).total_seconds() < budget + 1: + raise Rejected("Команда устарела до запуска. Повторите проверку.") + if group_mode: + if remote is not None: + self.state("testing") + return remote.drive(self, command, devices, moving, originals, unchanged) + from .group_test import run + return run(self, command, devices, moving, originals, backups, unchanged, preflight_record) + self.state("testing") + self.active = True + self.mode = "speed" if speed_mode else "current" + started = self.monotonic() + samples, outcome, cleanup = [], "duration", {} + limit_violation = None + failure = None + claimed = False + sent_current = 0.0 + last_command_at = started + stalled_since = None + stall_tachometer = None + hold = SpeedHold(command["parameters"]["erpm"], duration, started) if speed_mode else None + restored = not speed_mode + try: + if speed_mode: + target_motor = self.limits.apply(target, target_raw, current_a) + started = self.monotonic() + hold = SpeedHold(command["parameters"]["erpm"], duration, started) + while self.monotonic() - started < budget: + cycle = self.monotonic() + if self.stop.is_set(): + outcome = "stopped"; break + unchanged() + self.neutral(devices) + sample = {"at": self.monotonic() - started, "devices": {}} + current = values(target.link.query(4, timeout=0.06)) + sample["commanded_current_a"] = None + sample["devices"][target.id] = current + samples.append(sample) + check_values(current, moving=True, current_a=current_a, motor=target_motor) + if hold: + setpoint, done, error = hold.update(self.monotonic(), current) + sample.update(phase=hold.phase, rotation_s=hold.rotation_s, commanded_erpm=None) + if error: raise Rejected(error) + if done: break + # A current command is torque, not a speed setpoint. Do not + # repeatedly coast/restart at each Hall edge. A hard limit + # ends this operation and cannot automatically re-arm it. + # Above 5 A require continuing measured movement. Hall/FOC + # telemetry is not an independent physical motion sensor. + if max(abs(current["motor_current_a"]), sent_current) > TEST_LIMITS["stall_current_a"]: + if stalled_since is None: + stalled_since = self.monotonic() + stall_tachometer = current["tachometer"] + elif abs(current["erpm"]) >= 60 and abs(current["tachometer"] - stall_tachometer) >= 3: + stalled_since = self.monotonic() + stall_tachometer = current["tachometer"] + elif self.monotonic() - stalled_since >= TEST_LIMITS["stall_timeout_s"]: + raise Rejected("Тест остановлен: при токе выше 5 А движение не подтверждается 2 секунды. Проверьте мотор и датчики.") + else: + stalled_since = None + if self.monotonic() - cycle > 0.12: + raise Rejected("Связь слишком медленная для короткой проверки.") + # Refresh local leases only after fresh neutral/telemetry. A + # delayed process never sends current after an expired lease. + claimed = True + for device in devices: device.link.test_command("claim") + for device in devices: + if device is not target: device.link.test_command("release") + if self.stop.is_set(): + outcome = "stopped"; break + if self.monotonic() - cycle > 0.16: + raise Rejected("Связь слишком медленная для короткой проверки.") + if self.monotonic() - started >= budget: + if hold: raise Rejected("Истёк общий срок проверки; время вращения не набрано.") + break + if hold: + target.link.test_speed(setpoint) + sample["commanded_erpm"] = setpoint + else: + elapsed = self.monotonic() - last_command_at + sent_current = round(min(current_a, max(0.5, sent_current + elapsed * TEST_LIMITS["current_ramp_a_per_s"])), 3) if sent_current else 0.5 + target.link.test_current(sent_current) + last_command_at = self.monotonic() + sample["commanded_current_a"] = None if hold else sent_current + self.sleep(max(0, 0.05 - (self.monotonic() - cycle))) + except (OSError, ValueError, TimeoutError) as error: + failure = {"type": type(error).__name__, "message": str(error), "elapsed_s": self.monotonic()-started} + failure["native_rpc"] = getattr(error, "native_rpc", None) + failure["native_history"] = getattr(error, "native_history", []) + outcome = str(error) if isinstance(error, Rejected) else "Обмен с VESC прерван. Проверка остановлена." + if isinstance(error, LimitExceeded): limit_violation = error.violation + finally: + # Never reconnect to send a stop to a replacement device. Leases + # expire in firmware even if USB or this process is lost. + if claimed: + for device in devices: + try: + device.link.test_command("release") + cleanup[device.id] = "zero_current_sent" + except (OSError, ValueError, TimeoutError): + cleanup[device.id] = "unconfirmed" + self.active = False + self.mode = None + if not self.latched: self.state("ready") + self.sleep(0.3) + after = {} + for device in devices: + try: after[device.id] = values(device.link.query(4, timeout=0.1)) + except (OSError, ValueError, TimeoutError): after[device.id] = None + confirmed = all(value is not None and abs(value["motor_current_a"]) <= 1 for value in after.values()) + if claimed and not confirmed: + self.state("rc") + outcome = "Снятие тока не подтверждено. Проверьте фактическое состояние моторов." + if speed_mode: + try: restored = self.limits.restore(target) + except (OSError, ValueError, TimeoutError): + self.state("rc") + outcome += " Восстановление прежних токовых пределов не подтверждено; новые запуски заблокированы." + if outcome == "duration" and hold.rotation_s < duration: + outcome = "Проверка закончилась до набора заданного времени вращения." + return {"observed_at": self.utc(), "device_id": target.id, "current_a": current_a, + "mode": "speed" if speed_mode else "current", "rotation_s": hold.rotation_s if hold else None, + "erpm_target": hold.erpm if hold else None, "limits_restored": restored, + "current_ramp_a_per_s": TEST_LIMITS["current_ramp_a_per_s"], + "test_limits": TEST_LIMITS, "preflight": preflight_record, + "duration_limit_s": duration, "outcome": outcome, "samples": samples, + "limit_violation": limit_violation, "failure": failure, + "release": cleanup, "release_confirmed": confirmed, "after": after, "backups": backups} diff --git a/plugins/vesc/runtime/native_link.py b/plugins/vesc/runtime/native_link.py new file mode 100644 index 0000000..e15b421 --- /dev/null +++ b/plugins/vesc/runtime/native_link.py @@ -0,0 +1,171 @@ +"""Private lifecycle/RPC boundary to unmodified upstream VESC Tool C++. + +No wire encoding or calibration algorithm lives here. The native process owns +one exact USB attachment and sends all commands through upstream Commands. +""" +import base64 +from collections import deque +import hashlib +import json +import os +from pathlib import Path +import select +import subprocess +import time + +from .serial import check_attachment + + +class NativeLink: + def __init__(self, attachment): + self.attachment = attachment + self.process = None + self.buffer = b"" + self.sequence = 0 + self.hall_pending = False + self.history = deque(maxlen=32) + self.check() + root = Path("/usr/lib/mission-core-vesc/native") + config = Path("/run/mission-core-vesc/native") / hashlib.sha256(attachment.binding.encode()).hexdigest()[:24] + config.mkdir(parents=True, mode=0o700, exist_ok=True) + env = dict(os.environ, QT_QPA_PLATFORM="offscreen", XDG_CONFIG_HOME=str(config), + XDG_CACHE_HOME=str(config / "cache"), LD_LIBRARY_PATH=str(root / "lib"), + QT_PLUGIN_PATH=str(root / "plugins")) + # Preserve native startup diagnostics in the private runtime directory. + with (config / "engine.log").open("wb") as diagnostic: + self.process = subprocess.Popen([str(root / "bin/mission-core-vesc-engine"), "/dev/" + attachment.tty], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=diagnostic, + env=env, bufsize=0, close_fds=True) + try: + hello = self._receive(time.monotonic() + 6) + if hello.get("ready") is not True or not hello.get("engine", {}).get("connected"): + raise OSError("Native VESC Tool did not connect") + self.engine = hello["engine"] + self.check() + except BaseException: + self.close() + raise + + @property + def alive(self): + return self.process is not None and self.process.poll() is None + + def check(self): + check_attachment(self.attachment) + + def _receive(self, deadline): + while b"\n" not in self.buffer: + if not self.alive or not select.select([self.process.stdout], [], [], max(0, deadline-time.monotonic()))[0]: + raise TimeoutError("Native VESC Tool response timed out") + data = os.read(self.process.stdout.fileno(), 65536) + if not data: raise OSError("Native VESC Tool exited") + self.buffer += data + if len(self.buffer) > 2 * 1024 * 1024: raise ValueError("Native response exceeds bound") + line, self.buffer = self.buffer.split(b"\n", 1) + return json.loads(line) + + def rpc(self, method, timeout=2, **parameters): + self.sequence += 1 + request = json.dumps({"id": self.sequence, "method": method, **parameters}, allow_nan=False).encode()+b"\n" + if len(request) > 65536: raise ValueError("Native request exceeds bound") + started = time.monotonic() + deadline = started + timeout + trace = {"method": method, "command": parameters.get("command"), + "timeout_ms": parameters.get("timeout_ms", timeout*1000), + "attachment": {"usb": self.attachment.usb, "address": self.attachment.address, + "tty": self.attachment.tty}} + try: + trace["stage"] = "attachment_before" + self.check() + trace["attachment_before_ms"] = (time.monotonic()-started)*1000 + trace["stage"] = "request_write" + if not self.alive: raise OSError("Native VESC Tool is not running") + if not select.select([], [self.process.stdin], [], max(0, deadline-time.monotonic()))[1]: + raise TimeoutError("Native VESC Tool request timed out") + if os.write(self.process.stdin.fileno(), request) != len(request): + raise OSError("Native request write incomplete") + sent_at = time.monotonic() + trace["request_write_ms"] = (sent_at-started)*1000-trace["attachment_before_ms"] + trace["stage"] = "native_response" + response = self._receive(deadline) + received_at = time.monotonic() + trace["native_response_ms"] = (received_at-sent_at)*1000 + if not isinstance(response, dict): raise ValueError("Invalid native response") + if response.get("id") != self.sequence: raise ValueError("Native response identity mismatch") + if response.get("ok") is not True: + if isinstance(response.get("diagnostics"), dict): + trace["transport"] = response["diagnostics"] + raise OSError(response.get("error", "Native operation failed")) + trace["stage"] = "attachment_after" + self.check() + trace["attachment_after_ms"] = (time.monotonic()-received_at)*1000 + trace["stage"] = "complete" + result = response.get("result") + if not isinstance(result, dict): raise ValueError("Invalid native result") + trace.update(ok=True, elapsed_ms=(time.monotonic()-started)*1000) + self.last_rpc = trace + if hasattr(self, "history"): self.history.append(trace) + return result + except (OSError, ValueError, TimeoutError) as error: + # An unconfirmed reply is never silently retried on the same stream. + trace.update(ok=False, elapsed_ms=(time.monotonic()-started)*1000, + process_alive=self.alive, error=str(error)) + try: self.check(); trace["attachment_present"] = True + except OSError: trace["attachment_present"] = False + self.last_rpc = trace + if hasattr(self, "history"): self.history.append(trace) + error.native_rpc = trace + error.native_history = list(getattr(self, "history", [])) + self.close() + raise + + def query(self, command, timeout=2): + result = self.rpc("query", timeout=timeout+0.1, command=command, timeout_ms=max(20, int(timeout*1000))) + return base64.b64decode(result["payload"], validate=True) + + def test_command(self, action): + if action not in ("claim", "release"): raise ValueError("Unknown control action") + self.rpc("lease" if action == "claim" else "release", timeout=0.1) + + def test_current(self, current_a): + self.rpc("current", timeout=0.1, current_a=current_a) + + def test_speed(self, erpm): + self.rpc("rpm", timeout=0.1, erpm=erpm) + + def set_temporary_limits(self, config): + from .temporary_limits import FIELDS + self.rpc("limits", timeout=2.2, parameters={k: config[k] for k in FIELDS}) + + def configuration(self): + return self.rpc("configuration", timeout=5) + + def detect_hall(self): + if self.hall_pending: raise ValueError("Hall measurement already pending") + self.hall_pending = True + self.rpc("hall_start", timeout=0.2, current_a=5) + + def calibrate_foc(self, max_power_loss_w): + self.rpc("foc_start", timeout=0.2, max_power_loss_w=max_power_loss_w) + + def procedure_result(self): + return self.rpc("procedure_result", timeout=0.2) + + @property + def hall_result(self): + if not self.hall_pending: return None + state = self.rpc("procedure_result", timeout=0.1) + result = state.get("result", {}) + if state.get("running") or not result.get("completed"): return None + return base64.b64decode(result["payload"], validate=True) + + def close(self): + process, self.process = self.process, None + if process is None: return + if process.poll() is None: + process.terminate() + try: process.wait(timeout=1) + except subprocess.TimeoutExpired: + process.kill(); process.wait(timeout=1) + for stream in (process.stdin, process.stdout): + if stream: stream.close() diff --git a/plugins/vesc/runtime/protocol.py b/plugins/vesc/runtime/protocol.py new file mode 100644 index 0000000..72bb070 --- /dev/null +++ b/plugins/vesc/runtime/protocol.py @@ -0,0 +1,154 @@ +"""Bounded VESC serial reader. + +Wire reference: vedderb/vesc_tool dc53c658cbb89a947246034f7a00149cf79abdfc, +packet.cpp, commands.cpp and datatypes.h. No arbitrary packet transmit API. +Config payloads remain opaque until their exact firmware schema is admitted. +""" + +import binascii +import struct + +READ_COMMANDS = frozenset({0, 4, 14, 17, 31, 62}) +MAX_PACKET = 10000 + + +def request(command): + if type(command) is not int or command not in READ_COMMANDS: + raise ValueError("Unsupported read command") + data = bytes([command]) + return b"\x02\x01" + data + binascii.crc_hqx(data, 0).to_bytes(2, "big") + b"\x03" + + +TEST_LIMITS = {"min_current_a": 0.5, "max_current_a": 30, "min_duration_s": 0.5, + "max_duration_s": 30, "current_ramp_a_per_s": 2.0, + "continuous_current": True, "max_erpm": 6000, "max_duty": 0.25, + "stall_current_a": 5, "stall_timeout_s": 2.0} + +# A separate action/capability keeps old clients from silently changing modes. +SPEED_LIMITS = {"min_erpm": 300, "max_erpm": 3000, "ramp_erpm_per_s": 600, + "startup_timeout_s": 15, "settle_s": 1, "speed_tolerance": 0.15, + "lost_speed_timeout_s": 2, "duration_basis": "measured_speed", + "reverse_supported": True, "standstill_confirmation_required": True} + + +def frame(data): + if not 1 <= len(data) <= 255: raise ValueError("Invalid bounded command size") + return bytes([2, len(data)]) + data + binascii.crc_hqx(data, 0).to_bytes(2, "big") + b"\x03" + + +def speed_packet(erpm): + if type(erpm) not in (int, float) or not -SPEED_LIMITS["max_erpm"] <= erpm <= SPEED_LIMITS["max_erpm"]: + raise ValueError("Invalid test speed") + return frame(bytes([8]) + struct.pack(">i", round(erpm))) + + +def hall_packet(): + # FW 5.02 native FOC Hall sweep, fixed 5 A; no store and no CAN forwarding. + return frame(bytes([28]) + struct.pack(">i", 5000)) + + +def current_packet(current_a): + if type(current_a) not in (int, float) or not TEST_LIMITS["min_current_a"] <= current_a <= TEST_LIMITS["max_current_a"]: + raise ValueError("Test current must be between 0.5 and 30 A") + data = b"\x06" + struct.pack(">i", round(current_a * 1000)) + return bytes([2, len(data)]) + data + binascii.crc_hqx(data, 0).to_bytes(2, "big") + b"\x03" + + +def test_packet(action): + """Only fixed volatile commands; no arbitrary current/lease/packet.""" + data = {"current": b"\x06" + struct.pack(">i", 2000), + "release": b"\x06" + bytes(4), + "claim": b"\x3f\x00" + struct.pack(">i", 250)}[action] + return bytes([2, len(data)]) + data + binascii.crc_hqx(data, 0).to_bytes(2, "big") + b"\x03" + + +def ppm(packet): + if len(packet) != 9 or packet[0] != 31: + raise ValueError("Incomplete PPM reply") + level, pulse = struct.unpack(">ii", packet[1:]) + if not -1100000 <= level <= 1100000 or not 0 <= pulse <= 3000000: + raise ValueError("Invalid PPM values") + return {"level": level / 1e6, "pulse_ms": pulse / 1e6} + + +class Decoder: + def __init__(self): + self.buffer = bytearray() + + def feed(self, data): + if len(self.buffer) + len(data) > MAX_PACKET * 2 + 16: + self.buffer.clear() + raise ValueError("Serial buffer overflow") + self.buffer.extend(data) + packets = [] + while self.buffer: + start = self.buffer[0] + if start not in (2, 3, 4): + del self.buffer[0] + continue + width = start - 1 + if len(self.buffer) < width + 1: + break + size = int.from_bytes(self.buffer[1:width + 1], "big") + if not 1 <= size <= MAX_PACKET: + del self.buffer[0] + continue + end = width + 1 + size + if len(self.buffer) < end + 3: + break + payload = bytes(self.buffer[width + 1:end]) + if self.buffer[end + 2] != 3 or int.from_bytes(self.buffer[end:end + 2], "big") != binascii.crc_hqx(payload, 0): + del self.buffer[0] + continue + del self.buffer[:end + 3] + packets.append(payload) + return packets + + +def firmware(packet): + if len(packet) < 4 or packet[0] != 0: + raise ValueError("Incomplete firmware reply") + end = packet.find(b"\0", 3, 132) + if end <= 3 or len(packet) < end + 13: + raise ValueError("Firmware has no complete hardware identity") + name = packet[3:end].decode("ascii") + if not all(32 <= ord(c) < 127 for c in name): + raise ValueError("Invalid hardware name") + uuid = packet[end + 1:end + 13] + if uuid in (bytes(12), b"\xff" * 12): + raise ValueError("Invalid hardware UUID") + optional = packet[end + 13:] + return {"major": packet[1], "minor": packet[2], "version": f"{packet[1]}.{packet[2]:02d}", + "hardware": name, "uuid": uuid.hex(), + "test_firmware": optional[1] if len(optional) > 1 else None, + "hardware_type": optional[2] if len(optional) > 2 else None, + "custom_configs": optional[3] if len(optional) > 3 else None} + + +def values(packet): + if len(packet) < 54 or packet[0] != 4: + raise ValueError("Incomplete telemetry reply") + fields = (("mos_temperature_c", "h", 10), ("motor_temperature_c", "h", 10), + ("motor_current_a", "i", 100), ("input_current_a", "i", 100), + ("id_current_a", "i", 100), ("iq_current_a", "i", 100), + ("duty", "h", 1000), ("erpm", "i", 1), ("input_voltage_v", "h", 10), + ("amp_hours", "i", 10000), ("amp_hours_charged", "i", 10000), + ("watt_hours", "i", 10000), ("watt_hours_charged", "i", 10000), + ("tachometer", "i", 1), ("tachometer_abs", "i", 1), ("fault_code", "B", 1)) + result, offset = {}, 1 + for key, fmt, scale in fields: + result[key] = struct.unpack_from(">" + fmt, packet, offset)[0] / scale + offset += struct.calcsize(fmt) + # Optional tail is ordered, not an independent set of guessed offsets. + for key, fmt, scale in (("position_deg", "i", 1e6), ("can_id", "B", 1), + ("mos1_c", "h", 10), ("mos2_c", "h", 10), ("mos3_c", "h", 10), + ("vd_v", "i", 1000), ("vq_v", "i", 1000), ("status", "B", 1)): + size = struct.calcsize(fmt) + if len(packet) < offset + size: + break + result[key] = struct.unpack_from(">" + fmt, packet, offset)[0] / scale + offset += size + if "status" in result: + flags = int(result.pop("status")) + result.update(timeout=bool(flags & 1), kill_switch=bool(flags & 2)) + return result diff --git a/plugins/vesc/runtime/receiver.py b/plugins/vesc/runtime/receiver.py new file mode 100644 index 0000000..05b8d4c --- /dev/null +++ b/plugins/vesc/runtime/receiver.py @@ -0,0 +1,22 @@ +"""Interpret the admitted FW 5.02 PPM input before its firmware deadband. + +app_ppm.c publishes input_val before utils_deadband. A nonzero decoded value +inside app_ppm_conf.hyst is therefore not a motor command. Do not infer radio +link presence from this value: the receiver can keep emitting failsafe pulses. +""" +import math + + +def neutral_band(application): + band = application["app_ppm_conf.hyst"] + if (application["app_to_use"] not in (1, 4) + or application["app_ppm_conf.ctrl_type"] != 4 + or not math.isfinite(band) or not .01 <= band <= .3): + raise ValueError("Unsupported PPM neutral configuration") + return band + + +def active(level, band): + if not math.isfinite(level) or not math.isfinite(band) or not .01 <= band <= .3: + raise ValueError("Invalid PPM level or neutral band") + return abs(level) > band diff --git a/plugins/vesc/runtime/remote_control.py b/plugins/vesc/runtime/remote_control.py new file mode 100644 index 0000000..9966af1 --- /dev/null +++ b/plugins/vesc/runtime/remote_control.py @@ -0,0 +1,343 @@ +"""Single Node-owned, volatile keyboard control session and live read projection. + +Configuration/calibration keeps the same exclusive hardware owner. Browser input +is a short lease, not a queue. Native Tool still owns all serial commands. +""" +import copy +import math +import re +import threading +import time +import uuid +from concurrent.futures import ThreadPoolExecutor +from datetime import datetime, timedelta, timezone + +from .group_test import batch +from .protocol import ppm, values +from .drive_profile import LAYOUTS, slot_label + + +class ControlEnded(ValueError): + """A terminal input lease is normal stop; cleanup still verifies release.""" + + +class InputLease: + def __init__(self, clock=time.monotonic): + self.clock = clock + self.id = None + self.sequence = -1 + self.until = 0 + self.demand = (0., 0.) + self.retired = set() + + def accept(self, command): + if not isinstance(command, dict) or set(command) != {"id", "sequence", "ttl_ms", "left", "right", "settings"}: + raise ValueError("Invalid control envelope") + if (not re.fullmatch(r"[0-9a-f]{32}", str(command["id"])) + or type(command["sequence"]) is not int or not 0 <= command["sequence"] < 2**53 + or any(type(command[k]) not in (int,float) or not math.isfinite(command[k]) for k in ("left","right","ttl_ms")) + or max(abs(command["left"]), abs(command["right"])) > 1 + or not 0 < command["ttl_ms"] <= 400): + raise ValueError("Invalid control bounds") + s = command["settings"] + if (not isinstance(s, dict) or set(s) != {"standstill_confirmed","current_a","max_erpm"} + or s["standstill_confirmed"] is not True + or type(s["current_a"]) not in (int,float) or not .5 <= s["current_a"] <= 30 + or type(s["max_erpm"]) not in (int,float) or not 300 <= s["max_erpm"] <= 3000): + raise ValueError("Invalid control settings") + if command["id"] in self.retired: + return False + if self.id is not None and (self.id != command["id"] or self.clock() >= self.until): + self.stop() + return False + if self.id == command["id"] and command["sequence"] <= self.sequence: + return False # Repeated frames cannot extend a lease. + self.id, self.sequence = command["id"], command["sequence"] + self.until = self.clock()+command["ttl_ms"]/1000 + self.demand = (command["left"], command["right"]) + return True + + def stop(self): + if self.id: + self.retired.add(self.id) + # Bound tombstones; Core never reuses a cryptographic session id. + if len(self.retired)>1024: + raise ValueError("Restart control service after excessive sessions") + self.until = 0 + self.demand = (0.,0.) + + def live(self): + return self.id is not None and self.id not in self.retired and self.clock() < self.until + + +class RemoteControl: + def __init__(self, service): + self.service = service + self.lock = threading.RLock() + self.lease = InputLease() + self.instance = uuid.uuid4().hex + self.relay = None + self.primed = False + self.thread = None + self.watch_until = 0 + self.state = "observing" + self.message = None + self.readings = {} + self.release_confirmed = None + + def feed(self, body): + if (set(body) != {"watch","command","relay_id"} or type(body["watch"]) is not bool + or not re.fullmatch(r"[0-9a-f]{32}", str(body["relay_id"]))): + raise ValueError("Invalid relay") + with self.lock: + if self.relay != body["relay_id"]: + self.lease.stop() + self.relay = body["relay_id"] + self.primed = False + if body["watch"]: + self.watch_until = time.monotonic()+2 + command = body["command"] + if command is None: + self.primed = True + self.lease.stop() + elif not self.primed: + self.lease.retired.add(command.get("id")) + else: + running = self.thread is not None and self.thread.is_alive() + if not running and command.get("id") != self.lease.id: + self.lease.id = None + self.lease.sequence = -1 + accepted = self.lease.accept(command) + if accepted and not running: + self.state, self.message = "preparing", None + self.thread = threading.Thread(target=self._prepare, args=(copy.deepcopy(command),), daemon=True, + name="vesc-remote-control") + self.thread.start() + return self.snapshot() + + def snapshot(self): + with self.lock: + readings = [{**copy.deepcopy(v), "age_ms": int((time.monotonic()-v["sampled_at"])*1000)} for v in self.readings.values()] + for v in readings: v.pop("sampled_at", None) + return {"supported": True, "instance": self.instance, "state": self.state, + "session_id": self.lease.id, "message": self.message, "devices": readings, + "release_confirmed": self.release_confirmed, + "profile": copy.deepcopy(self.service.drive.value)} + + def observe(self): + with self.lock: + # Let an in-flight read finish, but do not start another one while + # the control worker is waiting to become the exclusive owner. + if self.thread is not None and self.thread.is_alive(): + return + if time.monotonic() >= self.watch_until or not self.service.operation_lock.acquire(False): + return + try: + with self.service.lock: devices = [d for d in self.service.devices.values() if d.link and d.readable] + # Reading is explicit window interest, never discovery-port reset. + for d in devices: + if not d.lock.acquire(False): continue + try: + self._publish(d, values(d.link.query(4, timeout=.06)), ppm(d.link.query(31, timeout=.06))) + except (OSError, ValueError, TimeoutError): + pass # Old values retain age; a read failure is never zero. + finally: d.lock.release() + finally: self.service.operation_lock.release() + + def _publish(self, device, value, receiver): + profile = self.service.drive.value + slot = next((k for k,b in profile["bindings"].items() if b["device_id"]==device.id), None) + with self.lock: + self.readings[device.id] = {"id": device.id,"uuid":device.identity["uuid"], + "slot":slot,"label":slot_label(profile["layout"],slot) if slot else "VESC "+device.identity["uuid"][:6].upper(), + "values":value,"receiver":receiver,"sampled_at":time.monotonic()} + + def _prepare(self, envelope): + owner = self.service.motor + acquired = False + try: + # Observation also owns this lock. A nonblocking attempt made + # arming depend on which thread happened to read first. Wait only + # briefly, with a live input lease, never enqueue a future drive. + deadline = time.monotonic() + .5 + while not acquired: + self.ensure_live() + remaining = deadline - time.monotonic() + if remaining <= 0: + raise ValueError("Другая операция с VESC ещё выполняется.") + acquired = self.service.operation_lock.acquire(timeout=min(.02, remaining)) + self.ensure_live() + with self.service.lock: devices = list(self.service.devices.values()) + profile = self.service.drive.value + slots = LAYOUTS.get(profile["layout"], ()) + if not slots or set(profile["bindings"]) != set(slots): + raise ValueError("Назначьте все моторы в настройках борта.") + if not devices or any(not d.link for d in devices): + raise ValueError("Один из VESC недоступен.") + now = datetime.now(timezone.utc) + settings = envelope["settings"] + command = {"action_id":"vesc.drive.run","operation_id":"op_"+uuid.uuid4().hex, + "requested_at":now.isoformat(),"deadline_at":(now+timedelta(seconds=300)).isoformat(), + "parameters":{"current_a":settings["current_a"],"duration_s":30,"erpm":settings["max_erpm"], + "standstill_confirmed":True,"profile_revision":profile["revision"], + "device_ids":[profile["bindings"][s]["device_id"] for s in slots]}} + owner.run(command, devices, devices[0], remote=self) + except ControlEnded: + with self.lock: + self.state = "fault" if self.message or self.release_confirmed is False else "stopped" + except (OSError, ValueError, TimeoutError, KeyError) as error: + with self.lock: + self.state = "fault" + self.message = str(error) if self.message is None else self.message + " " + str(error) + finally: + with self.lock: self.lease.stop() + if acquired: self.service.operation_lock.release() + + def ensure_live(self): + with self.lock: + if not self.lease.live(): raise ControlEnded("Управление остановлено: команда больше не подтверждается.") + + def drive(self, owner, command, devices, moving, originals, unchanged): + from .motor_test import check_values + limit = command["parameters"]["current_a"] + maximum = command["parameters"]["erpm"] + profile = copy.deepcopy(self.service.drive.value) + sides = {b["device_id"]:0 if slot.startswith("left.") else 1 for slot,b in profile["bindings"].items()} + configs, minimum_speeds, claimed, neutral_since = {}, {}, False, None + previous, speeds = time.monotonic(), {d.id:0. for d in moving} + last_sign, undriven_since = {}, None + self.release_confirmed = None + owner.active, owner.mode = True, "remote" + receiver = False + zero_seen = False + stalls = {} + with ThreadPoolExecutor(max_workers=min(16,len(devices)),thread_name_prefix="vesc-remote") as pool: + try: + for d in moving: + self.ensure_live() + configs[d.id] = owner.limits.apply(d, originals[d.id]["motor"], limit) + minimum = configs[d.id]["s_pid_min_erpm"] + if not math.isfinite(minimum) or minimum < 0: + raise ValueError("Некорректный минимальный порог регулятора VESC.") + # Native Tool serializes setRpm as an integer. Round up so + # the first command actually reaches the firmware threshold. + minimum_speeds[d.id] = max(1, math.ceil(minimum)) + if maximum < minimum_speeds[d.id]: + raise ValueError(f"Минимальная скорость регулятора этого VESC: {minimum_speeds[d.id]} ERPM.") + self.state = "ready" + while True: + cycle = time.monotonic() + if owner.stop.is_set(): break + if not receiver: self.ensure_live() + unchanged() + if self.service.drive.value != profile: raise ValueError("Назначения моторов изменились.") + def read(d): return values(d.link.query(4,timeout=.06)),ppm(d.link.query(31,timeout=.06)) + readouts = batch(pool, devices, read) + for d in devices: self._publish(d,*readouts[d.id]) + active = any(owner.receiver_active(d.id,readouts[d.id][1]["level"]) for d in devices) + if active: + receiver = True + self.state = "receiver" + owner.state("rc") + with self.lock: self.lease.stop() + if receiver: + # Hold zero locally through the first gesture. Neutral + # releases PPM, so only a subsequent gesture drives it. + stopped = all(abs(v[0]["motor_current_a"])<=1 and abs(v[0]["duty"])<.01 for v in readouts.values()) + neutral_since = (neutral_since or cycle) if not active and stopped else None + if neutral_since is not None and cycle-neutral_since>=.5: break + demand=(0.,0.) + else: + with self.lock: demand=self.lease.demand + if demand==(0.,0.): zero_seen=True + if not zero_seen: demand=(0.,0.) + now=time.monotonic() + dt=min(.15,now-previous);previous=now + targets = {} + for d in moving: + value=readouts[d.id][0] + check_values(value,moving=True,current_a=limit,motor=configs[d.id]) + target=demand[sides[d.id]]*maximum + minimum = minimum_speeds[d.id] + # A small analogue request must never be rounded UP to + # a faster requested speed. Release below the operable + # range; firmware would otherwise enter zero-duty mode. + if abs(target) < minimum: target=0 + targets[d.id] = target + signs = {key: 1 if target>0 else -1 if target<0 else 0 for key,target in targets.items()} + quiet = all(abs(readouts[d.id][0]["erpm"])<300 + and abs(readouts[d.id][0]["motor_current_a"])<=1 + and abs(readouts[d.id][0]["duty"])<.01 for d in moving) + # Count only observed neutral while ALL previous outputs + # were released. A long operator pause already satisfies it. + if quiet and not any(speeds.values()): + if undriven_since is None: undriven_since = now + else: undriven_since = None + reversing = any(sign and last_sign.get(key,sign)!=sign for key,sign in signs.items()) + if reversing and (undriven_since is None or now-undriven_since<.5): + # One shared barrier: after a turn, the side keeping its + # direction must not drive while the other waits to reverse. + targets = dict.fromkeys(targets, 0.) + else: + last_sign.update({key:sign for key,sign in signs.items() if sign}) + for d in moving: + value=readouts[d.id][0] + target=targets[d.id] + minimum=minimum_speeds[d.id] + # Zero is immediate release, never an RPM hold/brake. + if target==0: + speeds[d.id]=0 + else: + step=600*dt + speeds[d.id]+=max(-step,min(step,target-speeds[d.id])) + # FW 5.02 disables its speed PID below s_pid_min_erpm. + # Ramping from zero spent 900/600 = 1.5 s sending + # ineffective commands. Enter the configured range + # immediately, then keep the existing ramp above it. + if abs(speeds[d.id]) < minimum: + speeds[d.id] = math.copysign(minimum, target) + if abs(value["motor_current_a"])>5: + at,tacho=stalls.setdefault(d.id,(now,value["tachometer"])) + if abs(value["erpm"])>=60 and abs(value["tachometer"]-tacho)>=3: stalls[d.id]=(now,value["tachometer"]) + elif now-at>=2: raise ValueError("Мотор не движется при токе выше 5 А.") + else: stalls.pop(d.id,None) + if now-cycle>.12: raise ValueError("Связь с VESC слишком медленная.") + if not receiver: self.ensure_live() + claimed=True + batch(pool,devices,lambda d:d.link.test_command("claim")) + if time.monotonic()-cycle>.16: raise ValueError("Связь с VESC слишком медленная.") + if not receiver: self.ensure_live() + def send(d): + if not receiver: self.ensure_live() + if owner.stop.is_set() or receiver or abs(speeds.get(d.id,0))<1: d.link.test_command("release") + else: d.link.test_speed(speeds[d.id]) + batch(pool,devices,send) + if not receiver: self.state="driving" if any(speeds.values()) else "ready" + owner.sleep(max(0,.1-(time.monotonic()-cycle))) + finally: + self.state="stopping" + def release(d): + try: d.link.test_command("release") + except (OSError,ValueError,TimeoutError): pass + if claimed: batch(pool,devices,release) + if claimed: + owner.sleep(.3) + def released(d): + try: + value = values(d.link.query(4, timeout=.1)) + return all(math.isfinite(value[k]) and abs(value[k]) <= 1 + for k in ("motor_current_a", "input_current_a")) and abs(value["duty"]) < .01 + except (OSError, ValueError, TimeoutError): return False + self.release_confirmed = all(batch(pool, devices, released).values()) + if not self.release_confirmed: + self.message = "Снятие тока не подтверждено. Проверьте фактическое состояние моторов." + owner.state("rc") + for d in moving: + try: owner.limits.restore(d) + except (OSError,ValueError,TimeoutError): + notice="Восстановление пределов ожидает нейтрали." + self.message=(self.message+" " if self.message else "")+notice + owner.state("rc") + owner.active,owner.mode=False,None + self.state="fault" if self.release_confirmed is False else "receiver" if receiver else "stopped" + if not receiver and not owner.latched: owner.state("ready") diff --git a/plugins/vesc/runtime/schemas/5.02/info.xml b/plugins/vesc/runtime/schemas/5.02/info.xml new file mode 100644 index 0000000..28efebd --- /dev/null +++ b/plugins/vesc/runtime/schemas/5.02/info.xml @@ -0,0 +1,1008 @@ + + + + + Firmware Version + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The firmware version(s) that this version of VESC Tool supports.</span></p></body></html> + + 0 + 5.02 + + + Soft Battery Cutoff Calculator + 0 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Parameters for a soft battery cutoff can be calculated here. To do that, select the battery type and amount of cells. When the battery voltage is at the start value, the battery current will start to get reduced. At the end value battery current draw (and thus motor current) is disabled completely. In between the current is limited proportionally to where between the start and end values the input voltage is.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Notice that braking always is possible, even when the battery current is limited. That is because braking does not draw any current from the battery, it only charges the battery.</span></p></body></html> + + + + Detect BLDC Parameters + 0 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Spin up the motor in delay commutation mode and try to measure the following parameters:</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<ul style="margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; -qt-list-indent: 1;"><li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Cycle Integrator Limit</li> +<li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">BEMF Coupling</li> +<li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Hall Sensor Table</li></ul> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The settings mean the following:</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Current (I)</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The current to use for spinning up the motor.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">ERPM (ω)</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The minimum speed for the delay commutation mode to start the motor.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Duty (D)</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The duty cycle to measure the BEMF coupling at. This value should be as low as possible, but not so low that the motor cannot spin at the end of the detection sequence.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">If the motor is not able to spin up properly these settings can be tweaked. Symptoms:</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-style:italic;">The motor starts to spin, but is too weak to reach enough speed.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto'; font-style:italic;"><br /></p> +<ul style="margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; -qt-list-indent: 1;"><li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Increase the current setting.</li></ul> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-style:italic;">The motor cogs and is unable to spin up.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto'; font-style:italic;"><br /></p> +<ul style="margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; -qt-list-indent: 1;"><li style=" font-family:'Roboto'; font-style:italic;" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-style:normal;">Increase or decrease the current.</span></li> +<li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">If the motor has high inertia decrease ERPM. E-bike hub motors tend to have high inertia.</li> +<li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">If the motor has low inertia increase ERPM.</li></ul> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-style:italic;">The motor spins up properly, but does not spin at the end of the detection.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto'; font-style:italic;"><br /></p> +<ul style="margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; -qt-list-indent: 1;"><li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Increase the duty and try again. This is usually needed for low KV motor when using low voltage, such as ebike motors.</li></ul></body></html> + + + + Detect FOC Parameters + 0 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><img src="data:image/846930886.PNG;base64,i +VBORw0KGgoAAAANSUhEUgAAAZAAAAAsCAYAAABLwO52AAAACXBIWXMAAC4jAAAuIwF4pT92AAAAGXRFW +HRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAGMBJREFUeJztnXtU1NW+wD+/efASEpWHJCK+g +MwETC5HzVArH5WPsjzVKk1Ls1PZsbvsdlPpddZtSddHnI6WUbflyTqZCaZlpD1MzPD6iERC8ZoiiiKhM +AEDzMy+f2wZ/Tk8BphhBpjPWnutWfu3f/u3f7/fnt/e+/vacIWBwPPAXqACEB00mYDfgS3Aw0APPLSVP +sDTwG7gImDB9e+5NckMlAE7gUeBUAc+o65KKDAH+UwvIp+xq9+zJzk+VQA/AouRY4WKm4EdyI+vqxvqy +PQHsAYIvvaGPdjNDUA6UIPr36ej+8anQJjjH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TObB +/sIQzqj3dxcwU7Al8BjwDlXN6SDEIpU5k92dUPswdvb22Zjstra2jZFePb19bXR2xqNRrtCybcVHx8fe +vfubY05aDKZqKys5OLFi+1uWKRDDiCtj2DmwYMHD25MTU2NjZFGW6murm43MdG1GI1GTp486ZJrX4PQ4 +KLdx1xA0/GdPVxLLV3H4qeGrnOvjsCMm8da89AuVGlwk70hnIxA2tB7sJ9LdA0lrgU4jQzl78E+KpE+S +p3eltpDk+RqgE10oNAHreQCrtnnoyNjBpqPOdPxuYh03nSrCLVuTjUyLLzj90j10FEwIyM8Mwi5N4AJN +wg74IRUDaxEhkz30DL8kU5snbVvmIAPL9+nh5YRAPyTzts3PKnp/80O5NgBwHDk7mSdrTMYgH8AVzYn8 +dBSbkCGVrk2JlNHTwZgI+4XA6sjEYrc0fAPXP8+Pal9Uh0yeGc8XNkBrxi5Z/ZZ5GwsEBmDpyNSv53rD +iAFGZCwbTu3dG1KgSykzDsAuA65b3tHtNyzIMUue5B7jP+dLhIBwElUIkOtFCBDzvdEfjc6Yt/w0DQG5 +BYBbyEDwP4K8P/5NKktlEzCYQAAAABJRU5ErkJggg==" width="400" height="44" /></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Detect and calculate the necessary FOC motor and control parameters. The procedure is the following:</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<ol style="margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; -qt-list-indent: 1;"><li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Measure <span style=" font-weight:600;">R</span> and <span style=" font-weight:600;">L</span> and wait for the detection result. When the detection result arrives, <span style=" font-weight:600;">KP</span>, <span style=" font-weight:600;">KI</span> and <span style=" font-weight:600;">Observer Gain</span> will be calculated.</li> +<li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Measure <span style=" font-weight:600;">λ</span> and wait for the detection result. If the detections fails, tweak <span style=" font-weight:600;">I</span>, <span style=" font-weight:600;">D</span> and <span style=" font-weight:600;">ω </span>as described below and try again until it works.</li> +<li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Use the <span style=" font-weight:600;">Apply</span> button to apply the measured and calculated parameters.</li></ol> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The following parameters are measured:</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<ul style="margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; -qt-list-indent: 1;"><li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Resistance (R)</li> +<li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Inductance (L)</li> +<li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Flux Linkage (λ)</li></ul> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The following parameter are calculated from </span><span style=" font-family:'Roboto'; font-weight:600;">R</span><span style=" font-family:'Roboto';"> and </span><span style=" font-family:'Roboto'; font-weight:600;">L</span><span style=" font-family:'Roboto';">:</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<ul style="margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; -qt-list-indent: 1;"><li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Proportional gain for the current controller (KP)</li> +<li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Integral gain for the current controller (KI)</li> +<li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Gain for the observer</li></ul> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">For measuring resistance and inductance, signals are injected into the motor. Nothing requires configuration for doing that and the motor does not need to spin up.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">For measuring the flux linkage the motor needs to spin up, which is controlled by the </span><span style=" font-family:'Roboto'; font-weight:600;">I</span><span style=" font-family:'Roboto';">, </span><span style=" font-family:'Roboto'; font-weight:600;">D</span><span style=" font-family:'Roboto';"> and </span><span style=" font-family:'Roboto'; font-weight:600;">ω</span><span style=" font-family:'Roboto';"> startup settings. Notice that the resistance has to be measured first. The startup settings mean the following:</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Current (I)</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The current to use for spinning up the motor.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Duty (D)</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The duty cycle where to measure the flux linkage.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">ERPM (ω)</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The minimum speed for the delay commutation mode to start the motor.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">If the motor is not able to spin up properly these settings can be tweaked. Symptoms:</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-style:italic;">The motor starts to spin, but is too weak to reach enough speed.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto'; font-style:italic;"><br /></p> +<ul style="margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; -qt-list-indent: 1;"><li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Increase the current setting.</li> +<li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">If the load increases with speed (e.g. a propeller) you can decrease the duty cycle. This makes the detection slightly less accurate, but that does not matter in general.</li></ul> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-style:italic;">The motor cogs and is unable to spin up.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto'; font-style:italic;"><br /></p> +<ul style="margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; -qt-list-indent: 1;"><li style=" font-family:'Roboto'; font-style:italic;" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-style:normal;">Increase or decrease the current.</span></li> +<li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">If the motor has high inertia decrease ERPM. E-bike hub motors tend to have high inertia.</li> +<li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">If the motor has low inertia increase ERPM.</li></ul> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">After measuring the motor parameters, gain factors for the current PI control loop and the observer gain should be calculated. KP and KI are calculated based on a desired time constant of the current controller and the motor parameters R and L, which have to be measured first. The observer gain is calculated based on the motor inductance, which also has to be measured first.</span></p></body></html> + + + + Detect FOC Encoder Parameters + 0 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Detect the following encoder parameters:</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<ul style="margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; -qt-list-indent: 1;"><li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Offset</li> +<li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Ratio</li> +<li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Inverted</li></ul> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">To do that, the motor is turned slowly in open loop while the encoder output is sampled, once for the ratio and once for the offset. This is done in both directions for one full mechanical revolution to get rid off possible offsets and nonlinearities.</span></p></body></html> + + + + Detect FOC Hall Sensor Parameters + 0 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Detect the hall sensor table. To do that, the motor is turned slowly in open loop while the hall sensor outputs are sampled. This is done in both directions to get rid of offsets.</span></p></body></html> + + + + Detect IMU Calibration + 0 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Calibrate the IMU. This will set the curent IMU orientation to level. If your Pitch/Roll axes don't end up in the desired orientation, you can supply a yaw value.</span></p></body></html> + + + + NRF Pairing + 0 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Set the VESC in NRF pairing mode for the amount of time specified in the Time box (default 10 seconds). Afer that, you should put the device to pair in pairing mode before the time runs out. A popup should appear and show that pairing was successful, or that it timed out. After a sucessful pairing, the NRF settings will be updated according to the unique ID of the paired NRF device and stored to the VESC.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">NRF Nunchuk</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">For pairing the NRF nunchuk, set the VESC in pairing mode and switch on a nunchuk (that was switched off previously) before the pairing time runs out.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Notice that the unique ID of the NRF nunchuk is based on a hashed version of its microcontroller UUID, so the pairing should still be valid even after updating firmware. The chance of collisions between NRF nunchuks is practically non-existent.</p></body></html> + + + + CAN Forwarding + 0 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">When CAN forwarding is enabled, all communication will be forwarded over CAN bus to the VESC with the ID selected in the ID box in the connection page.</p></body></html> + + + + RT data logging + 0 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">VESC Tool (mobile and desktop) can log realtime data to CSV files. The output directory has to be chosen, which is where the log files are stored. Each time the logging checkbox is checked, a new CSV file with the current date and time is created in the output directory. This means that toggling the box will store the current file create a new one, which can be convenient to split the logs.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The output format is as follows:</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><span style=" font-family:'Roboto';">ms_today;v_in;temp_mos;temp_mos_1;temp_mos_2;temp_mos_3;</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><span style=" font-family:'Roboto';">temp_motor;current_motor;current_in;id;iq;rpm;duty_now;amp_hours;</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><span style=" font-family:'Roboto';">amp_hours_charged;watt_hours;watt_hours_charged;tachometer;</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><span style=" font-family:'Roboto';">tachometer_abs;position;fault_code;vesc_id</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The values mean the following:</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">ms_today</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Time today in milliseconds. This time is sampled in VESC Tool, so it can contain jitter compared to the data values depending in transmission latency.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">temp_mos</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">MOSFET temperature in °C.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">temp_mos_1, temp_mos_2, temp_mos_3</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Individual MOSFET temperatures for the legs in the power stage in </span><span style=" font-family:'Roboto';">°C. Only available on hardware with individual temperature sensors, such as the VESC 75/300.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">temp_motor</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Motor temperature in °C.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">current_motor</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Motor current in A. The sign is the same as the input current, thus positive when the motor is driving and negative when the motor is generating.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">current_in</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Input current in A.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">id, iq</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">D-axis and Q-axis current of the motor. Only available in FOC mode.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">rpm</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Motor speed in electrical rouds per minute. Has to be divided by the number of pole pairs to get the mechanical speed.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">duty_now</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Modulation, range -1.0 to 1.0</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">amp_hours</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Ampere hours consumed from the input.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">amp_hours_charged</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Ampere hours fed back to the input.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">watt_hours</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Watt hours consumed from the input.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">watt_hours_charged</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Watt hours fed back to the input.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">tachometer</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">1/6 electrical revolution counter. Will count 6 steps for every electrical revolution of the motor. Has to be multiplied by the number of pole pairs to get 6 times the counts per mechanical revolution. Will count backwards when the motor is turning backwards.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">tachometer_abs</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Same as </span><span style=" font-family:'Roboto'; font-weight:600;">tachometer</span><span style=" font-family:'Roboto';">, but couts the absolute value</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">position</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Motor position in degrees. It is the mechanical position when using an encoder, the electrical position otherwise. In sensorless mode the position is not valid when the motor is not turning.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">fault_code</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Current fault code.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">vesc_id</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">CAN ID of this VESC.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p></body></html> + + + + Motor Setting Description + 0 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p align="center" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Motor Settings</span></p> +<p align="center" style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto'; font-weight:600;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">This is where you can edit your motor settings. It is </span><span style=" font-family:'Roboto'; color:#00A1E4;">very important</span><span style=" font-family:'Roboto';"> to setup your VESC every time you connect a different motor, otherwise the VESC and/or the motor are likely to get damaged. The easiest way to set up your VESC for your motor is to use the </span><span style=" font-family:'Roboto'; font-weight:600;">Motor Setup Wizard</span><span style=" font-family:'Roboto';">. This wizard can be accessed from the welcome page, from the help menu or using the button at the bottom of this page.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The motor settings are stored in their own configuration structure. Every time you make changes to the motor configuration you have to write the configuration to the VESC in order to apply the new settings. Reading/writing the motor configuration can be done using the buttons on the toolbar to the right. The functions of these toolbar buttons are the following:</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><img src="data:image/846930886.PNG;base64,i +VBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAACXBIWXMAABLDAAASwwFyLQTKAAAAGXRFW +HRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAWtJREFUSInt1L9LlVEYB/CPP9I7iFAkpojgq +lOCg0u4COIi0aAipuDQv+Ag4dbQ7ChUSNASNIWLiAjSkEugIAjXSREUU0QMUYdzgpfTe7tXsu1+4YX3P +N/nnO95Hr7PoYoq/hfq/sK14TyzbsE0+rCP0yS/BuN4hiYUy4k34Fvc8Bu9uME13uTs6cJl5BezRG0Jk +Zl447dRMIsfGEUhiU/gEMfpYXkij/FaKL8Pkwn/Ca0YyMQeRJElXFUiMocn8b8G83iU4YtYxctMrF9o1 +8ec8/4Q6cGrJNaB2ST2HsOCGWAKG9ipRORaKHsMF1jAC6wkuV8j/xwPMYJ3eQJQn6y341cQeruJz5Hrz +eSdxfgUfglt/VKpyF3wQXBhaxQ4QWNeYikLV4Lv2EJnFCyJf6nkCkPCdO/dRaRdcFiD8OR0YxA/5fhfG +L7DcrdJ3642PEUzlnEkuKdWmPRdrMuZ6ogbHGBNmeqqqOJ+cAulnEDcgz/2JwAAAABJRU5ErkJggg==" width="25" height="25" /><br /><span style=" font-weight:600;">Read Motor Configuration</span>. This button will read the current motor configuration from the VESC to VESC Tool.</p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><span style=" color:#00A1E4;">Warning</span>: All of the motor settings currently in VESC Tool will be overwritten by pressing this button.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><img src="data:image/1681692777.PNG;base64,i +VBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAACXBIWXMAABLDAAASwwFyLQTKAAAAGXRFW +HRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAbJJREFUSInt002IjlEUB/Cfd8Y0xTsWGjYWE +7MkKZRYqMl3Yulj7CykbC2sbJSsLKSJohEWk0RZiIhYKmUiSmoWamgsNIbxORb3PLpuzzAWdu+/nnru+ +frfc87/0kIL/wuz0Ibb6C18U+jHg5q8fqzBGI5GbI5lOBD/xyvjDvyI4Oq7gUb427A0K3Iu4j9jec0lB +vA9YlbkHT3OCD4VRbdjHDszkjEM40RBMDd890qS9fiCb0FyskjswHm8w+IgGcVhjKAzi92N9zhUktyJ7 +zTeoLtmBF14hVMZSQ8+YFs2kZu4gH05ybzoYg8WYG8NQYVjeBlFRjEb1zAU/h5Moi8naWAR2vEcb3HpD +yTPMB/NOE9hEJuxMC74GvfzpAY+RnDT39GFr1LnFW5JotgVJBel3f5GMiKpYcMMSDbiKSYy2wSu4AiW4 +HKZ1JDmdgYHI2g69GELztb4BqW3dBcvpivQxBNpL6tqLrJV2td1aX+VutqzuM7i/GvxlXE8Cg3hofSQH +knqWYeVkor2K+adYXK6Dkp0SFK+KilpWFLbJukNVOjF6sJWohtrMWem5C208O/4CY0gaupzHd1QAAAAA +ElFTkSuQmCC" width="25" height="25" /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><span style=" font-weight:600;">Read Default Motor Configuration</span>. This button will read the default motor configuration from the VESC to VESC Tool. The default configuration is hard-coded in firmware, and is how the VESC is configured right after uploading new firmware.</p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><span style=" color:#00A1E4;">Warning</span>: All of the motor settings currently in VESC Tool will be overwritten by pressing this button.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><img src="data:image/1714636915.PNG;base64,i +VBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAACXBIWXMAABLDAAASwwFyLQTKAAAAGXRFW +HRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAWdJREFUSInt1L9LlVEcx/FXYupYkJhLEDTEx +cmQaKpcjJZoCCLJxMF/wKFFBJeKaG20KFSQtpbGRIlCcGhRiAhJIZUyEH/itdvwnEuPD+c+XC+03Q88c +L7f8/2c9+E533Ooq67/pROZ+CK6I3VrmMGdEL/FSmStuziNRbyvBD2L6+jBNp6G+BI6UcIfPI54z2M/z +I9VAqTVgk0MpHJlyGd8CzVpDWMZP7OQhmqIGU2hDddSuZPoxTiKWUMtkCVMoy+VuyL5XZMxQy0QeIWba +A3xA3zEl1hxYybuQAFNYa4LW9iRdFhZ77CL23iDWxiqdoeFsGAp8z3x7+Dvhdrn+IB+/MIpNGNVFd31T +NKGZcB3Se9nIZexh694EXJRSOxMHuFHGJcwgt+Runks4Bxe5+06BtnAaAB8wkQFbxE3JK/E7HEh8BJze +IiDHP+65GIe5kHy1O7o23YGg7iQ42nAfVytFVpXXcfTX2+vTfc/khePAAAAAElFTkSuQmCC" width="25" height="25" /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><span style=" font-weight:600;">Write Motor Configuration</span>. This button will write the motor configuration that currently is in VESC Tool to the VESC. Every time you make a change to the motor configuration in VESC Tool you must use this button to apply the new settings. The new settings will be used as soon as you write them to the VESC, and they will be stored in the flash memory of the VESC persistently.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Every motor setting has three small buttons to the right of its value. They have the following functions:</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><img src="data:image/719885386.PNG;base64,i +VBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAApUlEQ +VQ4je2UOwoCMRRFz4iduAOX4AJ0HwqW2YIrcQfpZzYy1rMGG8sB21Gb+yCIUZOJ2HjgwsuHk0cggR8xU +4pQAV6pSggdcFXcWNkS6IGb0msuiznQBTJLp7Vk/BOZxafKHDC8EA5E7nMaEZ6Bneo9sFbdAgfVl9Quj +TrorHm3eZJ7yl/4PWFx7PdYAKuRriNwssGG+Kv4NNvHDu015NKGHRbjDvLBOhzaahdWAAAAAElFTkSuQ +mCC" width="20" height="20" /><br /><span style=" font-weight:600;">Read Current Value</span>. This button will read the current value for this setting from the VESC.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><img src="data:image/1189641421.PNG;base64,i +VBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAACXBIWXMAAA7EAAAOxAGVKw4bAAABy0lEQ +VQ4ja3UuWsUUBAG8N9uNCbe8T4LDdqpYGNhBCWQxsZCRMWjEBsbK5vUVv4DBkQR7ETwQkUhoCBBRAQRQ +RuPRDwKC2M0mpCsxcyaZY+sRQYejzfvvZlvvjmYYSk00C/BBqzCbPzCh1y//9d4Cw6gHz8xiVLFmsRXX +MK2ZgiLuIwjiaYfT/ERY5iPTdiN7RjHcVxtZHhnIriO5U0i2YHBdFYjxdxXa8xnPSlgbb2LWVXnfejBQ +wxgCH+wEJvRja2C72llvyD+guBvRG1SJkwlZSB1TRG+xUksRifWoDUdvMc7kZC+dNgU4QTu4qjIarvge +anIbiWAeYKKaQ2+wGhVqCVRSl1Vf3rybhjn03FNyOfwAHtE8a5DG+7gE07gYr79nPsCPFZFQRnhoCjYj +jpRXEv0nXlehidpeAhz6xkcy30Ez3EbZ0WZjCbSshSwCGcSXRdThV2WUxnWPdFu3blaMQdfKt6W8D11h +Qz9n+xKLzc0br1XgscVFboi7osJtF7VxZU0+gM30YtjYgJtwSFRVi9xGHtxK//01UPQgoN4pHZ8vRZ8n +RZlUtaPi85pLxtpNBA6sNFUpwyLJH3DSpGANjzDmwY2Zkb+AmCVfJ8j/k4uAAAAAElFTkSuQmCC" width="20" height="20" /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><span style=" font-weight:600;">Read Default Value</span>. This button will read the default value for this setting from the VESC.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><img src="data:image/1350490027.PNG;base64,i +VBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAACXBIWXMAAA7EAAAOxAGVKw4bAAABiUlEQ +VQ4ja3UQUtVURAH8F8iiOt4lRuJBF/wAj9Drtzk24maguuo71G67xtIayNa5t6lqagrFVMRdGdQ1LPFm +fu8He99mvSHA/fcmf//zJyZM/xn3LvBPoAmhmN/gB38+NeDHmIJR+jgMlYn/i2Fz60ifI4PeIANrGA3b +KNo4xlOMYPVXpGN4zvOMI2+Cp++EDoL3/E6sQaOcY5WJvDE1T0WaIXvcXCvYVG6o+nSv/tYw2/8wicMl +uwzwVnMxQaky173d5qvpWK8wpv4XsiiX8e30OiSn+KRVIBOifAFU1iOSEnFKtDBRwyFRheTcfpcHnopg +89SEVqZbT64L6C/RiDHW0zEgZu9HIuU9+OUZo3fT7yX+jNHM7gHZcFtqfxt1b23j60g5gG1g7udk4q2m +a0Q3IiV42Vw3lXYNKTWOcdYZhuJVcZY+B6paWzSM7oIx1n1T28ufC6kt99F3XBYlvryq9RnO2FruhoOJ +1LKPYdDgYZ0p4euj6/DsFWmedsB+zj2e+44YO+MPwJ2YaVTOqggAAAAAElFTkSuQmCC" width="20" height="20" /><br /><span style=" font-weight:600;">Show Help</span>. This button will show a help dialog describing what this setting does. If you are not sure about a setting the help dialog can be very useful.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The full motor configuration, including the notes you make on the <span style=" font-weight:600;">Description</span> page, can also be written to and read from XML files using the <span style=" font-weight:600;">File</span> menu. This is a good way to keep your settings when going between different VESC Tool versions, to share your settings and to store your configuration in general.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Notice that uploading new firmware to the VESC will reset all its settings to their default values for that firmware. This means that after uploading firmware to the VESC you have to perform the motor configuration again.</p></body></html> + + + + App Setting Description + 0 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p align="center" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">App Settings</span></p> +<p align="center" style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto'; font-weight:600;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">This is where you can edit your app settings. The VESC can run one or more apps, and the apps are used to enable different functions on the communication interfaces of the VESC. If you are going to use your VESC with USB or CAN-bus you don't have to change the app configuration since these interfaces always are active. If you want to use conventional input devices such as nunchuks, ebike throttles or RC remote controllers you have to configure the apps accordingly.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The easiest way to configure your VESC for conventional input devices is to use the </span><span style=" font-family:'Roboto'; font-weight:600;">Input Setup Wizard</span><span style=" font-family:'Roboto';">. This wizard can be accessed from the welcome page, from the help menu or using the button at the bottom of this page.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The app settings are stored in their own configuration structure. Every time you make changes to the app configuration you have to write the configuration to the VESC in order to apply the new settings. Reading/writing the app configuration can be done using the buttons on the toolbar to the right. The functions of these toolbar buttons are the following:</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><img src="data:image/1804289383.PNG;base64,i +VBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAACXBIWXMAABLDAAASwwFyLQTKAAAAGXRFW +HRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAVdJREFUSInt079LW1EYxvFP1PgrVFCwDh0FB +wvSQnEQuhRsJykJdLCrg5uLuJTSSXToH5A/oFuhIjhI/wFxqlYquAu2OliCLaUaicM5kcuNCTHoli+8c +O9933ue5xyeQ5s290Vng94Asjiv089hDuPYa9XAKlYa9GdRiSYmWhEYwx+cxeeb+Iod/MLHVkTWBJcVf +EEm1R/FP8yjiEP03UbgFcoJkTJepmY+oIQRTOESr5sV6Mb3hEC1vqE3MXOAz/E9i32sNysyiDwK2I5Vi +DUYZ15E5zOJ/97jLx41K1RlLVaaTzjCsBDjnJCuCyzehcgwfuM/jhN1IuxuDx3phbpuKZzHA7wTopvkC +RYwKRxzU6R3ksEWftQxNyQkrphupId78Dwu+DB+mxYSVsIzLAuxTnOKTbzBknCZr90l6cdbtedawS6eY +gM/bxCBx8K92VB7nG3a3ANXA4ZLC/b9+0UAAAAASUVORK5CYII=" width="25" height="25" /><br /><span style=" font-weight:600;">Read App Configuration</span>. This button will read the current app configuration from the VESC to VESC Tool.</p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><span style=" color:#00A1E4;">Warning</span>: All of the app settings currently in VESC Tool will be overwritten by pressing this button.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><img src="data:image/846930886.PNG;base64,i +VBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAACXBIWXMAABLDAAASwwFyLQTKAAAAGXRFW +HRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAZpJREFUSInt1L9LVmEUB/BPWr0qJUENQViXl +qIh0KaIhoyghiCyFyKC/ANaWmuxsK3FEGyooCjQoZaagqagoPYGM/qJCoaCFFiWNTwHul7ufd+ltvcLh +8vhfM/5nuee5zm00ML/xgF8wMeCPcX6JrlrcAmj2NFM6DF+52wFJ3Px7eguyduFH8EfaiayH79yIk/Qn +os/wktsKeQN4wseYgprG4ncxXIILKG3EN+DTxiXfhF04C1uoT+aPFIlsDsEzmMGYxW8U/iOvvCPRuFD0 +uymcL9K5ALmUMNpbK3gdcRpLoY/gTdYF/4wFrE5n9QW3wzvostxzFaILAUvi0aOBX854vfQhXqZyDdsy +PmNsDH49Sj4IkQz6Za9xmBZ4kB0s7OJQBYCZ/HK6iuft5/YW0zuxHvp6O3FYKANd6RHejgKXca+gh3EV +1wrK3JcmskNbCrEujEizaSO61FoW0VDD6RbWisLnsF8EG5LL/gmPmMB56SZTEsbogoD0gY4UUXowRU8w +ySe46q/e6lL2nU9DURqwckacFpo4R/gDwhEYoEYfLxOAAAAAElFTkSuQmCC" width="25" height="25" /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><span style=" font-weight:600;">Read Default App Configuration</span>. This button will read the default app configuration from the VESC to VESC Tool. The default configuration is hard-coded in firmware, and is how the VESC is configured right after uploading new firmware.</p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><span style=" color:#00A1E4;">Warning</span>: All of the app settings currently in VESC Tool will be overwritten by pressing this button.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><img src="data:image/1681692777.PNG;base64,i +VBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAACXBIWXMAABLDAAASwwFyLQTKAAAAGXRFW +HRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAVZJREFUSInt1D1LXUEQxvGfIor4UgiCL6VYC +WqVSjQSsReC+IKFRSxtJEUs0qXyAySlYKGV2gbEwkICIQhikS8QURHFBAyJihY7By4H782BaHf/MOzO7 +s4+e2aGQ5Uqz0VNzm/CHGpz6/dYxe9Hzl5jLc4Uoh4jGMVe2Chexl4p03HxX/QXFcizGVaOzzjACVYqX +ZRPS1F6MIxP2MIUGp9aZFZK07ZUjy6MP6VIPWakdJ3iK75jvlxAXc5vw1jMu2OcjHEHFxhCL97G+g3W8 +S5ifhR55YHUNaX2DQ1xZg3HaJfauEnqrhss/UsgYywCMoFbvIq9dlzij5SqzM5wh0OPlCCfLlJatvE6/ +E3sxnwCLViWWreUQSziBb4U+Zpe/MLPmJP+Dvs4KvO4NlzhYxGBjA9hGQNS276vELOBczQXFWmViprRh +wV0Vojpwxt0FBWpUuX/eABXPUWBkBgNpgAAAABJRU5ErkJggg==" width="25" height="25" /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><span style=" font-weight:600;">Write App Configuration</span>. This button will write the app configuration that currently is in VESC Tool to the VESC. Every time you make a change to the app configuration in VESC Tool you must use this button to apply the new settings. The new settings will be used as soon as you write them to the VESC, and they will be stored in the flash memory of the VESC persistently.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Every app setting has three small buttons to the right of its value. They have the following functions:</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><img src="data:image/719885386.PNG;base64,i +VBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAApUlEQ +VQ4je2UOwoCMRRFz4iduAOX4AJ0HwqW2YIrcQfpZzYy1rMGG8sB21Gb+yCIUZOJ2HjgwsuHk0cggR8xU +4pQAV6pSggdcFXcWNkS6IGb0msuiznQBTJLp7Vk/BOZxafKHDC8EA5E7nMaEZ6Bneo9sFbdAgfVl9Quj +TrorHm3eZJ7yl/4PWFx7PdYAKuRriNwssGG+Kv4NNvHDu015NKGHRbjDvLBOhzaahdWAAAAAElFTkSuQ +mCC" width="20" height="20" /><br /><span style=" font-weight:600;">Read Current Value</span>. This button will read the current value for this setting from the VESC.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><img src="data:image/1189641421.PNG;base64,i +VBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAACXBIWXMAAA7EAAAOxAGVKw4bAAABy0lEQ +VQ4ja3UuWsUUBAG8N9uNCbe8T4LDdqpYGNhBCWQxsZCRMWjEBsbK5vUVv4DBkQR7ETwQkUhoCBBRAQRQ +RuPRDwKC2M0mpCsxcyaZY+sRQYejzfvvZlvvjmYYSk00C/BBqzCbPzCh1y//9d4Cw6gHz8xiVLFmsRXX +MK2ZgiLuIwjiaYfT/ERY5iPTdiN7RjHcVxtZHhnIriO5U0i2YHBdFYjxdxXa8xnPSlgbb2LWVXnfejBQ +wxgCH+wEJvRja2C72llvyD+guBvRG1SJkwlZSB1TRG+xUksRifWoDUdvMc7kZC+dNgU4QTu4qjIarvge +anIbiWAeYKKaQ2+wGhVqCVRSl1Vf3rybhjn03FNyOfwAHtE8a5DG+7gE07gYr79nPsCPFZFQRnhoCjYj +jpRXEv0nXlehidpeAhz6xkcy30Ez3EbZ0WZjCbSshSwCGcSXRdThV2WUxnWPdFu3blaMQdfKt6W8D11h +Qz9n+xKLzc0br1XgscVFboi7osJtF7VxZU0+gM30YtjYgJtwSFRVi9xGHtxK//01UPQgoN4pHZ8vRZ8n +RZlUtaPi85pLxtpNBA6sNFUpwyLJH3DSpGANjzDmwY2Zkb+AmCVfJ8j/k4uAAAAAElFTkSuQmCC" width="20" height="20" /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><span style=" font-weight:600;">Read Default Value</span>. This button will read the default value for this setting from the VESC.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:1; text-indent:0px;"><img src="data:image/1350490027.PNG;base64,i +VBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAACXBIWXMAAA7EAAAOxAGVKw4bAAABiUlEQ +VQ4ja3UQUtVURAH8F8iiOt4lRuJBF/wAj9Drtzk24maguuo71G67xtIayNa5t6lqagrFVMRdGdQ1LPFm +fu8He99mvSHA/fcmf//zJyZM/xn3LvBPoAmhmN/gB38+NeDHmIJR+jgMlYn/i2Fz60ifI4PeIANrGA3b +KNo4xlOMYPVXpGN4zvOMI2+Cp++EDoL3/E6sQaOcY5WJvDE1T0WaIXvcXCvYVG6o+nSv/tYw2/8wicMl +uwzwVnMxQaky173d5qvpWK8wpv4XsiiX8e30OiSn+KRVIBOifAFU1iOSEnFKtDBRwyFRheTcfpcHnopg +89SEVqZbT64L6C/RiDHW0zEgZu9HIuU9+OUZo3fT7yX+jNHM7gHZcFtqfxt1b23j60g5gG1g7udk4q2m +a0Q3IiV42Vw3lXYNKTWOcdYZhuJVcZY+B6paWzSM7oIx1n1T28ufC6kt99F3XBYlvryq9RnO2FruhoOJ +1LKPYdDgYZ0p4euj6/DsFWmedsB+zj2e+44YO+MPwJ2YaVTOqggAAAAAElFTkSuQmCC" width="20" height="20" /><br /><span style=" font-weight:600;">Show Help</span>. This button will show a help dialog describing what this setting does. If you are not sure about a setting the help dialog can be very useful.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The full app configuration can also be written to and read from XML files using the <span style=" font-weight:600;">File</span> menu. This is a good way to keep your settings when going between different VESC Tool versions, to share your settings and to store your configuration in general.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Notice that uploading new firmware to the VESC will reset all its settings to their default values for that firmware. This means that after uploading firmware to the VESC you have to perform the app configuration again.</p></body></html> + + + + Data Analysis Description + 0 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p align="center" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Data Analysis</span></p> +<p align="center" style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-weight:600;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Here you can stream and plot data from the VESC to analyze what is going on. Next to all plots the following buttons are available:</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><img src="data:image/1804289383.PNG;base64,i +VBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAACXBIWXMAACKaAAAimgG+3fsqAAAAGXRFW +HRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAOtJREFUSInt0j9KQ0EQx/FPTODlIMY7iIXWg +VgoSmzEE3gEsRDvoCm0Tx0lJ/AUsbW0TUCfFhkhLlmeAcv9wrAzO39+u+xSKBT+k0P0w+9H/Ce2GvJdn +KBCB+3Yb0dcRb67qUgL+xjhDedYZPoXuIi6EQ6iP0sPN3hFja+w08gfYRD+IGI4W6mto/8WO6nANT5Xi +lftCQ+YJiLT2H/O9NUx9xfbuMIsucmw4SbDZPAshvdSgZRd3OMdkwaRSdTdYc+aN+lkRF7CLmNglamr8 +IhjzHMnzon8MMc4/A/LdxNry/J3jdf0FQqFDfkG0GlAe84ws98AAAAASUVORK5CYII=" width="25" height="25" /> <img src="data:image/1714636915.PNG;base64,i +VBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAACXBIWXMAACKaAAAimgG+3fsqAAAAGXRFW +HRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3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m5O6hleiGT4K9bnq/k7EVAN3dafdb//GM/ +x+/VnbD/vV3198lXlrK5rk7bAAAAABJRU5ErkJggg==" width="25" height="25" /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">If this button is toggled active (blue), scolling with the mouse on the graph will zoom the graph horizontally.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><img src="data:image/719885386.PNG;base64,i +VBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAACXBIWXMAACKaAAAimgG+3fsqAAAAGXRFW +HRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAARFJREFUSInN1DFKA0EUxvFfVDBipa1l9BbBG +1ioWMbeM4jYCnZeII1dChHPolXwCpvOFCZa7CwmC4lvTBb8wzI7s/PNNzvz3uOfctO0wREmOMwRbWSa9 +JKml6kL08I7vlLbasLkGNNkMk39EDnHdeln963UXys7GCn/onpGaEfEm0GTM+zhFru4xj4+8Ja338Vsz +7z3F4wvZCsw57Q27wAXM/1PPK1qMjZ/rA+175PAGs0TSagTywNkgpdlC+SWFbj6gybEStEVzZNz3CnLS +Te198o8eQ2u8SttFOYzvhDM+OidjDGojQ3S+Fqpjqmqwt11G1QMk8kwR5Qbwo+1thE6yuTr5IiiIVxRK +O/jOVPXPN97eDNuBsQAEwAAAABJRU5ErkJggg==" width="25" height="25" /> <img src="data:image/1649760492.PNG;base64,i +VBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAACXBIWXMAACKaAAAimgG+3fsqAAAAGXRFW +HRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAzdJREFUSImN1rtvXEUUBvDf3bu7Xtu7Xju2C +YiGDslSk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5CYII=" width="25" height="25" /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">If this button is toggled active (blue), scolling with the mouse on the graph will zoom the graph vertically. Often it is useful to deactivate this button and only zoom in the horizontal direction because the sampled data can be squeezed together horizontally for long sampling sequences.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><img src="data:image/1681692777.PNG;base64,i +VBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAACXBIWXMAACdjAAAnYwEdzQRDAAAAGXRFW +HRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAS5JREFUSInd1j9LA0EQh+EnEr+BYBdJKrFST +KGIimhh52cTLMReBEH80ymCjZ0INlqpRToLeyHqWeSCe6fEy92mcWDgbmbn93J7s8PWkBixjY0aAPXge +Q2diNoNXOUhHTxHEJ/EWxiIuV3T2MM9xvPJJPVWSfElnOIj1dlO461AuxSkhi1cB/UJupiKAVnEQ0687 +/vBukqQut4WHeEzqP/EbCxI35p4DOrPc/nKkKbeGWjgOK1fjwkJAbCMm1/WFYa0ZXs+D5Dm21Ugt1gZA +BhkhSAbafykBKAw5MJ3az4NCSgEmZM9AwnOsCo7VCtBDnKAvt9hIQakpTeDwpN8ic2C4oUgO+n7Ow4xP +6T4n5AJvGJX+dH/A5L/iV3M4KUiIGMhJGzRql+R0av5L1eiL2cWjCtk8xZ0AAAAAElFTkSuQmCC" width="25" height="25" /> <img src="data:image/424238335.PNG;base64,i +VBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAACXBIWXMAACdjAAAnYwEdzQRDAAAAGXRFW +HRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAA4hJREFUSImt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X5G23Ni1z1vi+M+9I1JC+6vnzRz8cyjmVBurG1aJy16xoTTmvoNa0W/zP97Z2RRyZ2ibBGyE +5zBuE332eMjTZF5kTmxaXHBg52ZcLarf47/8W9lfUjxjf/43/U3pE5Iq8YBubkAAAAASUVORK5CYII=" width="25" height="25" /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">This is the auto fit button. If the toggle verion of the button is active (blue), new realtime data that drops in will cause a rezoom in the graph to fit all data. Deactivating this button can be useful of you want to zoom in on the realtime data manually while samples are dropping in.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><img src="data:image/1681692777.PNG;base64,i +VBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAACXBIWXMAACdjAAAnYwEdzQRDAAAAGXRFW +HRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAS5JREFUSInd1j9LA0EQh+EnEr+BYBdJKrFST +KGIimhh52cTLMReBEH80ymCjZ0INlqpRToLeyHqWeSCe6fEy92mcWDgbmbn93J7s8PWkBixjY0aAPXge +Q2diNoNXOUhHTxHEJ/EWxiIuV3T2MM9xvPJJPVWSfElnOIj1dlO461AuxSkhi1cB/UJupiKAVnEQ0687 +/vBukqQut4WHeEzqP/EbCxI35p4DOrPc/nKkKbeGWjgOK1fjwkJAbCMm1/WFYa0ZXs+D5Dm21Ugt1gZA +BhkhSAbafykBKAw5MJ3az4NCSgEmZM9AwnOsCo7VCtBDnKAvt9hIQakpTeDwpN8ic2C4oUgO+n7Ow4xP +6T4n5AJvGJX+dH/A5L/iV3M4KUiIGMhJGzRql+R0av5L1eiL2cWjCtk8xZ0AAAAAElFTkSuQmCC" width="25" height="25" /> </p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">This is the non-toggle version of the auto fit button. Pressing it will zoom the plots so that all data fits in them.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Realtime Data</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The realtime data page can be used to stream and plot filtered data continuously, which can be useful for visualizing things in real time while they are happening. For example, if you run a motor and put some load on it, you can see that reflected right away in the current and RPM graphs. Tuning the position and speed PID control parameters is also a lot easier when looking at the step response in a graph.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">In ordet to stream realtime data, the </span><span style=" font-family:'Roboto'; font-style:italic;">Stream realtime data</span><span style=" font-family:'Roboto';"> button in the main toolbar to the right has to be activated:</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><img src="data:image/1681692777.PNG;base64,i +VBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAACXBIWXMAAC4jAAAuIwF4pT92AAAAGXRFW +HRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAABRdJREFUSIm111+MnFUZx/H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BS ++EAy4piccQOX3W7H3vIh/09HKYAp1FIp2ls8rK3a9po1oSqaUX9bduka1pdS1NTX1NHoibTGKpeCodY8 +LAt5t3kZw660XlcKtlFXI5FUlk45fUWjC5G0cwTE2ohgfKiEFs2pRrCMghr21gyZ4cjdnnKYde6YFS1x +l4nxeUqam23BOwY6PiOnVJLWAyKLodTjymQWvA17/Co6zzjkQDthL2WS9Zj1J16ygqL9Pismx2z12lnP +OF54zW5rLhnvz2etd0zjrrKxeCBdoCXD9CjqK15g75SWtR21LTH3eY3vuhVk+53Q1BbqMwtdck99jhlx +q894ioXgncW14SHx0A5j7vDhb8zsM8++815l7/5lUN+bleoOiMXpy66w81e0nLKERv8E28FK+BLpQN0C +9j48za/4ZM2mXeNV/zeLxVF/7QZt3vAgx5zj/N6qm71ER2Zpx3XHN6RwnPtAF0cWunps/pdnfiY2Pu86 +csmNBla3QmzPu0Bh3zPAR9U95bnHVcda4HLYyHL4aseeyvBN+Ahu+31oszqFlez324HfdNuTzrlcY1Qp +Ub9d5QVRXzXeNyXwVM4iXvxaniYJSVo0Xli87ba583wu5X/JIq0+Y8P+jL4MH6Bn46t+D/9hSmP69ddk +anI1GTqMo1g9TC3fqcrjX8Bmh7iKXvL0NIAAAAASUVORK5CYII=" width="30" height="30" /></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Sampled Data</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The sampled data page can be used to sample data at high rate internally on the VESC and send it back for plotting after that. This page can be used to visualize all samples taken by the ADCs to analyze the current and voltage waveforms in detail. Since this data is sampled at such a high rate it cannot be streamed in real time, which is why sampling and plotting has to be toggled manually. There are two buttons for starting the sampling in the lower toolbar in this page:</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><img src="data:image/596516649.PNG;base64,i +VBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAxklEQ +VRIie2UwQnCMBiFv4oHnaPgzRF0CD24lR7sEm4hCl3Am07QFidoqV7+YAykTW0CBfvBI7wkzctPksK/M +gOO0gYhAvbAS9ooRMgGKCWkFO+VGMglQCmXfi/MgdQIUEplvDcHoLaE1DLeiy2fc7CplHk/EQNFS4BSQ +cP5NF3DFbDU/A5Ya/4CnDR/A66uFdhI+N594vrhpG/yGDKGWJl2mPsAzoYfDvqLX9CtsjYq4G52Zrj9p +1yVqYX1nT89VhFivQHwBrDpUhHNZWIJAAAAAElFTkSuQmCC" width="25" height="25" /> </p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Sample data now and send it when this is done.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><img src="data:image/1189641421.PNG;base64,i +VBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAACXBIWXMAAAZoAAAGaAHEuzO0AAAAGXRFW +HRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAy9JREFUSImN1l9ol2UUB/DPby6ynK4MZ1uh9 +gdHeZFSpBBd5I0FboQXEZEhDMn+KShRUiJlEV54URIFiehtWuT2s2CRE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; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Sample data the next time the motor starts moving. This can be useful to analyze the startup behaviour in real time.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">There are also options to apply filters to the sampled data and/or to plot a FFT of all samples if desired.</p></body></html> + + + + App ADC Information + 0 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The cruise control button will maintain the current speed while pressed when current control is used and no throttle is given. The reverse button is used to reverse the throttle when one of the corresponding control modes is used.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">When only the ADC app is used, the TX pin is used for the cruise control button and the RX pin is used for the reverse button. When the ADC and UART apps are used at the same time, the servo input will be used as the button. In this case it will be used for the reverse button when a control mode with button is selected, otherwise it will be used for the cruise control button.</span></p></body></html> + + + + Chuk Info + 0 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">This app has been tested with the wireless Nyko Kama nunchuk. The receiver can be connected directly to the I2C port on the ESC. The y-axis on the joystick is used for acceleration/braking. The buttons have the following functions:</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">C-Button:</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Cruise control. If the C-button is pressed, the ESC will maintail the current speed with a PID control loop. The joystick can still be used to accelerate and brake, but as soon as it is returned to the center position the new speed will be maintained, as long as the C-button remains pressed.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Z-Button:</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The Z-button is used to change the direction of the motor if reverse is activated. Without reverse, Z has no effect.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">There is also a safety function. If nothing received from the nunchuk (including the accelerometers) changes for longer than the timeout value in the <span style=" font-style:italic;">APP General</span> page, the timeout function will be activated and either release the motor or brake with the current specified next to the timeout value.</p></body></html> + + + + PPM Pulselength Mapping + 0 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">PPM pulselength mapping is used to map the minimum and maximum throttle values from the PPM remote to the minimum and maximum throttle values of the VESC. The following procedure can be used:</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<ol style="margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; -qt-list-indent: 1;"><li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Activate the PPM app and reboot the VESC.</li> +<li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Set the PPM control mode to disabled to avoid motor movement and write the configuration.</li> +<li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Connect the remote.</li> +<li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Activate app realtime data streaming in the main toolbar. The input display should show the decoded input value and pulse length if the remote is connected and on.</li> +<li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Move the throttle between the minimum and maximum values to get them sampled.</li> +<li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Apply the result.</li></ol> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Input mapping should also be usable for those oneshot pulselengths that are popular for some multirotor flight controllers that don't have support for proper ESC communication such as CAN-bus or UART.</span></p></body></html> + + + + ADC Voltage Mapping + 0 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">ADC voltage mapping is used to map the minimum and maximum throttle values from the analog throttle to the minimum and maximum throttle values of the VESC. The following procedure can be used:</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<ol style="margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; -qt-list-indent: 1;"><li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Activate the ADC app and write the app configuration to the VESC.</li> +<li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Set the ADC control mode to disabled to avoid motor movement and write the configuration.</li> +<li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Connect the throttle(s).</li> +<li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Activate realtime <span style=" font-weight:600;">app</span> data streaming in the main toolbar. The input displays should show the decoded input value and voltage if the throttle is connected.</li> +<li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Move the throttle between the minimum and maximum values to get them sampled.</li> +<li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Apply the result.</li></ol> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p></body></html> + + + + Welcome to VESC® Tool + 0 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Welcome to <span style=" font-weight:600;">VESC</span> <span style=" font-weight:600;">Tool</span>. Since this is the first time you start this version of VESC Tool, the introduction is shown. Please read all instructions carefully for your own safety.</p></body></html> + + + + Usage + 3 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'arial,helvetica,sans-serif'; font-weight:600;">VESC® Tool</span><span style=" font-family:'arial,helvetica,sans-serif';"> and the </span><span style=" font-family:'arial,helvetica,sans-serif'; font-weight:600;">VESC® firmware</span><span style=" font-family:'arial,helvetica,sans-serif';"> are experimental software designed to develop and test electrical systems incorporating electric motors or actuators. Electrical systems can cause danger to humans, property and nature; therefore precautions shall be taken to avoid any risk. Under no circumstances shall the software be used where humans or property are put to risk without </span><span style=" font-family:'arial,helvetica,sans-serif';">thoroughly</span><span style=" font-family:'arial,helvetica,sans-serif';"> validating and testing the whole system. Software and hardware interact in various ways, and software developers cannot foresee all possible combinations of hardware used together with their software, nor problems that can occur in these different combinations.</span> </p> +<p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'arial,helvetica,sans-serif';">Things that can happen, even when using the correct settings, are</span></p> +<ul style="margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; -qt-list-indent: 1;"><li style=" font-family:'arial,helvetica,sans-serif';" style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">electrical failure</li> +<li style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'arial,helvetica,sans-serif';">fire</span></li> +<li style=" font-family:'arial,helvetica,sans-serif';" style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">electric shock</li> +<li style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'arial,helvetica,sans-serif';">hazardous smoke</span></li> +<li style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'arial,helvetica,sans-serif';">overheating motors and actuators</span></li> +<li style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'arial,helvetica,sans-serif';">overstrained power sources, causing fire or explosions (e.g. Lithium Ion Batteries)</span></li> +<li style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'arial,helvetica,sans-serif';">motors or actuators stopping from spinning/moving</span></li> +<li style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'arial,helvetica,sans-serif';">motors or actuators locking in, acting like a brake (full stop)</span></li> +<li style=" font-family:'arial,helvetica,sans-serif';" style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">motors or actuators losing control over torque production (uncontrolled acceleration or braking)</li> +<li style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'arial,helvetica,sans-serif';">interferences with other systems</span></li> +<li style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'arial,helvetica,sans-serif';">other non-intended or unforeseeable behavior of the system</span></li></ul> +<p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'arial,helvetica,sans-serif';">VESC Tool and the VESC firmware are developer tools that for safety reasons may only be used</span></p> +<ul style="margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; -qt-list-indent: 1;"><li style=" font-family:'arial,helvetica,sans-serif';" style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">by experts and experienced users, knowing exactly what they do.</li> +<li style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'arial,helvetica,sans-serif';">following safety standards applicable in the area of usage.</span></li> +<li style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'arial,helvetica,sans-serif';">under safe conditions where software or hardware malfunction will not lead to death, injuries or severe property damage.</span></li> +<li style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'arial,helvetica,sans-serif';">keeping in mind that software and hardware failures can happen. Although we design our products to minimize such issues, you should always operate with the understanding that a failure can occur at any point of time and without warning. As such, you shall take the appropriate precautions to minimize danger in case of failure.</span> </li></ul></body></html> + + Important usage information + + + Warranty + 3 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Times New Roman,serif';">LIMITED WARRANTY STATEMENT </span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Times New Roman,serif';">1. Warranty</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Times New Roman,serif';">1.1 THERE IS NO WARRANTY FOR THE VESC® SOFTWARE (VESC TOOL AND THE VESC FIRMWARE - PROGRAM FOR SHORT) TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM AS IS WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. </span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Times New Roman,serif';">1.2 Benjamin Vedder and contributors (the publisher(s) for short) shall not be liable for any defects that are caused by neglect, misuse or mistreatment by the Customer, including improper installation or testing, or for any products that have been altered or modified in any way by the Customer. Moreover, the publisher(s) shall not be liable for any defects that result from the Customers design, specifications or instructions for such products. Testing and other quality control techniques are used to the extent the publisher(s) deems necessary. </span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Times New Roman,serif';">1.3 The Customer agrees that prior to using any systems that include Open Source VESC® Software, the Customer will test such systems and the functionality of the products as used in such systems. The publisher(s) may provide technical, applications or design advice, quality characterization, reliability data or other services. The Customer acknowledges and agrees that providing these services shall not expand or otherwise alter the publisher(s) warranties, as set forth above, and that no additional obligations or liabilities shall arise from the publisher(s) providing such services. </span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Times New Roman,serif';">1.4 VESC® software products are not authorized for use in safety-critical applications where a failure of the Open Source VESC® software would reasonably be expected to cause severe personal injury or death. Safety-critical applications include, without limitation, life support devices and systems, equipment or systems for the operation of nuclear facilities and weapons systems. Open Source VESC® software is neither designed nor intended for use in military or aerospace applications or environments, nor for automotive applications or the automotive environment. The Customer acknowledges and agrees that any such use of VESC® software is solely at the Customer's risk, and that the Customer is solely responsible for compliance with all legal and regulatory requirements in connection with such use. </span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Times New Roman,serif';">1.5 The Customer acknowledges and agrees that the Customer is solely responsible for compliance with all legal, regulatory and safety-related requirements concerning the products and any use of the publisher(s) softwrae products in the Customer's applications, not withstanding any applications-related information or support that may be provided by the publisher(s). </span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Times New Roman,serif';">2. Limitation of Liability </span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Times New Roman,serif';">IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED THROUGH THE GNU GENERAL PUBLIC LICENSE (GNU GPL), BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. </span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Times New Roman,serif';">This section will survive the termination of the warranty period. </span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Times New Roman,serif';">3. Consequential Damages Waiver.</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Times New Roman,serif';">In no event shall the publisher(s) be liable to the Customer or any third parties for any special, collateral, indirect, punitive, incidental, consequential or exemplary damages in connection with or arising out of the products provided hereunder, regardless of whether the publisher(s) has been advised of the possibility of such damages. </span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Times New Roman,serif';">This section will survive the termination of the warranty period. </span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Times New Roman,serif';">4. Changes to Specifications.</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Times New Roman,serif';">The publisher(s) may make changes to specifications and product descriptions at any time, without notice. The Customer must not rely on the absence or characteristics of any features or instructions marked, reserved or undefined. The publisher(s) reserves these for future definition and shall have no responsibility whatsoever for conflicts or incompatibilities arising from future changes to them. The product information on the Web Site or Materials is subject to change without notice. Do not finalize a design with this information. </span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Times New Roman,serif';">5. Statutory laws. *</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Times New Roman,serif';">(i) some countries, regions, states or provinces do not allow the exclusion or limitation of remedies or of incidental, punitive, or consequential damages, or the applicable time periods, so the above limitations or exclusions may not apply.</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Times New Roman,serif';">(ii) except to the extent lawfully permitted, this limited warranty does not exclude, restrict or modify statutory rights applicable to where the product is sold but, rather, is in addition to these rights.</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Times New Roman,serif';">(*) European Consumer Centres provide information on EU-wide consumer laws as well as consumer laws for specific countries: http://ec.europa.eu/consumers/ecc/contact_en.htm </span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Times New Roman,serif';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Times New Roman,serif';">The LIMITED WARRANTY STATEMENT is released as Creative Commons Attribution ShareAlike 3.0. </span></p> +<p style=" margin-top:0px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Times New Roman,serif';">This means you can use it on your own derived works, in part or completely, as long as you also adopt the same license. You find the complete text of the license at https://creativecommons.org/licenses/by-sa/3.0/legalcode</span></p></body></html> + + LIMITED WARRANTY STATEMENT + + + Conclusion + 0 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">You are now ready to start using VESC Tool. If you have any questions, visit </span></p> +<p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><a href="http://vesc-project.com/forum"><span style=" font-family:'Roboto'; text-decoration: underline; color:#5555ff;">http://vesc-project.com/forum</span></a></p></body></html> + + + + License + 0 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif'; font-weight:600;">GNU GENERAL PUBLIC LICENSE</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">Version 3, 29 June 2007</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">Copyright © 2007 Free Software Foundation, Inc. &lt;</span><a href="https://fsf.org/"><span style=" font-family:'Helvetica, serif'; text-decoration: underline; color:#0000ff;">https://fsf.org/</span></a><span style=" font-family:'Helvetica, serif';">&gt;</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif'; font-weight:600;">Preamble</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">The GNU General Public License is a free, copyleft license for software and other kinds of works.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">The precise terms and conditions for copying, distribution and modification follow.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif'; font-weight:600;">TERMS AND CONDITIONS</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif'; font-weight:600;">0. Definitions.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;">“<span style=" font-family:'Helvetica, serif';">This License” refers to version 3 of the GNU General Public License.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;">“<span style=" font-family:'Helvetica, serif';">Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;">“<span style=" font-family:'Helvetica, serif';">The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">A “covered work” means either the unmodified Program or a work based on the Program.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif'; font-weight:600;">1. Source Code.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">The Corresponding Source for a work in source code form is that same work.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif'; font-weight:600;">2. Basic Permissions.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif'; font-weight:600;">3. Protecting Users' Legal Rights From Anti-Circumvention Law.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif'; font-weight:600;">4. Conveying Verbatim Copies.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif'; font-weight:600;">5. Conveying Modified Source Versions.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;">•<span style=" font-family:'Helvetica, serif';"> a) The work must carry prominent notices stating that you modified it, and giving a relevant date.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;">•<span style=" font-family:'Helvetica, serif';"> b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;">•<span style=" font-family:'Helvetica, serif';"> c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;">•<span style=" font-family:'Helvetica, serif';"> d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif'; font-weight:600;">6. Conveying Non-Source Forms.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;">•<span style=" font-family:'Helvetica, serif';"> a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;">•<span style=" font-family:'Helvetica, serif';"> b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;">•<span style=" font-family:'Helvetica, serif';"> c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;">•<span style=" font-family:'Helvetica, serif';"> d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;">•<span style=" font-family:'Helvetica, serif';"> e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;">“<span style=" font-family:'Helvetica, serif';">Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif'; font-weight:600;">7. Additional Terms.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;">“<span style=" font-family:'Helvetica, serif';">Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;">•<span style=" font-family:'Helvetica, serif';"> a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;">•<span style=" font-family:'Helvetica, serif';"> b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;">•<span style=" font-family:'Helvetica, serif';"> c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;">•<span style=" font-family:'Helvetica, serif';"> d) Limiting the use for publicity purposes of names of licensors or authors of the material; or</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;">•<span style=" font-family:'Helvetica, serif';"> e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;">•<span style=" font-family:'Helvetica, serif';"> f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif'; font-weight:600;">8. Termination.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif'; font-weight:600;">9. Acceptance Not Required for Having Copies.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif'; font-weight:600;">10. Automatic Licensing of Downstream Recipients.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif'; font-weight:600;">11. Patents.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif'; font-weight:600;">12. No Surrender of Others' Freedom.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif'; font-weight:600;">13. Use with the GNU Affero General Public License.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif'; font-weight:600;">14. Revised Versions of this License.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif'; font-weight:600;">15. Disclaimer of Warranty.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif'; font-weight:600;">16. Limitation of Liability.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif'; font-weight:600;">17. Interpretation of Sections 15 and 16.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">END OF TERMS AND CONDITIONS</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif'; font-weight:600;">How to Apply These Terms to Your New Programs</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Courier, serif';">&lt;one line to give the program's name and a brief idea of what it does.&gt;</span><br /><span style=" font-family:'Courier, serif';">Copyright (C) &lt;year&gt; &lt;name of author&gt;</span><br /><br /><span style=" font-family:'Courier, serif';">This program is free software: you can redistribute it and/or modify</span><br /><span style=" font-family:'Courier, serif';">it under the terms of the GNU General Public License as published by</span><br /><span style=" font-family:'Courier, serif';">the Free Software Foundation, either version 3 of the License, or</span><br /><span style=" font-family:'Courier, serif';">(at your option) any later version.</span><br /><br /><span style=" font-family:'Courier, serif';">This program is distributed in the hope that it will be useful,</span><br /><span style=" font-family:'Courier, serif';">but WITHOUT ANY WARRANTY; without even the implied warranty of</span><br /><span style=" font-family:'Courier, serif';">MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the</span><br /><span style=" font-family:'Courier, serif';">GNU General Public License for more details.</span><br /><br /><span style=" font-family:'Courier, serif';">You should have received a copy of the GNU General Public License</span><br /><span style=" font-family:'Courier, serif';">along with this program. If not, see &lt;https://www.gnu.org/licenses/&gt;.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">Also add information on how to contact you by electronic and paper mail.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Courier, serif';">&lt;program&gt; Copyright (C) &lt;year&gt; &lt;name of author&gt;</span><br /><span style=" font-family:'Courier, serif';">This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.</span><br /><span style=" font-family:'Courier, serif';">This is free software, and you are welcome to redistribute it</span><br /><span style=" font-family:'Courier, serif';">under certain conditions; type `show c' for details.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see &lt;</span><a href="https://www.gnu.org/licenses/"><span style=" font-family:'Helvetica, serif'; text-decoration: underline; color:#0000ff;">https://www.gnu.org/licenses/</span></a><span style=" font-family:'Helvetica, serif';">&gt;.</span></p> +<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; line-height:100%;"><span style=" font-family:'Helvetica, serif';">The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read &lt;</span><a href="https://www.gnu.org/licenses/why-not-lgpl.html"><span style=" font-family:'Helvetica, serif'; text-decoration: underline; color:#0000ff;">https://www.gnu.org/licenses/why-not-lgpl.html</span></a><span style=" font-family:'Helvetica, serif';">&gt;.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p></body></html> + + + + + diff --git a/plugins/vesc/runtime/schemas/5.02/parameters_appconf.xml b/plugins/vesc/runtime/schemas/5.02/parameters_appconf.xml new file mode 100644 index 0000000..96277ea --- /dev/null +++ b/plugins/vesc/runtime/schemas/5.02/parameters_appconf.xml @@ -0,0 +1,3626 @@ + + + + + VESC ID + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">VESC ID. Used to identify this VESC on the CAN-bus.</span></p></body></html> + APPCONF_CONTROLLER_ID + 1 + 0 + 255 + 0 + 0 + 1 + 74 + + 1 + + + Timeout + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Switch off the motor when no input has beed received for this amount of time. Notice that VESC Tool will send alive packets while connected, so the timeout won't occur before you disconnect VESC Tool even if the input gets disconnected.</p></body></html> + APPCONF_TIMEOUT_MSEC + 1 + 0 + 30000000 + 0 + 0 + 1 + 1000 + ms + 5 + + + Timeout Brake Current + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Apply brake with this amount of current after a timeout.</p></body></html> + APPCONF_TIMEOUT_BRAKE_CURRENT + 2 + 1 + 0 + 500 + 0 + 0 + 1 + 0 + 1000 + A + 9 + + + Can Status Message Mode + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Send a status message on the CAN bus with a periodic interval. Useful for letting other VESCs know which VESCs are on the CAN-bus. This is required by some apps to function with multiple VESCs. The master VESC of the app does not need this option checked.</span></p></body></html> + APPCONF_SEND_CAN_STATUS + 0 + CAN_STATUS_DISABLED + CAN_STATUS_1 + CAN_STATUS_1_2 + CAN_STATUS_1_2_3 + CAN_STATUS_1_2_3_4 + CAN_STATUS_1_2_3_4_5 + + + Can Status Rate + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Rate at which CAN status messages are sent on the CAN-bus.</span></p></body></html> + APPCONF_SEND_CAN_STATUS_RATE_HZ + 1 + 0 + 10000 + 0 + 0 + 1 + 50 + Hz + 3 + + + CAN Baud Rate + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The baud rate of the CAN-Bus. Note that all devices on the bus must have the same baud rate.</span></p></body></html> + APPCONF_CAN_BAUD_RATE + 2 + CAN_BAUD_125K + CAN_BAUD_250K + CAN_BAUD_500K + CAN_BAUD_1M + CAN_BAUD_10K + CAN_BAUD_20K + CAN_BAUD_50K + CAN_BAUD_75K + CAN_BAUD_100K + + + Pairing Done + 5 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Pairing done flag. If this flag is set, a bluetooth connection can only be made if the VESC Tool instance making the connection has been paired to this VESC. The pairing is done by storing the UUID of the VESC in the pairing list.</span></p></body></html> + APPCONF_PAIRING_DONE + 0 + + + Enable Permanent UART + 5 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Enable the permanent UART port (if the hardware has one). This port can be connected to e.g. the NRF51 for providing a BLE link. You may want to disable this to prevent access to your VESC over BLE.</span></p></body></html> + APPCONF_PERMANENT_UART_ENABLED + 1 + + + Shutdown Mode + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Shutdown mode for hardware that supports it (such as the VESC HD). Determines how the VESC shuts itself off, which eliminates the need for an external switch.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">NOTE:</span> Most VESCs with this feature also support push to start, which means that the VESC will switch on as soon as the motor is turned at a minimum speed.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The available modes are:</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">ALWAYS_OFF</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The VESC power is only determined by the inverted state of the shutdown input.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">ALWAYS_ON</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The VESC always stays on after being powered.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">TOGGLE_BUTTON_ONLY</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">A normally closed (NC) momentary button can be connected to the shutdown input to toggle the power on or off. The VESC will sample the button and determine whether it is pressed, which can be used to shut down after the button is released.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">OFF_AFTER_x</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Same as the TOGGLE_BUTTON_ONLY mode, but the VESC will shut down after X time of inactivity. This mode is useful for setups without any switch at all if the hardware supports push to start, such as the VESC HD.</p></body></html> + APPCONF_SHUTDOWN_MODE + 7 + ALWAYS_OFF + ALWAYS_ON + TOGGLE_BUTTON_ONLY + OFF_AFTER_10S + OFF_AFTER_1M + OFF_AFTER_5M + OFF_AFTER_10M + OFF_AFTER_30M + OFF_AFTER_1H + OFF_AFTER_5H + + + CAN Mode + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">CAN-bus mode.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">VESC</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Default VESC CAN-bus. Required for CAN forwarding and configuring multiple VESCs using VESC Tool.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">UAVCAN</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Basic implementation of UAVCAN. Currently needs some work.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Comm Brigde</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Bridge CAN-bus to commands. Useful for using the VESC as a generic CAN interface.</span></p></body></html> + APPCONF_CAN_MODE + 0 + VESC + UAVCAN + Comm Bridge + + + UAVCAN ESC Index + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">ESC index in UAVCAN messages.</span></p></body></html> + APPCONF_UAVCAN_ESC_INDEX + 1 + 0 + 255 + 0 + 0 + 1 + 0 + + 1 + + + UAVCAN Raw Throttle Mode + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Drive mode for the raw throttle command in UAVCAN.</span></p></body></html> + APPCONF_UAVCAN_RAW_MODE + 0 + Current Control + Current No Reverse Brake + Duty Cycle Control + + + APP to Use + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The APP to use. With multiple VESC connected over CAN only the master needs to have an app to use set up. Notice that using the NRF nunchuk needs the NRF app.</span></p></body></html> + APPCONF_APP_TO_USE + 3 + No App + PPM + ADC + UART + PPM and UART + ADC and UART + Nunchuk (I2C, Nyko Kama) + NRF + Custom User App + Balance + PAS + ADC and PAS + + + Control Type + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Off</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The output is switched off regardless of the input.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Current</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Current control. The output is off when the input is centered. Input less than center brakes until the motor stops, at which point it it starts in the reverse direction.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Current No Reverse</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Current control. The output is off when the input is at minimum.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Current No Reverse With Brake</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Current control. The output is off when the input is centered. Input less than center brakes until the motor stops, but not further.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Duty Cycle</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Current control. The output is off when the input is centered. Input less than center gives negative duty cycle.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Duty Cycle No Reverse</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Duty cycle control. The output is off when the input is at minimum.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">PID Speed Control</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">PID speed control. The output is off when the input is centered. Input less than center gives negative set speed.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">PID Speed Control No Reverse</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Duty cycle control. The output is off when the input is at minimum.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Current Hyst Reverse With Brake</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Current Hyst Reverse With Brake. The output is off when the input is centered. Input less than center brakes until the motor stops, at which point it starts in the reverse direction, but if Max dir switch ERPM is enabled it will stop the reverse when it reaches the Max ERPM for direction switch.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Current Smart Reverse</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Similar to the </span><span style=" font-family:'Roboto'; font-weight:600;">Current No Reverse With Brake </span><span style=" font-family:'Roboto';">mode, but</span><span style=" font-family:'Roboto';"> holding full brake will switch to duty cycle mode in the reverse direction when the speed is so low that not enough brake torque can be produced. This is useful when trying to stop downhill where you normally would roll forwards slowly even at full brake. Instead, the board will start to go reverse slowly in duty cycle mode if this mode is activated.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto'; font-weight:600;"><br /></p></body></html> + APPCONF_PPM_CTRL_TYPE + 0 + Off + Current + Current No Reverse + Current No Reverse With Brake + Duty Cycle + Duty Cycle No Reverse + PID Speed Control + PID Speed Control No Reverse + Current Hyst Reverse With Brake + Current Smart Reverse + + + PID Max ERPM + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The ERPM setpoint corresponding to max input when using PID Speed Control.</p></body></html> + APPCONF_PPM_PID_MAX_ERPM + 2 + 1 + 0 + 1e+06 + 0 + 0 + 100 + 15000 + 1000 + + 9 + + + Input Deadband + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; ;">Deadband region for the input.</span></p></body></html> + APPCONF_PPM_HYST + 0 + 100 + 0 + 1 + 0 + 1 + 1 + 0.15 + 1000 + % + 9 + + + Pulselength Start + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The shortest pulse length for the PPM input </span><span style=" font-family:'Roboto';">in milliseconds</span><span style=" font-family:'Roboto';">. Can be checked by enabling display and giving the minimum input.</span></p></body></html> + APPCONF_PPM_PULSE_START + 4 + 1 + 0 + 100 + 0 + 0 + 0.1 + 1 + 1000 + ms + 9 + + + Pulselength End + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The longest pulse length for the PPM input </span><span style=" font-family:'Roboto';">in milliseconds</span><span style=" font-family:'Roboto';">. Can be checked by enabling display and giving the maximum input.</span></p></body></html> + APPCONF_PPM_PULSE_END + 4 + 1 + 0 + 100 + 0 + 0 + 0.1 + 2 + 1000 + ms + 9 + + + Pulselength Center + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The PPM input in milliseconds at which the throttle is centered. Can be checked by enabling display and leaving the throttle centered. This setting has no effect in control modes where the output is not off when the stick is centered.</span></p></body></html> + APPCONF_PPM_PULSE_CENTER + 4 + 1 + 0 + 100 + 0 + 0 + 0.1 + 1.5 + 1000 + ms + 9 + + + Median Filter + 5 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Use a median filter on the decoded pulses. Will delay the signal slightly, but rejects outliers caused by noise.</p></body></html> + APPCONF_PPM_MEDIAN_FILTER + 1 + + + Safe Start + 5 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Only allow the motor to start if the commanded power has been zero for several cycles after boot, after faults and after configuration updates.</p></body></html> + APPCONF_PPM_SAFE_START + 1 + + + Throttle Expo + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Exponential gain for the throttle.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Zero (0)</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Linear throttle</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Negative (&lt;0)</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The throttle is softer close to 0 and increases exponentially towards full throttle.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Positive (&gt;0)</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The throttle reacts fast around 0 and decreases exponentially towards full throttle.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Increasing the magnitude of this value will increase the exponential effect. The full throttle curve can be seen in the throttle curve plot.</span></p></body></html> + APPCONF_PPM_THROTTLE_EXP + 2 + 1 + 1 + 5 + -5 + 1 + 1 + 0 + 1 + + 9 + + + Throttle Expo Brake + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Exponential gain for the throttle.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Zero (0)</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Linear throttle</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Negative (&lt;0)</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The throttle is softer close to 0 and increases exponentially towards full throttle.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Positive (&gt;0)</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The throttle reacts fast around 0 and decreases exponentially towards full throttle.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Increasing the magnitude of this value will increase the exponential effect. The full throttle curve can be seen in the throttle curve plot.</span></p></body></html> + APPCONF_PPM_THROTTLE_EXP_BRAKE + 2 + 1 + 1 + 5 + -5 + 1 + 1 + 0 + 1 + + 9 + + + Throttle Expo Mode + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The throttle curve mode.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Exponential</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">y = x^(1 + c)</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Natural</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">y = (e^(cx) - 1) / (e^c - 1)</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Polynomial</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">y = x / (1 + c(1 - x))</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">where</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">y:</span> output</p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">x:</span> input</p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">c:</span> curve</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The curve parameter, offsets and signs are mapped accordingly for each mode.</p></body></html> + APPCONF_PPM_THROTTLE_EXP_MODE + 2 + Exponential + Natural + Polynomial + + + Positive Ramping Time + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Positive ramping time constant. This filters the input with ramping. This constant represents the amount of secods it takes to ramp from zero to full output.</span></p></body></html> + APPCONF_PPM_RAMP_TIME_POS + 2 + 1 + 0 + 1000 + 0 + 0 + 0.1 + 0.4 + 1000 + s + 9 + + + Negative Ramping Time + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Negative ramping time constant. This filters the input with ramping. This constant represents the amount of secods it takes to ramp from full output (acceleration or braking) back to zero.</span></p></body></html> + APPCONF_PPM_RAMP_TIME_NEG + 2 + 1 + 0 + 1000 + 0 + 0 + 0.1 + 0.2 + 1000 + s + 9 + + + Multiple VESCs Over CAN + 5 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Listen for other VESCs on the CAN-bus and send the same control commands to them. Notice that the application only has to be set up on the master VESC.</p></body></html> + APPCONF_PPM_MULTI_ESC + 1 + + + Traction Control + 5 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Enable traction control between multiple VESCs connected over CAN-bus. This is only is only used for current control modes.</p></body></html> + APPCONF_PPM_TC + 0 + + + TC Max ERPM Difference + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The ERPM difference at which the fastest motor gets swtiched off completely. If the difference in ERPM is lower than that the current to faster motors is scaled down proportionally to the difference.</p></body></html> + APPCONF_PPM_TC_MAX_DIFF + 2 + 1 + 0 + 100000 + 0 + 0 + 100 + 3000 + 1000 + + 9 + + + Max ERPM for direction switch + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The Max ERPM where the direction can be switched to reverse by braking 2 times.</span></p></body></html> + APPCONF_PPM_MAX_ERPM_FOR_DIR + 2 + 1 + 0 + 100000 + 0 + 0 + 100 + 4000 + 1000 + + 9 + + + Smart Reverse Max Duty Cycle + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Maximum duty cycle to use in smart reverse mode.</span></p></body></html> + APPCONF_PPM_SMART_REV_MAX_DUTY + 3 + 1 + 1 + 1 + 0 + 1 + 0.01 + 0.07 + 1000 + + 9 + + + Smart Reverse Ramp Time + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Time to ramp to maximum duty cycle in smart reverse mode.</span></p></body></html> + APPCONF_PPM_SMART_REV_RAMP_TIME + 2 + 1 + 0 + 100 + 0 + 0 + 0.1 + 3 + 1000 + s + 9 + + + Control Type + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Off</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The output is switched off regardless of the input.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Current</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Current control. The output is off when the input is at minimum.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Current Reverse Center</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Current control. The output is off when the input is centered. Input less than center brakes until the motor stops, at which point it it starts in the reverse direction.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Current Reverse Button</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Current control with a button for reversing the throttle. The output is off when the input is at minimum.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Current Reverse Button Brake ADC2</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Current control with a button for reversing the throttle. The output is off when the input is at minimum. The second ADC channel acs as a brake.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">ADC_CTRL_TYPE_CURRENT_REV_BUTTON_BRAKE_CENTER</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Current control with a button for reversing throttle. The output is off when the input is centered. Input less than center brakes until the motor stops, but not further.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Current No Reverse Brake Center</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Current control. The output is off when the input is centered. Input less than center brakes until the motor stops, but not further.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Current No Reverse Brake Button</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Current control with a button for turning the throttle into a brake. The output is off when the input is at minimum.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Current No Reverse Brake ADC2</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Current control with one separate throttle connected to ADC2 for braking.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Duty Cycle</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Duty cycle control. The output is off when the input is at minimum.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Duty Cycle Reverse Center</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Current control. The output is off when the input is centered. Input less than center gives negative duty cycle.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Duty Cycle Reverse Button</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Duty cycle control with a button on UART RX for inverting the throttle. The output is off when the input is at minimum.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">PID Speed</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">PID speed control. The speed setpoint is mapped between 0 and the configured maximum motor speed limit.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">PID Speed Reverse Center</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">PID speed control. The output is mapped between the minimum and maximum motor speed limits. Throttle center corresponds to 0 speed.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">PID Speed Reverse Button</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">PID speed control with a button for reversing the throttle. The speed setpoint is mapped between 0 and the configured maximum motor speed limit, or between 0 and the minimum motor speed limit when the UART RX input is high.</p></body></html> + APPCONF_ADC_CTRL_TYPE + 8 + Off + Current + Current Reverse Center + Current Reverse Button + Current Reverse ADC2 Brake Button + Current Reverse Button Brake Center + Current No Reverse Brake Center + Current No Reverse Brake Button + Current No Reverse Brake ADC2 + Duty Cycle + Duty Cycle Reverse Center + Duty Cycle Reverse Button + PID Speed + PID Speed Reverse Center + PID Speed Reverse Button + + + Input Deadband + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Deadband region for the input.</span></p></body></html> + APPCONF_ADC_HYST + 0 + 100 + 0 + 1 + 0 + 1 + 1 + 0.05 + 1000 + % + 9 + + + ADC1 Min Voltage + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" ;">Input voltage at the start of the throttle range for ADC1. Can be checked by enabling display and giving the minimum input. If </span><span style=" ; font-weight:600;">Control Type</span><span style=" ;"> is set to off while doing that the motor won't turn.</span></p></body></html> + APPCONF_ADC_VOLTAGE_START + 2 + 1 + 0 + 3.3 + 0 + 1 + 0.01 + 0.6 + 1000 + V + 9 + + + ADC1 Max Voltage + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" ;">Input voltage at the end of the throttle range for ADC1. Can be checked by enabling display and giving the maximum input. If </span><span style=" ; font-weight:600;">Control Type</span><span style=" ;"> is set to off while doing that the motor won't turn.</span></p></body></html> + APPCONF_ADC_VOLTAGE_END + 2 + 1 + 0 + 3.3 + 0 + 1 + 0.01 + 2.54 + 1000 + V + 9 + + + ADC1 Center Voltage + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Input voltage at the center of the throttle range for ADC1. Can be checked by enabling display and centering the input. If <span style=" font-weight:600;">Control Type</span> is set to off while doing that the motor won't turn.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Notice that this parameter only is used for the contered control types. For the other types the voltage will always be mapped linearly between start and end.</p></body></html> + APPCONF_ADC_VOLTAGE_CENTER + 2 + 1 + 0 + 3.3 + 0 + 1 + 0.01 + 0.6 + 1000 + V + 9 + + + ADC2 Min Voltage + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Input voltage at the start of the throttle range for ADC2. Can be checked by enabling display and giving the minimum input. If <span style=" font-weight:600;">Control Type</span> is set to off while doing that the motor won't turn.</p></body></html> + APPCONF_ADC_VOLTAGE2_START + 2 + 1 + 0 + 3.3 + 0 + 1 + 0.01 + 0 + 1000 + V + 9 + + + ADC2 Max Voltage + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Input voltage at the end of the throttle range for ADC2. Can be checked by enabling display and giving the maximum input. If <span style=" font-weight:600;">Control Type</span> is set to off while doing that the motor won't turn.</p></body></html> + APPCONF_ADC_VOLTAGE2_END + 2 + 1 + 0 + 3.3 + 0 + 1 + 0.01 + 2 + 1000 + V + 9 + + + Use Filter + 5 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Use a median filter to reject noise. This will introduce a slight delay.</p></body></html> + APPCONF_ADC_USE_FILTER + 1 + + + Safe Start + 5 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Only allow the motor to start if the commanded power has been zero for several cycles after boot, after faults and after configuration updates.</p></body></html> + APPCONF_ADC_SAFE_START + 1 + + + Invert Cruise Control Button + 5 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Invert the cruise control button. For supporting both normally-closed and normally-open buttons.</p></body></html> + APPCONF_ADC_CC_BUTTON_INVERTED + 1 + + + Invert Reverse Button + 5 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Invert the reverse button. For supporting both normally-closed and normally-open buttons.</p></body></html> + APPCONF_ADC_REV_BUTTON_INVERTED + 0 + + + Invert ADC1 Voltage + 5 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Invert the voltage from ADC1.</span></p></body></html> + APPCONF_ADC_VOLTAGE_INVERTED + 0 + + + Invert ADC2 Voltage + 5 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Invert the voltage from ADC2.</span></p></body></html> + APPCONF_ADC_VOLTAGE2_INVERTED + 1 + + + Throttle Expo + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Exponential gain for the throttle.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Zero (0)</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Linear throttle</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Negative (&lt;0)</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The throttle is softer close to 0 and increases exponentially towards full throttle.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Positive (&gt;0)</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The throttle reacts fast around 0 and decreases exponentially towards full throttle.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Increasing the magnitude of this value will increase the exponential effect. The full throttle curve can be seen in the throttle curve plot.</span></p></body></html> + APPCONF_ADC_THROTTLE_EXP + 2 + 1 + 1 + 5 + -5 + 1 + 1 + -0.5 + 1 + + 9 + + + Throttle Expo Brake + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Exponential gain for the throttle.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Zero (0)</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Linear throttle</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Negative (&lt;0)</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The throttle is softer close to 0 and increases exponentially towards full throttle.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Positive (&gt;0)</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The throttle reacts fast around 0 and decreases exponentially towards full throttle.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Increasing the magnitude of this value will increase the exponential effect. The full throttle curve can be seen in the throttle curve plot.</span></p></body></html> + APPCONF_ADC_THROTTLE_EXP_BRAKE + 2 + 1 + 1 + 5 + -5 + 1 + 1 + 0 + 1 + + 9 + + + Throttle Expo Mode + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The throttle curve mode.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Exponential</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">y = x^(1 + c)</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Natural</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">y = (e^(cx) - 1) / (e^c - 1)</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Polynomial</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">y = x / (1 + c(1 - x))</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">where</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">y:</span> output</p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">x:</span> input</p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">c:</span> curve</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The curve parameter, offsets and signs are mapped accordingly for each mode.</p></body></html> + APPCONF_ADC_THROTTLE_EXP_MODE + 2 + Exponential + Natural + Polynomial + + + Positive Ramping Time + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Positive ramping time constant. This filters the input with ramping. This constant represents the amount of secods it takes to ramp from zero to full output.</span></p></body></html> + APPCONF_ADC_RAMP_TIME_POS + 2 + 1 + 0 + 1000 + 0 + 0 + 0.1 + 0.3 + 1000 + s + 9 + + + Negative Ramping Time + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Negative ramping time constant. This filters the input with ramping. This constant represents the amount of secods it takes to ramp from full output (acceleration or braking) back to zero.</span></p></body></html> + APPCONF_ADC_RAMP_TIME_NEG + 2 + 1 + 0 + 1000 + 0 + 0 + 0.1 + 0.1 + 1000 + s + 9 + + + Multiple VESCs Over CAN + 5 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Listen for other VESCs on the CAN-bus and send the same control commands to them. Notice that the application only has to be set up on the master VESC.</p></body></html> + APPCONF_ADC_MULTI_ESC + 1 + + + Traction Control + 5 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Enable traction control between multiple VESCs connected over CAN-bus. This is only is only used for current control modes.</p></body></html> + APPCONF_ADC_TC + 0 + + + TC Max ERPM Difference + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The ERPM difference at which the fastest motor gets swtiched off completely. If the difference in ERPM is lower than that the current to faster motors is scaled down proportionally to the difference.</p></body></html> + APPCONF_ADC_TC_MAX_DIFF + 2 + 1 + 0 + 100000 + 0 + 0 + 100 + 3000 + 1000 + + 9 + + + Update Rate + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Rate at which the input is sampled.</p></body></html> + APPCONF_ADC_UPDATE_RATE_HZ + 1 + 0 + 100000 + 0 + 0 + 10 + 500 + Hz + 3 + + + Baudrate + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">UART Baudrate.</p></body></html> + APPCONF_UART_BAUDRATE + 1 + 0 + 20000000 + 0 + 0 + 1 + 115200 + bps + 5 + + + Control Type + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Off</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The output is switched off regardless of the input.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Current</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Current control. The output is off when the joystick is centered. Positive input gives acceleration and negative input braking. To go reverse the Z button can be used to toggle direction.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Current No Reverse</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Current control. The output is off when the joystick is centered. Positive input gives acceleration and negative input braking. The reverse function of the Z button is disabled.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Current Bidirectional</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Current control. The output is off when the joystick is centered. Positive input always gives forward current and negative current always gives reverse current. This means that when current is applied through 0 speed, the motor will accelerate in the other direction.</span></p></body></html> + APPCONF_CHUK_CTRL_TYPE + 1 + Off + Current + Current No Reverse + Current Bidirectional + + + Input Deadband + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Deadband region for the input.</span></p></body></html> + APPCONF_CHUK_HYST + 0 + 100 + 0 + 1 + 0 + 1 + 1 + 0.15 + 1000 + % + 9 + + + Positive Ramping Time + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Positive ramping time constant. This filters the joystick input with ramping. This constant represents the amount of secods it takes to ramp from zero to full output.</p></body></html> + APPCONF_CHUK_RAMP_TIME_POS + 2 + 1 + 0 + 1000 + 0 + 0 + 0.1 + 0.4 + 1000 + s + 9 + + + Negative Ramping Time + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Negative ramping time constant. This filters the joystick input with ramping. This constant represents the amount of secods it takes to ramp from full output (acceleration or braking) back to zero.</p></body></html> + APPCONF_CHUK_RAMP_TIME_NEG + 2 + 1 + 0 + 1000 + 0 + 0 + 0.1 + 0.2 + 1000 + s + 9 + + + ERPM Per Second Cruise Control + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The amount of ERPM per second the setpoint changes when giving full joystick input with criuse control activated.</p></body></html> + APPCONF_STICK_ERPM_PER_S_IN_CC + 2 + 1 + 0 + 1e+06 + 0 + 0 + 500 + 3000 + 1000 + + 9 + + + Throttle Expo + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Exponential gain for the throttle.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Zero (0)</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Linear throttle</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Negative (&lt;0)</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The throttle is softer close to 0 and increases exponentially towards full throttle.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Positive (&gt;0)</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The throttle reacts fast around 0 and decreases exponentially towards full throttle.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Increasing the magnitude of this value will increase the exponential effect. The full throttle curve can be seen in the throttle curve plot.</span></p></body></html> + APPCONF_CHUK_THROTTLE_EXP + 2 + 1 + 1 + 5 + -5 + 1 + 1 + 0 + 1 + + 9 + + + Throttle Expo Brake + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Exponential gain for the throttle.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Zero (0)</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Linear throttle</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Negative (&lt;0)</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The throttle is softer close to 0 and increases exponentially towards full throttle.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Positive (&gt;0)</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The throttle reacts fast around 0 and decreases exponentially towards full throttle.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Increasing the magnitude of this value will increase the exponential effect. The full throttle curve can be seen in the throttle curve plot.</span></p></body></html> + APPCONF_CHUK_THROTTLE_EXP_BRAKE + 2 + 1 + 1 + 5 + -5 + 1 + 1 + 0 + 1 + + 9 + + + Throttle Expo Mode + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The throttle curve mode.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Exponential</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">y = x^(1 + c)</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Natural</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">y = (e^(cx) - 1) / (e^c - 1)</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Polynomial</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">y = x / (1 + c(1 - x))</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">where</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">y:</span> output</p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">x:</span> input</p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">c:</span> curve</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The curve parameter, offsets and signs are mapped accordingly for each mode.</p></body></html> + APPCONF_CHUK_THROTTLE_EXP_MODE + 2 + Exponential + Natural + Polynomial + + + Multiple VESCs Over CAN + 5 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Listen for other VESCs on the CAN-bus and send the same control commands to them. Notice that the application only has to be set up on the master VESC.</p></body></html> + APPCONF_CHUK_MULTI_ESC + 1 + + + Traction Control + 5 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Enable traction control between multiple VESCs connected over CAN-bus. This is only is only used for current control modes.</p></body></html> + APPCONF_CHUK_TC + 0 + + + TC Max ERPM Difference + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The ERPM difference at which the fastest motor gets swtiched off completely. If the difference in ERPM is lower than that the current to faster motors is scaled down proportionally to the difference.</p></body></html> + APPCONF_CHUK_TC_MAX_DIFF + 2 + 1 + 0 + 100000 + 0 + 0 + 100 + 3000 + 1000 + + 9 + + + Use Smart Reverse + 5 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Use smart reverse function. If enabled, holding full brake will switch to duty cycle mode in the reverse direction when the speed is so low that not enough brake torque can be produced.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">This is useful when trying to stop downhill where you normally would roll forwards slowly even at full brake. Instead, the board will start to go reverse slowly in duty cycle mode if this mode is activated.</span></p></body></html> + APPCONF_CHUK_USE_SMART_REV + 1 + + + Smart Reverse Max Duty Cycle + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Maximum duty cycle to use in smart reverse mode.</span></p></body></html> + APPCONF_CHUK_SMART_REV_MAX_DUTY + 3 + 1 + 1 + 1 + 0 + 1 + 0.01 + 0.07 + 1000 + + 9 + + + Smart Reverse Ramp Time + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Time to ramp to maximum duty cycle in smart reverse mode.</span></p></body></html> + APPCONF_CHUK_SMART_REV_RAMP_TIME + 2 + 1 + 0 + 100 + 0 + 0 + 0.1 + 3 + 1000 + s + 9 + + + Speed + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The air bit rate.</p></body></html> + APPCONF_NRF_SPEED + 1 + 250 Kbit/s + 1 MBit/s + 2 MBit/s + + + TX Power + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Transmit power or power off setting.</p></body></html> + APPCONF_NRF_POWER + 3 + -18 dBm + -12 dBm + -6 dBm + 0 dBm + OFF + + + CRC + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">CRC checksum type.</p></body></html> + APPCONF_NRF_CRC + 1 + Disabled + 1 Byte + 2 Byte + + + Retry Delay + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Delay between retries when no ack is received. If the speed is lower than 2MBit, at least 500 µS should be used.</span></p></body></html> + APPCONF_NRF_RETR_DELAY + 0 + 250 µS + 500 µS + 750 µS + 1000 µS + 1250 µS + 1500 µS + 1750 µS + 2000 µS + 2250 µS + 2500 µS + 2750 µS + 3000 µS + 3250 µS + 3500 µS + 3750 µS + 4000 µS + + + Retries + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Maximum number of retries when no ack is received before giving up on the current packet.</p></body></html> + APPCONF_NRF_RETRIES + 1 + 0 + 15 + 0 + 0 + 1 + 3 + + 2 + + + Radio Channel + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Radio channel.</p></body></html> + APPCONF_NRF_CHANNEL + 1 + 0 + 125 + 0 + 0 + 1 + 76 + + 2 + + + Address 0 + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Address byte 0.</p></body></html> + APPCONF_NRF_ADDR_B0 + 1 + 0 + 255 + 0 + 0 + 1 + 198 + + 1 + + + Address 1 + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Address byte 1.</p></body></html> + APPCONF_NRF_ADDR_B1 + 1 + 0 + 255 + 0 + 0 + 1 + 199 + + 1 + + + Address 2 + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Address byte 2.</p></body></html> + APPCONF_NRF_ADDR_B2 + 1 + 0 + 255 + 0 + 0 + 1 + 0 + + 1 + + + Send ACK + 5 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Send ACK when valid packets are received.</p></body></html> + APPCONF_NRF_SEND_CRC_ACK + 1 + + + P + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">P value for the PID balance loop.</p></body></html> + APPCONF_BALANCE_KP + 4 + 1 + 0 + 1e+06 + 0 + 0 + 0.1 + 0 + 1000 + + 9 + + + I + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">I value for the PID balance loop.</p></body></html> + APPCONF_BALANCE_KI + 4 + 1 + 0 + 1e+06 + 0 + 0 + 0.1 + 0 + 1000 + + 9 + + + D + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">D value for the PID balance loop.</p></body></html> + APPCONF_BALANCE_KD + 4 + 1 + 0 + 1e+06 + 0 + 0 + 0.1 + 0 + 1000 + + 9 + + + Loop Hertz + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Loop Hertz.</p></body></html> + APPCONF_BALANCE_HERTZ + 1 + 0 + 4000 + 50 + 0 + 100 + 1000 + Hz + 3 + + + Pitch Axis Fault Cutoff + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Angle to turn off driving (on the pitch axis).</span></p></body></html> + APPCONF_BALANCE_FAULT_PITCH + 1 + 1 + 0 + 180 + -180 + 0 + 1 + 20 + 1000 + ° + 9 + + + Roll Axis Fault Cutoff + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Angle to turn off driving (on the roll axis).</span></p></body></html> + APPCONF_BALANCE_FAULT_ROLL + 1 + 1 + 0 + 180 + -180 + 0 + 1 + 45 + 1000 + ° + 9 + + + Duty Cycle Fault Cutoff + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Duty cycle value to trigger a safety cutoff 0-1% (This cutoff will lock the app untill another fault occurs).</span></p></body></html> + APPCONF_BALANCE_FAULT_DUTY + 2 + 1 + 0 + 1 + 0 + 0 + 0.01 + 0.9 + 1000 + + 9 + + + ADC1 Switch Voltage + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Voltage below this value will trigger a fault. To disable this switch set this value to 0. Hint: consider a pulldown resisitor!</span></p></body></html> + APPCONF_BALANCE_FAULT_ADC1 + 2 + 1 + 0 + 3.3 + 0 + 1 + 0.1 + 0 + 1000 + V + 9 + + + ADC2 Switch Voltage + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Voltage below this value will trigger a fault. To disable this switch set this value to 0. Hint: consider a pulldown resisitor!</span></p></body></html> + APPCONF_BALANCE_FAULT_ADC2 + 2 + 1 + 0 + 3.3 + 0 + 1 + 0.1 + 0 + 1000 + V + 9 + + + Pitch Fault Delay + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Pitch fault cutoff time delay in ms.</p></body></html> + APPCONF_BALANCE_FAULT_DELAY_PITCH + 1 + 0 + 10000 + 0 + 0 + 10 + 0 + ms + 3 + + + Roll Fault Delay + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Roll fault cutoff time delay in ms.</p></body></html> + APPCONF_BALANCE_FAULT_DELAY_ROLL + 1 + 0 + 10000 + 0 + 0 + 10 + 0 + ms + 3 + + + Duty Fault Delay + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Duty cycle cutoff time delay in ms.</p></body></html> + APPCONF_BALANCE_FAULT_DELAY_DUTY + 1 + 0 + 10000 + 0 + 0 + 10 + 0 + ms + 3 + + + Half Switch Fault Delay + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Half switch cutoff time delay in ms.</p></body></html> + APPCONF_BALANCE_FAULT_DELAY_SWITCH_HALF + 1 + 0 + 10000 + 0 + 0 + 10 + 0 + ms + 3 + + + Full Switch Fault Delay + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Full switch cutoff time delay in ms.</p></body></html> + APPCONF_BALANCE_FAULT_DELAY_SWITCH_FULL + 1 + 0 + 10000 + 0 + 0 + 10 + 0 + ms + 3 + + + ADC Half State Fault ERPM + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">ERPM (absoulte value) below which a half state on the ADC switches will be considered a fault.</p></body></html> + APPCONF_BALANCE_FAULT_ADC_HALF_ERPM + 1 + 0 + 100000 + 0 + 0 + 10 + 1000 + ERPM + 3 + + + Tiltback Angle + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Angle of rise for tiltback.</p></body></html> + APPCONF_BALANCE_TILTBACK_ANGLE + 1 + 1 + 0 + 45 + 0 + 0 + 0.1 + 15 + 1000 + ° + 9 + + + Tiltback Speed + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Speed at which tiltback is applied (High speed tiltback can be dangerous!).</p></body></html> + APPCONF_BALANCE_TILTBACK_SPEED + 1 + 1 + 0 + 100 + 0 + 0 + 0.1 + 5 + 1000 + °/s + 9 + + + Duty Cycle Tiltback + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Duty cycle value to trigger a safety tiltback (Tiltback raises the nose of the vehicle informing you to slow down).</p></body></html> + APPCONF_BALANCE_TILTBACK_DUTY + 2 + 1 + 0 + 1 + 0 + 0 + 0.01 + 0.75 + 1000 + + 9 + + + High Voltage Tiltback + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">High voltage value to trigger a safety tiltback (Tiltback raises the nose of the vehicle informing you to slow down).</p></body></html> + APPCONF_BALANCE_TILTBACK_HIGH_V + 2 + 1 + 0 + 700 + 0 + 0 + 0.01 + 100 + 1000 + V + 9 + + + Low Voltage Tiltback + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Low voltage value to trigger a safety tiltback (Tiltback raises the nose of the vehicle informing you to slow down).</p></body></html> + APPCONF_BALANCE_TILTBACK_LOW_V + 2 + 1 + 0 + 700 + 0 + 0 + 0.01 + 0 + 1000 + V + 9 + + + Constant Tiltback + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Tiltback that will be applied above 3% duty cycle. AKA nose angle adjustment, can be downwards too.</p></body></html> + APPCONF_BALANCE_TILTBACK_CONSTANT + 2 + 1 + 0 + 80 + -80 + 0 + 1 + 0 + 1 + ° + 9 + + + Constant Tiltback ERPM + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; APPCONF_BALANCE_FAULT_ADC_HALF_ERPMmargin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">ERPM (absoulte value) above which constant tiltback will be applied.</p></body></html> + APPCONF_BALANCE_TILTBACK_CONSTANT_ERPM + 1 + 0 + 100000 + 200 + 0 + 100 + 500 + ERPM + 3 + + + Startup Pitch Axis Angle Tolerance + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Angle at which balancing will start (on the main axis). Measured in degrees from upright (0).</span></p></body></html> + APPCONF_BALANCE_STARTUP_PITCH_TOLERANCE + 1 + 1 + 0 + 80 + 0 + 0 + 0.1 + 20 + 1000 + ° + 9 + + + Startup Roll Axis Angle Tolerance + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Angle at which balancing will start (on the cross axis). Measured in degrees from upright (0).</span></p></body></html> + APPCONF_BALANCE_STARTUP_ROLL_TOLERANCE + 1 + 1 + 0 + 80 + 0 + 0 + 0.1 + 8 + 1000 + ° + 9 + + + Startup Centering Speed + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Speed at which wheel will center itself on startup.</p></body></html> + APPCONF_BALANCE_STARTUP_SPEED + 1 + 1 + 0 + 100 + 0 + 0 + 0.1 + 30 + 1000 + °/s + 9 + + + Deadzone + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Deadzone disables balancing at center.</p></body></html> + APPCONF_BALANCE_DEADZONE + 2 + 1 + 0 + 5 + 0 + 0 + 0.01 + 0 + 1000 + ° + 9 + + + Current Boost + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">All non-zero current output values will be boosted.</p></body></html> + APPCONF_BALANCE_CURRENT_BOOST + 2 + 1 + 0 + 10 + 0 + 0 + 0.01 + 0 + 1000 + A + 9 + + + Multiple VESCs Over CAN + 5 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Listen for other VESCs on the CAN-bus and send the same control commands to them. Notice that the application only has to be set up on the master VESC.</p></body></html> + APPCONF_BALANCE_MULTI_ESC + 0 + + + Yaw P + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">P value for yaw PID stabilization.</p></body></html> + APPCONF_BALANCE_YAW_KP + 3 + 1 + 0 + 10000 + -10000 + 0 + 0.01 + 0 + 1000 + + 9 + + + Yaw I + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">I value for yaw PID stabilization.</p></body></html> + APPCONF_BALANCE_YAW_KI + 3 + 1 + 0 + 10000 + -10000 + 0 + 0.01 + 0 + 1000 + + 9 + + + Yaw D + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">D value for yaw PID stabilization.</p></body></html> + APPCONF_BALANCE_YAW_KD + 3 + 1 + 0 + 10000 + -10000 + 0 + 0.01 + 0 + 1000 + + 9 + + + Roll Steer KP + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Roll angle to yaw setpoint adjustment proportion. This is a constant turning speed regardless of forward travel speed. It will turn tighter at low speeds</p></body></html> + APPCONF_BALANCE_ROLL_STEER_KP + 3 + 1 + 0 + 10000 + -10000 + 0 + 0.01 + 0 + 1000 + + 9 + + + Roll Steer ERPM KP + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Roll angle multiplied by ERPM to yaw setpoint adjustment proportion. Scaling turn speed by erpm will give a constant turning radius at all speeds, like a normal vehicle.</p></body></html> + APPCONF_BALANCE_ROLL_STEER_ERPM_KP + 5 + 1 + 0 + 10000 + -10000 + 0 + 0.0001 + 0 + 1000 + + 9 + + + Brake Current + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Breaking current to be applied when balance app is not actively balancing.</p></body></html> + APPCONF_BALANCE_BRAKE_CURRENT + 2 + 1 + 0 + 100 + 0 + 0 + 0.01 + 0 + 1000 + A + 9 + + + Yaw Current Clamp + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Maximum current to be applied to yaw motions. This lets you overpower the pid traction.</p></body></html> + APPCONF_BALANCE_YAW_CURRENT_CLAMP + 2 + 1 + 0 + 100 + 0 + 0 + 0.01 + 0 + 1000 + A + 9 + + + Setpoint Pitch Low Pass Filter + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Low pass filter that combines the pitch angle with the desired balanceing angle. 0 = 100% setpoint, 1 = 100% current pitch angle.</p></body></html> + APPCONF_BALANCE_SETPOINT_PITCH_FILTER + 5 + 1 + 0 + 1 + 0 + 0 + 0.0001 + 0 + 1000 + + 9 + + + Setpoint Target Low Pass Filter + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Low pass filter that combines the desired setpoint (0 or tiltback) with the current setpoint (modified by the setpoint pitch filter). 0 = 100% current setpoint angle, 1 = 100% desired setpoint. Non 1 values will effect your tiltback speed</p></body></html> + APPCONF_BALANCE_SETPOINT_TARGET_FILTER + 5 + 1 + 0 + 1 + 0 + 0 + 0.0001 + 1 + 1000 + + 9 + + + Setpoint Filter Clamp + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Maximum angle (absolute value) the setpoint can travel to. There will be no filtering past this angle.</p></body></html> + APPCONF_BALANCE_SETPOINT_FILTER_CLAMP + 2 + 1 + 0 + 80 + 0 + 0 + 1 + 8 + 1 + ° + 9 + + + D term PT1 Filter + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">D term filter above this frequency. 0 = Disabled.</p></body></html> + APPCONF_BALANCE_KD_PT1_FREQUENCY + 1 + 0 + 4000 + 0 + 0 + 10 + 0 + Hz + 3 + + + Control Type + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Off</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The output is switched off regardless of the input.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Cadence</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Cadence control. The output is proportional to the pedalling speed, off when there is no pedalling.</p></body></html> + APPCONF_PAS_CTRL_TYPE + 1 + Off + Cadence + + + Sensor Type + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Quadrature</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">This interface provides 2 signals that can be decoded to know the pedalling direction (forward of backwards).</p></body></html> + APPCONF_PAS_SENSOR_TYPE + 0 + Quadrature + + + Pedal RPM Start + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Pedal RPM at which the assist starts. Below this value the output current is zero.</p></body></html> + APPCONF_PAS_PEDAL_RPM_START + 1 + 1 + 0 + 200 + 1 + 0 + 1 + 10 + 10 + + 7 + + + Pedal RPM End + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Pedal RPM at which the assist stops increasing. Above this pedal speed the assist output will stay at its maximum.</p></body></html> + APPCONF_PAS_PEDAL_RPM_END + 1 + 1 + 0 + 300 + 1 + 0 + 1 + 120 + 10 + + 7 + + + Invert Pedal Direction + 5 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Inverts pedal direction</p></body></html> + APPCONF_PAS_INVERT_PEDAL_DIRECTION + 0 + + + Sensor Magnets + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">How many magnets the PAS sensor assembly has. 24 magnets would provide 24 pulses per pedal revolution.</p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">12 and 24 magnet setups are typical.</p></body></html> + APPCONF_PAS_MAGNETS + 1 + 0 + 128 + 6 + 0 + 6 + 24 + + 3 + + + Use Filter + 5 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Use a low pass filter in the PAS input signal</p></body></html> + APPCONF_PAS_USE_FILTER + 1 + + + PAS Max Current + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Maximum PAS output current will be limited to this percentage of the global output current.</p></body></html> + APPCONF_PAS_CURRENT_SCALING + 2 + 1 + 1 + 1 + 0 + 1 + 0.05 + 0.08 + 1000 + + 7 + + + Positive Ramping Time + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Positive ramping time constant. This filters the PAS input with ramping and represents the amount of secods it takes to ramp from zero to full output.</span></p></body></html> + APPCONF_PAS_RAMP_TIME_POS + 2 + 1 + 0 + 5 + 0.2 + 0 + 0.05 + 0.3 + 100 + s + 7 + + + Negative Ramping Time + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Negative ramping time constant. This filters the PAS input with ramping and represents the amount of secods it takes to ramp from full to zero output.</span></p></body></html> + APPCONF_PAS_RAMP_TIME_NEG + 2 + 1 + 0 + 5 + 0.2 + 0 + 0.05 + 0.2 + 100 + s + 7 + + + Update Rate + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Frequency at which the PAS control loop is executed</span></p></body></html> + APPCONF_PAS_UPDATE_RATE_HZ + 1 + 0 + 1000 + 10 + 0 + 10 + 500 + Hz + 3 + + + IMU Type + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">IMU type. The internal IMU is only available if the hardware supports it. External IMUs can be connected to the SDA and SCL pins. If using an external IMU, make sure that no app that uses the same pins is selected.</p></body></html> + APPCONF_IMU_TYPE + 1 + IMU_TYPE_OFF + IMU_TYPE_INTERNAL + IMU_TYPE_EXTERNAL_MPU9X50 + IMU_TYPE_EXTERNAL_ICM20948 + IMU_TYPE_EXTERNAL_BMI160 + IMU_TYPE_EXTERNAL_LSM6DS3 + + + IMU AHRS Mode + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Use the Madgwick or Mahony AHRS filter.</p></body></html> + APPCONF_IMU_AHRS_MODE + 0 + AHRS_MODE_MADGWICK + AHRS_MODE_MAHONY + + + Sample Rate + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">IMU sample rate. Higher sample rates use more CPU cycles, but perform better.</p></body></html> + APPCONF_IMU_SAMPLE_RATE_HZ + 1 + 0 + 1000 + 1 + 0 + 10 + 200 + Hz + 3 + + + Accelerometer Confidence Decay + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">This factor sets how fast the accelerometer confidence will be decreased if the acceleration vector differs from 1.0.</p></body></html> + APPCONF_IMU_ACCEL_CONFIDENCE_DECAY + 3 + 1 + 0 + 999 + 0 + 0 + 0.1 + 1 + 1 + + 9 + + + Mahony KP + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">KP for Mahony filter. Decides how much the accelerometer is used for attitude estimation. Increasing this value helps against gyro offsets, but makes the output noisier.</p></body></html> + APPCONF_IMU_MAHONY_KP + 3 + 1 + 0 + 999 + 0 + 0 + 0.1 + 0.3 + 1 + + 9 + + + Mahony KI + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">KI for Mahony filter. Integrates gyro offsets over time.</p></body></html> + APPCONF_IMU_MAHONY_KI + 3 + 1 + 0 + 999 + 0 + 0 + 0.1 + 0 + 1 + + 9 + + + Madgwick Beta + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Beta for Madgwick filter. Decides how much the accelerometer is used for attitude estimation. Increasing this value helps against gyro offsets, but makes the output noisier.</p></body></html> + APPCONF_IMU_MADGWICK_BETA + 3 + 1 + 0 + 999 + 0 + 0 + 0.01 + 0.1 + 1 + + 9 + + + Imu Rotation Roll + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Roll rotation of IMU. Can be adjusted if the IMU is not aligned with the vehicle.</p></body></html> + APPCONF_IMU_ROT_ROLL + 3 + 1 + 0 + 360 + -360 + 0 + 1 + 0 + 1 + ° + 9 + + + Imu Rotation Pitch + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Pitch rotation of IMU. Can be adjusted if the IMU is not aligned with the vehicle.</p></body></html> + APPCONF_IMU_ROT_PITCH + 3 + 1 + 0 + 360 + -360 + 0 + 1 + 0 + 1 + ° + 9 + + + Imu Rotation Yaw + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Yaw rotation of IMU. Can be adjusted if the IMU is not aligned with the vehicle.</p></body></html> + APPCONF_IMU_ROT_YAW + 3 + 1 + 0 + 360 + -360 + 0 + 1 + 0 + 1 + ° + 9 + + + Accel Offset X + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Accelerometer offset X.</p></body></html> + APPCONF_IMU_A_OFFSET_0 + 3 + 1 + 0 + 16 + -16 + 0 + 0.01 + 0 + 1 + G + 9 + + + Accel Offset Y + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Accelerometer offset Y.</p></body></html> + APPCONF_IMU_A_OFFSET_1 + 3 + 1 + 0 + 16 + -16 + 0 + 0.01 + 0 + 1 + G + 9 + + + Accel Offset Z + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Accelerometer offset Z.</p></body></html> + APPCONF_IMU_A_OFFSET_2 + 3 + 1 + 0 + 16 + -16 + 0 + 0.01 + 0 + 1 + G + 9 + + + Gyro Offset X + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Gyro offset (drift) X.</p></body></html> + APPCONF_IMU_G_OFFSET_0 + 3 + 1 + 0 + 1000 + -1000 + 0 + 0.01 + 0 + 1 + °/s + 9 + + + Gyro Offset Y + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Gyro offset (drift) Y.</p></body></html> + APPCONF_IMU_G_OFFSET_1 + 3 + 1 + 0 + 1000 + -1000 + 0 + 0.01 + 0 + 1 + °/s + 9 + + + Gyro Offset Z + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Gyro offset (drift) Z.</p></body></html> + APPCONF_IMU_G_OFFSET_2 + 3 + 1 + 0 + 1000 + -1000 + 0 + 0.01 + 0 + 1 + °/s + 9 + + + Gyro Offset Comp X + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Gyro offset compensation for X axis. Setting this value to a positive number will integrate the gyro offset towards the current gyro value with this rate. This is useful in order to remove gyro bias on axes that do not rotate on average, such as roll and pitch on most applications.</p></body></html> + APPCONF_IMU_G_OFFSET_COMP_FACT_0 + 4 + 1 + 0 + 1 + 0 + 0 + 0.001 + 0 + 1 + °/s + 9 + + + Gyro Offset Comp Y + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Gyro offset compensation for Y axis. Setting this value to a positive number will integrate the gyro offset towards the current gyro value with this rate. This is useful in order to remove gyro bias on axes that do not rotate on average, such as roll and pitch on most applications.</p></body></html> + APPCONF_IMU_G_OFFSET_COMP_FACT_1 + 4 + 1 + 0 + 1 + 0 + 0 + 0.001 + 0 + 1 + °/s + 9 + + + Gyro Offset Comp Z + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Gyro offset compensation for Z axis. Setting this value to a positive number will integrate the gyro offset towards the current gyro value with this rate. This is useful in order to remove gyro bias on axes that do not rotate on average, such as roll and pitch on most applications.</p></body></html> + APPCONF_IMU_G_OFFSET_COMP_FACT_2 + 4 + 1 + 0 + 1 + 0 + 0 + 0.001 + 0 + 1 + °/s + 9 + + + Gyro Offset Comp Clamp + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Gyro offset compensation clamping. This value clamps the integrated gyro offsets.</p></body></html> + APPCONF_IMU_G_OFFSET_COMP_CLAMP + 3 + 1 + 0 + 1000 + 0 + 0 + 0.1 + 5 + 1 + °/s + 9 + + + + controller_id + timeout_msec + timeout_brake_current + send_can_status + send_can_status_rate_hz + can_baud_rate + pairing_done + permanent_uart_enabled + shutdown_mode + can_mode + uavcan_esc_index + uavcan_raw_mode + app_to_use + app_ppm_conf.ctrl_type + app_ppm_conf.pid_max_erpm + app_ppm_conf.hyst + app_ppm_conf.pulse_start + app_ppm_conf.pulse_end + app_ppm_conf.pulse_center + app_ppm_conf.median_filter + app_ppm_conf.safe_start + app_ppm_conf.throttle_exp + app_ppm_conf.throttle_exp_brake + app_ppm_conf.throttle_exp_mode + app_ppm_conf.ramp_time_pos + app_ppm_conf.ramp_time_neg + app_ppm_conf.multi_esc + app_ppm_conf.tc + app_ppm_conf.tc_max_diff + app_ppm_conf.max_erpm_for_dir + app_ppm_conf.smart_rev_max_duty + app_ppm_conf.smart_rev_ramp_time + app_adc_conf.ctrl_type + app_adc_conf.hyst + app_adc_conf.voltage_start + app_adc_conf.voltage_end + app_adc_conf.voltage_center + app_adc_conf.voltage2_start + app_adc_conf.voltage2_end + app_adc_conf.use_filter + app_adc_conf.safe_start + app_adc_conf.cc_button_inverted + app_adc_conf.rev_button_inverted + app_adc_conf.voltage_inverted + app_adc_conf.voltage2_inverted + app_adc_conf.throttle_exp + app_adc_conf.throttle_exp_brake + app_adc_conf.throttle_exp_mode + app_adc_conf.ramp_time_pos + app_adc_conf.ramp_time_neg + app_adc_conf.multi_esc + app_adc_conf.tc + app_adc_conf.tc_max_diff + app_adc_conf.update_rate_hz + app_uart_baudrate + app_chuk_conf.ctrl_type + app_chuk_conf.hyst + app_chuk_conf.ramp_time_pos + app_chuk_conf.ramp_time_neg + app_chuk_conf.stick_erpm_per_s_in_cc + app_chuk_conf.throttle_exp + app_chuk_conf.throttle_exp_brake + app_chuk_conf.throttle_exp_mode + app_chuk_conf.multi_esc + app_chuk_conf.tc + app_chuk_conf.tc_max_diff + app_chuk_conf.use_smart_rev + app_chuk_conf.smart_rev_max_duty + app_chuk_conf.smart_rev_ramp_time + app_nrf_conf.speed + app_nrf_conf.power + app_nrf_conf.crc_type + app_nrf_conf.retry_delay + app_nrf_conf.retries + app_nrf_conf.channel + app_nrf_conf.address__0 + app_nrf_conf.address__1 + app_nrf_conf.address__2 + app_nrf_conf.send_crc_ack + app_balance_conf.kp + app_balance_conf.ki + app_balance_conf.kd + app_balance_conf.hertz + app_balance_conf.fault_pitch + app_balance_conf.fault_roll + app_balance_conf.fault_duty + app_balance_conf.fault_adc1 + app_balance_conf.fault_adc2 + app_balance_conf.fault_delay_pitch + app_balance_conf.fault_delay_roll + app_balance_conf.fault_delay_duty + app_balance_conf.fault_delay_switch_half + app_balance_conf.fault_delay_switch_full + app_balance_conf.fault_adc_half_erpm + app_balance_conf.tiltback_angle + app_balance_conf.tiltback_speed + app_balance_conf.tiltback_duty + app_balance_conf.tiltback_high_voltage + app_balance_conf.tiltback_low_voltage + app_balance_conf.tiltback_constant + app_balance_conf.tiltback_constant_erpm + app_balance_conf.startup_pitch_tolerance + app_balance_conf.startup_roll_tolerance + app_balance_conf.startup_speed + app_balance_conf.deadzone + app_balance_conf.current_boost + app_balance_conf.multi_esc + app_balance_conf.yaw_kp + app_balance_conf.yaw_ki + app_balance_conf.yaw_kd + app_balance_conf.roll_steer_kp + app_balance_conf.roll_steer_erpm_kp + app_balance_conf.brake_current + app_balance_conf.yaw_current_clamp + app_balance_conf.setpoint_pitch_filter + app_balance_conf.setpoint_target_filter + app_balance_conf.setpoint_filter_clamp + app_balance_conf.kd_pt1_frequency + app_pas_conf.ctrl_type + app_pas_conf.sensor_type + app_pas_conf.current_scaling + app_pas_conf.pedal_rpm_start + app_pas_conf.pedal_rpm_end + app_pas_conf.invert_pedal_direction + app_pas_conf.magnets + app_pas_conf.use_filter + app_pas_conf.ramp_time_pos + app_pas_conf.ramp_time_neg + app_pas_conf.update_rate_hz + imu_conf.type + imu_conf.mode + imu_conf.sample_rate_hz + imu_conf.accel_confidence_decay + imu_conf.mahony_kp + imu_conf.mahony_ki + imu_conf.madgwick_beta + imu_conf.rot_roll + imu_conf.rot_pitch + imu_conf.rot_yaw + imu_conf.accel_offsets__0 + imu_conf.accel_offsets__1 + imu_conf.accel_offsets__2 + imu_conf.gyro_offsets__0 + imu_conf.gyro_offsets__1 + imu_conf.gyro_offsets__2 + imu_conf.gyro_offset_comp_fact__0 + imu_conf.gyro_offset_comp_fact__1 + imu_conf.gyro_offset_comp_fact__2 + imu_conf.gyro_offset_comp_clamp + + + + General + + General + + app_to_use + controller_id + timeout_msec + timeout_brake_current + send_can_status + send_can_status_rate_hz + can_baud_rate + pairing_done + permanent_uart_enabled + shutdown_mode + can_mode + uavcan_esc_index + uavcan_raw_mode + + + + + PPM + + General + + app_ppm_conf.ctrl_type + app_ppm_conf.median_filter + app_ppm_conf.safe_start + app_ppm_conf.pid_max_erpm + app_ppm_conf.ramp_time_pos + app_ppm_conf.ramp_time_neg + app_ppm_conf.max_erpm_for_dir + app_ppm_conf.smart_rev_max_duty + app_ppm_conf.smart_rev_ramp_time + ::sep::Multiple VESCs over CAN + app_ppm_conf.multi_esc + app_ppm_conf.tc + app_ppm_conf.tc_max_diff + + + + Mapping + + app_ppm_conf.pulse_start + app_ppm_conf.pulse_end + app_ppm_conf.pulse_center + app_ppm_conf.hyst + + + + Throttle Curve + + app_ppm_conf.throttle_exp + app_ppm_conf.throttle_exp_brake + app_ppm_conf.throttle_exp_mode + + + + + ADC + + General + + app_adc_conf.ctrl_type + app_adc_conf.use_filter + app_adc_conf.safe_start + app_adc_conf.cc_button_inverted + app_adc_conf.rev_button_inverted + app_adc_conf.update_rate_hz + app_adc_conf.ramp_time_pos + app_adc_conf.ramp_time_neg + ::sep::Multiple VESCs over CAN-bus + app_adc_conf.multi_esc + app_adc_conf.tc + app_adc_conf.tc_max_diff + + + + Mapping + + app_adc_conf.hyst + ::sep::ADC 1 + app_adc_conf.voltage_start + app_adc_conf.voltage_end + app_adc_conf.voltage_center + app_adc_conf.voltage_inverted + ::sep::ADC 2 + app_adc_conf.voltage2_start + app_adc_conf.voltage2_end + app_adc_conf.voltage2_inverted + + + + Throttle Curve + + app_adc_conf.throttle_exp + app_adc_conf.throttle_exp_brake + app_adc_conf.throttle_exp_mode + + + + + UART + + General + + app_uart_baudrate + + + + + VESC Remote + + General + + app_chuk_conf.ctrl_type + app_chuk_conf.ramp_time_pos + app_chuk_conf.ramp_time_neg + app_chuk_conf.stick_erpm_per_s_in_cc + app_chuk_conf.hyst + app_chuk_conf.use_smart_rev + app_chuk_conf.smart_rev_max_duty + app_chuk_conf.smart_rev_ramp_time + ::sep::Multiple VESCs over CAN-bus + app_chuk_conf.multi_esc + app_chuk_conf.tc + app_chuk_conf.tc_max_diff + + + + Throttle Curve + + app_chuk_conf.throttle_exp + app_chuk_conf.throttle_exp_brake + app_chuk_conf.throttle_exp_mode + + + + + NRF + + General + + ::sep::Radio + app_nrf_conf.power + app_nrf_conf.speed + app_nrf_conf.channel + ::sep::Integrity + app_nrf_conf.crc_type + app_nrf_conf.send_crc_ack + app_nrf_conf.retry_delay + app_nrf_conf.retries + ::sep::Address + app_nrf_conf.address__0 + app_nrf_conf.address__1 + app_nrf_conf.address__2 + + + + + Balance + + Tune + + ::sep::PID + app_balance_conf.kp + app_balance_conf.ki + app_balance_conf.kd + ::sep::Main Loop + app_balance_conf.hertz + ::sep::Balance Filtering + app_balance_conf.setpoint_pitch_filter + app_balance_conf.setpoint_target_filter + app_balance_conf.setpoint_filter_clamp + app_balance_conf.kd_pt1_frequency + ::sep::Experimental + app_balance_conf.deadzone + app_balance_conf.current_boost + + + + Startup + + ::sep::Tolerances + app_balance_conf.startup_pitch_tolerance + app_balance_conf.startup_roll_tolerance + ::sep::Centering + app_balance_conf.startup_speed + ::sep::Holding + app_balance_conf.brake_current + + + + Tiltback + + ::sep::Tiltback Config + app_balance_conf.tiltback_angle + app_balance_conf.tiltback_speed + ::sep::Tiltbacks + app_balance_conf.tiltback_duty + app_balance_conf.tiltback_high_voltage + app_balance_conf.tiltback_low_voltage + ::sep::Angling + app_balance_conf.tiltback_constant + app_balance_conf.tiltback_constant_erpm + + + + Fault + + ::sep::Angle Faults + app_balance_conf.fault_pitch + app_balance_conf.fault_delay_pitch + app_balance_conf.fault_roll + app_balance_conf.fault_delay_roll + ::sep::Speed Faults + app_balance_conf.fault_duty + app_balance_conf.fault_delay_duty + ::sep::Switches + app_balance_conf.fault_adc1 + app_balance_conf.fault_adc2 + app_balance_conf.fault_delay_switch_half + app_balance_conf.fault_delay_switch_full + app_balance_conf.fault_adc_half_erpm + + + + Multi ESC + + ::sep::Multi ESC + app_balance_conf.multi_esc + ::sep::Stabilization PID + app_balance_conf.yaw_kp + app_balance_conf.yaw_ki + app_balance_conf.yaw_kd + ::sep::Steering + app_balance_conf.roll_steer_kp + app_balance_conf.roll_steer_erpm_kp + app_balance_conf.yaw_current_clamp + + + + + IMU + + General + + imu_conf.type + imu_conf.sample_rate_hz + ::sep::Filters + imu_conf.mode + imu_conf.accel_confidence_decay + imu_conf.mahony_kp + imu_conf.mahony_ki + imu_conf.madgwick_beta + ::sep::Rotation + imu_conf.rot_roll + imu_conf.rot_pitch + imu_conf.rot_yaw + ::sep::Offsets + imu_conf.accel_offsets__0 + imu_conf.accel_offsets__1 + imu_conf.accel_offsets__2 + imu_conf.gyro_offsets__0 + imu_conf.gyro_offsets__1 + imu_conf.gyro_offsets__2 + imu_conf.gyro_offset_comp_fact__0 + imu_conf.gyro_offset_comp_fact__1 + imu_conf.gyro_offset_comp_fact__2 + imu_conf.gyro_offset_comp_clamp + + + + + PAS + + General + + app_pas_conf.ctrl_type + app_pas_conf.sensor_type + app_pas_conf.pedal_rpm_start + app_pas_conf.pedal_rpm_end + app_pas_conf.invert_pedal_direction + app_pas_conf.magnets + app_pas_conf.use_filter + app_pas_conf.current_scaling + app_pas_conf.ramp_time_pos + app_pas_conf.ramp_time_neg + app_pas_conf.update_rate_hz + + + + + diff --git a/plugins/vesc/runtime/schemas/5.02/parameters_mcconf.xml b/plugins/vesc/runtime/schemas/5.02/parameters_mcconf.xml new file mode 100644 index 0000000..866e27a --- /dev/null +++ b/plugins/vesc/runtime/schemas/5.02/parameters_mcconf.xml @@ -0,0 +1,3911 @@ + + + + + PWM Mode + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The PWM mode to use for BLDC motors. Synchronous is the most tested and recommended mode. The others are likely to cause problems.</p></body></html> + MCCONF_PWM_MODE + 1 + Nonsynchronous HISW + Synchronous + Bipolar + + + Commutation Mode + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Delay</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">This is what most cheap hobby ESCs use, which is detecting a BEMF zero crossing and adding a delay</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Integrate</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The back-EMF is sampled continuously after a zero crossing and the area under it is integrated. This is more robust and works better at low speed. For this mode the BEMF coupling and integration limit has to be know. The detect function can be used to measure these parameters.</p></body></html> + MCCONF_COMM_MODE + 0 + Integrate + Delay + + + Motor Type + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">BLDC</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Trapezoidal commutation mode for PMSM motors.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">DC</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">DC motor. A DC motor is connected to phase 1 and phase 3.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">FOC</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Field Oriented Control (FOC) for PMSM (or BLDC) motors. The motor is commutated with sine waves instead of a trapezoidal waveform as is the case for BLDC commutation. FOC runs the motors more quietly (especially at low speed and high load), is slightly more efficient and provides automatic optimal timing.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">GPD</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">General Purpose Drive between phase 1 and 3. Should be used with a custom application on the VESC, or on the computer with the VESC Tool backend providing samples.</span></p></body></html> + MCCONF_DEFAULT_MOTOR_TYPE + 2 + BLDC + DC + FOC + GPD + + + Sensor Mode + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Sensor mode for BLDC commutation. Hybrid means that sensors will be used at low speed and sensorless at high speed.</p></body></html> + MCCONF_SENSOR_MODE + 0 + Sensorless + Sensored + Hybrid + + + Motor Current Max + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Maximum motor current.</span></p></body></html> + MCCONF_L_CURRENT_MAX + 2 + 1 + 0 + 1000 + 0 + 0 + 1 + 60 + 1000 + A + 9 + + + Motor Current Max Brake + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Maximum (braking) motor current. The is the maximum current that will be fed back to the VESC and when braking, thus negative. The energy from the braking current will be fed back to the battery.</span></p></body></html> + MCCONF_L_CURRENT_MIN + 2 + 1 + 0 + 0 + -1000 + 0 + 1 + -60 + 1000 + A + 9 + + + Battery Current Max + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The maximum current that can be drawn from the battery. The battery current is always lower than or equal to the motor current.</span></p></body></html> + MCCONF_L_IN_CURRENT_MAX + 2 + 1 + 0 + 1000 + 0 + 0 + 1 + 99 + 1000 + A + 9 + + + Battery Current Max Regen + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The maximum regenerative current that can be fed to the battery (thus negative). The battery current is always lower than or equal to the motor current.</span></p></body></html> + MCCONF_L_IN_CURRENT_MIN + 2 + 1 + 0 + 0 + -1000 + 0 + 1 + -60 + 1000 + A + 9 + + + Absolute Maximum Current + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The current magnitute above which all output will be switched off and a fault code thrown. Usually the current control loops take care of limiting the current, but in some conditions short current spikes can appear very quickly. The system can handle them quite well in most cased, so this value can be set relatively high compared to the other current values to avoid cutouts.</span></p></body></html> + MCCONF_L_MAX_ABS_CURRENT + 2 + 1 + 0 + 1000 + 0 + 0 + 1 + 150 + 1000 + A + 9 + + + Max ERPM Reverse + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The maximum reverse electrical RPM.</p></body></html> + MCCONF_L_RPM_MIN + 2 + 1 + 0 + 0 + -1e+06 + 0 + 100 + -100000 + 1000 + + 9 + + + Max ERPM + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The maximum electrical RPM.</p></body></html> + MCCONF_L_RPM_MAX + 2 + 1 + 0 + 1e+06 + 0 + 0 + 100 + 100000 + 1000 + + 9 + + + ERPM Limit Start + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Start to reduce the current at this fraction of the ERPM limit. Lowering this number will make the ERPM limit softer.</span></p></body></html> + MCCONF_L_RPM_START + 2 + 1 + 1 + 1 + 0 + 1 + 0.01 + 0.8 + 1e+06 + + 9 + + + Max ERPM Full Brake + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The maximum ERPM at which a full brake is allowed (BLDC Only).</p></body></html> + MCCONF_L_CURR_MAX_RPM_FBRAKE + 2 + 1 + 0 + 1e+06 + 0 + 0 + 100 + 300 + 1000 + + 9 + + + Max ERPM Full Brake Current Control + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The ERPM below which a direction change is allowed in current control (BLDC Only).</p></body></html> + MCCONF_L_CURR_MAX_RPM_FBRAKE_CC + 2 + 1 + 0 + 1e+06 + 0 + 0 + 100 + 1500 + 1000 + + 9 + + + Minimum Input Voltage + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The input voltage below which a fault code is thrown.</p></body></html> + MCCONF_L_MIN_VOLTAGE + 2 + 1 + 0 + 700 + 0 + 0 + 1 + 8 + 1000 + V + 9 + + + Maximum Input Voltage + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The input voltage above which a fault code is thrown.</p></body></html> + MCCONF_L_MAX_VOLTAGE + 2 + 1 + 0 + 700 + 0 + 0 + 1 + 57 + 1000 + V + 9 + + + Battery Voltage Cutoff Start + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The input voltage where current starts to get reduced. There is still full braking current available as braking only charges the battery.</p></body></html> + MCCONF_L_BATTERY_CUT_START + 2 + 1 + 0 + 700 + 0 + 0 + 1 + 10 + 1000 + V + 9 + + + Battery Voltage Cutoff End + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The input voltage below which current draw is not allowed anymore. There is still full braking current available as braking only charges the battery.</p></body></html> + MCCONF_L_BATTERY_CUT_END + 2 + 1 + 0 + 700 + 0 + 0 + 1 + 8 + 1000 + V + 9 + + + Slow ABS Current Limit + 5 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Use the filtered current for the ABS max fault code. Will not trigger as easily on very short spikes.</p></body></html> + MCCONF_L_SLOW_ABS_OVERCURRENT + 1 + + + MOSFET Temp Cutoff Start + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The MOSFET temperature at which motor current starts to get reduced.</p></body></html> + MCCONF_L_LIM_TEMP_FET_START + 1 + 1 + 0 + 120 + 0 + 1 + 1 + 85 + 1000 + °C + 9 + + + MOSFET Temp Cutoff End + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The MOSFET temperature above which motor current is not allowed and a fault is thrown.</p></body></html> + MCCONF_L_LIM_TEMP_FET_END + 1 + 1 + 0 + 120 + 0 + 1 + 1 + 100 + 1000 + °C + 9 + + + Motor Temp Cutoff Start + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The motor temperature at which motor current starts to get reduced.</p></body></html> + MCCONF_L_LIM_TEMP_MOTOR_START + 1 + 1 + 0 + 120 + 0 + 1 + 1 + 85 + 1000 + °C + 9 + + + Motor Temp Cutoff End + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The motor temperature above which motor current is not allowed and a fault is thrown.</p></body></html> + MCCONF_L_LIM_TEMP_MOTOR_END + 1 + 1 + 0 + 120 + 0 + 1 + 1 + 100 + 1000 + °C + 9 + + + Acceleration Temperature Decrease + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Decrease the motor and MOSFET temperature limits by this amount during acceleration. This is useful to still have braking torque left when the components get warm. A decrease of 0 % means that the acceleration temperature limits are the same as the braking temperature limits, and a decrease of 100 % meanse that the acceleration temperature limits are at 25 °C.</span></p></body></html> + MCCONF_L_LIM_TEMP_ACCEL_DEC + 0 + 100 + 1 + 1 + 0 + 1 + 1 + 0.15 + 1000 + % + 9 + + + Minimum Duty Cycle + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Minimum allowed duty cycle.</span></p></body></html> + MCCONF_L_MIN_DUTY + 1 + 100 + 0 + 1 + 0 + 1 + 0.5 + 0.005 + 1e+06 + % + 9 + + + Maximum Duty Cycle + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Maximum allowed duty cycle.</span></p></body></html> + MCCONF_L_MAX_DUTY + 1 + 100 + 0 + 1 + 0 + 1 + 0.5 + 0.95 + 1e+06 + % + 9 + + + Maximum Wattage + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Maximum allowed wattage output. If your region has laws that only allow a limited wattage, this parameter can be useful. However, keep in mind that limiting the wattage does not make much sense in practise since torque, heat losses, mechanical wear and component load are all current dependent.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Notice that setting this parameter to a very high value essentially disables it, which is why the default value is high. The other limits will still apply.</p></body></html> + MCCONF_L_WATT_MAX + 1 + 1 + 0 + 2e+06 + 0 + 0 + 1 + 1.5e+06 + 1 + W + 9 + + + Maximum Braking Wattage + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Maximum allowed braking wattage (thus negative). There usuallt aren't any laws limiting how much braking is allowed, and limiting the wattage does not make much sense in general, so this parameter is present mostly for the sake of completeness. There might be some applications where limiting the braking wattage is useful though.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Notice that setting this parameter to a very high value essentially disables it, which is why the default value is high. The other limits will still apply.</p></body></html> + MCCONF_L_WATT_MIN + 1 + 1 + 0 + 0 + -2e+06 + 0 + 1 + -1.5e+06 + 1 + W + 9 + + + Max Current Scale + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Maximum current scale. This value is multiplied with the maximum current. It is a convenient method to scale the current limits without forgetting the actual maximum value.</span></p></body></html> + MCCONF_L_CURRENT_MAX_SCALE + 2 + 1 + 1 + 1 + 0 + 1 + 0.05 + 1 + 1000 + + 9 + + + Min Current Scale + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Minimum current scale. This value is multiplied with the minimum current. It is a convenient method to scale the current limits without forgetting the actual maximum value.</span></p></body></html> + MCCONF_L_CURRENT_MIN_SCALE + 2 + 1 + 1 + 1 + 0 + 1 + 0.05 + 1 + 1000 + + 9 + + + Duty Cycle Current Limit Start + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Start to reduce the current at this duty cycle. Lowering this number will make the motor limit the torque softly when reaching max speed, however, it will also decrease the top speed a bit.</span></p></body></html> + MCCONF_L_DUTY_START + 2 + 1 + 1 + 1 + 0 + 1 + 0.01 + 1 + 1e+06 + + 9 + + + Minimum ERPM + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Minimum sensorless ERPM (BLDC Only). Run the motor in open loop when the estimated ERPM is below this value.</p></body></html> + MCCONF_SL_MIN_RPM + 2 + 1 + 0 + 1e+06 + 0 + 0 + 100 + 150 + 1000 + + 9 + + + Minimum ERPM Integrator + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The minimum ERPM for which the integrator limit is calculated. Setting this too low will make the coupling compensation too large at low speed resulting in bad startup.</span></p></body></html> + MCCONF_SL_MIN_ERPM_CYCLE_INT_LIMIT + 2 + 1 + 0 + 1e+06 + 0 + 0 + 100 + 1100 + 1000 + + 9 + + + Max Brake Current at Direction Change + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Only allow motor direction change below this current.</p></body></html> + MCCONF_SL_MAX_FB_CURR_DIR_CHANGE + 2 + 1 + 0 + 500 + 0 + 0 + 1 + 10 + 1000 + A + 9 + + + Cycle Integrator Limit + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Cycle ingegrator limit. This is how much area will be integrated under the back EMF after a zero crossing before doing a commutation. A too low value will cause a too early commutation, and a too high value will cause a too late commutation. A too late commutation will cause more problems than too early commutations.</p></body></html> + MCCONF_SL_CYCLE_INT_LIMIT + 2 + 1 + 0 + 5000 + 0 + 0 + 1 + 62 + 1000 + + 9 + + + Phase Advance at BR ERPM + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Phase (timing) advance at the BR ERPM value. Below that value the advance will be less proportional to the current ERPM.</p></body></html> + MCCONF_SL_PHASE_ADVANCE_AT_BR + 2 + 1 + 0 + 1 + 0 + 0 + 0.05 + 0.8 + 1000 + + 9 + + + BR ERPM + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The ERPM at which phase advance (timing) is the maximum.</p></body></html> + MCCONF_SL_CYCLE_INT_BR + 2 + 1 + 0 + 1e+06 + 0 + 0 + 100 + 80000 + 1000 + + 9 + + + BEMF Coupling + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">BEMF coupling. Roughly describes how much of the input voltage is seen on the BEMF at low modulation. Compensating for that at low speed helps the startup a lot.</p></body></html> + MCCONF_SL_BEMF_COUPLING_K + 2 + 1 + 0 + 5000 + 0 + 0 + 1 + 600 + 1000 + + 9 + + + Hall Table [0] + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Hall sensor table entry for sensor output 0.</p></body></html> + MCCONF_HALL_TAB_0 + 1 + 0 + 6 + -1 + 0 + 1 + -1 + + 2 + + + Hall Table [1] + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Hall sensor table entry for sensor output 1.</p></body></html> + MCCONF_HALL_TAB_1 + 1 + 0 + 6 + -1 + 0 + 1 + 1 + + 2 + + + Hall Table [2] + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Hall sensor table entry for sensor output 2.</p></body></html> + MCCONF_HALL_TAB_2 + 1 + 0 + 6 + -1 + 0 + 1 + 3 + + 2 + + + Hall Table [3] + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Hall sensor table entry for sensor output 3.</p></body></html> + MCCONF_HALL_TAB_3 + 1 + 0 + 6 + -1 + 0 + 1 + 2 + + 2 + + + Hall Table [4] + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Hall sensor table entry for sensor output 4.</p></body></html> + MCCONF_HALL_TAB_4 + 1 + 0 + 6 + -1 + 0 + 1 + 5 + + 2 + + + Hall Table [5] + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Hall sensor table entry for sensor output 5.</p></body></html> + MCCONF_HALL_TAB_5 + 1 + 0 + 6 + -1 + 0 + 1 + 6 + + 2 + + + Hall Table [6] + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Hall sensor table entry for sensor output 6.</p></body></html> + MCCONF_HALL_TAB_6 + 1 + 0 + 6 + -1 + 0 + 1 + 4 + + 2 + + + Hall Table [7] + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Hall sensor table entry for sensor output 7.</p></body></html> + MCCONF_HALL_TAB_7 + 1 + 0 + 6 + -1 + 0 + 1 + -1 + + 2 + + + Sensorless ERPM Hybrid + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">ERPM above which sensorless commutation is used in hybrid mode.</p></body></html> + MCCONF_HALL_ERPM + 2 + 1 + 0 + 1e+06 + 0 + 0 + 100 + 2000 + 1000 + + 9 + + + Current KP + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Current controller proportional gain.</span></p></body></html> + MCCONF_FOC_CURRENT_KP + 4 + 1 + 0 + 100000 + 0 + 0 + 0.01 + 0.03 + 100000 + + 9 + + + Current KI + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Current controller integral gain.</span></p></body></html> + MCCONF_FOC_CURRENT_KI + 2 + 1 + 0 + 100000 + 0 + 0 + 0.01 + 50 + 100000 + + 9 + + + Switching Frequency + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The switching frequency. The controllers and estimators will run at half of this frequency.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">If the option </span><span style=" font-family:'Roboto'; font-weight:600;">Sample in V0 and V7</span><span style=" font-family:'Roboto';"> is active the controllers and estimators will run at the full switching frequency, but this option is only available on hardware with phase shunts.</span></p></body></html> + MCCONF_FOC_F_SW + 1 + 0.001 + 0 + 150000 + 0 + 0 + 1 + 25000 + 1000 + kHz + 9 + + + Dead Time Compensation + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Compensation for dead time distortion. Makes some difference at low speed.</p></body></html> + MCCONF_FOC_DT_US + 3 + 1 + 0 + 1000 + 0 + 0 + 0.01 + 0.12 + 1e+06 + µS + 9 + + + Encoder Inverted + 5 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The encoder is inverted if it counts backwards while the motor is turning forwards.</p></body></html> + MCCONF_FOC_ENCODER_INVERTED + 0 + + + Encoder Offset + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Offset between the encoder zero and motor zero points.</p></body></html> + MCCONF_FOC_ENCODER_OFFSET + 2 + 1 + 0 + 360 + 0 + 0 + 1 + 180 + 1000 + + 9 + + + Encoder Ratio + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Ratio between encoder and motor. E.g. a 14 pole motor with a directly attached encoder has ratio 7.</p></body></html> + MCCONF_FOC_ENCODER_RATIO + 2 + 1 + 0 + 10000 + 0 + 0 + 1 + 7 + 1000 + + 9 + + + Sin/Cos Sine Gain Compensation + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Sin/Cos Encoder Sine gain compensation to reduce nonlinearity errors in the signal path.</span></p></body></html> + MCCONF_FOC_ENCODER_SIN_GAIN + 2 + 1 + 0 + 2 + 0 + 0 + 0.01 + 1 + 1000 + + 9 + + + Sin/Cos Cosine Gain Compensation + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Sin/Cos Encoder Cosine gain compensation to reduce nonlinearity errors in the signal path.</span></p></body></html> + MCCONF_FOC_ENCODER_COS_GAIN + 2 + 1 + 0 + 2 + 0 + 0 + 0.01 + 1 + 1000 + + 9 + + + Sin/Cos Sine Offset + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Sin/Cos Encoder Sine Offset.</span></p></body></html> + MCCONF_FOC_ENCODER_SIN_OFFSET + 2 + 1 + 0 + 3.3 + 0 + 0 + 0.01 + 1.65 + 1000 + + 9 + + + Sin/Cos Cosine Offset + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Sin/Cos Encoder Sine Offset.</span></p></body></html> + MCCONF_FOC_ENCODER_COS_OFFSET + 2 + 1 + 0 + 3.3 + 0 + 0 + 0.01 + 1.65 + 1000 + + 9 + + + Sin/Cos Filter Constant + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Sin/Cos Encoder low pass filter constant. </span><span style=" font-family:'Roboto';">Will affect the ratio between lag and noise on the encoder position feedback. Range 0 to 1, where 0 has the lowest noise and most phase lag, and 1 has no lag and unfiltered noise.</span></p></body></html> + MCCONF_FOC_ENCODER_SINCOS_FILTER + 2 + 1 + 0 + 1 + 0 + 0 + 0.01 + 0.5 + 1000 + + 9 + + + Sensor Mode + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Sensor mode for the motor.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Sensorless</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Don't use any position sensor on the motor and only rely on the observer and starting algorithm. Works well for most applications (not position control), but the start can be a bit delayed.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Encoder</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Use an encoder on the motor shaft. Works well for position control applications such as CNC mills.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Hall Sensors</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Use hall sensors with 60 or 120 degree spacing in the motor. Gives starts without any delay at all, but does not work that well for most position control applications.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">HFI</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">High Frequency Injection. Track the position down to 0 speed by injecting voltage pulses and analyzing the response of the motor. Works on most motors that have enough difference in D-axis and Q-axis inductance.</span></p></body></html> + MCCONF_FOC_SENSOR_MODE + 0 + Sensorless + Encoder + Hall Sensors + HFI + + + Speed Tracker Kp + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Speed tracker proportional gain. The speed tracker estimates the motor speed by tracking the phase angle.</p></body></html> + MCCONF_FOC_PLL_KP + 2 + 1 + 0 + 1e+06 + 0 + 0 + 1 + 2000 + 1000 + + 9 + + + Speed Tracker Ki + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Speed tracker integral gain. The speed tracker estimates the motor speed by tracking the phase angle.</p></body></html> + MCCONF_FOC_PLL_KI + 2 + 1 + 0 + 1e+06 + 0 + 0 + 1 + 30000 + 1000 + + 9 + + + Motor Inductance (L) + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The average of LD and LQ inductance.</p></body></html> + MCCONF_FOC_MOTOR_L + 2 + 1e+06 + 0 + 10 + 0 + 0 + 0.1 + 7e-06 + 1e+08 + µH + 9 + + + Motor Inductance Difference (Ld - Lq) + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The difference between Ld and Lq inductance. It represents the motor saliency. This can be measured using the </span><span style=" font-family:'Roboto'; font-style:italic;">measure_ind</span><span style=" font-family:'Roboto';"> terminal command, but the regular detection interface does not print it yet.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">A value different than zero will enable the Maximum Torque Per Amp (MTPA) algorithm that injects a negative id current to follow the optimum torque trajectory. This is specially valuable on Interior Permanent Magnet (IPM) motors because they have large saliency and can yield a substantial torque increase.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Note:</span><span style=" font-family:'Roboto';"> Only enable this feature if you know very well what you are doing. IPM motors are not popular and injecting negative id current can increase the motor speed. If id current suddenly collapses (under a fault condition for example) the DC Bus voltage can increase well beyond the powerstage rating causing a fire and maximum braking power at the motor shaft.</span></p></body></html> + MCCONF_FOC_MOTOR_LD_LQ_DIFF + 2 + 1e+06 + 0 + 10 + 0 + 0 + 0.1 + 0 + 1e+08 + µH + 9 + + + Motor Resistance (R) + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The motor winding resistance. Should be half of what is measured between two motor wires.</span></p></body></html> + MCCONF_FOC_MOTOR_R + 1 + 1000 + 0 + 1000 + 0 + 0 + 0.1 + 0.015 + 100000 + mΩ + 9 + + + Motor Flux Linkage (λ) + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The flux linkage of the motor (λ) [mWb]</span></p></body></html> + MCCONF_FOC_MOTOR_FLUX_LINKAGE + 3 + 1000 + 0 + 1000 + 0 + 0 + 0.01 + 0.00245 + 100000 + mWb + 9 + + + Observer Gain (x1M) + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The observer gain. If the motor does not run smoothly with the calculated value, this value can be tweaked. Try with doubling or halving it in that case.</span></p></body></html> + MCCONF_FOC_OBSERVER_GAIN + 2 + 1e-06 + 0 + 2e+10 + 0 + 0 + 1 + 9e+07 + 0.01 + + 9 + + + Observer Gain At Minimum Duty + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The observer gain scaled at minimum duty cycle. Decreasing this parameter will make observer gain lower at lower modulation, which can help tracking the motor. Setting this parameter to 1 will make the observer gain constant at all modulations.</span></p></body></html> + MCCONF_FOC_OBSERVER_GAIN_SLOW + 2 + 1 + 1 + 1 + 0 + 1 + 0.01 + 0.05 + 0.01 + + 9 + + + Duty Downramp Kp + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The proportional gain for the duty downramp controller. This controller is used in duty cycle mode when the duty cycle is decreased. Since this is done by limiting the modulation, very large current spikes can be caused. By using a controller these current spikes can be limited.</p></body></html> + MCCONF_FOC_DUTY_DOWNRAMP_KP + 2 + 1 + 0 + 1e+06 + 0 + 0 + 1 + 10 + 1000 + + 9 + + + Duty Downramp Ki + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The integral gain for the duty downramp controller. This controller is used in duty cycle mode when the duty cycle is decreased. Since this is done by limiting the modulation, very large current spikes can be caused. By using a controller these current spikes can be limited.</p></body></html> + MCCONF_FOC_DUTY_DOWNRAMP_KI + 2 + 1 + 0 + 1e+06 + 0 + 0 + 1 + 200 + 1000 + + 9 + + + Openloop ERPM + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">ERPM below which openloop commutation is used when running sensorless. Can be tweaked for the best startup depending on e.g. the load inertia.</p></body></html> + MCCONF_FOC_OPENLOOP_RPM + 2 + 1 + 0 + 1e+06 + 0 + 0 + 100 + 400 + 1000 + + 9 + + + Openloop ERPM at Min Current + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The openloop ERPM is scaled with the set motor current. This is the fraction of Openloop ERPM at the minimum current.</span></p></body></html> + MCCONF_FOC_OPENLOOP_RPM_LOW + 2 + 1 + 1 + 1 + 0 + 1 + 0.01 + 0.1 + 1000 + + 7 + + + D Axis Gain Scaling Start + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Start decreasing the D axis current controller gain at this modulation.</span></p></body></html> + MCCONF_FOC_D_GAIN_SCALE_START + 2 + 1 + 1 + 1 + 0 + 1 + 0.01 + 0.9 + 1000 + + 9 + + + D Axis Gain Scaling at Max Mod + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">D axis current controller gain at maximum modulation.</span></p></body></html> + MCCONF_FOC_D_GAIN_SCALE_MAX_MOD + 2 + 1 + 1 + 1 + 0 + 1 + 0.01 + 0.2 + 1000 + + 9 + + + Openloop Hysteresis + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Go to openloop mode if the ERPM has been below the openloop RPM for this amount of time.</span></p></body></html> + MCCONF_FOC_SL_OPENLOOP_HYST + 2 + 1 + 0 + 100 + 0 + 0 + 0.05 + 0.1 + 100 + S + 7 + + + Openloop Lock Time + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Lock motor for this amount of time in the beginning of the open loop sequence.</span></p></body></html> + MCCONF_FOC_SL_OPENLOOP_T_LOCK + 2 + 1 + 0 + 100 + 0 + 0 + 0.05 + 0 + 100 + S + 7 + + + Openloop Ramp Time + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Ramp up the openloop speed in the openloop sequence for this amount of time.</span></p></body></html> + MCCONF_FOC_SL_OPENLOOP_T_RAMP + 2 + 1 + 0 + 100 + 0 + 0 + 0.05 + 0 + 100 + S + 7 + + + Openloop Time + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Stay in openloop for this amount of time after finishing the ramp.</span></p></body></html> + MCCONF_FOC_SL_OPENLOOP_TIME + 2 + 1 + 0 + 100 + 0 + 0 + 0.05 + 0.1 + 100 + S + 7 + + + Hall Table [0] + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Hall sensor table entry for sensor output 0.</p></body></html> + MCCONF_FOC_HALL_TAB_0 + 1 + 0 + 255 + 0 + 0 + 1 + 255 + + 1 + + + Hall Table [1] + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Hall sensor table entry for sensor output 1.</p></body></html> + MCCONF_FOC_HALL_TAB_1 + 1 + 0 + 255 + 0 + 0 + 1 + 255 + + 1 + + + Hall Table [2] + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Hall sensor table entry for sensor output 2.</p></body></html> + MCCONF_FOC_HALL_TAB_2 + 1 + 0 + 255 + 0 + 0 + 1 + 255 + + 1 + + + Hall Table [3] + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Hall sensor table entry for sensor output 3.</p></body></html> + MCCONF_FOC_HALL_TAB_3 + 1 + 0 + 255 + 0 + 0 + 1 + 255 + + 1 + + + Hall Table [4] + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Hall sensor table entry for sensor output 4.</p></body></html> + MCCONF_FOC_HALL_TAB_4 + 1 + 0 + 255 + 0 + 0 + 1 + 255 + + 1 + + + Hall Table [5] + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Hall sensor table entry for sensor output 5.</p></body></html> + MCCONF_FOC_HALL_TAB_5 + 1 + 0 + 255 + 0 + 0 + 1 + 255 + + 1 + + + Hall Table [6] + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Hall sensor table entry for sensor output 6.</p></body></html> + MCCONF_FOC_HALL_TAB_6 + 1 + 0 + 255 + 0 + 0 + 1 + 255 + + 1 + + + Hall Table [7] + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Hall sensor table entry for sensor output 7.</p></body></html> + MCCONF_FOC_HALL_TAB_7 + 1 + 0 + 255 + 0 + 0 + 1 + 255 + + 1 + + + Hall Interpolation ERPM + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">ERPM above which hall sensors are interpolated.</span></p></body></html> + MCCONF_FOC_HALL_INTERP_ERPM + 2 + 1 + 0 + 1e+06 + 0 + 0 + 10 + 500 + 1 + + 9 + + + Sensorless ERPM + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">ERPM above which sensorless commutation is used in sensored modes.</p></body></html> + MCCONF_FOC_SL_ERPM + 2 + 1 + 0 + 1e+06 + 0 + 0 + 100 + 2500 + 1000 + + 9 + + + Sample in V0 and V7 + 5 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Sample currents and voltages in both V0 and V7 of the space vector modulation, and run the control loop at twice the rate. Can be useful for high speed motors at limited switching frequency, or in order to decrease the modulation noise. Notice that this option will require twice the amount of computational power for a given switching frequency.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Note</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">This option is only valid for hardware with phase shunts, such as the VESC Six. For other shunt configurations it is ignored.</span></p></body></html> + MCCONF_FOC_SAMPLE_V0_V7 + 0 + + + High Current Sampling Mode + 5 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Choose the lowest currents during sampling to derive the highest current. Since the motor currents are balanced and sum to 0, two of the phase currents can be used to derive the third one. Enabling this option will make the current measurement compare all motor currents and derive the highest one from the two lower currents. This way higher currents can be measured than the ADC gain allows by a factor of 2 / sqrt(3), or roughly 1.15. For example, for the VESC6 this increases the current measurement capability from 165A to roughly 190A.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Note</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">This option is only valid for hardware with three shunts, such as the VESC Six. For other shunt configurations it is ignored.</span></p></body></html> + MCCONF_FOC_SAMPLE_HIGH_CURRENT + 0 + + + Stator Saturation Compensation + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Stator saturation compensation.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">When using high currents the stator of the motor can get saturated. This will change the motor parameters, making it difficult for the sensorless observer to track the rotor position. The effect is most noticeable when running the motor with high current at low speed - it will get stuck and then &quot;cog&quot; when open loop operation tries to restart the motor. If you observe this behavior you can try to increase this parameter. This parameter attempts to compensate for effects of stator saturation, making it possible to run motors sensorlessly even at high current and low speed.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Reasonable values for this parameters are 15 % or less. If going higher than that gives good results something else is most likely wrong in your configuration.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Consider the following:</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<ul style="margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; -qt-list-indent: 1;"><li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Motors that run at low speed and high torque tend to get saturated, such as e-bike direct drive hub motors.</li> +<li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Coreless motors should in theory never get saturated.</li> +<li style=" font-family:'Roboto';" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The effect of this parameter is proportional to the maximum motor current limit, meaning that this parameter has no effect at zero current and full effect at full current. If you change the maximum motor current limit you have to adapt this parameter accordingly.</li></ul></body></html> + MCCONF_FOC_SAT_COMP + 2 + 1 + 1 + 1 + 0 + 1 + 0.01 + 0 + 1000 + + 7 + + + Temp Comp + 5 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Use temperature compensation for the motor resistance used by the observer. Should help at low speed when the motor temperature is far away from the temperature at which the resistance was measured.</p></body></html> + MCCONF_FOC_TEMP_COMP + 0 + + + Temp Comp Base Temp + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Motor temperature at which the motor resistance was measured.</span></p></body></html> + MCCONF_FOC_TEMP_COMP_BASE_TEMP + 1 + 1 + 0 + 120 + -120 + 0 + 1 + 25 + 100 + °C + 7 + + + Current Filter Constant + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Constant for the filtered current in the FOC implementation. Will affect how fast the slow abs max current fault triggers. Range 0 to 1, where 0 is the slowest and 1 is no filtering.</span></p></body></html> + MCCONF_FOC_CURRENT_FILTER_CONST + 3 + 1 + 0 + 1 + 0 + 0 + 0.01 + 0.1 + 1 + + 9 + + + Current Controller Decoupling + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">FOC current controller decoupling using feed forward. This will make the current controller perform better during transient conditions; it may also introduce some noise. The available modes are:</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">FOC_CC_DECOUPLING_DISABLED</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Decoupling is disabled</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">FOC_CC_DECOUPLING_CROSS</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Cross decoupling between the D and Q axes is enabled.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">FOC_CC_DECOUPLING_BEMF</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Back EMF decoupling on the Q axis is enabled. This improves perfomance significantly if the motor speed changes rapidly, but makes the current controller depend on the speed tracker.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">FOC_CC_DECOUPLING_CROSS_BEMF</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Both options above are enabled.</p></body></html> + MCCONF_FOC_CC_DECOUPLING + 2 + FOC_CC_DECOUPLING_DISABLED + FOC_CC_DECOUPLING_CROSS + FOC_CC_DECOUPLING_BEMF + FOC_CC_DECOUPLING_CROSS_BEMF + + + Observer Type + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Type of rotor position observer for field oriented control (FOC). The options are:</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">FOC_OBSERVER_ORTEGA_ORIGINAL</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The observer described here:</p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><a href="http://cas.ensmp.fr/~praly/Telechargement/Journaux/2010-IEEE_TPEL-Lee-Hong-Nam-Ortega-Praly-Astolfi.pdf"><span style=" text-decoration: underline; color:#0000ff;">http://cas.ensmp.fr/~praly/Telechargement/Journaux/2010-IEEE_TPEL-Lee-Hong-Nam-Ortega-Praly-Astolfi.pdf</span></a></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">FOC_OBSERVER_ORTEGA_ITERATIVE</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Same as above, but with some iterations to make it track better when the ERPM is high relative to the switching frequency. It seems to make things worse for most regular speed motors though (e.g. &lt; 120k ERPM @ 25 kHz).</p></body></html> + MCCONF_FOC_OBSERVER_TYPE + 0 + FOC_OBSERVER_ORTEGA_ORIGINAL + FOC_OBSERVER_ORTEGA_ITERATIVE + + + HFI Start Voltage + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">HFI voltage at start to resolve ambiguity. This voltage has to cause a current that is high enough to see signs of saturation in the motor.</span></p></body></html> + MCCONF_FOC_HFI_VOLTAGE_START + 2 + 1 + 0 + 700 + 0 + 0 + 1 + 20 + 1000 + V + 9 + + + HFI Run Voltage + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">HFI voltage during operation, after ambiguity has been resolved.</span></p></body></html> + MCCONF_FOC_HFI_VOLTAGE_RUN + 2 + 1 + 0 + 700 + 0 + 0 + 1 + 4 + 1000 + V + 9 + + + HFI Max Voltage + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">HFI voltage during operation, at maximum current. Increasing the voltage at higher currents helps with tracking. A higher voltage makes HFI noisier and wastes more power, which is why this option allows increasing it at high motor currents when it is needed.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The HFI voltage is mapped between voltage_run and voltage_max, relative to the motor current.</span></p></body></html> + MCCONF_FOC_HFI_VOLTAGE_MAX + 2 + 1 + 0 + 700 + 0 + 0 + 1 + 10 + 1000 + V + 9 + + + Sensorless ERPM HFI + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">ERPM below which HFI is used.</span></p></body></html> + MCCONF_FOC_SL_ERPM_HFI + 2 + 1 + 0 + 1e+06 + 0 + 0 + 100 + 2000 + 1000 + + 9 + + + HFI Start Samples + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Number of HFI samples to resolve ambiguity at start. Every sample takes a bit more than 0.5 ms, and no throttle can be applied during this time. The default value is barely noticeable.</p></body></html> + MCCONF_FOC_HFI_START_SAMPLES + 1 + 0 + 60000 + 2 + 0 + 1 + 65 + + 3 + + + HFI Observer Override Time + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Override HFI position with observer position for this amount of time after dropping below the HFI ERPM threshold. This can prevent oscillating between the two at a transition. Settings this value too high can make HFI catch the motor 180 electrical degrees off, as the observer position might degrade too much.</p></body></html> + MCCONF_FOC_HFI_OBS_OVR_SEC + 1 + 1000 + 0 + 5000 + 0 + 0 + 1 + 0.001 + 1000 + ms + 9 + + + HFI Samples + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Number of HFI samples for each motor revolution. This can't be an arbitrary number as the size of fourier transforms and sine tables depends on it.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Fewer samples will give noisier measurements, but allows estimating the position at a higher rate. The noise can be reduced by increasing the HFI voltage.</p></body></html> + MCCONF_FOC_HFI_SAMPLES + 1 + 8 + 16 + 32 + + + Buffer Notification Length + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Send notification when the sample fifo buffer has less than this amount of samples left.</p></body></html> + MCCONF_GPD_BUFFER_NOTIFY_LEFT + 1 + 0 + 2048 + 0 + 0 + 10 + 200 + + 4 + + + Buffer Sampling Interpolation + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Interpolate buffer samples, meaning that they are used for several pwm cycles. This number defines for how many samples a sample is reused. 0 means that a new sample is picked every cycle, 1 means that one sample is used twice etc.</p></body></html> + MCCONF_GPD_BUFFER_INTERPOL + 1 + 0 + 2048 + 0 + 0 + 1 + 0 + + 4 + + + Current Filter Constant + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Constant for the filtered current in the GPD implementation. Will affect how fast the slow abs max current fault triggers. Range 0 to 1, where 0 is the slowest and 1 is no filtering.</span></p></body></html> + MCCONF_GPD_CURRENT_FILTER_CONST + 3 + 1 + 0 + 1 + 0 + 0 + 0.01 + 0.1 + 1 + + 9 + + + Current KP + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Current controller proportional gain.</span></p></body></html> + MCCONF_GPD_CURRENT_KP + 4 + 1 + 0 + 100000 + 0 + 0 + 0.01 + 0.03 + 100000 + + 9 + + + Current KI + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Current controller integral gain.</span></p></body></html> + MCCONF_GPD_CURRENT_KI + 2 + 1 + 0 + 100000 + 0 + 0 + 0.01 + 50 + 100000 + + 9 + + + Speed PID Kp + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Proportional gain for the speed controller. FOC and BLDC need different parameters because their speed controllers differ.</p></body></html> + MCCONF_S_PID_KP + 5 + 1 + 0 + 10000 + 0 + 0 + 0.0001 + 0.004 + 1e+06 + + 9 + + + Speed PID Ki + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Integral gain for the speed controller. FOC and BLDC need different parameters because their speed controllers differ.</p></body></html> + MCCONF_S_PID_KI + 5 + 1 + 0 + 10000 + 0 + 0 + 0.0001 + 0.004 + 1e+06 + + 9 + + + Speed PID Kd + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Derivative gain for the speed controller. FOC and BLDC need different parameters because their speed controllers differ.</p></body></html> + MCCONF_S_PID_KD + 5 + 1 + 0 + 10000 + 0 + 0 + 0.0001 + 0.0001 + 1e+06 + + 9 + + + Speed PID Kd Filer + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Filter on derivative term for speed controller. </span><span style=" font-family:'Roboto';">The range is 0 to 1, where 0 is the maximum amount of filtering (infinite) and 1 is no filtering.</span></p></body></html> + MCCONF_S_PID_KD_FILTER + 3 + 1 + 0 + 1 + 0 + 0 + 0.01 + 0.2 + 1e+06 + + 9 + + + Minimum ERPM + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">ERPM below which the speed controller is disabled.</p></body></html> + MCCONF_S_PID_MIN_RPM + 1 + 1 + 0 + 1e+06 + 0 + 0 + 100 + 900 + 1000 + + 9 + + + Allow Braking + 5 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Allow the speed controller to to apply braking current. In general this option should be enabled, but for some applications it might make sense to disable braking during speed control.</p></body></html> + MCCONF_S_PID_ALLOW_BRAKING + 1 + + + Ramp eRPMs per second + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">This allows to control how fast the input of the speed command is allowed to increase each second. If user does not want to use this ramp, just apply a negative value such as -1.0. Only positive values are considered.</span></p></body></html> + MCCONF_S_PID_RAMP_ERPMS_S + 2 + 1 + 0 + 100000 + -1 + 0 + 1 + -1 + 1000 + + 9 + + + Position PID Kp + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Proportional gain for the position controller.</p></body></html> + MCCONF_P_PID_KP + 5 + 1 + 0 + 10000 + 0 + 0 + 0.001 + 0.03 + 1e+06 + + 9 + + + Position PID Ki + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Integral gain for the position controller.</p></body></html> + MCCONF_P_PID_KI + 5 + 1 + 0 + 10000 + 0 + 0 + 0.001 + 0 + 1e+06 + + 9 + + + Position PID Kd + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Derivative gain for the position controller.</p></body></html> + MCCONF_P_PID_KD + 5 + 1 + 0 + 10000 + 0 + 0 + 0.0001 + 0.0004 + 1e+06 + + 9 + + + Position PID Kd Filer + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Filter on derivative term for position controller. The range is 0 to 1, where 0 is the maximum amount of filtering (infinite) and 1 is no filtering.</span></p></body></html> + MCCONF_P_PID_KD_FILTER + 3 + 1 + 0 + 1 + 0 + 0 + 0.01 + 0.2 + 1e+06 + + 9 + + + Position Angle Division + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Angle division for the position controller. Can be used to map one control rotation to several motor rotations.</p></body></html> + MCCONF_P_PID_ANG_DIV + 3 + 1 + 0 + 10000 + 0 + 0 + 1 + 1 + 100000 + + 9 + + + Startup boost + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Startup boost in current control. Essentially defines the lowest duty cycle to be used in current control mode, to give a bit more punch when starting.</p></body></html> + MCCONF_CC_STARTUP_BOOST_DUTY + 3 + 1 + 0 + 1 + 0 + 0 + 0.005 + 0.01 + 1e+06 + + 9 + + + Minimum Current + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Minimum current used by the current controller. Commanded currents below this value will release the motor.</p></body></html> + MCCONF_CC_MIN_CURRENT + 2 + 1 + 0 + 500 + 0 + 0 + 1 + 0.05 + 1000 + A + 9 + + + Current Controller Gain + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Gain for the BLDC and DC current controller. Should be lower for low inductance motors.</p></body></html> + MCCONF_CC_GAIN + 5 + 1 + 0 + 5 + 0 + 0 + 0.0005 + 0.0046 + 1e+06 + + 9 + + + Current Control Ramp Step Max + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Maximum duty cycle ramp step in current control mode for DC and BLDC motors.</p></body></html> + MCCONF_CC_RAMP_STEP + 4 + 1 + 0 + 1 + 0 + 0 + 0.005 + 0.04 + 1e+06 + + 9 + + + Fault Stop Time + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Amount of time to leave the motor disabled after a fault code.</p></body></html> + MCCONF_M_FAULT_STOP_TIME + 1 + 0 + 30000000 + -1 + 0 + 500 + 500 + ms + 6 + + + Duty Ramp Step Max + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Maximum duty cycle ramp step for DC and BLDC motors.</p></body></html> + MCCONF_M_RAMP_STEP + 4 + 1 + 0 + 1 + 0 + 0 + 0.005 + 0.02 + 1e+06 + + 9 + + + Current Backoff Gain + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Gain for the BLDC and DC current backoff. Used to limit the current in duty cycle mode.</p></body></html> + MCCONF_M_CURRENT_BACKOFF_GAIN + 4 + 1 + 0 + 50 + 0 + 0 + 0.01 + 0.5 + 1e+06 + + 9 + + + ABI Encoder Counts + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Number of counts for the A-B-Index encoder. This usually is the encoder resolution times 4, since every edge in the quadrature signal is counted. This setting only matters when using an ABI encoder.</p></body></html> + MCCONF_M_ENCODER_COUNTS + 1 + 0 + 30000000 + 0 + 0 + 1 + 8192 + + 5 + + + Sensor Port Mode + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Mode for the sensor port. Can be changed for compatibility with different rotor position sensors. Notice that this setting does not have any impact when running sensorless. </span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The modes are:</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">Hall Sensors</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The motor has hall sensors built in which give a position resolution of 120 degrees.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">ABI Encoder</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">A rotary encoder with A-B-Index output. Notice that this encoder does not help until the index pulse is found, so when running FOC open loop mode will be used for up to one mechanical revolution to find the index position when trying to run a motor for the first time after a power cycle.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Notice that you also have to set the number of encoder counts in order to use this type of encoder. This usually is the number of pulses per revolution times 4, since every edge of both pulse trains is counted.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">AS5047 Encoder</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">An AS5047 magnetic encoder connected over SPI. This one provides absolute positions from start, but tends to have a bit of nonlinearity.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">SIN/COS Encoder</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">A Sin/Cos encoder is a position feedback device similar to a quadrature encoder, except instead of outputting digital pulses, it outputs analog voltages with sinusoidal shapes offset by 90°. Provides absolute positions from the start, but its sensitive to EMI and requires special filtering, transient protections and shielded wiring.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">TS5700N8501 Encoder</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">This encoder uses RS485, so it has to be connected to the COMM port. A RS485-transceiver such as the </span><span style=" font-family:'sans-serif';">ADM485 is required, where RX and TX are used as the data lines. ADC1 is used to trigger between RX and TX, which is needed as the communication is half duplex. To use this encoder, you have to make sure that no app uses UART or ADC1.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'sans-serif';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">TS5700N8501 Encoder Multiturn</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Same as above, but uses the multiturn function. The angle is divided by 10000, thus can be used for up to 10000 revolutions. The position PID parameters need to be increased by a factor of around 10000 for this to work similarly to the single turn mode. Note that this is not a good implementation and needs improvement in the future. 180 degrees PID setpoint corresponds to multiturn position 0.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'sans-serif';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto'; font-weight:600;">MT6816 Encoder</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">A magnetic encoder using a high speed SPI communication. Provides absolute position from start. It has to be connected to a hardware-based SPI peripheral.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p></body></html> + MCCONF_M_SENSOR_PORT_MODE + 0 + Hall Sensors + ABI Encoder + AS5047 Encoder + AD2S1205 Resolver + Sin/Cos Encoder + TS5700N8501 Encoder + TS5700N8501 Encoder (Multiturn) + MT6816 Encoder (SPI) + + + Invert Motor Direction + 5 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Invert the motor direction. This option can be used to make the motor turn in the opposite direction. All state and control commands in <span style=" font-weight:600;">mc_interface</span> will respect this setting, so it should work as well as swithcing two motor cables for all applications.</p></body></html> + MCCONF_M_INVERT_DIRECTION + 0 + + + DRV8301 OC Mode + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The mode for the over current protection feature of the DRV8301. The over current protection in the DRV8301 works by measuring the voltage drop across the MOSFETs and shuts them off of it exceeds a configurable limit.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Notice</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">This setting only has impact on hardware with the DRV8301</p></body></html> + MCCONF_M_DRV8301_OC_MODE + 0 + Current Limit + OC Latch Shutdown + Report Only + Disabled + + + DRV8301 OC Adjustment + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The threshold for the over current protection feature of the DRV8301. Lower values correspond to lower currents. See the datasheet for more imformation about this setting.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Notice</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">This setting only has impact on hardware with the DRV8301</p></body></html> + MCCONF_M_DRV8301_OC_ADJ + 1 + 0 + 31 + 0 + 0 + 1 + 16 + + 1 + + + Minimum Switching Frequency + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The minimum switching frequency in BLDC mode.</p></body></html> + MCCONF_M_BLDC_F_SW_MIN + 2 + 0.001 + 0 + 40000 + 3000 + 0 + 1 + 3000 + 1 + kHz + 9 + + + Maximum Switching Frequency + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The maximum switching frequency in BLDC mode.</p></body></html> + MCCONF_M_BLDC_F_SW_MAX + 2 + 0.001 + 0 + 40000 + 3000 + 0 + 1 + 35000 + 1 + kHz + 9 + + + Switching Frequency + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The switching frequency in DC mode.</p></body></html> + MCCONF_M_DC_F_SW + 2 + 0.001 + 0 + 25000 + 3000 + 0 + 1 + 25000 + 1 + kHz + 9 + + + Beta Value for Motor Thermistor + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Beta Value for Motor Thermistor.</p></body></html> + MCCONF_M_NTC_MOTOR_BETA + 1 + 1 + 0 + 100000 + 100 + 0 + 1 + 3380 + 1 + K + 9 + + + Auxiliary Output Mode + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Auxiliary output mode. Can be used to e.g. activate a relay after a certain delay for bus capacitor precharging.</span></p></body></html> + MCCONF_M_OUT_AUX_MODE + 0 + Off + On after 2 seconds + On after 5 seconds + On after 10 seconds + Unused + + + Motor Temperature Sensor Type + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Motor temperature sensor type. Most small hobby motors have a 10K NTC thermistor, whereas some larger motors have 1K PTC thermistors (such as the KTY84).</p></body></html> + MCCONF_M_MOTOR_TEMP_SENS_TYPE + 0 + NTC 10K at 25°C + PTC 1K at 100 °C + KTY83/122 + NTC 100K at 25°C + + + Coefficient for PTC Motor Thermistor + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Coefficient for PTC Motor Thermistor. Unit: %/K</span></p></body></html> + MCCONF_M_PTC_MOTOR_COEFF + 3 + 1 + 0 + 100 + 0.05 + 0 + 0.01 + 0.61 + 1 + %/K + 9 + + + Hall Sensor Extra Samples + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Read the hall sensor port this many extra samples and use a median filter. Increasing this number will reduce noise on the hall sensor readings, but makes the motor control interrupt take longer and thus limits the maximum switching frequency.</p></body></html> + MCCONF_M_HALL_EXTRA_SAMPLES + 1 + 0 + 99 + 0 + 0 + 1 + 1 + + 1 + + + Motor Poles + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Motor pole count. Most outrunners have 14 poles. Inrunners usually have 2 or 4 poles. The motor pole count is required for speed and travel distance calculation.</p></body></html> + MCCONF_SI_MOTOR_POLES + 1 + 0 + 254 + 2 + 0 + 2 + 14 + + 1 + + + Gear Ratio + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Gear ratio. For example, if the motor has a 12 tooth pulley and the wheel has a 36 tooth pulley, the gear ratio is:</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">36 / 12 = <span style=" font-weight:600;">3.0</span></p></body></html> + MCCONF_SI_GEAR_RATIO + 3 + 1 + 0 + 9999 + 0 + 0 + 0.1 + 3 + 1 + + 9 + + + Wheel Diameter + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Wheel diameter, in mm.</p></body></html> + MCCONF_SI_WHEEL_DIAMETER + 2 + 1000 + 0 + 9999 + 0 + 0 + 1 + 0.083 + 1 + mm + 9 + + + Battery Type + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Battery Type</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">BATTERY_TYPE_LIION_3_0__4_2</span>,</p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Lithoium ion, voltage range: 3.0 to 4.2</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">BATTERY_TYPE_LIIRON_2_6__3_6</span>,</p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Lithoium iron phosphate, voltage range: 2.6 to 3.6</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">BATTERY_TYPE_LEAD_ACID</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Lead Acic, voltage range: 2.1 to 2.36</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p></body></html> + MCCONF_SI_BATTERY_TYPE + 0 + BATTERY_TYPE_LIION_3_0__4_2 + BATTERY_TYPE_LIIRON_2_6__3_6 + BATTERY_TYPE_LEAD_ACID + + + Battery Cells Series + 2 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Battery cells in series.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p></body></html> + MCCONF_SI_BATTERY_CELLS + 1 + 0 + 255 + 1 + 0 + 1 + 3 + + 1 + + + Battery Capacity + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Battery capacity in ampere hours.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p></body></html> + MCCONF_SI_BATTERY_AH + 3 + 1 + 0 + 1000 + 0 + 0 + 0.1 + 6 + 1 + Ah + 9 + + + Motor Brand + 3 + 0 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The motor brand, e.g. Turnigy.</p></body></html> + + Unnamed + + + Motor Model + 3 + 0 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The motor model, e.g. 6374 168KV.</p></body></html> + + Not Specified + + + Motor Weight + 1 + 0 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The weight of the motor in grams.</span></p></body></html> + + 2 + 1 + 0 + 500000 + 0 + 0 + 1 + 0 + 1 + g + 9 + + + Motor Poles + 2 + 0 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The number of motor poles. This is always a multiple of two.</span></p></body></html> + + 1 + 0 + 100 + 2 + 0 + 2 + 14 + + 1 + + + Position Sensor + 4 + 0 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Does this motor come with some kind of position sensor?</p></body></html> + + 0 + No sensor + Hall Sensors + ABI Encoder + AS5047 Encoder + Other Sensor + + + Motor Description + 3 + 0 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">This is an editor where a description can be stored for your motor configuration. Images can also be inserted. Notice that this information is not written to the VESC, so it has to be stored in an XML file.</span></p></body></html> + + A motor description can be edited here. + + + Motor Loss Torque + 1 + 0 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The motor loss torque in nm.</span></p></body></html> + + 2 + 1 + 0 + 99 + 0 + 0 + 0.01 + 0.03 + 1 + nm + 9 + + + Bearing Quality + 2 + 0 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Motor bearing quality. 0 is neutral/unknown, negative is bad and positive is good.</span></p></body></html> + + 1 + 0 + 5 + -5 + 1 + 1 + 0 + + 2 + + + Magnet Quality + 2 + 0 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Motor magnet quality. 0 is neutral/unknown, negative is bad and positive is good.</span></p></body></html> + + 1 + 0 + 5 + -5 + 1 + 1 + 0 + + 2 + + + Construction Quality + 2 + 0 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">Motor construction quality. 0 is neutral/unknown, negative is bad and positive is good.</span></p></body></html> + + 1 + 0 + 5 + -5 + 1 + 1 + 0 + + 2 + + + Quality Description + 3 + 0 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">A text summary of the motor quality.</p></body></html> + + Some comments about the motor quality. Images can be added as well. + + + BMS Type + 4 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Type of BMS. This determines how BMS-related messages on the CAN-bus are interpreted. Options are:</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">None</span>:</p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">No BMS is used. All messages on the CAN-bus are ignored by the BMS module.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">VESC BMS:</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The VESC BMS is used.</p></body></html> + MCCONF_BMS_TYPE + 1 + None + VESC BMS + + + Temperature Limit Start + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The battery temperature above which battery current starts to get reduced.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">If there is more than one BMS on the CAN-bus, the one with the highest value will be ued.</span></p></body></html> + MCCONF_BMS_T_LIMIT_START + 1 + 1 + 0 + 99 + 0 + 1 + 1 + 45 + 100 + °C + 7 + + + Temperature Limit End + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The battery temperature above which battery current is not allowed and a fault is thrown.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">If there is more than one BMS on the CAN-bus, the one with the highest value will be ued.</span></p></body></html> + MCCONF_BMS_T_LIMIT_END + 1 + 1 + 0 + 99 + 0 + 1 + 1 + 65 + 100 + °C + 7 + + + SOC Limit Start + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The battery state of charge (SOC) below which battery current starts to get reduced.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">If there is more than one BMS on the CAN-bus, the one with the lowest value will be ued.</span></p></body></html> + MCCONF_BMS_SOC_LIMIT_START + 2 + 1 + 1 + 1 + 0 + 1 + 0.01 + 0.05 + 1000 + + 7 + + + SOC Limit End + 1 + 1 + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Roboto'; ; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">The battery state of charge (SOC) below which battery current is not allowed anymore.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Roboto';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Roboto';">If there is more than one BMS on the CAN-bus, the one with the lowest value will be ued.</span></p></body></html> + MCCONF_BMS_SOC_LIMIT_END + 2 + 1 + 1 + 1 + 0 + 1 + 0.01 + 0 + 1000 + + 7 + + + + pwm_mode + comm_mode + motor_type + sensor_mode + l_current_max + l_current_min + l_in_current_max + l_in_current_min + l_abs_current_max + l_min_erpm + l_max_erpm + l_erpm_start + l_max_erpm_fbrake + l_max_erpm_fbrake_cc + l_min_vin + l_max_vin + l_battery_cut_start + l_battery_cut_end + l_slow_abs_current + l_temp_fet_start + l_temp_fet_end + l_temp_motor_start + l_temp_motor_end + l_temp_accel_dec + l_min_duty + l_max_duty + l_watt_max + l_watt_min + l_current_max_scale + l_current_min_scale + l_duty_start + sl_min_erpm + sl_min_erpm_cycle_int_limit + sl_max_fullbreak_current_dir_change + sl_cycle_int_limit + sl_phase_advance_at_br + sl_cycle_int_rpm_br + sl_bemf_coupling_k + hall_table__0 + hall_table__1 + hall_table__2 + hall_table__3 + hall_table__4 + hall_table__5 + hall_table__6 + hall_table__7 + hall_sl_erpm + foc_current_kp + foc_current_ki + foc_f_sw + foc_dt_us + foc_encoder_inverted + foc_encoder_offset + foc_encoder_ratio + foc_encoder_sin_gain + foc_encoder_cos_gain + foc_encoder_sin_offset + foc_encoder_cos_offset + foc_encoder_sincos_filter_constant + foc_sensor_mode + foc_pll_kp + foc_pll_ki + foc_motor_l + foc_motor_ld_lq_diff + foc_motor_r + foc_motor_flux_linkage + foc_observer_gain + foc_observer_gain_slow + foc_duty_dowmramp_kp + foc_duty_dowmramp_ki + foc_openloop_rpm + foc_openloop_rpm_low + foc_d_gain_scale_start + foc_d_gain_scale_max_mod + foc_sl_openloop_hyst + foc_sl_openloop_time_lock + foc_sl_openloop_time_ramp + foc_sl_openloop_time + foc_hall_table__0 + foc_hall_table__1 + foc_hall_table__2 + foc_hall_table__3 + foc_hall_table__4 + foc_hall_table__5 + foc_hall_table__6 + foc_hall_table__7 + foc_hall_interp_erpm + foc_sl_erpm + foc_sample_v0_v7 + foc_sample_high_current + foc_sat_comp + foc_temp_comp + foc_temp_comp_base_temp + foc_current_filter_const + foc_cc_decoupling + foc_observer_type + foc_hfi_voltage_start + foc_hfi_voltage_run + foc_hfi_voltage_max + foc_sl_erpm_hfi + foc_hfi_start_samples + foc_hfi_obs_ovr_sec + foc_hfi_samples + gpd_buffer_notify_left + gpd_buffer_interpol + gpd_current_filter_const + gpd_current_kp + gpd_current_ki + s_pid_kp + s_pid_ki + s_pid_kd + s_pid_kd_filter + s_pid_min_erpm + s_pid_allow_braking + s_pid_ramp_erpms_s + p_pid_kp + p_pid_ki + p_pid_kd + p_pid_kd_filter + p_pid_ang_div + cc_startup_boost_duty + cc_min_current + cc_gain + cc_ramp_step_max + m_fault_stop_time_ms + m_duty_ramp_step + m_current_backoff_gain + m_encoder_counts + m_sensor_port_mode + m_invert_direction + m_drv8301_oc_mode + m_drv8301_oc_adj + m_bldc_f_sw_min + m_bldc_f_sw_max + m_dc_f_sw + m_ntc_motor_beta + m_out_aux_mode + m_motor_temp_sens_type + m_ptc_motor_coeff + m_hall_extra_samples + si_motor_poles + si_gear_ratio + si_wheel_diameter + si_battery_type + si_battery_cells + si_battery_ah + bms.type + bms.t_limit_start + bms.t_limit_end + bms.soc_limit_start + bms.soc_limit_end + + + + General + + General + + motor_type + m_invert_direction + m_sensor_port_mode + m_encoder_counts + + + + Current + + ::sep::Motor + l_current_max + l_current_min + l_abs_current_max + l_slow_abs_current + l_current_max_scale + l_current_min_scale + ::sep::Battery + l_in_current_max + l_in_current_min + ::sep::DRV8301 + m_drv8301_oc_mode + m_drv8301_oc_adj + + + + Voltage + + l_battery_cut_start + l_battery_cut_end + + + + RPM + + l_max_erpm + l_min_erpm + l_erpm_start + + + + Wattage + + l_watt_max + l_watt_min + + + + Temperature + + ::sep::General + l_temp_accel_dec + ::sep::MOSFET + l_temp_fet_start + l_temp_fet_end + ::sep::Motor + l_temp_motor_start + l_temp_motor_end + + + + BMS + + bms.type + bms.t_limit_start + bms.t_limit_end + bms.soc_limit_start + bms.soc_limit_end + + + + Advanced + + l_min_vin + l_max_vin + l_min_duty + l_max_duty + cc_min_current + m_fault_stop_time_ms + m_out_aux_mode + m_motor_temp_sens_type + m_ntc_motor_beta + m_ptc_motor_coeff + l_duty_start + m_hall_extra_samples + + + + + BLDC + + General + + sensor_mode + comm_mode + cc_startup_boost_duty + + + + Sensorless + + sl_cycle_int_limit + sl_min_erpm + sl_min_erpm_cycle_int_limit + sl_bemf_coupling_k + + + + Sensors + + hall_sl_erpm + hall_table__0 + hall_table__1 + hall_table__2 + hall_table__3 + hall_table__4 + hall_table__5 + hall_table__6 + hall_table__7 + + + + Advanced + + sl_phase_advance_at_br + sl_cycle_int_rpm_br + l_max_erpm_fbrake + pwm_mode + cc_gain + cc_ramp_step_max + m_duty_ramp_step + m_current_backoff_gain + m_bldc_f_sw_min + m_bldc_f_sw_max + + + + + DC + + General + + cc_gain + cc_ramp_step_max + m_duty_ramp_step + m_current_backoff_gain + m_dc_f_sw + + + + + FOC + + General + + foc_sensor_mode + foc_motor_r + foc_motor_l + foc_motor_flux_linkage + foc_current_kp + foc_current_ki + foc_observer_gain + + + + Sensorless + + foc_openloop_rpm + foc_openloop_rpm_low + foc_sl_openloop_hyst + foc_sl_openloop_time_lock + foc_sl_openloop_time_ramp + foc_sl_openloop_time + foc_sat_comp + foc_temp_comp + foc_temp_comp_base_temp + + + + Hall Sensors + + foc_sl_erpm + foc_hall_interp_erpm + foc_hall_table__0 + foc_hall_table__1 + foc_hall_table__2 + foc_hall_table__3 + foc_hall_table__4 + foc_hall_table__5 + foc_hall_table__6 + foc_hall_table__7 + m_hall_extra_samples + + + + Encoder + + foc_sl_erpm + foc_encoder_offset + foc_encoder_ratio + foc_encoder_inverted + foc_encoder_sin_gain + foc_encoder_sin_offset + foc_encoder_cos_gain + foc_encoder_cos_offset + foc_encoder_sincos_filter_constant + + + + HFI + + foc_hfi_samples + foc_hfi_voltage_start + foc_hfi_voltage_run + foc_hfi_voltage_max + foc_sl_erpm_hfi + foc_hfi_start_samples + foc_hfi_obs_ovr_sec + + + + Advanced + + foc_f_sw + foc_dt_us + foc_pll_kp + foc_pll_ki + foc_duty_dowmramp_kp + foc_duty_dowmramp_ki + foc_sample_v0_v7 + foc_sample_high_current + foc_observer_gain_slow + foc_current_filter_const + foc_cc_decoupling + foc_observer_type + foc_motor_ld_lq_diff + foc_d_gain_scale_start + foc_d_gain_scale_max_mod + + + + + GPD + + General + + pwm_mode + gpd_buffer_notify_left + gpd_buffer_interpol + gpd_current_filter_const + gpd_current_kp + gpd_current_ki + + + + + PID Controllers + + General + + ::sep::Speed Controller + s_pid_kp + s_pid_ki + s_pid_kd + s_pid_kd_filter + s_pid_min_erpm + s_pid_allow_braking + s_pid_ramp_erpms_s + ::sep::Position Controller + p_pid_kp + p_pid_ki + p_pid_kd + p_pid_kd_filter + p_pid_ang_div + + + + + Additional Info + + Setup + + si_motor_poles + si_gear_ratio + si_wheel_diameter + si_battery_type + si_battery_cells + si_battery_ah + + + + General + + motor_brand + motor_model + motor_weight + motor_poles + motor_sensor_type + motor_loss_torque + + + + Quality + + motor_quality_bearings + motor_quality_magnets + motor_quality_construction + + + + + diff --git a/plugins/vesc/runtime/schemas/NOTICE b/plugins/vesc/runtime/schemas/NOTICE new file mode 100644 index 0000000..90faf71 --- /dev/null +++ b/plugins/vesc/runtime/schemas/NOTICE @@ -0,0 +1 @@ +Firmware 5.02 configuration definitions from official vedderb/vesc_tool commit 01d5f10901116c311e3fb84d5a1541f663d3ce20, res/config/5.02. Copyright Benjamin Vedder and contributors; see VESC_TOOL_LICENSE. Definitions are unchanged. diff --git a/plugins/vesc/runtime/schemas/VESC_TOOL_LICENSE b/plugins/vesc/runtime/schemas/VESC_TOOL_LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/plugins/vesc/runtime/schemas/VESC_TOOL_LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/plugins/vesc/runtime/serial.py b/plugins/vesc/runtime/serial.py new file mode 100644 index 0000000..2cd5da1 --- /dev/null +++ b/plugins/vesc/runtime/serial.py @@ -0,0 +1,163 @@ +"""Exclusive serial ownership and OS attachment generation checks.""" + +import fcntl +import hashlib +import os +from pathlib import Path +import re +import select +import stat +import termios +import time +from dataclasses import dataclass + +from .protocol import Decoder, request, test_packet, current_packet, speed_packet, hall_packet + + +def device_id(value): + return "vesc_" + hashlib.sha256(value.encode()).hexdigest()[:32] + + +@dataclass(frozen=True) +class Attachment: + usb: str + address: str + tty: str + speed: str + + @property + def binding(self): + return self.usb + ":" + self.address + + @property + def id(self): + return device_id("provisional:" + self.binding) + + +def attachment_at(path): + """Read one physical USB generation; never walk sibling devices or drivers.""" + if not re.fullmatch(r"[0-9]+-[0-9]+(?:\.[0-9]+)*", path.name): return None + try: + if ((path / "idVendor").read_text().strip() != "0483" + or (path / "idProduct").read_text().strip() != "5740" + or (path / "product").read_text().strip() != "ChibiOS/RT Virtual COM Port"): + return None + address = (path / "devnum").read_text().strip() + tty = [p.name for p in path.glob(path.name + ":*/tty/ttyACM*") + if re.fullmatch(r"ttyACM[0-9]+", p.name)] + speed = (path / "speed").read_text().strip() + " Мбит/с" + if len(tty) != 1 or address != (path / "devnum").read_text().strip(): return None + return Attachment(path.name, address, tty[0], speed) + except (OSError, ValueError): return None + + +def check_attachment(attachment, root=Path("/sys/bus/usb/devices")): + if (not re.fullmatch(r"[0-9]+-[0-9]+(?:\.[0-9]+)*", attachment.usb) + or attachment_at(root / attachment.usb) != attachment): + raise OSError("USB attachment changed") + + +def discover(root=Path("/sys/bus/usb/devices")): + found = [attachment_at(path) for path in sorted(root.iterdir())] + return [item for item in found if item is not None][:128] + + +class Link: + def __init__(self, attachment): + self.attachment = attachment + self.fd = -1 + self.decoder = Decoder() + self.hall_result = None + self.hall_pending = False + self.check() + fd = os.open("/dev/" + attachment.tty, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK | os.O_NOFOLLOW) + try: + info = os.fstat(fd) + if not stat.S_ISCHR(info.st_mode) or os.major(info.st_rdev) != 166: + raise ValueError("Not a CDC ACM device") + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + fcntl.ioctl(fd, termios.TIOCEXCL) + settings = termios.tcgetattr(fd) + settings[0] = settings[1] = settings[3] = 0 + settings[2] = termios.CLOCAL | termios.CREAD | termios.CS8 + settings[4] = settings[5] = termios.B115200 + settings[6][termios.VMIN] = settings[6][termios.VTIME] = 0 + termios.tcsetattr(fd, termios.TCSANOW, settings) + self.check() + self.fd = fd + except BaseException: + os.close(fd) + raise + + def check(self): + check_attachment(self.attachment) + + def close(self): + if self.fd >= 0: + os.close(self.fd) + self.fd = -1 + + def query(self, command, timeout=2): + return self._exchange(request(command), command, timeout) + + def _exchange(self, payload, command, timeout): + self.check() + if not self.hall_pending: + self.decoder = Decoder() + termios.tcflush(self.fd, termios.TCIFLUSH) + deadline = time.monotonic() + min(timeout, 8 if command == 62 else 2) + sent = 0 + while sent < len(payload): + if not select.select([], [self.fd], [], max(0, deadline - time.monotonic()))[1]: + raise TimeoutError("Serial write timeout") + sent += os.write(self.fd, payload[sent:]) + total = 0 + while time.monotonic() < deadline: + if not select.select([self.fd], [], [], max(0, deadline - time.monotonic()))[0]: + break + raw = os.read(self.fd, 4096) + if not raw: + raise OSError("Serial device disconnected") + total += len(raw) + if total > 32768: + raise ValueError("Unexpected serial traffic") + answer = None + for packet in self.decoder.feed(raw): + if self.hall_pending and packet[0] == 28: + self.hall_result = packet + if packet[0] == command: + answer = packet + if answer is not None: + self.check() + return answer + raise TimeoutError("Controller did not reply") + + def test_command(self, action): + self._test_write(test_packet(action)) + + def test_current(self, current_a): + self._test_write(current_packet(current_a)) + + def test_speed(self, erpm): + self._test_write(speed_packet(erpm)) + + def set_temporary_limits(self, config): + from .temporary_limits import packet + if self._exchange(packet(config), 48, 2) != bytes([48]): + raise ValueError("Invalid volatile limits ACK") + + def detect_hall(self): + if self.hall_pending: raise ValueError("Hall detection already started") + self.decoder = Decoder() + self.hall_result = None + self.hall_pending = True + self._test_write(hall_packet()) + + def _test_write(self, payload): + self.check() + deadline = time.monotonic() + 0.04 + sent = 0 + while sent < len(payload): + if not select.select([], [self.fd], [], max(0, deadline - time.monotonic()))[1]: + raise TimeoutError("Test command write timeout") + sent += os.write(self.fd, payload[sent:]) diff --git a/plugins/vesc/runtime/server.py b/plugins/vesc/runtime/server.py new file mode 100644 index 0000000..25bb2e5 --- /dev/null +++ b/plugins/vesc/runtime/server.py @@ -0,0 +1,139 @@ +"""Private Unix socket endpoint; peer UID must be the installed Node service.""" + +import json +import os +from pathlib import Path +import pwd +import re +import socket +import socketserver +import struct +import threading +from http.server import BaseHTTPRequestHandler +from urllib.parse import urlsplit, parse_qs + +from .service import Service +from .remote_control import RemoteControl + + +class Handler(BaseHTTPRequestHandler): + def log_message(self, *_): + pass + + def do_GET(self): + self.dispatch() + + def do_POST(self): + self.dispatch() + + def dispatch(self): + self.connection.settimeout(10) + status = 200 + try: + node = self.headers.get("X-Node-Id", "") + if not re.fullmatch(r"[a-zA-Z0-9_.:-]{1,128}", node) or self.headers.get("Transfer-Encoding"): + raise ValueError("Invalid request") + if self.command == "GET" and self.path == "/inventory": + result = self.server.service.inventory(node) + elif self.command == "GET" and self.path.startswith("/archives/"): + url = urlsplit(self.path) + parts = url.path.split("/") + if len(parts) not in (3, 4) or not re.fullmatch(r"vesc_[0-9a-f]{32}", parts[2]): + raise ValueError("Invalid archive target") + archive = self.server.service.archive + if len(parts) == 4: + result = archive.read("local", parts[2], parts[3]) + else: + before = int(parse_qs(url.query).get("before", ["0"])[0]) + result = archive.listing("local", parts[2], before) + elif self.command == "GET" and self.path.startswith("/archive-export?"): + after = int(parse_qs(urlsplit(self.path).query).get("after", ["0"])[0]) + result = self.server.service.archive.export("local", after) + elif self.command == "POST" and self.path in ("/operation", "/remote"): + size = int(self.headers.get("Content-Length", "0")) + if not 0 < size <= 65536 or self.headers.get("Content-Type") != "application/json": + raise ValueError("Invalid command") + raw = self.rfile.read(size) + if len(raw) != size: + raise ValueError("Truncated command") + result = (self.server.service.execute(json.loads(raw)) if self.path == "/operation" + else self.server.service.remote.feed(json.loads(raw))) + else: + raise ValueError("Unknown route") + except (ValueError, KeyError, TypeError, OSError): + status, result = 400, {"error": "Запрос VESC отклонён. Обновите сведения об устройстве."} + data = json.dumps(result, ensure_ascii=False, allow_nan=False).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.send_header("Connection", "close") + self.end_headers() + self.wfile.write(data) + + +class Server(socketserver.ThreadingMixIn, socketserver.UnixStreamServer): + daemon_threads = True + + def __init__(self, path, handler): + self.slots = threading.BoundedSemaphore(8) + super().__init__(path, handler) + + def process_request(self, request, address): + if not self.slots.acquire(blocking=False): + self.shutdown_request(request) + return + try: + super().process_request(request, address) + except BaseException: + self.slots.release() + raise + + def process_request_thread(self, request, address): + try: + super().process_request_thread(request, address) + finally: + self.slots.release() + + def verify_request(self, request, address): + _, uid, _ = struct.unpack("3i", request.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12)) + return uid == self.node_uid + + +def main(): + if os.geteuid() == 0: + raise RuntimeError("VESC must run as its own unprivileged user") + os.umask(0o007) + service = Service("/var/lib/mission-core-vesc") + service.remote = RemoteControl(service) + stop = threading.Event() + + def scan(): + while not stop.is_set(): + try: + service.scan() + except OSError: + # A transient sysfs race must not silently kill discovery. + pass + stop.wait(2) + + def observe(): + while not stop.is_set(): + service.remote.observe() + stop.wait(.2) + + path = Path("/run/mission-core-vesc/driver.sock") + path.unlink(missing_ok=True) + with Server(str(path), Handler) as server: + server.node_uid = pwd.getpwnam("mission-core-node").pw_uid + server.service = service + thread = threading.Thread(target=scan, daemon=True) + thread.start() + threading.Thread(target=observe, daemon=True, name="vesc-observer").start() + try: + server.serve_forever() + finally: + stop.set() + + +if __name__ == "__main__": + main() diff --git a/plugins/vesc/runtime/service.py b/plugins/vesc/runtime/service.py new file mode 100644 index 0000000..3774ade --- /dev/null +++ b/plugins/vesc/runtime/service.py @@ -0,0 +1,364 @@ +"""One onboard owner; both operator surfaces consume the same bounded device operations.""" + +import base64 +import hashlib +import json +import os +from pathlib import Path +import re +import tempfile +import threading +import time +import uuid +from datetime import datetime, timezone + +from . import MODEL, SCHEMA, VERSION +from .protocol import firmware, values, ppm, TEST_LIMITS, SPEED_LIMITS +from .motor_test import MotorTest, Rejected +from .drive_profile import DriveProfile, slot_label, validate as validate_drive +from .serial import device_id, discover +from .native_link import NativeLink +try: + from .archive import Archive +except ImportError: # Source checkout; packaging copies this exact shared file. + from k1link.device_plugins.vesc.archive import Archive + +ACTIONS = frozenset({"verify", "details", "vesc.link.check", "vesc.telemetry.read", "vesc.limits.read", "vesc.config.backup", "vesc.input.read", "vesc.can.read", "vesc.drive.assign", "vesc.drive.unassign", "vesc.drive.layout", "vesc.motor.pulse", "vesc.motor.run", "vesc.drive.run", "vesc.hall.measure", "vesc.foc.calibrate", "vesc.motor.stop", "vesc.control.release"}) + + +def utc(): + return datetime.now(timezone.utc).isoformat() + + +def atomic(path, value): + fd, name = tempfile.mkstemp(prefix=".vesc-", dir=path.parent) + try: + with os.fdopen(fd, "w") as stream: + os.fchmod(stream.fileno(), 0o600) + json.dump(value, stream, ensure_ascii=False, allow_nan=False) + stream.flush() + os.fsync(stream.fileno()) + os.replace(name, path) + fd = os.open(path.parent, os.O_RDONLY) + try: + os.fsync(fd) + finally: + os.close(fd) + finally: + if os.path.exists(name): + os.unlink(name) + + +class Device: + def __init__(self, attachment): + self.attachment = attachment + self.id = attachment.id + self.session = "vesc_" + uuid.uuid4().hex + self.opened = utc() + self.link = None + self.identity = None + self.error = None + self.telemetry = None + self.backup = None + self.lock = threading.Lock() + self.retry_at = 0 + + @property + def readable(self): + identity = self.identity + return self.readable_identity(identity) + + @staticmethod + def readable_identity(identity): + return bool(identity and identity["major"] in (5, 6, 7) + and identity["hardware_type"] in (None, 0)) + + def connect(self, factory): + with self.lock: + try: + self.session = "vesc_" + uuid.uuid4().hex + self.link = factory(self.attachment) + identity = firmware(self.link.query(0)) + self.identity = identity + self.id = device_id("uuid:" + identity["uuid"]) + self.error = None + except (OSError, ValueError, TimeoutError): + if self.link: + self.link.close() + self.link = None + self.error = "Контроллер не ответил. Проверьте питание, USB и доступность порта." + self.retry_at = time.monotonic() + 15 + + def close(self): + with self.lock: + if self.link: + self.link.close() + self.link = None + + +class Service: + def __init__(self, root, discover_fn=discover, link_factory=NativeLink): + self.root = Path(root) + self.root.mkdir(mode=0o700, parents=True, exist_ok=True) + self.archive = Archive(self.root / "archive") + for path in sorted(self.root.glob("backup_op_*.json")): + self.archive.add("local", json.loads(path.read_text())) + self.discover_fn, self.link_factory = discover_fn, link_factory + self.devices = {} + self.lock = threading.RLock() + self.operation_lock = threading.Lock() + self.journal_lock = threading.Lock() + self.motor = MotorTest(self, atomic, utc) + self.drive = DriveProfile(self.root, atomic) + self.instance = "vesc_" + uuid.uuid4().hex + self.revision = 0 + + def scan(self): + attachments = {item.binding: item for item in self.discover_fn()} + with self.lock: + removed = [self.devices.pop(k) for k, d in list(self.devices.items()) + if attachments.get(k) != d.attachment] + for key, item in attachments.items(): + if key not in self.devices: + self.devices[key] = Device(item) + devices = list(self.devices.values()) + for device in removed: + device.close() + for device in devices: + if device.link is not None and not getattr(device.link, "alive", True): + device.close() + if device.link is None and time.monotonic() >= device.retry_at: + device.connect(self.link_factory) + if self.operation_lock.acquire(blocking=False): + try: + for device in devices: + if device.link is not None and self.motor.limits.pending(device): + with device.lock: + try: + self.motor.limits.restore(device) + device.error = None + except (OSError, ValueError, TimeoutError): + device.error = "Прежние токовые пределы ещё не восстановлены. Новые проверки заблокированы." + finally: + self.operation_lock.release() + with self.lock: + self.revision += 1 + + def inventory(self, node_id): + with self.lock: + # Copy each generation before counting identities. Serial I/O never + # holds the inventory lock; it can complete during this projection. + devices = [d.__dict__.copy() for d in self.devices.values()] + keys = [device_id("uuid:" + d["identity"]["uuid"]) if d["identity"] and d["link"] else d["attachment"].id for d in devices] + items = [] + for d, key in zip(devices, keys): + identity, attachment = d["identity"], d["attachment"] + unique = keys.count(key) == 1 and identity is not None and d["link"] is not None + identifier = key if unique else attachment.id + message = d["error"] if keys.count(key) == 1 else "Контроллеры сообщили одинаковый UUID. Настройка недоступна." + items.append({"id": identifier, "attachment_id": attachment.id, + "name": "VESC " + (identity["uuid"][:6].upper() if unique else "· USB " + attachment.usb), + "model": identity["hardware"] if unique else "VESC · USB", "kind": MODEL, + "firmware": identity["version"] if unique else None, + "initializable": True, "prepared": True, "configured": unique, "verified": unique, + "preparation_safe": True, "online": True, "usb": attachment.speed, + "connection_label": "USB " + attachment.usb + next((" · " + slot_label(self.drive.value["layout"], slot) for slot, binding in self.drive.value["bindings"].items() if binding["device_id"] == identifier), ""), "layers": [], + "vesc_status": {"identity": identity if unique else None, "readable": unique and Device.readable_identity(identity), + "engine": getattr(d["link"], "engine", None), "message": message, "telemetry": d["telemetry"], "backup": d["backup"], "board_settings_supported": True, "group_test_supported": True, "link_check_supported": True, "test_supported": unique and identity["version"] == "5.02" and identity["hardware"] == "75_300_R2", "drive_profile": self.drive.value, "test_limits": TEST_LIMITS, "speed_limits": SPEED_LIMITS, "hall_measurement": {"current_a": 5, "interruptible": False, "standstill_confirmation_required": True}, "foc_calibration": {"min_power_loss_w": 10, "max_power_loss_w": 150, "interruptible": False}, "test_mode": self.motor.mode, "test_active": self.motor.active, "rc_latched": self.motor.latched}, + "snapshot": {"context": {"session_id": d["session"], + "device": {"device_id": identifier, "model": {"plugin_id": "missioncore.vesc", + "plugin_version": VERSION, "model_id": MODEL}, + "stability": "stable" if unique else "provisional", + "basis": "hardware-identifier" if unique else "transport-local"}, + "execution": {"node_id": node_id, "agent_instance_id": self.instance, "platform": "linux"}, + "opened_at": d["opened"]}, "revision": self.revision, "observed_at": utc(), + "enrollment": "enrolled" if unique else "empty", "acquisition": "idle", + "connectivity": "connected" if unique else "degraded", "message": message}}) + return {"items": items} + + def validate(self, command): + if not isinstance(command, dict) or command.get("api_version") != SCHEMA or command.get("kind") != "OperationRequest": + raise ValueError("Invalid contract") + identifier = command.get("operation_id", "") + if not re.fullmatch(r"op_[0-9a-f]{32}", identifier) or command.get("idempotency_key") != identifier: + raise ValueError("Invalid operation identity") + action, params = command.get("action_id"), command.get("parameters") + if action not in ACTIONS or not isinstance(params, dict): + raise ValueError("Unsupported operation") + if action in ("vesc.motor.pulse", "vesc.motor.run", "vesc.drive.run", "vesc.control.release"): + keys = {"sessions", "rig_clear", "duration_s", "current_a"} | ({"standstill_confirmed"} if action != "vesc.motor.pulse" else set()) | ({"erpm"} if action in ("vesc.motor.run", "vesc.drive.run") else set()) | ({"profile_revision", "device_ids"} if action == "vesc.drive.run" else set()) + if (set(params) != keys or params["rig_clear"] is not True + or not isinstance(params["sessions"], dict) or not 1 <= len(params["sessions"]) <= 128 + or type(params["current_a"]) not in (int, float) or not TEST_LIMITS["min_current_a"] <= params["current_a"] <= TEST_LIMITS["max_current_a"] + or type(params["duration_s"]) not in (int, float) or not TEST_LIMITS["min_duration_s"] <= params["duration_s"] <= TEST_LIMITS["max_duration_s"]): + raise ValueError("Explicit raised-rig confirmation, duration and controller sessions required") + if action != "vesc.motor.pulse" and params["standstill_confirmed"] is not True: + raise ValueError("Explicit observation of all motors at standstill required") + if action in ("vesc.motor.run", "vesc.drive.run") and (type(params["erpm"]) not in (int, float) or not SPEED_LIMITS["min_erpm"] <= abs(params["erpm"]) <= SPEED_LIMITS["max_erpm"]): + raise ValueError("Speed is outside the supported range") + if action == "vesc.drive.run" and (type(params["profile_revision"]) is not int or params["profile_revision"] < 0 + or not isinstance(params["device_ids"], list) or not 2 <= len(params["device_ids"]) <= 128 + or any(not isinstance(v, str) for v in params["device_ids"]) + or len(set(params["device_ids"])) != len(params["device_ids"])): + raise ValueError("Explicit complete drive profile required") + elif action in ("vesc.hall.measure", "vesc.foc.calibrate"): + extra = {"max_power_loss_w"} if action == "vesc.foc.calibrate" else {"standstill_confirmed"} + if (set(params) != ({"sessions", "rig_clear", "native_cycle_confirmed"} | extra) + or params["rig_clear"] is not True or params["native_cycle_confirmed"] is not True + or not isinstance(params["sessions"], dict) or not 1 <= len(params["sessions"]) <= 128): + raise ValueError("Native procedure and rig confirmation required") + if action == "vesc.hall.measure" and params["standstill_confirmed"] is not True: + raise ValueError("Explicit observation of all motors at standstill required") + if action == "vesc.foc.calibrate" and (type(params["max_power_loss_w"]) not in (int,float) or not 10 <= params["max_power_loss_w"] <= 150): + raise ValueError("Heating budget must be between 10 and 150 W") + elif action == "vesc.link.check": + if set(params) != {"sessions"} or not isinstance(params["sessions"], dict) or not 1 <= len(params["sessions"]) <= 128: + raise ValueError("Controller sessions required") + elif action in ("vesc.drive.assign", "vesc.drive.unassign", "vesc.drive.layout"): + validate_drive(action, params) + elif params != {}: + raise ValueError("This operation has no parameters") + start = datetime.fromisoformat(command["requested_at"].replace("Z", "+00:00")) + end = datetime.fromisoformat(command["deadline_at"].replace("Z", "+00:00")) + if start.tzinfo is None or end.tzinfo is None or not 0 < (end - start).total_seconds() <= 360: + raise ValueError("Invalid operation deadline") + return end + + def execute(self, command): + deadline = self.validate(command) + path = self.root / (command["operation_id"] + ".json") + digest = hashlib.sha256(json.dumps(command, sort_keys=True).encode()).hexdigest() + if command["action_id"] == "vesc.motor.stop": + with self.journal_lock: + if path.exists(): + previous = json.loads(path.read_text()) + if previous["digest"] != digest: raise ValueError("Operation identity conflict") + return previous["receipt"] + if deadline <= datetime.now(timezone.utc): raise ValueError("Operation expired") + self.motor.cancel() + result = {"state": "complete", "result": {"stop_requested": True, "interruptible": self.motor.mode not in ("hall", "foc"), "drive_profile": self.drive.value, "test_limits": TEST_LIMITS, "test_active": self.motor.active}} + atomic(path, {"digest": digest, "receipt": result}) + return result + if not self.operation_lock.acquire(blocking=False): + raise ValueError("Another VESC operation is running") + try: + if path.exists(): + previous = json.loads(path.read_text()) + if previous["digest"] != digest: + raise ValueError("Operation identity conflict") + return previous["receipt"] + if deadline <= datetime.now(timezone.utc): + raise ValueError("Operation expired") + with self.lock: + matches = [d for d in self.devices.values() if d.id == command["session"]["device_id"]] + if len(matches) != 1 or matches[0].session != command["session"]["session_id"]: + raise ValueError("Device session changed") + device = matches[0] + # Keep backups and receipts bounded without deleting evidence automatically. + if sum(p.stat().st_size for p in self.root.glob("*.json")) > 32 * 1024 * 1024: + raise ValueError("Read journal is full") + record = {"digest": digest, "receipt": {"state": "unknown", "error": "Чтение не подтверждено. Обновите состояние."}} + with self.journal_lock: + if path.exists(): raise ValueError("Operation identity already reserved") + atomic(path, record) + try: + if command["action_id"] == "vesc.link.check": + from .link_check import measure + with self.lock: devices = list(self.devices.values()) + result = measure(self, command, devices) + record["receipt"] = {"state": "complete", "result": result} + atomic(path, record) + return record["receipt"] + if command["action_id"] in ("vesc.drive.assign", "vesc.drive.unassign", "vesc.drive.layout"): + if device.identity is None: raise Rejected("Сначала подтвердите личность VESC.") + try: + result = self.drive.update(command["action_id"], command["parameters"], device) + except ValueError as error: + raise Rejected(str(error)) from error + record["receipt"] = {"state": "complete", "result": result} + atomic(path, record) + return record["receipt"] + if command["action_id"] in ("vesc.motor.pulse", "vesc.motor.run", "vesc.drive.run", "vesc.hall.measure", "vesc.foc.calibrate", "vesc.control.release"): + with self.lock: + devices = list(self.devices.values()) + actual = {d.id: d.session for d in devices} + if len(actual) != len(devices) or actual != command["parameters"]["sessions"]: + raise Rejected("Состав или сеансы VESC изменились. Обновите устройства.") + run_command = command + if command["action_id"] == "vesc.hall.measure": + run_command = {**command, "parameters": {**command["parameters"], "current_a": 5, "duration_s": 30}} + if command["action_id"] == "vesc.foc.calibrate": + run_command = {**command, "parameters": {**command["parameters"], "current_a": 5, "duration_s": 225}} + result = self.motor.run(run_command, devices, device, command["action_id"] == "vesc.control.release") + record["receipt"] = {"state": "complete", "result": result} + atomic(path, record) + return record["receipt"] + with device.lock: + if device.link is None: + raise OSError("Device disconnected") + remaining = (deadline - datetime.now(timezone.utc)).total_seconds() + if remaining < 8: + raise TimeoutError("Insufficient time for bounded read") + actual = firmware(device.link.query(0)) + if actual != device.identity: + device.link.close() + device.link = None + device.identity = None + device.session = "vesc_" + uuid.uuid4().hex + raise ValueError("Controller identity changed") + result = {"identity": actual, "device_id": device.id, "observed_at": utc()} + action = command["action_id"] + if action in {"vesc.telemetry.read", "vesc.limits.read", "vesc.config.backup"} and not device.readable: + raise ValueError("Firmware read layout is unsupported") + if action == "vesc.telemetry.read": + result.update(values=values(device.link.query(4)), monotonic_at=time.monotonic()) + device.telemetry = result + elif action == "vesc.limits.read": + from .limits_view import read_limits + result.update(parameters=read_limits(device.link)) + if firmware(device.link.query(0)) != actual: + raise ValueError("Controller changed during configuration read") + elif action == "vesc.input.read": + if actual["version"] != "5.02": raise ValueError("Input layout unsupported") + result["input"] = ppm(device.link.query(31)) + elif action == "vesc.can.read": + if actual["version"] != "5.02": raise ValueError("CAN layout unsupported") + started = time.monotonic() + reply = device.link.query(62, timeout=8) + if not reply or reply[0] != 62: raise ValueError("Invalid CAN reply") + result.update(can_ids=list(reply[1:]), elapsed_s=time.monotonic()-started) + elif action == "vesc.config.backup": + configs = {} + for name, code in (("motor", 14), ("application", 17)): + raw = device.link.query(code) + if not 5 <= len(raw) <= 10000: + raise ValueError("Incomplete configuration") + configs[name] = {"encoding": "base64", "payload": base64.b64encode(raw).decode(), + "bytes": len(raw), "sha256": hashlib.sha256(raw).hexdigest(), + "signature_hex": raw[1:5].hex()} + # Identity is checked on the same exclusively held attachment at both ends. + if firmware(device.link.query(0)) != actual: + raise ValueError("Controller changed during backup") + result.update(schema="missioncore.vesc.config-backup/v1", configs=configs, + decoded=False, operation_id=command["operation_id"], monotonic_at=time.monotonic()) + backup_path = self.root / ("backup_" + command["operation_id"] + ".json") + atomic(backup_path, result) + self.archive.add("local", result) + device.backup = {"observed_at": result["observed_at"], "operation_id": command["operation_id"], + "configs": {k: {"bytes": v["bytes"], "sha256": v["sha256"]} for k, v in configs.items()}} + record["receipt"] = {"state": "complete", "result": result} + except (OSError, ValueError, TimeoutError) as error: + record["receipt"] = {"state": "error", "error": str(error) if isinstance(error, Rejected) else "Операция не выполнена. Проверьте связь и совместимость контроллера."} + if getattr(error, "native_rpc", None) is not None: + # Keep transport evidence in the receipt, not product copy. + # This covers ordinary reads and preflight before a motor + # procedure has its own result/failure envelope. + record["receipt"]["result"] = {"failure": { + "type": type(error).__name__, "native_rpc": error.native_rpc, + "native_history": getattr(error, "native_history", []), + }} + atomic(path, record) + return record["receipt"] + + finally: + self.operation_lock.release() diff --git a/plugins/vesc/runtime/speed_hold.py b/plugins/vesc/runtime/speed_hold.py new file mode 100644 index 0000000..9251609 --- /dev/null +++ b/plugins/vesc/runtime/speed_hold.py @@ -0,0 +1,52 @@ +"""Speed acquisition and measured hold time; never infers motion from a command.""" +from .protocol import SPEED_LIMITS + + +class SpeedHold: + def __init__(self, erpm, duration, started): + self.erpm, self.duration, self.started = erpm, duration, started + self.previous = started + self.tachometer = None + self.motion_at = None + self.stable_at = None + self.hold_started = None + self.lost_at = None + self.rotation_s = 0.0 + self.phase = "accelerating" + self.previous_good = False + + def update(self, now, value): + delta = now - self.previous + self.previous = now + if self.tachometer is not None and value["tachometer"] != self.tachometer: + self.motion_at = now + self.tachometer = value["tachometer"] + good = (abs(value["erpm"] - self.erpm) <= abs(self.erpm) * SPEED_LIMITS["speed_tolerance"] + and self.motion_at is not None and now - self.motion_at <= 0.25) + error = None + if self.hold_started is None: + if good: + if self.stable_at is None: self.stable_at = now + if now - self.stable_at >= SPEED_LIMITS["settle_s"]: + self.hold_started = now + self.phase = "holding" + else: + self.stable_at = None + if self.hold_started is None and now - self.started >= SPEED_LIMITS["startup_timeout_s"]: + error = "Мотор не вышел на заданную скорость за 15 секунд. Отсчёт вращения не начался." + else: + if good: + # Both endpoints must be observed in band. Do not count a gap, + # USB delay, stationary tachometer or an unobserved last interval. + if self.previous_good and delta <= 0.25: self.rotation_s += delta + self.lost_at = None + else: + if self.lost_at is None: self.lost_at = now + if now - self.lost_at >= SPEED_LIMITS["lost_speed_timeout_s"]: + error = "Мотор перестал удерживать заданную скорость. Проверка завершена досрочно." + self.previous_good = good + if now - self.started > SPEED_LIMITS["startup_timeout_s"] + self.duration + 5: + error = "Истёк общий срок проверки; заданное время вращения не набрано." + done = self.rotation_s >= self.duration + setpoint = (1 if self.erpm > 0 else -1) * min(abs(self.erpm), max(1, (now - self.started) * SPEED_LIMITS["ramp_erpm_per_s"])) + return setpoint, done, error diff --git a/plugins/vesc/runtime/temporary_limits.py b/plugins/vesc/runtime/temporary_limits.py new file mode 100644 index 0000000..322f190 --- /dev/null +++ b/plugins/vesc/runtime/temporary_limits.py @@ -0,0 +1,88 @@ +"""FW 5.02 volatile limits with durable, identity-bound restoration. + +COMM_SET_MCCONF_TEMP (48): store=false, forward=false, ack=true, divide=false. +Reference: pinned bldc 3f670137 commands.c. No flash write, no app changes. +""" +import base64 +import json +import math +import struct + +from .configuration import decode +from .protocol import frame, firmware, values, ppm + +FIELDS = ("l_current_min_scale", "l_current_max_scale", "l_min_erpm", "l_max_erpm", + "l_min_duty", "l_max_duty", "l_watt_min", "l_watt_max", + "l_in_current_min", "l_in_current_max") + + +def packet(config): + numbers = [config[key] for key in FIELDS] + if not all(math.isfinite(v) for v in numbers): raise ValueError("Invalid volatile limits") + return frame(bytes([48, 0, 0, 1, 0]) + struct.pack(">10f", *numbers)) + + +class TemporaryLimits: + def __init__(self, service, atomic): + self.service, self.atomic = service, atomic + + def path(self, device): + return self.service.root / ("limits_" + device.id + ".json") + + def pending(self, device): + return self.path(device).exists() + + def apply(self, device, raw, current_a): + if self.pending(device): raise ValueError("Previous limits restoration is pending") + old = decode(raw, "motor") + if not (old["l_current_min"] < 0 < old["l_current_max"] + and 0 < old["l_current_min_scale"] <= 1 and 0 < old["l_current_max_scale"] <= 1): + raise ValueError("Unsupported motor current limits") + changed = dict(old) + changed["l_current_max_scale"] = min(old["l_current_max_scale"], current_a / old["l_current_max"]) + changed["l_current_min_scale"] = min(old["l_current_min_scale"], current_a / -old["l_current_min"]) + # Persist BEFORE sending: a lost ACK or killed process must be recoverable. + record = {"identity": device.identity, "original": base64.b64encode(raw).decode(), + "applied": {key: changed[key] for key in FIELDS}} + self.atomic(self.path(device), record) + device.link.set_temporary_limits(changed) + actual = decode(device.link.query(14), "motor") + if any(actual[k] != old[k] for k in old if k not in FIELDS): + raise ValueError("Unexpected configuration change") + if (actual["l_current_max"] * actual["l_current_max_scale"] > current_a + 0.001 + or -actual["l_current_min"] * actual["l_current_min_scale"] > current_a + 0.001): + raise ValueError("Current limit readback failed") + if any(not math.isclose(actual[k], changed[k], rel_tol=1e-6, abs_tol=1e-8) for k in FIELDS): + raise ValueError("Volatile limits readback differs") + return actual + + def restore(self, device): + path = self.path(device) + if not path.exists(): return True + record = json.loads(path.read_text()) + if firmware(device.link.query(0)) != record["identity"]: raise ValueError("Restoration identity changed") + raw = base64.b64decode(record["original"], validate=True) + old = decode(raw, "motor") + actual_raw = device.link.query(14) + actual = decode(actual_raw, "motor") + # An independently changed configuration is never overwritten. + if any(actual[k] != old[k] for k in old if k not in FIELDS): + raise ValueError("Configuration changed outside this operation; restoration pending") + if any(not (math.isclose(actual[k], old[k], rel_tol=1e-6, abs_tol=1e-8) + or math.isclose(actual[k], record["applied"][k], rel_tol=1e-6, abs_tol=1e-8)) for k in FIELDS): + raise ValueError("Limits changed outside this operation; restoration pending") + if actual_raw != raw: + state = values(device.link.query(4)) + from .receiver import active, neutral_band + application = decode(device.link.query(17), "application") + if abs(state["motor_current_a"]) > 1 or active(ppm(device.link.query(31))["level"], neutral_band(application)): + raise ValueError("Wait for zero current and neutral before restoring limits") + device.link.set_temporary_limits(old) + if device.link.query(14) != raw: raise ValueError("Original configuration readback failed") + path.unlink() + # atomic() fsyncs the directory on writes; persist removal as well. + import os + fd = os.open(path.parent, os.O_RDONLY) + try: os.fsync(fd) + finally: os.close(fd) + return True diff --git a/plugins/vesc/tests/test_attachment.py b/plugins/vesc/tests/test_attachment.py new file mode 100644 index 0000000..a24dafb --- /dev/null +++ b/plugins/vesc/tests/test_attachment.py @@ -0,0 +1,50 @@ +"""Targeted attachment checks preserve generation and topology rejection.""" +from pathlib import Path +import sys,tempfile,unittest +from unittest.mock import patch +sys.path.insert(0,str(Path(__file__).resolve().parents[1])) +from runtime.serial import Attachment, attachment_at, check_attachment, discover + +class AttachmentTests(unittest.TestCase): + def setUp(self): + self.temp=tempfile.TemporaryDirectory();self.addCleanup(self.temp.cleanup) + self.root=Path(self.temp.name);self.device=self.root/'1-2.3';self.device.mkdir() + for name,value in {'idVendor':'0483','idProduct':'5740','product':'ChibiOS/RT Virtual COM Port','devnum':'17','speed':'12'}.items(): + (self.device/name).write_text(value) + (self.device/'1-2.3:1.0/tty/ttyACM2').mkdir(parents=True) + self.expected=Attachment('1-2.3','17','ttyACM2','12 Мбит/с') + + def test_target_check_never_enumerates_siblings(self): + original=Path.iterdir + def entries(path): + if path==self.root:raise AssertionError('full bus scan in per-request check') + return original(path) + with patch.object(Path,'iterdir',entries):check_attachment(self.expected,self.root) + self.assertEqual(discover(self.root),[self.expected]) + + def test_generation_change_or_removed_port_invalidates_old_owner(self): + (self.device/'devnum').write_text('18') + with self.assertRaises(OSError):check_attachment(self.expected,self.root) + (self.device/'devnum').write_text('17') + (self.device/'1-2.3:1.0/tty/ttyACM2').rmdir() + with self.assertRaises(OSError):check_attachment(self.expected,self.root) + + def test_ambiguous_tty_or_other_vendor_rejected(self): + extra=self.device/'1-2.3:1.1/tty/ttyACM3';extra.mkdir(parents=True) + self.assertIsNone(attachment_at(self.device)) + extra.rmdir();(self.device/'idVendor').write_text('1234') + self.assertIsNone(attachment_at(self.device)) + + def test_driver_sibling_tty_cannot_be_mistaken_for_device_interface(self): + (self.device/'driver/tty/ttyACM9').mkdir(parents=True) + self.assertEqual(attachment_at(self.device),self.expected) + with self.assertRaises(OSError):check_attachment(Attachment('../1-2.3','17','ttyACM2','12 Мбит/с'),self.root) + + def test_generation_change_during_read_is_rejected(self): + original=Path.read_text;reads=0 + def read(path,*args,**kwargs): + nonlocal reads + if path==self.device/'devnum': + reads+=1;return '17' if reads==1 else '18' + return original(path,*args,**kwargs) + with patch.object(Path,'read_text',read):self.assertIsNone(attachment_at(self.device)) diff --git a/plugins/vesc/tests/test_drive_profile.py b/plugins/vesc/tests/test_drive_profile.py new file mode 100644 index 0000000..759bb77 --- /dev/null +++ b/plugins/vesc/tests/test_drive_profile.py @@ -0,0 +1,74 @@ +"""User-assigned drive layout, persistence and conflict tests; no motor I/O.""" +from pathlib import Path +import sys +sys.path.insert(0,str(Path(__file__).resolve().parents[1])) +import test_reader + + +class DriveTests(test_reader.ServiceTests): + def test_change_layout_keeps_assignments_without_motor_commands(self): + left, right = list(self.service.devices.values()) + self.assign(left, 'left.1') + self.assign(right, 'right.1') + command = self.command(action='vesc.drive.layout') + command['parameters'] = {'layout': '2x2', 'revision': 2} + result = self.service.execute(command) + self.assertEqual(result['state'], 'complete') + self.assertEqual(result['result']['layout'], '2x2') + self.assertEqual(result['result']['bindings']['left.1']['device_id'], left.id) + self.assertEqual(len(result['result']['bindings']), 2) + self.assertTrue(all(link.commands == [0] for link in test_reader.FakeLink.instances)) + + def assign(self, device, slot, layout='1x1', revision=None): + item=next(i for i in self.service.inventory('node_synthetic')['items'] if i['id']==device.id) + command=self.command(item,action='vesc.drive.assign') + command['parameters']={'layout':layout,'slot':slot,'revision':self.service.drive.value['revision'] if revision is None else revision} + return self.service.execute(command) + + def test_assign_is_user_metadata_without_serial_commands_and_survives_restart(self): + left,right=list(self.service.devices.values()) + self.assertEqual(self.assign(left,'left.1')['state'],'complete') + self.assertEqual(self.assign(right,'right.1')['state'],'complete') + self.assertTrue(all(link.commands==[0] for link in test_reader.FakeLink.instances)) + from runtime.drive_profile import DriveProfile + restored=DriveProfile(self.service.root,self.service.drive.atomic) + self.assertEqual(restored.value,self.service.drive.value) + self.assertEqual(restored.value['layout'],'1x1') + self.assertEqual(restored.value['bindings']['left.1']['device_id'],left.id) + self.assertEqual(self.service.drive.path.stat().st_mode & 0o777,0o600) + + def test_duplicate_slot_and_stale_revision_never_replace_an_assignment(self): + left,right=list(self.service.devices.values()) + self.assign(left,'left.1') + self.assertEqual(self.assign(right,'left.1')['state'],'error') + self.assertEqual(self.assign(right,'right.1',revision=0)['state'],'error') + self.assertEqual(list(self.service.drive.value['bindings']),['left.1']) + + def test_layout_shrink_requires_explicit_unassign_of_removed_slots(self): + left,right=list(self.service.devices.values()) + self.assign(left,'left.2','2x2') + self.assign(right,'right.1','2x2') + self.assertEqual(self.assign(right,'right.1','1x1')['state'],'error') + command=self.command(action='vesc.drive.unassign') + command['parameters']={'slot':'left.2','revision':self.service.drive.value['revision']} + self.assertEqual(self.service.execute(command)['state'],'complete') + self.assertEqual(self.assign(right,'right.1','1x1')['state'],'complete') + self.assertEqual(list(self.service.drive.value['bindings']),['right.1']) + + def test_reassign_moves_one_controller_and_replay_does_not_repeat(self): + device=next(iter(self.service.devices.values())) + self.assign(device,'left.1') + command=self.command(action='vesc.drive.assign') + command['parameters']={'layout':'2x2','slot':'right.2','revision':1} + result=self.service.execute(command) + self.assertEqual(result['state'],'complete') + self.assertEqual(list(result['result']['bindings']),['right.2']) + self.assertEqual(self.service.execute(command),result) + self.assertEqual(self.service.drive.value['revision'],2) + + test_two_attachments_promote_independently = None + test_uuid_collision_never_aliases_a_controller = None + test_reconnect_invalidates_old_session_but_retains_uuid = None + test_receipt_replay_never_repeats_serial_query = None + test_backup_is_raw_hashed_and_bound_to_identity = None + test_arbitrary_writes_parameters_and_expired_requests_rejected = None diff --git a/plugins/vesc/tests/test_foc_calibration.py b/plugins/vesc/tests/test_foc_calibration.py new file mode 100644 index 0000000..724a7e3 --- /dev/null +++ b/plugins/vesc/tests/test_foc_calibration.py @@ -0,0 +1,180 @@ +"""Fault injection at the native calibration transaction boundary; no hardware.""" +from datetime import datetime, timedelta +import unittest +import struct + +import test_motor_test +from test_motor_test import configuration +from runtime.configuration import decode + + +class CalibrationTests(unittest.TestCase): + def setUp(self): + self.case = test_motor_test.PulseTests('test_fixed_wire_commands_no_broadcast_and_no_parameters') + self.case.setUp() + self.addCleanup(self.case.tearDown) + c = self.case + self.original = configuration('motor', {**decode(c.motor, 'motor'), + 'l_current_min': -60, 'l_in_current_min': -55, 'foc_openloop_rpm': 600, 'foc_sl_erpm': 2000}) + self.configs = {d.id: self.original for d in c.devices} + self.starts = [] + self.finished = False + for device in c.devices: + previous = device.link.query + def query(code, timeout=2, previous=previous, device=device): + if code == 14: return self.configs[device.id] + if code == 62: return bytes([62]) + return previous(code, timeout) + device.link.query = query + def start(loss, device=device): + self.starts.append((device.id, loss)) + self.configs[device.id] = configuration('motor', {**decode(self.original, 'motor'), + 'foc_motor_r': 0.08, 'foc_motor_l': 0.00003, 'foc_motor_flux_linkage': 0.009, 'foc_sensor_mode': 0}) + device.link.calibrate_foc = start + def result(): + if not self.finished: + self.finished = True + return {'running': True} + return {'running': False, 'uncertain': False, 'result': { + 'kind': 'foc', 'completed': True, 'success': True, 'validated': True, 'code': 0, 'sensor_mode': 0}} + device.link.procedure_result = result + + def command(self): + c = self.case.command(action='vesc.foc.calibrate') + c['deadline_at'] = (datetime.fromisoformat(c['requested_at']) + timedelta(seconds=300)).isoformat() + c['parameters'] = {'rig_clear': True, 'native_cycle_confirmed': True, 'max_power_loss_w': 50, + 'sessions': {d.id: d.session for d in self.case.devices}} + return c + + def test_native_success_archives_both_versions_and_never_sends_host_torque(self): + command = self.command() + receipt = self.case.service.execute(command) + result = receipt['result'] + self.assertTrue(result['success'], receipt) + self.assertEqual(result['native']['sensor_mode'], 0) + self.assertEqual(self.starts, [(self.case.devices[0].id, 50)]) + self.assertEqual(len(result['backups']), 2) + self.assertEqual(len(result['after_backups']), 2) + self.assertEqual(self.case.currents, []) + self.assertTrue(all(action == 'release' for _, action in self.case.sent)) + self.assertFalse((self.case.service.root/'calibration-pending.json').exists()) + self.assertEqual(self.case.service.execute(command), receipt) + self.assertEqual(len(self.starts), 1) + + def test_unknown_completion_persists_across_service_restart_and_blocks_new_motion(self): + target = self.case.devices[0] + target.link.procedure_result = lambda: {'running': False, 'uncertain': True, 'result': {}} + result = self.case.service.execute(self.command())['result'] + self.assertFalse(result['completed']) + self.assertFalse(result['success']) + self.assertTrue((self.case.service.root/'calibration-pending.json').exists()) + self.assertTrue(self.case.service.motor.latched) + from runtime.service import Service + restarted = Service(self.case.service.root, discover_fn=self.case.service.discover_fn) + self.assertTrue(restarted.motor.latched) + self.assertEqual(self.case.service.execute(self.case.command_for_pulse())['state'], 'error') + self.assertEqual(len(self.starts), 1) + + def test_peer_configuration_change_is_archived_and_blocks_further_movement(self): + start = self.case.devices[0].link.calibrate_foc + def mutate(loss): + start(loss) + self.configs[self.case.devices[1].id] = configuration('motor', {**decode(self.original, 'motor'), 'foc_motor_r': 1}) + self.case.devices[0].link.calibrate_foc = mutate + result = self.case.service.execute(self.command())['result'] + self.assertFalse(result['success']) + self.assertFalse(result['configuration_verified']) + self.assertEqual(len(result['after_backups']), 2) + self.assertTrue(self.case.service.motor.latched) + + def test_known_can_peers_still_block_upstream_broadcast_side_effect(self): + target = self.case.devices[0] + query = target.link.query + target.link.query = lambda code, timeout=2: bytes([62, 11]) if code == 62 else query(code, timeout) + result = self.case.service.execute(self.command()) + self.assertEqual(result['state'], 'error') + self.assertEqual(self.starts, []) + + def test_confirmed_failed_cycle_restores_and_can_be_retried_explicitly(self): + target = self.case.devices[0] + target.link.calibrate_foc = lambda loss: self.starts.append((target.id, loss)) + target.link.procedure_result = lambda: {'running': False, 'uncertain': False, 'result': { + 'completed': True, 'success': False, 'validated': True, 'code': -10}} + result = self.case.service.execute(self.command())['result'] + self.assertTrue(result['completed']) + self.assertFalse(result['success']) + self.assertTrue(result['configuration_verified']) + self.assertFalse((self.case.service.root/'calibration-pending.json').exists()) + + def test_missing_native_write_ack_never_accepts_calibration(self): + target = self.case.devices[0] + target.link.procedure_result = lambda: {'running': False, 'uncertain': True, 'result': { + 'completed': True, 'success': False, 'validated': False, 'code': 0, 'error': 'ACK missing'}} + result = self.case.service.execute(self.command())['result'] + self.assertFalse(result['success']) + self.assertTrue((self.case.service.root/'calibration-pending.json').exists()) + + def test_calibration_heating_budget_is_finite_and_explicit(self): + for loss in (True, float('nan'), float('inf'), 0, 151): + command = self.command(); command['parameters']['max_power_loss_w'] = loss + with self.assertRaises(ValueError): self.case.service.execute(command) + self.assertEqual(self.starts, []) + + def averaged_current(self, transient=True): + target = self.case.devices[0] + query = target.link.query + reads = [] + def read(code, timeout=2): + raw = query(code, timeout) + if code == 4 and self.starts: + reads.append(1) + if not transient or len(reads) == 1: + return raw[:5] + struct.pack('>i', 367) + raw[9:] + return raw + target.link.query = read + return query, reads + + def test_cycle_average_is_drained_before_verifying_released_current(self): + _, reads = self.averaged_current() + result = self.case.service.execute(self.command())['result'] + self.assertTrue(result['success'], result) + self.assertTrue(result['release_confirmed']) + self.assertGreaterEqual(len(reads), 2) + self.assertEqual(result['after'][self.case.devices[0].id]['motor_current_a'], 0) + + def test_explicit_neutral_recovery_after_verified_cycle_never_recalibrates(self): + query, _ = self.averaged_current(transient=False) + command = self.command() + receipt = self.case.service.execute(command) + self.assertFalse(receipt['result']['release_confirmed']) + self.assertTrue(receipt['result']['configuration_verified']) + self.case.devices[0].link.query = query + release = self.case.command_for_pulse(); release['action_id'] = 'vesc.control.release'; release['parameters']['standstill_confirmed'] = True + result = self.case.service.execute(release)['result'] + self.assertEqual(result['authority'], 'ready') + self.assertFalse(result['calibration_recovered']['calibration_replayed']) + self.assertEqual(len(self.starts), 1) + self.assertEqual(self.case.service.execute(command), receipt) + self.assertFalse((self.case.service.root/'calibration-pending.json').exists()) + self.assertEqual(self.case.currents, []) + + def test_recovery_rejects_new_configuration_and_does_not_overwrite_it(self): + query, _ = self.averaged_current(transient=False) + self.case.service.execute(self.command()) + self.case.devices[0].link.query = query + key = self.case.devices[0].id + self.configs[key] = configuration('motor', {**decode(self.configs[key], 'motor'), 'foc_motor_r': .5}) + before = self.configs[key] + release = self.case.command_for_pulse(); release['action_id'] = 'vesc.control.release'; release['parameters']['standstill_confirmed'] = True + receipt = self.case.service.execute(release) + self.assertEqual(receipt['state'], 'error') + self.assertEqual(self.configs[key], before) + self.assertTrue((self.case.service.root/'calibration-pending.json').exists()) + self.assertEqual(len(self.starts), 1) + + def test_unknown_completion_cannot_be_cleared_by_neutral_return(self): + self.case.devices[0].link.procedure_result = lambda: {'running': False, 'uncertain': True, 'result': {}} + self.case.service.execute(self.command()) + release = self.case.command_for_pulse(); release['action_id'] = 'vesc.control.release'; release['parameters']['standstill_confirmed'] = True + self.assertEqual(self.case.service.execute(release)['state'], 'error') + self.assertTrue((self.case.service.root/'calibration-pending.json').exists()) diff --git a/plugins/vesc/tests/test_group_test.py b/plugins/vesc/tests/test_group_test.py new file mode 100644 index 0000000..e77ce13 --- /dev/null +++ b/plugins/vesc/tests/test_group_test.py @@ -0,0 +1,159 @@ +"""Synthetic complete-profile motion, shared timing and all-peer failure tests.""" +import struct +import unittest +from datetime import datetime, timedelta + +import test_motor_test +import test_reader +from test_motor_test import configuration +from runtime.configuration import decode +from runtime.drive_profile import LAYOUTS +from runtime.temporary_limits import FIELDS + + +class GroupTests(unittest.TestCase): + def setUp(self): + self.case = test_motor_test.PulseTests('test_fixed_wire_commands_no_broadcast_and_no_parameters') + self.case.setUp() + self.addCleanup(self.case.tearDown) + self.configure(2) + + def configure(self, count): + c = self.case + if len(c.devices) != count: + c.attachments = [test_reader.Attachment(f'2-{i+1}', str(i+1), f'ttyACM{i}', '12') for i in range(count)] + c.service.scan(); c.configure_controllers() + self.configs, self.speeds, self.commands, self.tacho, self.sets = {}, {}, [], {}, [] + self.motion = lambda device: True + for device in c.devices: + self.configs[device.id] = configuration('motor', {**decode(c.motor, 'motor'), + 'l_current_min': -60, 'l_current_min_scale': 1, 'l_current_max_scale': 1}) + original = device.link.query + def query(code, timeout=2, original=original, device=device): + if code == 14: return self.configs[device.id] + raw = original(code, timeout) + if code == 4 and device.id in self.speeds and self.motion(device): + self.tacho[device.id] = self.tacho.get(device.id, 0)+6 + raw = raw[:23]+struct.pack('>i', round(self.speeds[device.id]))+raw[27:] + raw = raw[:45]+struct.pack('>ii', self.tacho[device.id], self.tacho[device.id])+raw[53:] + return raw + device.link.query = query + def limits(config, device=device): + self.sets.append(device.id) + self.configs[device.id] = configuration('motor', {**decode(self.configs[device.id], 'motor'), + **{k: config[k] for k in FIELDS}}) + device.link.set_temporary_limits = limits + def speed(value, device=device): + self.speeds[device.id] = value + self.commands.append((device.id, value)) + device.link.test_speed = speed + self.originals = dict(self.configs) + layout = '1x1' if count == 2 else '2x2' + c.service.drive.value = {'layout': layout, 'revision': 4, + 'bindings': {slot: {'device_id': d.id, 'uuid': d.identity['uuid']} + for slot, d in zip(LAYOUTS[layout], c.devices)}} + + def command(self): + command = self.case.command_for_pulse() + command['action_id'] = 'vesc.drive.run' + command['parameters'].update(erpm=2000, current_a=30, duration_s=3, profile_revision=4, standstill_confirmed=True, + device_ids=[d.id for d in self.case.devices]) + command['deadline_at'] = (datetime.fromisoformat(command['requested_at'])+timedelta(seconds=120)).isoformat() + return command + + def test_pair_and_four_motors_run_one_common_interval_and_restore(self): + for count in (2, 4): + with self.subTest(count=count): + self.configure(count) + command = self.command() + receipt = self.case.service.execute(command) + result = receipt['result'] + self.assertEqual(result['outcome'], 'duration', result) + self.assertGreaterEqual(result['rotation_s'], 3) + self.assertLess(result['rotation_s'], 3.2) + self.assertEqual(set(self.speeds), {d.id for d in self.case.devices}) + self.assertTrue(result['release_confirmed']) + self.assertTrue(result['limits_restored']) + self.assertEqual(self.configs, self.originals) + before = list(self.commands) + self.assertEqual(self.case.service.execute(command), receipt) + self.assertEqual(before, self.commands) + + def test_count_starts_only_after_slower_motor_reaches_speed(self): + self.motion = lambda d: d is self.case.devices[0] or self.case.clock.now >= 8 + result = self.case.service.execute(self.command())['result'] + self.assertEqual(result['outcome'], 'duration') + first = next(s['at'] for s in result['samples'] if s['rotation_s'] > 0) + self.assertGreater(first, 7.5) + self.assertGreaterEqual(result['rotation_s'], 3) + + def test_stationary_peer_never_counts_single_motor_as_joint_rotation(self): + self.motion = lambda d: d is self.case.devices[0] + result = self.case.service.execute(self.command())['result'] + self.assertEqual(result['rotation_s'], 0) + self.assertIn('не вышел', result['outcome']) + self.assertEqual(set(result['release']), {d.id for d in self.case.devices}) + self.assertEqual(self.configs, self.originals) + + def test_rc_preemption_releases_every_motor_and_latches(self): + original = self.case.devices[0].link.test_speed + def speed(value): + original(value); self.case.changed = True + self.case.devices[0].link.test_speed = speed + result = self.case.service.execute(self.command())['result'] + self.assertEqual(result['rotation_s'], 0) + self.assertTrue(self.case.service.motor.latched) + self.assertTrue(result['release_confirmed']) + self.assertFalse(result['limits_restored']) + self.assertTrue(list(self.case.service.root.glob('limits_*.json'))) + self.case.changed = False + self.case.service.scan() + self.assertEqual(self.configs, self.originals) + + def test_losing_one_motor_stops_joint_timer_and_releases_pair(self): + self.motion = lambda d: d is self.case.devices[0] or self.case.clock.now < 7 + result = self.case.service.execute(self.command())['result'] + self.assertLess(result['rotation_s'], 3) + self.assertIn('перестал удерживать', result['outcome']) + self.assertTrue(result['release_confirmed']) + self.assertEqual(self.configs, self.originals) + + def test_failed_peer_lease_never_sends_speed_and_keeps_cause(self): + original = self.case.devices[1].link.test_command + def send(action): + if action == 'claim': raise TimeoutError('synthetic lease timeout') + original(action) + self.case.devices[1].link.test_command = send + result = self.case.service.execute(self.command())['result'] + self.assertEqual(self.commands, []) + self.assertEqual(result['failure']['message'], 'synthetic lease timeout') + self.assertEqual(set(result['release']), {d.id for d in self.case.devices}) + self.assertEqual(self.configs, self.originals) + + def test_second_limit_ack_failure_restores_both_without_motion(self): + original = self.case.devices[1].link.set_temporary_limits + def apply(config): + original(config) + if len(self.sets) == 2: raise TimeoutError('lost second ACK') + self.case.devices[1].link.set_temporary_limits = apply + result = self.case.service.execute(self.command())['result'] + self.assertEqual(self.commands, []) + self.assertTrue(result['limits_restored']) + self.assertEqual(self.configs, self.originals) + + def test_stale_incomplete_duplicate_or_changed_profile_never_runs(self): + command = self.command(); command['parameters']['profile_revision'] -= 1 + self.assertEqual(self.case.service.execute(command)['state'], 'error') + command = self.command(); command['parameters']['device_ids'] *= 2 + with self.assertRaises(ValueError): self.case.service.execute(command) + self.case.service.drive.value['bindings'].pop('right.1') + self.assertEqual(self.case.service.execute(self.command())['state'], 'error') + self.assertEqual(self.commands, []) + self.assertEqual(self.sets, []) + + def test_current_bound_is_checked_for_every_motor(self): + device = self.case.devices[1] + self.configs[device.id] = configuration('motor', {**decode(self.configs[device.id], 'motor'), 'l_current_max': 10}) + self.assertEqual(self.case.service.execute(self.command())['state'], 'error') + self.assertEqual(self.commands, []) + self.assertEqual(self.sets, []) diff --git a/plugins/vesc/tests/test_hall_standstill.py b/plugins/vesc/tests/test_hall_standstill.py new file mode 100644 index 0000000..f261f07 --- /dev/null +++ b/plugins/vesc/tests/test_hall_standstill.py @@ -0,0 +1,108 @@ +"""Sensorless idle drift must not become a general motion-check bypass.""" +import math +import struct +import unittest + +import test_speed_and_hall +from test_motor_test import configuration +from runtime.configuration import decode +from runtime.motor_test import check_values, LimitExceeded +from runtime.protocol import values + + +class HallStandstillTests(unittest.TestCase): + def setUp(self): + self.rig = test_speed_and_hall.RunTests('test_native_hall_returns_measured_table_without_applying_it') + self.rig.setUp() + self.addCleanup(self.rig.doCleanups) + self.case = self.rig.case + + def command(self): + command = self.case.command(action='vesc.hall.measure') + command['parameters'] = {'rig_clear': True, 'native_cycle_confirmed': True, + 'standstill_confirmed': True, 'sessions': {d.id:d.session for d in self.case.devices}} + return command + + def drift(self, device, mode=0, late_duty=False): + config = decode(self.rig.configs[device.id], 'motor') + self.rig.configs[device.id] = configuration('motor', {**config, 'foc_sensor_mode':mode}) + query = device.link.query + reads = 0 + def read(code, timeout=2): + nonlocal reads + raw = query(code, timeout) + if code == 4: + reads += 1 + raw = raw[:23] + struct.pack('>i', -160) + raw[27:] + if late_duty and reads >= 6: + raw = raw[:21] + struct.pack('>h', 2) + raw[23:] + return raw + device.link.query = read + + def test_sensorless_peer_can_drift_but_raw_evidence_is_retained(self): + self.drift(self.case.devices[1]) + result = self.case.service.execute(self.command())['result'] + self.assertTrue(result['completed']) + self.assertTrue(result['configuration_restored']) + self.assertTrue(result['preflight']['standstill_confirmed']) + samples = result['preflight']['samples'] + self.assertEqual(len(samples), 20) + peer = [s for s in samples if s['device_id'] == self.case.devices[1].id] + self.assertTrue(all(s['values']['erpm'] == -160 for s in peer)) + self.assertGreaterEqual(peer[-1]['at'] - peer[0]['at'], 0.89) + + def test_sensored_speed_still_blocks_before_any_write(self): + self.drift(self.case.devices[1], mode=2) + self.assertEqual(self.case.service.execute(self.command())['state'], 'error') + self.assertIsNone(self.rig.hall_started) + self.assertEqual(self.case.sent, []) + + def test_modulation_above_one_wire_quantum_blocks_before_any_write(self): + self.drift(self.case.devices[1], late_duty=True) + self.assertEqual(self.case.service.execute(self.command())['state'], 'error') + self.assertIsNone(self.rig.hall_started) + self.assertEqual(self.case.sent, []) + + def test_missing_false_and_nonboolean_observation_rejected(self): + for confirmation in (None, False, 1, 'true'): + command = self.command() + if confirmation is None: del command['parameters']['standstill_confirmed'] + else: command['parameters']['standstill_confirmed'] = confirmation + with self.assertRaises(ValueError): self.case.service.execute(command) + self.assertEqual(self.case.sent, []) + + def test_sensorless_drift_does_not_bypass_ordinary_motor_test(self): + self.drift(self.case.devices[1]) + self.assertEqual(self.case.service.execute(self.case.command_for_pulse())['state'], 'error') + self.assertEqual(self.case.sent, []) + + def test_rc_still_blocks_hall_before_any_write(self): + self.drift(self.case.devices[1]) + self.case.changed = True + self.assertEqual(self.case.service.execute(self.command())['state'], 'error') + self.assertTrue(self.case.service.motor.latched) + self.assertEqual(self.case.sent, []) + + def test_electrical_and_finite_guards_cannot_be_replaced_by_observation(self): + device = self.case.devices[0] + sample = values(device.link.query(4)) + motor = decode(self.rig.configs[device.id], 'motor') + for field, value in (('erpm', math.nan), ('motor_current_a', 1.01), + ('input_current_a', -1.01), ('duty', .002), + ('fault_code', 1), ('mos_temperature_c', 66), + ('input_voltage_v', 61)): + with self.subTest(field=field), self.assertRaises(LimitExceeded): + check_values({**sample, 'erpm':-160, field:value}, motor=motor, + standstill_confirmed=True) + + def test_one_quantized_idle_modulation_step_requires_observed_standstill(self): + device = self.case.devices[0] + sample = values(device.link.query(4)) + motor = {**decode(self.rig.configs[device.id], 'motor'), 'foc_sensor_mode':0} + for duty in (-.001, 0, .001): + idle = {**sample, 'erpm':-160, 'duty':duty} + check_values(idle, motor=motor, standstill_confirmed=True) + with self.assertRaises(LimitExceeded): + check_values(idle, motor=motor) + with self.assertRaises(LimitExceeded): + check_values({**sample, 'duty':-.002}, motor=motor, standstill_confirmed=True) diff --git a/plugins/vesc/tests/test_limits_view.py b/plugins/vesc/tests/test_limits_view.py new file mode 100644 index 0000000..647481e --- /dev/null +++ b/plugins/vesc/tests/test_limits_view.py @@ -0,0 +1,34 @@ +"""Native configuration reads never acquire motor control or change settings.""" +from pathlib import Path +import sys +import unittest +from unittest.mock import patch +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import test_reader +from runtime.limits_view import FIELDS, read_limits + + +class LimitsTests(unittest.TestCase): + def test_native_export_only_and_missing_or_nonfinite_values_rejected(self): + class Link: + def configuration(self): + return {"motor": {"parameters": [{"name": key, "value": 1.0} for key in FIELDS]}} + self.assertEqual(set(read_limits(Link())), FIELDS) + for bad in (float('nan'), True, '300'): + with patch.object(Link, 'configuration', return_value={"motor":{"parameters":[{"name":key,"value":bad} for key in FIELDS]}}): + with self.assertRaises(ValueError): read_limits(Link()) + + def test_service_read_is_bound_to_uuid_and_cannot_write(self): + fixture = test_reader.ServiceTests() + fixture.setUp() + try: + service = fixture.service + with patch.object(test_reader.FakeLink, 'configuration', create=True, return_value={"motor":{"parameters":[{"name":key,"value":1.0} for key in FIELDS]}}) as native: + response = service.execute(fixture.command(action='vesc.limits.read')) + self.assertEqual(response['state'], 'complete') + self.assertEqual(set(response['result']['parameters']), FIELDS) + native.assert_called_once() + self.assertTrue(all(set(link.commands) == {0} for link in test_reader.FakeLink.instances)) + self.assertEqual(service.drive.value['revision'], 0) + finally: + fixture.tearDown() diff --git a/plugins/vesc/tests/test_link_check.py b/plugins/vesc/tests/test_link_check.py new file mode 100644 index 0000000..2db5919 --- /dev/null +++ b/plugins/vesc/tests/test_link_check.py @@ -0,0 +1,107 @@ +"""No-power read measurements and failure attribution; no USB hardware.""" +from unittest.mock import patch +import unittest +import struct +import test_motor_test +from runtime.link_check import measure, summary + + +class LinkCheckTests(unittest.TestCase): + def setUp(self): + self.case=test_motor_test.PulseTests('test_fixed_wire_commands_no_broadcast_and_no_parameters') + self.case.setUp(); self.addCleanup(self.case.tearDown) + self.reads=[] + for device in self.case.devices: + original=device.link.query + def query(code,timeout=2,original=original,device=device): + self.reads.append((device.id,code,timeout)) + return original(code,timeout) + device.link.query=query + + def command(self): + c=self.case.command_for_pulse();c['action_id']='vesc.link.check' + c['parameters']={'sessions':c['parameters']['sessions']} + return c + + def run_check(self): + return measure(self.case.service,self.command(),self.case.devices, + sleep=self.case.clock.sleep,monotonic=lambda:self.case.clock.now) + + def test_reads_pair_at_group_cadence_without_any_motor_commands(self): + result=self.run_check() + self.assertEqual(result['outcome'],'complete') + self.assertFalse(result['motor_commands_sent']) + self.assertEqual(len(self.reads),402) + self.assertEqual({r[1] for r in self.reads},{17,31,4}) + self.assertTrue(all(r[2]==.5 for r in self.reads if r[1]!=17)) + self.assertEqual(self.case.sent,[]) + self.assertTrue(all(v['summary']['replies']==200 for v in result['devices'].values())) + self.assertGreaterEqual(result['duration_s'],9.9) + + def test_late_replies_are_measured_without_relaxing_motor_budget(self): + result=summary([{'elapsed_ms':x} for x in [20,30,55,80,120]]) + self.assertEqual(result['over_60_ms'],2) + self.assertEqual(result['p50_ms'],55) + self.assertEqual(result['max_ms'],120) + + def test_no_response_keeps_peer_command_and_native_cause(self): + device=self.case.devices[1] + original=device.link.query + def query(code,timeout=2): + if code==17:return original(code,timeout) + error=OSError('native read timeout');error.native_rpc={'command':code,'process_alive':True,'attachment_present':True} + raise error + device.link.query=query + result=self.run_check() + self.assertEqual(result['outcome'],'read_failed') + self.assertEqual(result['failure'][0]['device_id'],device.id) + self.assertEqual(result['failure'][0]['command'],31) + self.assertTrue(result['failure'][0]['native_rpc']['attachment_present']) + self.assertEqual(self.case.sent,[]) + + def test_active_receiver_stops_measurement_without_claiming_control(self): + self.case.changed=True + result=self.run_check() + self.assertEqual(result['outcome'],'not_idle') + self.assertEqual(self.case.sent,[]) + self.assertEqual({r[1] for r in self.reads},{17,31}) + + def test_receiver_offset_inside_configured_deadband_is_idle(self): + for device in self.case.devices: + original=device.link.query + device.link.query=lambda code,timeout=2,original=original: bytes([31])+struct.pack('>ii',-66000,1466000) if code==31 else original(code,timeout) + result=self.run_check() + self.assertEqual(result['outcome'],'complete') + self.assertTrue(all(abs(d['neutral_band']-.15)<1e-6 for d in result['devices'].values())) + self.assertEqual(self.case.sent,[]) + + def test_config_failure_is_reported_before_ppm_or_motor_commands(self): + self.case.devices[0].link.query=lambda *args,**kwargs: b'bad config' + result=self.run_check() + self.assertEqual(result['outcome'],'read_failed') + self.assertEqual(result['failure'][0]['command'],17) + self.assertEqual(self.case.sent,[]) + self.assertFalse(any(r[1] in (31,4) for r in self.reads)) + + def test_service_keeps_idempotent_receipt_and_excludes_other_operations(self): + command=self.command() + original=measure + def fast(*args):return original(*args,sleep=self.case.clock.sleep,monotonic=lambda:self.case.clock.now) + with patch('runtime.link_check.measure',side_effect=fast): + result=self.case.service.execute(command) + self.assertEqual(result['state'],'complete') + self.assertEqual(self.case.service.execute(command),result) + self.assertEqual(len(self.reads),402) + self.case.service.operation_lock.acquire() + try: + with self.assertRaises(ValueError):self.case.service.execute(self.command()) + finally:self.case.service.operation_lock.release() + + def test_changed_sessions_rejected_before_reads_and_stop_is_respected(self): + command=self.command();command['parameters']['sessions']={} + with self.assertRaises(ValueError): measure(self.case.service,command,self.case.devices) + self.assertEqual(self.reads,[]) + command=self.command();self.case.service.motor.cancel() + result=measure(self.case.service,command,self.case.devices) + self.assertEqual(result['outcome'],'stopped') + self.assertEqual(self.reads,[]) diff --git a/plugins/vesc/tests/test_motor_test.py b/plugins/vesc/tests/test_motor_test.py new file mode 100644 index 0000000..3e0d992 --- /dev/null +++ b/plugins/vesc/tests/test_motor_test.py @@ -0,0 +1,352 @@ +"""Synthetic fault-injection tests. No real ports, private config or motors.""" +import math +from pathlib import Path +import struct +import sys +import unittest +from unittest.mock import patch +import xml.etree.ElementTree as ET + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from runtime.configuration import decode, crc32c +from runtime.motor_test import Rejected, LimitExceeded, check_configuration, check_values +from runtime.protocol import Decoder, test_packet, ppm, current_packet +import test_reader +from runtime.protocol import firmware +from test_reader import telemetry + + +def configuration(kind, overrides): + code, name = {"motor": (14, "mcconf"), "application": (17, "appconf")}[kind] + xml = ET.parse(Path(__file__).parents[1] / "runtime/schemas/5.02" / ("parameters_" + name + ".xml")).getroot() + params = {p.tag: p for p in xml.find("Params")}; order = [p.text for p in xml.find("SerOrder")] + sig = ''.join(n + params[n].findtext('type', '0') + params[n].findtext('vTx', '0') + ''.join(x.text or '' for x in params[n].findall('enumNames')) for n in order) + out = bytes([code]) + crc32c(sig.encode()).to_bytes(4, 'big') + for n in order: + p=params[n];typ=int(p.findtext('type'));tx=int(p.findtext('vTx','0'));v=overrides.get(n,0) + if typ in (4,5):fmt='b' + elif typ==6:fmt='B' + elif typ==2:fmt={1:'B',2:'b',3:'H',4:'h',5:'I',6:'i'}[tx] + else: + fmt={7:'h',8:'i',9:'I'}[tx] + if tx==9: + f,e=math.frexp(abs(v));v=0 if v==0 else ((e+126)<<23)|int((f-0.5)*16777216)|(0x80000000 if v<0 else 0) + else:v=round(v*float(p.findtext('vTxDoubleScale','1'))) + out+=struct.pack('>'+fmt,v) + return out + + +class Clock: + def __init__(self):self.now=0 + def monotonic(self):return self.now + def sleep(self,value):self.now+=value + + +class PulseTests(test_reader.ServiceTests): + def setUp(self): + super().setUp() + self.configure_controllers() + + def configure_controllers(self): + self.clock=Clock();self.service.motor.sleep=self.clock.sleep;self.service.motor.monotonic=self.clock.monotonic + self.devices=list(self.service.devices.values());self.changed=False + self.sent=[] + self.currents=[] + self.motor=configuration('motor',{'motor_type':2,'l_current_max':60,'l_in_current_max':55,'l_min_erpm':-60000,'l_max_erpm':60000,'l_max_duty':0.95}) + for i,device in enumerate(self.devices): + raw=b'\0\5\2' + b'75_300_R2\0' + bytes([i+1])*12 + bytes(4) + device.identity=firmware(raw) + app=configuration('application',{'controller_id':i+10,'app_to_use':1,'timeout_msec':1000,'timeout_brake_current':0,'app_ppm_conf.ctrl_type':4,'app_ppm_conf.hyst':0.15}) + def query(code,timeout=2,raw=raw,app=app): + if code==0:return raw + if code==14:return self.motor + if code==17:return app + if code==4:return telemetry()[:1]+struct.pack('>hhiiiihihiiiiiiB',250,-729,0,0,0,0,0,0,500,0,0,0,0,0,0,0) + if code==31:return bytes([31])+struct.pack('>ii',600000 if self.changed else 0,1500000) + if code==62:return bytes([62])+bytes(range(10,10+len(self.devices))) + raise AssertionError(code) + device.link.query=query + device.link.test_command=lambda action,i=i:self.sent.append((i,action)) + def send_current(amps,device=device,i=i): + self.currents.append((i,amps)) + device.link.test_command('current') + device.link.test_current=send_current + + def command_for_pulse(self): + c=self.command(action='vesc.motor.pulse') + c['parameters']={'rig_clear':True,'sessions':{d.id:d.session for d in self.devices},'duration_s':1.5,'current_a':2} + return c + + def test_fixed_wire_commands_no_broadcast_and_no_parameters(self): + self.assertEqual(Decoder().feed(test_packet('claim')),[bytes([63,0])+struct.pack('>i',250)]) + self.assertEqual(Decoder().feed(test_packet('current')),[bytes([6])+struct.pack('>i',2000)]) + self.assertEqual(Decoder().feed(current_packet(5)),[bytes([6])+struct.pack('>i',5000)]) + with self.assertRaises(KeyError):test_packet('arbitrary') + with self.assertRaises(ValueError):ppm(bytes([31])+bytes(7)) + + def test_only_selected_motor_receives_current_and_receipt_never_replays(self): + c=self.command_for_pulse();r=self.service.execute(c) + self.assertEqual(r['state'],'complete',r) + self.assertEqual(r['result']['outcome'],'duration') + self.assertTrue(r['result']['release_confirmed']) + self.assertIn((0,'current'),self.sent);self.assertNotIn((1,'current'),self.sent) + self.assertEqual(self.sent[-2:],[(0,'release'),(1,'release')]) + self.assertLessEqual(len([x for x in self.sent if x==(0,'current')]),31) + before=list(self.sent);self.assertEqual(self.service.execute(c),r);self.assertEqual(self.sent,before) + self.assertEqual(len(list(self.service.root.glob('backup_*.json'))),2) + + def test_active_rc_blocks_before_any_command_and_latches(self): + self.changed=True;r=self.service.execute(self.command_for_pulse()) + self.assertEqual(r['state'],'error');self.assertEqual(self.sent,[]);self.assertTrue(self.service.motor.latched) + self.changed=False;self.assertEqual(self.service.execute(self.command_for_pulse())['state'],'error') + + def test_rc_preemption_releases_both_and_blocks_next_click(self): + def send(action): + self.sent.append((0,action)) + if action=='current':self.changed=True + self.devices[0].link.test_command=send + r=self.service.execute(self.command_for_pulse()) + self.assertEqual(r['state'],'complete');self.assertTrue(self.service.motor.latched) + self.assertEqual(len([x for x in self.sent if x==(0,'current')]),1) + self.assertEqual(self.sent[-2:],[(0,'release'),(1,'release')]) + + def test_missing_second_lease_and_disconnect_release_first(self): + def send(action): + if action=='claim':raise OSError('Disconnected') + self.sent.append((1,action)) + self.devices[1].link.test_command=send + r=self.service.execute(self.command_for_pulse()) + self.assertNotIn((0,'current'),self.sent);self.assertIn((0,'release'),self.sent) + self.assertNotEqual(r['result']['outcome'],'duration') + + def test_bad_schema_stale_peer_and_no_rig_confirmation_never_write(self): + self.assertRaises(ValueError,decode,self.motor[:-1],'motor') + c=self.command_for_pulse();c['parameters']['sessions'][self.devices[1].id]='stale' + self.assertEqual(self.service.execute(c)['state'],'error') + c=self.command_for_pulse();c['parameters']['rig_clear']=False + with self.assertRaises(ValueError):self.service.execute(c) + self.assertEqual(self.sent,[]) + + def test_stop_received_before_queued_pulse_cannot_be_cleared_by_start(self): + pulse = self.command_for_pulse() + result = self.service.execute(self.command(action='vesc.motor.stop')) + self.assertTrue(result['result']['stop_requested']) + self.assertEqual(self.service.execute(pulse)['state'],'error') + self.assertEqual(self.sent,[]) + self.assertEqual(self.service.execute(self.command_for_pulse())['state'],'complete') + + def test_single_six_and_ten_controllers_target_only_with_durable_backups(self): + for count in (1, 6, 10): + with self.subTest(count=count): + self.attachments = [test_reader.Attachment(f"2-{i+1}", str(i+1), f"ttyACM{i}", "12") for i in range(count)] + self.service.scan(); self.configure_controllers() + command=self.command_for_pulse() + target=self.devices[-1] + command['session']={'device_id':target.id,'session_id':target.session} + command['parameters']['duration_s']=10 + result=self.service.execute(command) + self.assertEqual(result['state'],'complete',result) + self.assertEqual(result['result']['outcome'],'duration') + self.assertEqual(result['result']['duration_limit_s'],10) + self.assertEqual({i for i,action in self.sent if action=='current'},{count-1}) + self.assertTrue(result['result']['release_confirmed']) + self.assertEqual(len(result['result']['backups']),count) + self.assertEqual(len(result['result']['release']),count) + self.assertLessEqual(self.clock.now,11.36) + + def test_new_controller_during_preflight_or_pulse_stops_current(self): + extra=test_reader.Attachment('3-1','3','ttyACM3','12') + self.attachments.append(extra) + self.assertEqual(self.service.execute(self.command_for_pulse())['state'],'error') + self.assertEqual(self.sent,[]) + self.attachments.remove(extra) + def send(action): + self.sent.append((0,action)) + if action=='current':self.attachments.append(extra) + self.devices[0].link.test_command=send + result=self.service.execute(self.command_for_pulse()) + self.assertEqual(result['state'],'complete') + self.assertNotEqual(result['result']['outcome'],'duration') + self.assertEqual(self.sent.count((0,'current')),1) + self.assertEqual(self.sent[-2:],[(0,'release'),(1,'release')]) + + def test_unmanaged_can_peer_on_other_controller_blocks_all_current(self): + original=self.devices[1].link.query + self.devices[1].link.query=lambda code,timeout=2:bytes([62,99]) if code==62 else original(code,timeout) + result=self.service.execute(self.command_for_pulse()) + self.assertEqual(result['state'],'error') + self.assertEqual(self.sent,[]) + + def test_slow_multi_controller_cycle_never_sends_torque(self): + original=self.devices[1].link.query + def delayed(code,timeout=2): + if code==31:self.clock.sleep(0.13) + return original(code,timeout) + self.devices[1].link.query=delayed + result=self.service.execute(self.command_for_pulse()) + self.assertNotEqual(result['result']['outcome'],'duration') + self.assertEqual(self.sent,[]) + + def test_duration_is_allowlisted_and_stop_interrupts_ten_second_pulse(self): + for duration in (True,0,30.01,100,'10'): + command=self.command_for_pulse();command['parameters']['duration_s']=duration + with self.assertRaises(ValueError):self.service.execute(command) + def send(action): + self.sent.append((0,action)) + if action=='current':self.service.motor.cancel() + self.devices[0].link.test_command=send + command=self.command_for_pulse();command['parameters']['duration_s']=10 + result=self.service.execute(command) + self.assertEqual(result['result']['outcome'],'stopped') + self.assertEqual(self.sent.count((0,'current')),1) + self.assertLess(self.clock.now,2) + + def test_can_timeout_reports_preflight_failure_without_current(self): + original=self.devices[0].link.query + def query(code,timeout=2): + if code==62: + self.assertEqual(timeout,8) + raise TimeoutError('synthetic CAN timeout') + return original(code,timeout) + self.devices[0].link.query=query + result=self.service.execute(self.command_for_pulse()) + self.assertEqual(result['state'],'error') + self.assertIn('CAN',result['error']) + self.assertEqual(self.sent,[]) + + def test_can_inspection_does_not_claim_or_drive_motors(self): + result=self.service.execute(self.command(action='vesc.can.read')) + self.assertEqual(result['state'],'complete') + self.assertEqual(result['result']['can_ids'],[10,11]) + self.assertEqual(self.sent,[]) + + def test_old_coasting_thresholds_no_longer_interrupt_current(self): + original=self.devices[0].link.query + speeds=iter([0,210,880,1200,3000]) + def query(code,timeout=2): + raw=original(code,timeout) + if code==4: + speed=next(speeds,3000) + raw=raw[:21]+struct.pack('>hi',120 if speed else 0,speed)+raw[27:] + return raw + self.devices[0].link.query=query + command=self.command_for_pulse();command['parameters'].update(current_a=5,duration_s=30) + result=self.service.execute(command)['result'] + self.assertEqual(result['outcome'],'duration') + self.assertEqual(result['duration_limit_s'],30) + self.assertGreater(len(result['samples']),590) + self.assertTrue(all(s['commanded_current_a'] > 0 for s in result['samples'])) + self.assertEqual(self.sent.count((0,'release')),1) + self.assertTrue(result['release_confirmed']) + + def test_current_ramps_from_half_amp_to_entered_ceiling(self): + command=self.command_for_pulse();command['parameters'].update(current_a=5,duration_s=10) + result=self.service.execute(command)['result'] + amps=[value for _,value in self.currents] + self.assertEqual(amps[0],0.5) + self.assertEqual(max(amps),5) + self.assertTrue(all(0<=b-a<=0.10001 for a,b in zip(amps,amps[1:]))) + self.assertEqual(result['outcome'],'duration') + self.assertEqual(result['current_ramp_a_per_s'],2) + + def test_thirty_amp_thirty_second_moving_target_and_bounded_receipt(self): + original=self.devices[0].link.query + tacho=0 + def query(code,timeout=2): + nonlocal tacho + raw=original(code,timeout) + if code==4 and self.currents: + tacho+=4 + raw=raw[:23]+struct.pack('>i',1200)+raw[27:] + raw=raw[:45]+struct.pack('>ii',tacho,tacho)+raw[53:] + return raw + self.devices[0].link.query=query + command=self.command_for_pulse();command['parameters'].update(current_a=30,duration_s=30) + result=self.service.execute(command)['result'] + self.assertEqual(result['outcome'],'duration') + self.assertEqual(max(amps for _,amps in self.currents),30) + self.assertEqual({i for i,_ in self.currents},{0}) + self.assertEqual(self.sent[-2:],[(0,'release'),(1,'release')]) + self.assertTrue(result['release_confirmed']) + import json + self.assertLess(len(json.dumps(result).encode()),1024*1024) + + def test_high_current_without_motion_stops_and_does_not_auto_restart(self): + command=self.command_for_pulse();command['parameters'].update(current_a=30,duration_s=30) + result=self.service.execute(command)['result'] + self.assertIn('движение не подтверждается',result['outcome']) + self.assertLess(result['samples'][-1]['at'],5) + self.assertLess(max(amps for _,amps in self.currents),10) + self.assertIsNone(result['samples'][-1]['commanded_current_a']) + self.assertEqual(self.sent[-2:],[(0,'release'),(1,'release')]) + self.assertTrue(result['release_confirmed']) + + def test_reported_speed_alone_cannot_reset_stall_without_tachometer_motion(self): + original=self.devices[0].link.query + def query(code,timeout=2): + raw=original(code,timeout) + if code==4 and self.currents:raw=raw[:23]+struct.pack('>i',1200)+raw[27:] + return raw + self.devices[0].link.query=query + command=self.command_for_pulse();command['parameters'].update(current_a=30,duration_s=30) + result=self.service.execute(command)['result'] + self.assertIn('движение не подтверждается',result['outcome']) + self.assertTrue(result['release_confirmed']) + + def test_target_configuration_limits_remain_binding(self): + self.motor=configuration('motor',{'motor_type':2,'l_current_max':10,'l_in_current_max':10,'l_min_erpm':-2000,'l_max_erpm':2000,'l_max_duty':0.1}) + command=self.command_for_pulse();command['parameters'].update(current_a=30,duration_s=30) + result=self.service.execute(command) + self.assertEqual(result['state'],'error') + self.assertIn('настроенный предел',result['error']) + self.assertEqual(self.sent,[]) + limits=decode(self.motor,'motor') + baseline={'fault_code':0,'input_voltage_v':50,'mos_temperature_c':30,'motor_current_a':0,'erpm':0,'duty':0} + for field,value in [('erpm',2001),('duty',0.101),('motor_current_a',10.1)]: + with self.assertRaises(LimitExceeded):check_values({**baseline,field:value},moving=True,current_a=10,motor=limits) + + def test_arbitrary_current_cannot_enter_motor_loop(self): + for amps in (True,0,0.4,30.001,31,100,'5',float('nan'),float('inf')): + command=self.command_for_pulse();command['parameters']['current_a']=amps + with self.assertRaises(ValueError):self.service.execute(command) + self.assertEqual(self.sent,[]) + for amps in (0.5,1.7,3,5,10,30): + self.assertEqual(Decoder().feed(current_packet(amps)),[bytes([6])+struct.pack('>i',round(amps*1000))]) + for amps in (False,-1,0,30.001,float('nan'),float('inf')): + with self.assertRaises(ValueError):current_packet(amps) + + def test_limit_stop_keeps_triggering_sample_and_releases_every_controller(self): + original=self.devices[0].link.query + def query(code,timeout=2): + raw=original(code,timeout) + if code==4 and self.sent.count((0,'current'))==1: + raw=raw[:21]+struct.pack('>h',260)+raw[23:] + return raw + self.devices[0].link.query=query + result=self.service.execute(self.command_for_pulse())['result'] + self.assertIn('заполнение PWM 26 %',result['outcome']) + self.assertEqual(result['limit_violation'],{'field':'duty','value':0.26,'minimum':-0.25,'maximum':0.25}) + self.assertEqual(result['samples'][-1]['devices'][self.devices[0].id]['duty'],0.26) + self.assertIsNone(result['samples'][-1]['commanded_current_a']) + self.assertEqual(self.sent.count((0,'current')),1) + self.assertEqual(self.sent[-2:],[(0,'release'),(1,'release')]) + self.assertTrue(result['release_confirmed']) + + def test_each_telemetry_limit_reports_its_own_measured_value(self): + baseline={'fault_code':0,'input_voltage_v':50,'mos_temperature_c':30,'motor_current_a':0,'erpm':0,'duty':0} + for field,actual in [('fault_code',1),('input_voltage_v',61),('mos_temperature_c',66),('motor_current_a',-8.1),('erpm',6001),('duty',-0.251)]: + with self.subTest(field=field): + with self.assertRaises(LimitExceeded) as raised:check_values({**baseline,field:actual},moving=True,current_a=5) + self.assertEqual(raised.exception.violation['field'],field) + self.assertEqual(raised.exception.violation['value'],actual) + + # Parent ServiceTests use the generic firmware/read-only fake. + test_two_attachments_promote_independently = None + test_uuid_collision_never_aliases_a_controller = None + test_reconnect_invalidates_old_session_but_retains_uuid = None + test_receipt_replay_never_repeats_serial_query = None + test_backup_is_raw_hashed_and_bound_to_identity = None + test_arbitrary_writes_parameters_and_expired_requests_rejected = None + + +if __name__=='__main__':unittest.main() diff --git a/plugins/vesc/tests/test_native_link.py b/plugins/vesc/tests/test_native_link.py new file mode 100644 index 0000000..a5770b9 --- /dev/null +++ b/plugins/vesc/tests/test_native_link.py @@ -0,0 +1,93 @@ +"""Faults at the actual subprocess/RPC boundary, with no serial hardware.""" +import json +from pathlib import Path +import subprocess +import sys +import unittest +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from runtime.native_link import NativeLink +from runtime.serial import Attachment + + +class NativeBoundaryTests(unittest.TestCase): + def link(self, handler): + value = object.__new__(NativeLink) + value.attachment = Attachment('2-1', '11', 'ttyACM0', '12') + value.buffer = b""; value.sequence = 0; value.hall_pending = False + value.check = lambda:None + script = 'import sys,json,time\nfor line in sys.stdin:\n r=json.loads(line)\n ' + handler + '\n' + value.process = subprocess.Popen([sys.executable, '-u', '-c', script], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, bufsize=0) + self.addCleanup(value.close) + return value + + def test_success_returns_upstream_payload_and_keeps_one_process(self): + link = self.link('print(json.dumps({"id":r["id"],"ok":True,"result":{"payload":"BA=="}}),flush=True)') + pid = link.process.pid + self.assertEqual(link.query(4),b'\x04') + self.assertEqual(link.query(4),b'\x04') + self.assertEqual(link.process.pid,pid) + self.assertEqual(link.sequence,2) + trace=link.last_rpc + self.assertEqual(trace["stage"],"complete") + stages=[trace[k] for k in ("attachment_before_ms","request_write_ms","native_response_ms","attachment_after_ms")] + self.assertTrue(all(value>=0 for value in stages)) + self.assertLessEqual(sum(stages),trace["elapsed_ms"]+.1) + + def test_wrong_identity_closes_stream_and_cannot_replay_motor_command(self): + link = self.link('print(json.dumps({"id":r["id"]+1,"ok":True,"result":{}}),flush=True)') + with self.assertRaises(ValueError):link.test_current(5) + self.assertFalse(link.alive) + with self.assertRaises(OSError):link.test_current(5) + + def test_missing_ack_terminates_process_without_automatic_retry(self): + link = self.link('time.sleep(5)') + process = link.process + with self.assertRaises(TimeoutError):link.rpc('lease',timeout=.03) + self.assertFalse(link.alive) + self.assertIsNotNone(process.poll()) + self.assertEqual(link.sequence,1) + + def test_attachment_change_closes_owner_before_sending(self): + link = self.link('print(json.dumps({"id":r["id"],"ok":True,"result":{}}),flush=True)') + link.check = lambda: (_ for _ in ()).throw(OSError('changed attachment')) + with self.assertRaises(OSError):link.rpc('engine') + self.assertFalse(link.alive) + + def test_native_error_and_malformed_result_close_owner(self): + for response in ('{"id":r["id"],"ok":False,"error":"disconnected"}', + '{"id":r["id"],"ok":True,"result":[]}'): + with self.subTest(response=response): + link=self.link('print(json.dumps('+response+'),flush=True)') + with self.assertRaises((OSError,ValueError)):link.rpc('engine') + self.assertFalse(link.alive) + + def test_blocked_pipe_closes_owner(self): + link=self.link('time.sleep(5)') + with patch('runtime.native_link.select.select',return_value=([],[],[])): + with self.assertRaises(TimeoutError):link.rpc('engine') + self.assertFalse(link.alive) + + def test_timeout_retains_command_budget_and_attachment_state(self): + link=self.link('print(json.dumps({"id":r["id"],"ok":False,"error":"Native query timed out or disconnected"}),flush=True)') + with self.assertRaises(OSError) as caught: link.query(31,timeout=.06) + trace=caught.exception.native_rpc + self.assertEqual(trace['command'],31) + self.assertEqual(trace['attachment'], {'usb':'2-1','address':'11','tty':'ttyACM0'}) + self.assertEqual(trace['timeout_ms'],60) + self.assertTrue(trace['process_alive']) + self.assertTrue(trace['attachment_present']) + self.assertGreater(trace['elapsed_ms'],0) + self.assertFalse(link.alive) + + def test_native_packet_diagnostics_survive_fail_closed_boundary(self): + detail = {"request_emitted": True, "packets_sent": 1, "packets_received": 0, + "serial_bytes_written": 6, "port_connected": True, "serial_error": 0, + "events": [{"event": "serial_written", "bytes": 6, "at_ms": 0.2}]} + link = self.link('print(json.dumps({"id":r["id"],"ok":False,"error":"Native query timed out or disconnected","diagnostics":'+repr(detail)+'}),flush=True)') + with self.assertRaises(OSError) as caught: link.query(31, timeout=.06) + self.assertEqual(caught.exception.native_rpc['transport'], detail) + self.assertEqual(link.sequence, 1) + self.assertFalse(link.alive) diff --git a/plugins/vesc/tests/test_reader.py b/plugins/vesc/tests/test_reader.py new file mode 100644 index 0000000..f5abbf2 --- /dev/null +++ b/plugins/vesc/tests/test_reader.py @@ -0,0 +1,178 @@ +"""Synthetic protocol and ownership tests; never opens a real serial port.""" +import base64 +import binascii +from datetime import datetime, timedelta, timezone +import json +from pathlib import Path +import struct +import sys +import tempfile +import unittest +import uuid + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "src")) +from runtime import SCHEMA +from runtime.protocol import Decoder, firmware, request, values +from runtime.serial import Attachment +from runtime.service import Service + + +def frame(payload): + header = bytes([2, len(payload)]) if len(payload) < 256 else b"\x03" + len(payload).to_bytes(2, "big") + return header + payload + binascii.crc_hqx(payload, 0).to_bytes(2, "big") + b"\x03" + + +def fw(index=1): + return b"\x00\x06\x06SYNTHETIC\x00" + bytes([index]) * 12 + b"\x00\x00\x00\x00" + + +def telemetry(): + return b"\x04" + struct.pack(">hhiiiihihiiiiiiB", 215, 190, -123, 456, 0, 0, 123, 600, 481, + 100, 0, 200, 0, 30, 30, 0) + + +class ProtocolTests(unittest.TestCase): + def test_transmit_has_no_motor_or_write_escape_hatch(self): + for code in range(256): + if code in (0, 4, 14, 17, 31, 62): + self.assertEqual(Decoder().feed(request(code)), [bytes([code])]) + else: + with self.assertRaises(ValueError): request(code) + for value in (True, b"\0", "0", -1, 256): + with self.assertRaises(ValueError): request(value) + + def test_fragmented_and_combined_frames(self): + samples = [fw(), bytes([14]) + bytes(range(256)) * 4, telemetry()] + decoder = Decoder(); actual = [] + for byte in b"noise" + b"".join(map(frame, samples)): + actual += decoder.feed(bytes([byte])) + self.assertEqual(actual, samples) + + def test_crc_and_bounds(self): + bad = bytearray(frame(fw())); bad[-2] ^= 1 + self.assertEqual(Decoder().feed(bad), []) + self.assertEqual(Decoder().feed(b"\x04\xff\xff\xff" + frame(fw())), [fw()]) + with self.assertRaises(ValueError): Decoder().feed(bytes(30000)) + + def test_identity_requires_uuid_and_bounded_name(self): + self.assertEqual(firmware(fw())["uuid"], "01" * 12) + for data in (b"", fw()[:5], fw()[:20], b"\0\6\6" + b"x" * 150, fw(0)): + with self.assertRaises(ValueError): firmware(data) + + def test_telemetry_scales_signed_values_and_truncation(self): + result = values(telemetry()) + self.assertEqual(result["motor_current_a"], -1.23) + self.assertEqual(result["input_voltage_v"], 48.1) + self.assertEqual(result["erpm"], 600) + self.assertNotIn("timeout", result) + for length in range(54): + with self.assertRaises(ValueError): values(telemetry()[:length]) + + +class FakeLink: + instances = [] + identities = {} + + def __init__(self, attachment): + self.attachment = attachment; self.commands = []; self.closed = False + self.instances.append(self) + + def query(self, code, timeout=2): + request(code) + self.commands.append(code) + if code == 0: return fw(self.identities.get(self.attachment.usb, int(self.attachment.address))) + if code == 4: return telemetry() + return bytes([code]) + b"\x12\x34\x56\x78opaque-config" + + def close(self): + self.closed = True + + +class ServiceTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.attachments = [Attachment("1-2", "1", "ttyACM0", "12"), Attachment("1-3", "2", "ttyACM1", "12")] + FakeLink.instances = []; FakeLink.identities = {} + self.service = Service(self.temp.name, lambda: self.attachments, FakeLink) + self.service.scan() + + def tearDown(self): self.temp.cleanup() + + def command(self, item=None, action="vesc.telemetry.read"): + item = item or self.service.inventory("node_synthetic")["items"][0] + now = datetime.now(timezone.utc); identifier = "op_" + uuid.uuid4().hex + return {"api_version": SCHEMA, "kind": "OperationRequest", "operation_id": identifier, + "idempotency_key": identifier, "session": {"session_id": item["snapshot"]["context"]["session_id"], "device_id": item["id"]}, + "requested_at": now.isoformat(), "deadline_at": (now + timedelta(seconds=60)).isoformat(), + "action_id": action, "parameters": {}} + + def test_two_attachments_promote_independently(self): + items = self.service.inventory("node_synthetic")["items"] + self.assertEqual(len({i["id"] for i in items}), 2) + self.assertTrue(all(i["id"] != i["attachment_id"] and i["verified"] for i in items)) + result = self.service.execute(self.command(items[1])) + self.assertEqual(result["state"], "complete") + self.assertEqual(FakeLink.instances[0].commands, [0]) + self.assertEqual(FakeLink.instances[1].commands, [0, 0, 4]) + + def test_uuid_collision_never_aliases_a_controller(self): + FakeLink.identities = {"1-2": 1, "1-3": 1} + for device in self.service.devices.values(): device.close() + self.service.scan() + items = self.service.inventory("node_synthetic")["items"] + self.assertEqual(len({i["id"] for i in items}), 2) + self.assertTrue(all(not i["verified"] for i in items)) + with self.assertRaises(ValueError): self.service.execute(self.command(items[0])) + + def test_reconnect_invalidates_old_session_but_retains_uuid(self): + old = self.service.inventory("node_synthetic")["items"][0]; command = self.command(old) + self.attachments = self.attachments[1:]; self.service.scan() + self.assertTrue(FakeLink.instances[0].closed) + FakeLink.identities["1-2"] = 1 + self.attachments.append(Attachment("1-2", "3", "ttyACM4", "12")); self.service.scan() + current = next(i for i in self.service.inventory("node_synthetic")["items"] if i["id"] == old["id"]) + self.assertNotEqual(current["snapshot"]["context"]["session_id"], old["snapshot"]["context"]["session_id"]) + with self.assertRaises(ValueError): self.service.execute(command) + + def test_receipt_replay_never_repeats_serial_query(self): + command = self.command(); first = self.service.execute(command) + before = list(FakeLink.instances[0].commands) + self.assertEqual(self.service.execute(command), first) + self.assertEqual(FakeLink.instances[0].commands, before) + command["action_id"] = "vesc.config.backup" + with self.assertRaises(ValueError): self.service.execute(command) + + def test_native_process_exit_invalidates_session_before_reconnection(self): + old = self.service.inventory("node_synthetic")["items"][0] + command = self.command(old) + process = FakeLink.instances[0] + process.alive = False + self.service.scan() + current = next(i for i in self.service.inventory("node_synthetic")["items"] if i["id"] == old["id"]) + self.assertTrue(process.closed) + self.assertNotEqual(current["snapshot"]["context"]["session_id"], old["snapshot"]["context"]["session_id"]) + with self.assertRaises(ValueError): self.service.execute(command) + + def test_backup_is_raw_hashed_and_bound_to_identity(self): + result = self.service.execute(self.command(action="vesc.config.backup")) + self.assertEqual(result["state"], "complete") + value = result["result"] + self.assertFalse(value["decoded"]) + self.assertEqual(base64.b64decode(value["configs"]["motor"]["payload"])[0], 14) + backups = list(Path(self.temp.name).glob("backup_*.json")) + self.assertEqual(json.loads(backups[0].read_text()), value) + self.assertEqual(backups[0].stat().st_mode & 0o777, 0o600) + self.assertEqual(FakeLink.instances[0].commands, [0, 0, 14, 17, 0]) + + def test_arbitrary_writes_parameters_and_expired_requests_rejected(self): + for action in ("start", "stop", "settings.apply", "raw", "firmware.write"): + with self.assertRaises(ValueError): self.service.execute(self.command(action=action)) + command = self.command(); command["parameters"] = {"packet": "anything"} + with self.assertRaises(ValueError): self.service.execute(command) + command = self.command(); command["deadline_at"] = command["requested_at"] + with self.assertRaises(ValueError): self.service.execute(command) + self.assertTrue(all(link.commands == [0] for link in FakeLink.instances)) + + +if __name__ == "__main__": unittest.main() diff --git a/plugins/vesc/tests/test_receiver.py b/plugins/vesc/tests/test_receiver.py new file mode 100644 index 0000000..c1c657f --- /dev/null +++ b/plugins/vesc/tests/test_receiver.py @@ -0,0 +1,75 @@ +"""Firmware neutral-band regression and retained native failure evidence.""" +import json +import struct +import unittest + +import test_motor_test +from test_motor_test import configuration +from runtime.configuration import decode +from runtime.receiver import active, neutral_band + + +class ReceiverTests(unittest.TestCase): + def setUp(self): + self.case=test_motor_test.PulseTests('test_fixed_wire_commands_no_broadcast_and_no_parameters') + self.case.setUp(); self.addCleanup(self.case.tearDown) + + def offset(self, device, level, band=None): + original=device.link.query + def query(code,timeout=2): + if code==31:return bytes([31])+struct.pack('>ii',int(level*1e6),1466000) + raw=original(code,timeout) + if code==17 and band is not None: + return configuration('application',{**decode(raw,'application'),'app_ppm_conf.hyst':band}) + return raw + device.link.query=query + + def test_inside_deadband_allows_test_without_changing_ppm_configuration(self): + c=self.case + for device in c.devices:self.offset(device,-.066) + before=[d.link.query(17) for d in c.devices] + result=c.service.execute(c.command_for_pulse()) + self.assertEqual(result['state'],'complete',result) + self.assertEqual(result['result']['outcome'],'duration') + self.assertFalse(c.service.motor.latched) + self.assertEqual(before,[d.link.query(17) for d in c.devices]) + + def test_each_peer_uses_its_own_fresh_band_and_active_input_blocks_motion(self): + c=self.case + for device in c.devices:self.offset(device,-.066) + self.assertEqual(c.service.execute(c.command_for_pulse())['state'],'complete') + c.sent.clear() + self.offset(c.devices[1],-.066,.05) + result=c.service.execute(c.command_for_pulse()) + self.assertEqual(result['state'],'error') + self.assertTrue(c.service.motor.latched) + self.assertEqual(c.sent,[]) + + def test_unknown_band_and_invalid_input_do_not_assume_neutral(self): + with self.assertRaises(ValueError):self.case.service.motor.receiver_active('missing',0) + for level,band in [(float('nan'),.15),(0,float('nan')),(0,0),(0,.8)]: + with self.assertRaises(ValueError):active(level,band) + self.assertFalse(active(.15,.15)) + self.assertTrue(active(-.150001,.15)) + + def test_native_read_and_preflight_failures_keep_transport_diagnostics(self): + c=self.case + for action,code in [('vesc.input.read',31),('vesc.motor.pulse',17)]: + with self.subTest(action=action): + device=c.devices[0]; original=device.link.query + trace={'command':code,'stage':'native_response','transport':{'request_emitted':True,'packets_received':0}} + def query(actual,timeout=2): + if actual==code: + error=OSError('native timeout');error.native_rpc=trace;error.native_history=[trace] + raise error + return original(actual,timeout) + device.link.query=query + command=c.command_for_pulse() if action=='vesc.motor.pulse' else c.command(action=action) + result=c.service.execute(command) + self.assertEqual(result['state'],'error') + self.assertEqual(result['result']['failure']['native_rpc'],trace) + saved=json.loads((c.service.root/(command['operation_id']+'.json')).read_text()) + self.assertEqual(saved['receipt'],result) + self.assertEqual(c.service.execute(command),result) + self.assertEqual(c.sent,[]) + device.link.query=original diff --git a/plugins/vesc/tests/test_remote_control.py b/plugins/vesc/tests/test_remote_control.py new file mode 100644 index 0000000..cb5abe9 --- /dev/null +++ b/plugins/vesc/tests/test_remote_control.py @@ -0,0 +1,307 @@ +import unittest +from runtime.remote_control import InputLease + +def envelope(identifier='a'*32,seq=1,**kw): + return dict(id=identifier,sequence=seq,ttl_ms=300,left=1,right=-1, + settings=dict(standstill_confirmed=True,current_a=30,max_erpm=2000),**kw) + +class LeaseTests(unittest.TestCase): + def setUp(self): + self.now=0 + self.lease=InputLease(lambda:self.now) + + def test_no_duplicate_renewal_no_late_resume(self): + self.assertTrue(self.lease.accept(envelope())) + self.now=.2;self.assertFalse(self.lease.accept(envelope())) + self.now=.301;self.assertFalse(self.lease.live()) + self.assertFalse(self.lease.accept(envelope(seq=2))) + self.assertFalse(self.lease.live()) + + def test_stop_is_terminal_even_with_newer_frames(self): + self.lease.accept(envelope());self.lease.stop() + self.assertFalse(self.lease.accept(envelope(seq=20))) + self.assertEqual(self.lease.demand,(0,0)) + + def test_identity_change_stops_instead_of_stealing(self): + self.lease.accept(envelope()) + self.assertFalse(self.lease.accept(envelope('b'*32))) + self.assertFalse(self.lease.live()) + + def test_invalid_limits_and_nan(self): + for key,value in [('ttl_ms',401),('ttl_ms',0),('left',float('nan')),('right',2),('sequence',True)]: + item=envelope();item[key]=value + with self.subTest(key=key,value=value),self.assertRaises(ValueError):self.lease.accept(item) + +from types import SimpleNamespace +from unittest.mock import patch +import threading +from runtime.remote_control import ControlEnded, RemoteControl + + +class PreparationHandoffTests(unittest.TestCase): + """The observer and control worker share one hardware owner, not a queue.""" + def setUp(self): + self.now = [0.] + self.attempted = threading.Event() + self.operation = threading.Lock() + self.operation.acquire() + case = self + + class ObservedLock: + def acquire(self, *args, **kwargs): + case.attempted.set() + return case.operation.acquire(*args, **kwargs) + + def release(self): + case.operation.release() + + self.calls = [] + + def run(*args, **kwargs): + self.calls.append('prepare') + raise ControlEnded('synthetic completion') + + profile = {'layout': '1x1', 'revision': 1, 'bindings': { + 'left.1': {'device_id': 'left'}, 'right.1': {'device_id': 'right'}}} + service = SimpleNamespace(operation_lock=ObservedLock(), lock=threading.Lock(), + motor=SimpleNamespace(run=run), drive=SimpleNamespace(value=profile), + devices={'left': SimpleNamespace(link=object()), 'right': SimpleNamespace(link=object())}) + self.remote = RemoteControl(service) + self.remote.lease = InputLease(lambda: self.now[0]) + self.relay = 'b' * 32 + self.remote.feed({'watch': True, 'command': None, 'relay_id': self.relay}) + + def start(self): + self.remote.feed({'watch': True, 'command': envelope(), 'relay_id': self.relay}) + self.assertTrue(self.attempted.wait(1)) + + def finish(self): + self.operation.release() + self.remote.thread.join(1) + self.assertFalse(self.remote.thread.is_alive()) + + def tearDown(self): + self.remote.lease.stop() + if self.operation.locked(): + self.operation.release() + if self.remote.thread: + self.remote.thread.join(1) + + def test_existing_read_finishes_before_preparation(self): + self.start() + self.assertEqual(self.remote.state, 'preparing') + self.assertEqual(self.calls, []) + self.finish() + self.assertEqual(self.calls, ['prepare']) + self.assertEqual(self.remote.state, 'stopped') + self.assertFalse(self.operation.locked()) + + def test_stop_while_waiting_never_starts_preparation(self): + self.start() + self.remote.feed({'watch': True, 'command': None, 'relay_id': self.relay}) + self.finish() + self.assertEqual(self.calls, []) + self.assertEqual(self.remote.state, 'stopped') + + def test_expired_input_does_not_start_when_lock_is_released(self): + self.start() + self.now[0] = .301 + self.finish() + self.assertEqual(self.calls, []) + self.assertFalse(self.remote.lease.live()) + + def test_long_operation_does_not_queue_preparation(self): + self.start() + self.remote.thread.join(1) + self.assertFalse(self.remote.thread.is_alive()) + self.assertEqual(self.calls, []) + self.assertEqual(self.remote.state, 'fault') + self.assertTrue(self.operation.locked()) + + def test_observer_yields_to_waiting_control_worker(self): + self.start() + self.attempted.clear() + self.remote.observe() + # The observer does not even try to reacquire ownership. + # Its test devices intentionally have no serial read methods. + self.assertEqual(self.calls, []) + self.finish() + self.assertEqual(self.calls, ['prepare']) + +class DriveBoundaryTests(unittest.TestCase): + """Synthetic two-controller run: verify the actual output loop and cleanup.""" + def run_drive(self, scenario, *, broken_read=False, through_prepare=False, minimum_erpm=900): + now=[0.]; logs=[]; restored=[] + profile={'layout':'1x1','revision':1,'bindings':{ + 'left.1':{'device_id':'left','uuid':'left'}, + 'right.1':{'device_id':'right','uuid':'right'}}} + service=SimpleNamespace(drive=SimpleNamespace(value=profile)) + remote=RemoteControl(service) + remote._publish=lambda *args:None + remote.lease=InputLease(lambda:now[0]); remote.lease.accept(envelope()) + remote.lease.demand=(0,0) + def value():return dict(fault_code=0,input_voltage_v=48,mos_temperature_c=25, + motor_current_a=0,input_current_a=0,erpm=0,duty=0,tachometer=0) + class Link: + def __init__(self,name):self.name=name + def query(self,code,timeout): + if broken_read and self.name=='right' and now[0]>=.2:raise TimeoutError('lost right controller') + if code==4: + result=value() + if scenario=='coasting' and self.name=='right' and .4<=now[0]<.8:result['erpm']=1000 + return result + return {'level':.8 if scenario=='receiver' and .2<=now[0]<.5 else 0} + def test_command(self,name):logs.append((now[0],self.name,name,0)) + def test_speed(self,rpm):logs.append((now[0],self.name,'rpm',rpm)) + devices=[SimpleNamespace(id=name,link=Link(name)) for name in ('left','right')] + owner=SimpleNamespace(stop=threading.Event(),latched=False,active=False,mode=None) + def state(s):owner.latched=s=='rc' + owner.state=state + owner.receiver_active=lambda _,level:abs(level)>.15 + owner.limits=SimpleNamespace(apply=lambda d,*a:dict(l_current_max=35,l_max_erpm=100000,l_min_erpm=-100000,l_max_duty=.95, + s_pid_min_erpm=minimum_erpm[d.id] if isinstance(minimum_erpm,dict) else minimum_erpm),restore=lambda d:restored.append(d.id)) + def sleep(delta): + now[0]+=delta + if now[0]>=2:owner.stop.set() + if remote.lease.live(): + if scenario!='expire': remote.lease.until=now[0]+.4 + remote.lease.demand=((-1,-1) if scenario=='reverse' and now[0]>=.4 else (1,1)) + if scenario=='small': remote.lease.demand=(.2,-.2) + if scenario=='turn': remote.lease.demand=(-1,1) + if scenario=='release' and now[0]>=.4: remote.lease.demand=(0,0) + if scenario in ('turn-forward','coasting'): + remote.lease.demand=(-1,1) if now[0]<.4 else (1,1) + if scenario=='paused-reverse': + remote.lease.demand=(1,1) if now[0]<.4 else (0,0) if now[0]<1.2 else (-1,-1) + if scenario=='cancel-reverse': + remote.lease.demand=(-1,-1) if .4<=now[0]<.6 else (1,1) + owner.sleep=sleep + command={'parameters':{'current_a':30,'erpm':2000}} + originals={d.id:{'motor':b'config'} for d in devices} + service.motor=owner;service.operation_lock=threading.Lock();service.lock=threading.Lock() + service.devices={d.id:d for d in devices} + owner.run=lambda command,devices,target,remote:remote.drive(owner,command,devices,devices,originals,lambda:None) + error=None + with patch('runtime.remote_control.time.monotonic',lambda:now[0]),patch('runtime.remote_control.values',lambda v:v),patch('runtime.remote_control.ppm',lambda v:v): + try: + if through_prepare: remote._prepare(envelope()) + else: remote.drive(owner,command,devices,devices,originals,lambda:None) + except (ValueError,TimeoutError) as e:error=e + return logs,restored,remote,owner,error + + def test_start_enters_each_configured_pid_range_without_dead_ramp(self): + log,_,_,_,error=self.run_drive('forward',minimum_erpm={'left':900,'right':1100.1}) + self.assertIsNone(error) + for name,minimum in [('left',900),('right',1101)]: + commands=[v for v in log if v[1]==name and v[2]=='rpm'] + self.assertLessEqual(commands[0][0],.2) + self.assertEqual(commands[0][3],minimum) + self.assertTrue(all(minimum<=v[3]<=2000 for v in commands)) + for before,after in zip(commands,commands[1:]): + self.assertLessEqual(after[3]-before[3],600*(after[0]-before[0])+1e-6) + + def test_turn_starts_with_opposite_signs_at_pid_threshold(self): + log,_,_,_,error=self.run_drive('turn') + self.assertIsNone(error) + for name,sign in [('left',-1),('right',1)]: + first=next(v for v in log if v[1]==name and v[2]=='rpm') + self.assertEqual(first[3],sign*900) + + def test_subthreshold_request_is_released_never_amplified(self): + log,_,_,_,error=self.run_drive('small') + self.assertIsNone(error) + self.assertFalse(any(v[2]=='rpm' for v in log)) + + def test_release_still_has_no_ramp_or_minimum_speed(self): + log,_,_,_,error=self.run_drive('release') + self.assertIsNone(error) + self.assertTrue(any(v[2]=='rpm' for v in log)) + self.assertFalse(any(v[2]=='rpm' and v[0]>=.4 for v in log)) + + def test_invalid_or_unreachable_pid_threshold_never_claims_output(self): + for minimum in [-1,float('nan'),float('inf'),2000.1]: + with self.subTest(minimum=minimum): + log,_,_,_,error=self.run_drive('forward',minimum_erpm=minimum) + self.assertIsInstance(error,ValueError) + self.assertFalse(any(v[2] in ('rpm','claim') for v in log)) + + def test_turn_to_forward_releases_both_and_restarts_in_same_cycle(self): + log,_,_,_,error=self.run_drive('turn-forward') + self.assertIsNone(error) + restarts={name:next(v[0] for v in log if v[1]==name and v[2]=='rpm' and v[0]>=.4) + for name in ('left','right')} + self.assertEqual(restarts['left'],restarts['right']) + self.assertGreaterEqual(restarts['left'],.9) + self.assertFalse(any(v[2]=='rpm' and .4<=v[0]0 for v in log if v[2]=='rpm' and v[0]>=restarts['left'])) + + def test_shared_reversal_waits_for_every_motor_to_be_quiet(self): + log,_,_,_,error=self.run_drive('coasting') + self.assertIsNone(error) + first=next(v[0] for v in log if v[2]=='rpm' and v[0]>=.4) + self.assertGreaterEqual(first,1.3) + self.assertFalse(any(v[2]=='rpm' and .4<=v[0]<1.3 for v in log)) + + def test_neutral_pause_counts_before_reversal_command(self): + log,_,_,_,error=self.run_drive('paused-reverse') + self.assertIsNone(error) + first=next(v[0] for v in log if v[2]=='rpm' and v[3]<0) + self.assertLess(first,1.4) + + def test_cancelled_reversal_never_emits_old_direction(self): + log,_,_,_,error=self.run_drive('cancel-reverse') + self.assertIsNone(error) + self.assertFalse(any(v[2]=='rpm' and v[3]<0 for v in log)) + self.assertTrue(any(v[2]=='rpm' and v[0]>=.6 for v in log)) + + def test_expired_browser_lease_releases_every_controller(self): + log,restored,remote,owner,error=self.run_drive('expire') + self.assertIsNotNone(error) + self.assertFalse(any(row[2]=='rpm' and row[0]>=.3 for row in log)) + self.assertEqual(set(restored),{'left','right'}) + self.assertTrue(remote.release_confirmed) + self.assertTrue(any(row[2]=='rpm' for row in log)) + for name in ('left','right'):self.assertEqual([v[2] for v in log if v[1]==name][-1],'release') + + def test_terminal_lease_reports_stopped_after_verified_cleanup(self): + log,restored,remote,owner,error=self.run_drive('expire',through_prepare=True) + self.assertIsNone(error) + self.assertEqual(remote.state,'stopped') + self.assertIsNone(remote.message) + self.assertTrue(remote.release_confirmed) + self.assertTrue(any(row[2]=='rpm' for row in log)) + self.assertEqual(set(restored),{'left','right'}) + self.assertFalse(remote.service.operation_lock.locked()) + + def test_session_wrapper_preserves_unconfirmed_release_fault(self): + _,_,remote,owner,error=self.run_drive('lost',broken_read=True,through_prepare=True) + self.assertEqual(remote.state,'fault') + self.assertFalse(remote.release_confirmed) + self.assertIn('не подтверждено',remote.message) + self.assertFalse(remote.service.operation_lock.locked()) + + def test_receiver_first_gesture_holds_zero_until_neutral(self): + log,restored,remote,owner,error=self.run_drive('receiver') + self.assertIsNone(error) + self.assertTrue(any(v[2]=='rpm' for v in log)) + self.assertFalse(any(v[2]=='rpm' and v[0]>=.2 for v in log)) + self.assertTrue(owner.latched) + self.assertEqual(remote.state,'receiver') + self.assertGreaterEqual(max(v[0] for v in log),.9) + + def test_reversal_has_zero_interval(self): + log,_,_,_,error=self.run_drive('reverse') + self.assertIsNone(error) + first_negative=min(v[0] for v in log if v[2]=='rpm' and v[3]<0) + self.assertGreaterEqual(first_negative,.9) + self.assertFalse(any(v[2]=='rpm' and .4<=v[0]<.9 for v in log)) + + def test_one_port_failure_stops_both_and_does_not_claim_confirmed_release(self): + log,restored,remote,owner,error=self.run_drive('lost',broken_read=True) + self.assertIsInstance(error,TimeoutError) + self.assertFalse(any(v[2]=='rpm' and v[0]>=.2 for v in log)) + self.assertFalse(remote.release_confirmed) + self.assertTrue(owner.latched) + self.assertEqual(remote.state,'fault') + self.assertIn('не подтверждено',remote.message) + self.assertEqual(set(restored),{'left','right'}) diff --git a/plugins/vesc/tests/test_reverse_speed.py b/plugins/vesc/tests/test_reverse_speed.py new file mode 100644 index 0000000..1faef0c --- /dev/null +++ b/plugins/vesc/tests/test_reverse_speed.py @@ -0,0 +1,136 @@ +"""Signed upstream speed commands retain timing, preflight and RC interlocks.""" +import struct +import unittest + +import test_speed_and_hall +import test_group_test +from test_motor_test import configuration +from runtime.configuration import decode +from runtime.protocol import Decoder, speed_packet +from runtime.speed_hold import SpeedHold + + +class ReverseTests(unittest.TestCase): + def setUp(self): + self.rig = test_speed_and_hall.RunTests('test_thirty_seconds_excludes_ramp_and_settle_and_restores_limits') + self.rig.setUp() + self.addCleanup(self.rig.doCleanups) + self.case = self.rig.case + + def command(self): + command = self.rig.run_command() + command['parameters']['erpm'] = -3000 + return command + + def test_reverse_holds_thirty_seconds_with_signed_ramp_and_restores(self): + result = self.case.service.execute(self.command())['result'] + self.assertEqual(result['outcome'], 'duration', result) + self.assertGreaterEqual(result['rotation_s'], 30) + self.assertGreater(result['samples'][-1]['at'], 35) + speeds = [v for _, v in self.rig.speeds] + self.assertEqual(speeds[0], -1) + self.assertEqual(speeds[-1], -3000) + self.assertTrue(all(-3000 <= v < 0 for v in speeds)) + self.assertTrue(all(-31 <= b-a <= 0 for a, b in zip(speeds, speeds[1:]))) + self.assertTrue(result['release_confirmed']) + self.assertTrue(result['limits_restored']) + self.assertEqual(self.rig.configs, self.rig.originals) + self.assertEqual(len(result['preflight']['samples']), 20) + + def test_missing_false_or_nonboolean_stop_confirmation_never_writes(self): + for confirmation in (None, False, 1, 'true'): + command = self.command() + if confirmation is None: del command['parameters']['standstill_confirmed'] + else: command['parameters']['standstill_confirmed'] = confirmation + with self.assertRaises(ValueError): self.case.service.execute(command) + self.assertEqual(self.rig.speeds, []) + self.assertEqual(self.case.sent, []) + + def test_unsigned_size_bounds_are_checked_for_both_directions(self): + for erpm in (0, 299, -299, 3001, -3001, True, float('nan'), float('inf')): + command = self.command(); command['parameters']['erpm'] = erpm + with self.assertRaises(ValueError): self.case.service.execute(command) + self.assertEqual(self.rig.speeds, []) + + def test_reverse_respects_configured_negative_limit(self): + target = self.case.devices[0] + motor = decode(self.rig.configs[target.id], 'motor') + self.rig.configs[target.id] = configuration('motor', {**motor, 'l_min_erpm': -1000}) + self.assertEqual(self.case.service.execute(self.command())['state'], 'error') + self.assertEqual(self.rig.speeds, []) + + def test_sensorless_idle_observation_rejects_modulation_above_one_quantum(self): + peer = self.case.devices[1] + motor = decode(self.rig.configs[peer.id], 'motor') + self.rig.configs[peer.id] = configuration('motor', {**motor, 'foc_sensor_mode': 0}) + original = peer.link.query + reads = 0 + def query(code, timeout=2): + nonlocal reads + raw = original(code, timeout) + if code == 4: + reads += 1 + raw = raw[:23] + struct.pack('>i', -160) + raw[27:] + if reads >= 6: raw = raw[:21] + struct.pack('>h', 2) + raw[23:] + return raw + peer.link.query = query + result = self.case.service.execute(self.command()) + self.assertEqual(result['state'], 'error') + self.assertEqual(self.rig.speeds, []) + self.assertEqual(self.rig.sets, []) + + def test_attended_sensorless_peer_drift_allows_test_and_explicit_release(self): + peer = self.case.devices[1] + motor = decode(self.rig.configs[peer.id], 'motor') + self.rig.configs[peer.id] = configuration('motor', {**motor, 'foc_sensor_mode': 0}) + query = peer.link.query + def read(code, timeout=2): + raw = query(code, timeout) + return raw[:23] + struct.pack('>i', -160) + raw[27:] if code == 4 else raw + peer.link.query = read + self.case.service.motor.state('rc') + release = self.case.command_for_pulse() + release['action_id'] = 'vesc.control.release' + release['parameters']['standstill_confirmed'] = True + receipt = self.case.service.execute(release) + self.assertEqual(receipt['state'], 'complete', receipt) + self.assertFalse(self.case.service.motor.latched) + self.assertEqual(self.rig.speeds, []) + result = self.case.service.execute(self.command())['result'] + self.assertEqual(result['outcome'], 'duration', result) + self.assertTrue(any(s['values']['erpm'] == -160 for s in result['preflight']['samples'])) + + def test_reverse_rc_preemption_latches_without_restart(self): + speed = self.case.devices[0].link.test_speed + def send(value): + speed(value) + self.case.changed = True + self.case.devices[0].link.test_speed = send + result = self.case.service.execute(self.command())['result'] + self.assertEqual(len(self.rig.speeds), 1) + self.assertTrue(self.case.service.motor.latched) + self.assertEqual(result['rotation_s'], 0) + self.assertTrue(result['release_confirmed']) + + +class ReverseClockTests(unittest.TestCase): + def test_wrong_direction_never_counts_even_with_changing_tachometer(self): + hold = SpeedHold(-3000, 30, 0) + for i in range(151): _, _, error = hold.update(i/10, {'erpm':3000, 'tachometer':i}) + self.assertEqual(hold.rotation_s, 0) + self.assertIsNone(hold.hold_started) + self.assertIn('не вышел', error) + + def test_signed_wire_is_int32_not_absolute_value(self): + self.assertEqual(Decoder().feed(speed_packet(-3000)), [bytes([8])+struct.pack('>i', -3000)]) + + def test_common_reverse_holds_all_motors_and_restores(self): + rig = test_group_test.GroupTests('test_pair_and_four_motors_run_one_common_interval_and_restore') + rig.setUp(); self.addCleanup(rig.doCleanups) + command = rig.command(); command['parameters']['erpm'] = -3000 + result = rig.case.service.execute(command)['result'] + self.assertEqual(result['outcome'], 'duration', result) + self.assertGreaterEqual(result['rotation_s'], 3) + self.assertTrue(all(-3000 <= v < 0 for _, v in rig.commands)) + self.assertTrue(result['limits_restored']) + self.assertEqual(rig.configs, rig.originals) diff --git a/plugins/vesc/tests/test_speed_and_hall.py b/plugins/vesc/tests/test_speed_and_hall.py new file mode 100644 index 0000000..320b832 --- /dev/null +++ b/plugins/vesc/tests/test_speed_and_hall.py @@ -0,0 +1,206 @@ +"""Fault injection for true hold time, volatile limits and native Hall lifecycle.""" +import struct +import unittest + +import test_motor_test +from test_motor_test import configuration +from runtime.configuration import decode +from runtime.protocol import Decoder, speed_packet, hall_packet +from runtime.temporary_limits import FIELDS, packet +from runtime.speed_hold import SpeedHold +from runtime.hall_detection import parse_result + + +class RunTests(unittest.TestCase): + def setUp(self): + self.case = test_motor_test.PulseTests('test_fixed_wire_commands_no_broadcast_and_no_parameters') + self.case.setUp() + self.addCleanup(self.case.tearDown) + c = self.case + self.configs = {} + self.speeds = [] + self.moving = True + self.tacho = 0 + self.hall_started = None + self.sets = [] + for device in c.devices: + self.configs[device.id] = configuration('motor', {**decode(c.motor,'motor'), + 'l_current_min':-60,'l_current_max_scale':1,'l_current_min_scale':1}) + original = device.link.query + def query(code,timeout=2,original=original,device=device): + if code == 14: return self.configs[device.id] + raw = original(code,timeout) + if code == 4 and device is c.devices[0]: + if self.hall_started is not None and c.clock.now - self.hall_started >= 12: + device.link.hall_result = bytes([28,255,1,34,67,100,134,167,255,0]) + if self.moving and self.speeds: + self.tacho += 6 + rpm = round(self.speeds[-1][1]) + raw = raw[:23]+struct.pack('>i',rpm)+raw[27:] + raw = raw[:45]+struct.pack('>ii',self.tacho,self.tacho)+raw[53:] + return raw + device.link.query = query + def set_limits(config,device=device): + self.sets.append((device.id,config)) + old = decode(self.configs[device.id],'motor') + self.configs[device.id] = configuration('motor',{**old,**{k:config[k] for k in FIELDS}}) + device.link.set_temporary_limits = set_limits + device.link.test_speed = lambda speed,device=device:self.speeds.append((device.id,speed)) + device.link.hall_result = None + device.link.hall_pending = False + def hall(device=device): + self.hall_started = c.clock.now + device.link.hall_pending = True + device.link.detect_hall = hall + self.originals = dict(self.configs) + + def run_command(self): + command = self.case.command_for_pulse() + command['action_id'] = 'vesc.motor.run' + command['parameters'].update(erpm=1200,current_a=30,duration_s=30,standstill_confirmed=True) + from datetime import datetime,timedelta + command['deadline_at']=(datetime.fromisoformat(command['requested_at'])+timedelta(seconds=90)).isoformat() + return command + + def test_thirty_seconds_excludes_ramp_and_settle_and_restores_limits(self): + result=self.case.service.execute(self.run_command())['result'] + self.assertEqual(result['outcome'],'duration',result['outcome']) + self.assertGreaterEqual(result['rotation_s'],30) + self.assertLess(result['rotation_s'],30.1) + self.assertGreater(result['samples'][-1]['at'],32) + self.assertTrue(result['release_confirmed']) + self.assertTrue(result['limits_restored']) + self.assertEqual(self.configs,self.originals) + self.assertEqual({device for device,_ in self.speeds},{self.case.devices[0].id}) + applied=self.sets[0][1] + self.assertAlmostEqual(applied['l_current_max']*applied['l_current_max_scale'],30) + self.assertAlmostEqual(applied['l_current_min']*applied['l_current_min_scale'],-30) + self.assertFalse(list(self.case.service.root.glob('limits_*.json'))) + + def test_stationary_motor_never_counts_command_time_as_rotation(self): + self.moving=False + result=self.case.service.execute(self.run_command())['result'] + self.assertEqual(result['rotation_s'],0) + self.assertIn('не вышел',result['outcome']) + self.assertGreaterEqual(result['samples'][-1]['at'],15) + self.assertTrue(result['limits_restored']) + + def test_lost_ack_after_limit_write_restores_before_any_speed_command(self): + target=self.case.devices[0] + original=target.link.set_temporary_limits + def send(config): + original(config) + if len(self.sets)==1:raise TimeoutError('lost ACK after applying') + target.link.set_temporary_limits=send + result=self.case.service.execute(self.run_command())['result'] + self.assertEqual(self.speeds,[]) + self.assertTrue(result['limits_restored']) + self.assertEqual(self.configs,self.originals) + + def test_pending_limits_recovered_after_interruption_without_motor_command(self): + target=self.case.devices[0] + self.case.service.motor.limits.apply(target,self.originals[target.id],5) + self.assertTrue(self.case.service.motor.limits.pending(target)) + self.case.service.scan() + self.assertEqual(self.configs,self.originals) + self.assertEqual(self.speeds,[]) + self.assertFalse(self.case.service.motor.limits.pending(target)) + + def test_external_configuration_change_never_overwritten_by_recovery(self): + target=self.case.devices[0] + self.case.service.motor.limits.apply(target,self.originals[target.id],5) + self.configs[target.id]=configuration('motor',{**decode(self.configs[target.id],'motor'),'foc_motor_r':0.1}) + before=self.configs[target.id] + self.case.service.scan() + self.assertEqual(before,self.configs[target.id]) + self.assertTrue(self.case.service.motor.limits.pending(target)) + self.assertEqual(self.case.service.execute(self.run_command())['state'],'error') + self.assertEqual(self.speeds,[]) + + def test_native_hall_returns_measured_table_without_applying_it(self): + command=self.case.command(action='vesc.hall.measure') + command['parameters']={'rig_clear':True,'standstill_confirmed':True,'native_cycle_confirmed':True, + 'sessions':{d.id:d.session for d in self.case.devices}} + receipt=self.case.service.execute(command) + self.assertEqual(receipt['state'],'complete',receipt) + result=receipt['result'] + self.assertTrue(result['completed']) + self.assertTrue(result['measurement']['valid_six_states']) + self.assertTrue(result['configuration_restored']) + self.assertTrue(result['release_confirmed']) + self.assertFalse(result['configuration_written']) + self.assertEqual(self.configs,self.originals) + self.assertEqual(self.speeds,[]) + self.assertFalse((self.case.service.root/'hall-pending.json').exists()) + started=self.hall_started + self.assertEqual(self.case.service.execute(command),receipt) + self.assertEqual(started,self.hall_started) + + def test_native_hall_requires_its_own_explicit_confirmation(self): + command=self.case.command(action='vesc.hall.measure') + command['parameters']={'rig_clear':True,'standstill_confirmed':True,'native_cycle_confirmed':False, + 'sessions':{d.id:d.session for d in self.case.devices}} + with self.assertRaises(ValueError):self.case.service.execute(command) + self.assertIsNone(self.hall_started) + + def test_rc_preemption_releases_speed_control_and_restores_limits(self): + original=self.case.devices[0].link.test_speed + def speed(value): + original(value) + self.case.changed=True + self.case.devices[0].link.test_speed=speed + result=self.case.service.execute(self.run_command())['result'] + self.assertEqual(len(self.speeds),1) + self.assertEqual(result['rotation_s'],0) + self.assertTrue(self.case.service.motor.latched) + # Restoring while a receiver actively commands would enlarge RC torque; + # keep the lower limits until neutral, then recover without auto-start. + self.assertFalse(result['limits_restored']) + self.case.changed=False + self.case.service.scan() + self.assertEqual(self.configs,self.originals) + self.assertTrue(self.case.service.motor.latched) + self.assertEqual(len(self.speeds),1) + + def test_hall_result_timeout_latches_and_never_starts_a_second_cycle(self): + self.case.devices[0].link.detect_hall=lambda:None + command=self.case.command(action='vesc.hall.measure') + command['parameters']={'rig_clear':True,'standstill_confirmed':True,'native_cycle_confirmed':True, + 'sessions':{d.id:d.session for d in self.case.devices}} + result=self.case.service.execute(command)['result'] + self.assertFalse(result['completed']) + self.assertTrue((self.case.service.root/'hall-pending.json').exists()) + self.assertTrue(self.case.service.motor.latched) + self.assertEqual(self.case.service.execute(self.run_command())['state'],'error') + + +class HoldClockTests(unittest.TestCase): + def test_interrupted_motion_and_usb_gap_are_excluded(self): + hold=SpeedHold(1200,30,0) + for i in range(40):hold.update(i/10,{'erpm':1200,'tachometer':i}) + before=hold.rotation_s + hold.update(4.5,{'erpm':1200,'tachometer':50}) + self.assertEqual(hold.rotation_s,before) + hold.update(4.6,{'erpm':0,'tachometer':50}) + self.assertEqual(hold.rotation_s,before) + _,_,error=hold.update(6.7,{'erpm':0,'tachometer':50}) + self.assertIn('перестал удерживать',error) + + def test_speed_without_changing_tachometer_never_starts_timer(self): + hold=SpeedHold(1200,30,0) + for i in range(151):_,_,error=hold.update(i/10,{'erpm':1200,'tachometer':0}) + self.assertEqual(hold.rotation_s,0) + self.assertIsNone(hold.hold_started) + self.assertIn('не вышел',error) + + def test_exact_native_wire_no_flash_no_can_and_hall_failure(self): + self.assertEqual(Decoder().feed(speed_packet(1200)),[bytes([8])+struct.pack('>i',1200)]) + self.assertEqual(Decoder().feed(hall_packet()),[bytes([28])+struct.pack('>i',5000)]) + wire=Decoder().feed(packet(dict.fromkeys(FIELDS,1.0)))[0] + self.assertEqual(wire[:5],bytes([48,0,0,1,0])) + self.assertEqual(len(wire),45) + failure=parse_result(bytes([28,255,255,255,100,255,255,255,255,1])) + self.assertFalse(failure['valid_six_states']) + self.assertEqual(failure['observed_states'],[3]) + for value in (float('nan'),float('inf'),-3001,3001,True): + with self.assertRaises(ValueError):speed_packet(value) diff --git a/plugins/vesc/tests/test_upgrade.py b/plugins/vesc/tests/test_upgrade.py new file mode 100644 index 0000000..cc3744a --- /dev/null +++ b/plugins/vesc/tests/test_upgrade.py @@ -0,0 +1,26 @@ +"""Regression for deterministic package mtimes and root-created Python caches.""" +import os +from pathlib import Path +import py_compile +import runpy +import subprocess +import sys +import tempfile +import unittest + + +class UpgradeTests(unittest.TestCase): + def test_same_size_source_with_old_pyc_loads_new_version_after_installer_step(self): + clear = runpy.run_path(str(Path(__file__).parents[1] / "packaging/clear_runtime_cache.py"))["clear"] + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp); package = root / "runtime"; package.mkdir() + init = package / "__init__.py"; init.write_text('VERSION="0.1.0"\n'); os.utime(init,(0,0)) + py_compile.compile(str(init),doraise=True) + init.write_text('VERSION="0.2.0"\n');os.utime(init,(0,0)) + backup=root/'backup.json';backup.write_text('preserve') + code='import sys;sys.path.insert(0,sys.argv[1]);import runtime;print(runtime.VERSION)' + def version():return subprocess.check_output([sys.executable,'-I','-B','-c',code,str(root)],text=True).strip() + self.assertEqual(version(),'0.1.0') + clear(root);clear(root) + self.assertEqual(version(),'0.2.0') + self.assertEqual(backup.read_text(),'preserve') diff --git a/src/k1link/device_plugins/vesc/__init__.py b/src/k1link/device_plugins/vesc/__init__.py new file mode 100644 index 0000000..378b02a --- /dev/null +++ b/src/k1link/device_plugins/vesc/__init__.py @@ -0,0 +1 @@ +"""VESC configuration storage on Core; serial execution remains on the board.""" diff --git a/src/k1link/device_plugins/vesc/archive.py b/src/k1link/device_plugins/vesc/archive.py new file mode 100644 index 0000000..3ce43e3 --- /dev/null +++ b/src/k1link/device_plugins/vesc/archive.py @@ -0,0 +1,131 @@ +"""Immutable VESC backups, shared by Core and the packaged board plugin. + +Storage has no hardware or restore authority. Versions survive transient +operation receipt cleanup, reboots and controller disconnects. +""" +import base64 +import hashlib +import json +import re +import sqlite3 +from datetime import datetime +from pathlib import Path +from contextlib import contextmanager + + +def validate(value): + if not isinstance(value, dict) or len(json.dumps(value)) > 40000: + raise ValueError("Invalid configuration backup") + if value.get("schema") != "missioncore.vesc.config-backup/v1": + raise ValueError("Unsupported backup format") + if not re.fullmatch(r"op_[0-9a-f]{32}", value.get("operation_id", "")): + raise ValueError("Invalid backup identity") + identity = value["identity"] + uid = identity["uuid"] + if not re.fullmatch(r"[0-9a-f]{24}", uid) or int(uid, 16) == 0: + raise ValueError("Invalid controller identity") + expected = "vesc_" + hashlib.sha256(("uuid:" + uid).encode()).hexdigest()[:32] + if value.get("device_id") != expected: + raise ValueError("Backup controller mismatch") + if datetime.fromisoformat(value["observed_at"].replace("Z", "+00:00")).tzinfo is None: + raise ValueError("Backup time is missing its timezone") + if set(value["configs"]) != {"motor", "application"}: + raise ValueError("Incomplete backup") + for key, command in (("motor", 14), ("application", 17)): + blob = value["configs"][key] + data = base64.b64decode(blob["payload"], validate=True) + if (blob.get("encoding") != "base64" or not 5 <= len(data) <= 10000 + or data[0] != command or blob["bytes"] != len(data) + or blob["sha256"] != hashlib.sha256(data).hexdigest() + or blob["signature_hex"] != data[1:5].hex()): + raise ValueError("Backup integrity check failed") + return value + + +def metadata(sequence, value): + return {"sequence": sequence, "id": value["operation_id"], "device_id": value["device_id"], + "observed_at": value["observed_at"], "firmware": value["identity"]["version"], + "configs": {key: {"sha256": blob["sha256"], "bytes": blob["bytes"]} + for key, blob in value["configs"].items()}} + + +class Archive: + def __init__(self, root): + root = Path(root) + root.mkdir(mode=0o700, parents=True, exist_ok=True) + if root.is_symlink() or root.stat().st_mode & 0o077: + raise ValueError("Configuration archive must be private") + self.path = root / "configurations.sqlite3" + if self.path.is_symlink(): + raise ValueError("Invalid configuration archive path") + with self.connect() as db: + db.execute("CREATE TABLE IF NOT EXISTS versions (seq INTEGER PRIMARY KEY AUTOINCREMENT, " + "node TEXT NOT NULL, device TEXT NOT NULL, operation TEXT NOT NULL, " + "body TEXT NOT NULL, UNIQUE(node,device,operation))") + self.path.chmod(0o600) + + @contextmanager + def connect(self): + db = sqlite3.connect(self.path, timeout=10) + try: + db.execute("PRAGMA synchronous=FULL") + with db: + yield db + finally: + db.close() + + def add(self, node, value): + validate(value) + body = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + with self.connect() as db: + existing = db.execute("SELECT body FROM versions WHERE node=? AND device=? AND operation=?", + (node, value["device_id"], value["operation_id"])).fetchone() + if existing: + if existing[0] != body: + raise ValueError("An immutable configuration version changed") + return + db.execute("INSERT INTO versions(node,device,operation,body) VALUES(?,?,?,?)", + (node, value["device_id"], value["operation_id"], body)) + + def listing(self, node, device, before=0): + if type(before) is not int or before < 0: + raise ValueError("Invalid archive cursor") + with self.connect() as db: + rows = db.execute("SELECT seq,body FROM versions WHERE node=? AND device=? " + "AND (?=0 OR seq 50 else None} + + def read(self, node, device, operation): + with self.connect() as db: + row = db.execute("SELECT body FROM versions WHERE node=? AND device=? AND operation=?", + (node, device, operation)).fetchone() + if row is None: + raise ValueError("Configuration version not found") + return json.loads(row[0]) + + def export(self, node, after): + if type(after) is not int or after < 0: + raise ValueError("Invalid archive cursor") + with self.connect() as db: + rows = db.execute("SELECT seq,body FROM versions WHERE node=? AND seq>? ORDER BY seq LIMIT 4", + (node, after)).fetchall() + return {"after": after, "items": [{"sequence": seq, "backup": json.loads(body)} for seq, body in rows], + "next": rows[-1][0] if rows else after} + + def receive(self, node, batch): + if not isinstance(batch, dict) or len(json.dumps(batch)) > 165000: + raise ValueError("Invalid archive batch") + items, last = batch.get("items"), batch.get("after") + if not isinstance(items, list) or len(items) > 4 or type(last) is not int or last < 0: + raise ValueError("Invalid archive batch") + for row in items: + seq = row["sequence"] + if type(seq) is not int or seq <= last: + raise ValueError("Invalid archive sequence") + self.add(node, row["backup"]) + last = seq + if batch.get("next") != last: + raise ValueError("Invalid archive acknowledgement") + return last diff --git a/src/k1link/fleet/registry.py b/src/k1link/fleet/registry.py index ded58d9..f2ee526 100644 --- a/src/k1link/fleet/registry.py +++ b/src/k1link/fleet/registry.py @@ -1,6 +1,7 @@ from __future__ import annotations import json +import logging import secrets import sqlite3 import threading @@ -36,6 +37,8 @@ class FleetRegistry: from .monitor import MonitorReceiver self.monitor = MonitorReceiver(root) + from .rover_control import RoverControl + self.rover_control = RoverControl() self.trust = CoreTrust(root) path = root / "fleet.sqlite3" if path.is_symlink(): @@ -50,6 +53,16 @@ class FleetRegistry: "node_id TEXT UNIQUE NOT NULL, body TEXT NOT NULL)" ) self.db.commit() + from k1link.device_plugins.vesc.archive import Archive + + self.vesc_archive = Archive(root / "vesc-configurations") + # Preserve pre-archive releases' completed backups before the ordinary + # short-lived operation receipts are pruned. + for row in self.rows(): + for receipt in row.get("sensor_commands", {}).values(): + if receipt.get("state") == "complete" and receipt.get("command", {}).get("action_id") == "vesc.config.backup": + with suppress(ValueError, KeyError, TypeError): + self.vesc_archive.add(row["node_id"], receipt["result"]) self.previews: dict[str, dict] = {} self.listeners: dict[str, object] = {} self.stop = threading.Event() @@ -359,7 +372,11 @@ class FleetRegistry: if not isinstance(key, Ed25519PublicKey): return 403, {"error": "Unauthorized Node"} node_id = public_id("node_", key) + entered = time.monotonic() with self.lock: + waited = time.monotonic() - entered + if waited > .025: + logging.getLogger(__name__).warning("fleet timing path=%s lock_ms=%.1f", path, waited*1000) row = next((item for item in self.rows() if item["node_id"] == node_id), None) if ( row is None @@ -390,7 +407,7 @@ class FleetRegistry: ) self.save(row) return 200, {"ok": True} - if path != "/v1/node/heartbeat": + if path not in ("/v1/node/heartbeat", "/v1/node/rover", "/v1/node/rover-stream"): return 404, {"error": "Unknown operation"} # Endpoint revisions prevent an old in-flight heartbeat or lost ack # from reversing a migration. Use the actual listener, not a claimed IP. @@ -411,11 +428,33 @@ class FleetRegistry: row["core_address"] = address row["binding"]["endpoint"] = value["core_endpoint"] row["binding"]["endpoint_revision"] = revision + if path in ("/v1/node/rover", "/v1/node/rover-stream"): + if row["enrollment"] != "paired": + return 410, {"error": "Pairing incomplete"} + if path.endswith("-stream"): + relay = value.get("relay_id") + if not isinstance(relay, str) or len(relay) != 32: + return 400, {"error": "Invalid relay"} + return 200, self.rover_control.stream(node_id, relay) + return 200, self.rover_control.exchange(node_id, value) binding = ExecutionBinding.model_validate(value["execution_binding"]) if binding.node_id != node_id or binding.platform.value != "linux": return 400, {"error": "Invalid Node inventory"} sensor_state = sensors.validate_inventory(value, node_id) sensor_response = sensors.heartbeat(row, value) + archive_ack = None + archive_started = time.monotonic() + try: + if "vesc_configurations" in value: + archive_ack = self.vesc_archive.receive(node_id, value["vesc_configurations"]) + for receipt in row.get("sensor_commands", {}).values(): + if receipt.get("state") == "complete" and receipt.get("command", {}).get("action_id") == "vesc.config.backup": + self.vesc_archive.add(node_id, receipt["result"]) + except (ValueError, KeyError, TypeError, sqlite3.Error, OSError): + # No archive acknowledgement until durable storage succeeds. + # Archive failure must never delay a control/stop response. + archive_ack = None + archive_elapsed = time.monotonic() - archive_started enrollment_response = self.device_enrollment.heartbeat(row, value) host = value.get("host") if ( @@ -441,7 +480,12 @@ class FleetRegistry: "until": time.time() + 3600, } row["binding"]["client_pem"] = self.trust.leaf(node_id, key) + save_started = time.monotonic() self.save(row) + save_elapsed = time.monotonic() - save_started + if archive_elapsed > .025 or save_elapsed > .025: + logging.getLogger(__name__).warning( + "fleet heartbeat timing archive_ms=%.1f save_ms=%.1f", archive_elapsed*1000, save_elapsed*1000) monitor_ack = None try: monitor_ack = self.monitor.submit(node_id, value.get("monitor")) @@ -449,6 +493,7 @@ class FleetRegistry: # Telemetry persistence failure must not block device control. pass return 200, { + "vesc_configurations_ack": archive_ack, "monitor_ack": monitor_ack, "ok": True, "client_pem": row["binding"]["client_pem"], diff --git a/src/k1link/fleet/sensors.py b/src/k1link/fleet/sensors.py index b6a4e7e..0103907 100644 --- a/src/k1link/fleet/sensors.py +++ b/src/k1link/fleet/sensors.py @@ -30,6 +30,8 @@ ACTIONS = { "files.list", "recovery.configure", "power.wake", + "vesc.link.check", "vesc.telemetry.read", "vesc.limits.read", + "vesc.config.backup", "vesc.input.read", "vesc.can.read", "vesc.drive.assign", "vesc.drive.layout", "vesc.drive.unassign", "vesc.motor.pulse", "vesc.motor.run", "vesc.drive.run", "vesc.hall.measure", "vesc.foc.calibrate", "vesc.motor.stop", "vesc.control.release", } MAX_INVENTORY_ITEMS = 500 MAX_SENSOR_STATE_BYTES = 3 * 1024 * 1024 diff --git a/src/k1link/fleet/transport.py b/src/k1link/fleet/transport.py index ad51aa0..dd2b00d 100644 --- a/src/k1link/fleet/transport.py +++ b/src/k1link/fleet/transport.py @@ -47,6 +47,9 @@ class NodeChannelServer(ThreadingHTTPServer): class NodeChannelHandler(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" + # Header and JSON writes must not wait for a delayed ACK on the paired + # command channel. StreamRequestHandler applies TCP_NODELAY to the socket. + disable_nagle_algorithm = True def log_message(self, *_args): pass @@ -74,6 +77,31 @@ class NodeChannelHandler(BaseHTTPRequestHandler): except (ValueError, KeyError, TypeError): self.close_connection = True status, data = 400, {"error": "Invalid request"} + if self.path == "/v1/node/rover-stream" and status == 200: + self.close_connection = True + self.send_response(200) + self.send_header("Content-Type", "application/x-ndjson") + self.send_header("Cache-Control", "no-store") + self.send_header("Connection", "close") + self.end_headers() + try: + while not self.server.registry.stop.is_set(): + self.wfile.write(json.dumps(data, allow_nan=False).encode()+b"\n") + if not data.get("watch"): + break + # Every frame rechecks the same certificate and binding. + # No queued intent and no lease renewal from a keepalive. + self.server.registry.rover_control.wait_for_intent( + value["node_id"], value["relay_id"], data.get("command")) + status, data = self.server.registry.receive( + self.connection.getpeercert(binary_form=True), self.path, + value, address=self.server.address, + ) + if status != 200: + break + except (OSError, ValueError): + pass + return encoded = json.dumps(data).encode() self.send_response(status) self.send_header("Content-Type", "application/json") diff --git a/src/k1link/web/app.py b/src/k1link/web/app.py index 0fbc3ed..5008711 100644 --- a/src/k1link/web/app.py +++ b/src/k1link/web/app.py @@ -112,6 +112,7 @@ from k1link.web.advanced_laboratory_api import build_advanced_laboratory_router from k1link.web.artifact_health_api import build_artifact_health_router from k1link.web.compute_contour_api import build_compute_contour_router from k1link.web.fleet_api import router as fleet_router +from k1link.web.rover_api import router as rover_router from k1link.web.device_plugin_composition import load_installed_device_plugins from k1link.web.e30_engineering_api import build_e30_engineering_router from k1link.web.e30_human_review_api import build_e30_human_review_router @@ -1003,6 +1004,7 @@ app.add_middleware(ResponseCompressionMiddleware, minimum_size=1_024, compressle app.include_router(fleet_router) +app.include_router(rover_router) @app.exception_handler(RequestValidationError) diff --git a/src/k1link/web/fleet_api.py b/src/k1link/web/fleet_api.py index 59c498e..6c353e2 100644 --- a/src/k1link/web/fleet_api.py +++ b/src/k1link/web/fleet_api.py @@ -6,12 +6,12 @@ import asyncio import ipaddress import json from contextlib import suppress -from typing import Annotated +from typing import Annotated, Literal from urllib.parse import urlsplit from fastapi import APIRouter, Depends, HTTPException, Request, Response from fastapi.responses import StreamingResponse -from pydantic import BaseModel, ConfigDict, Field +from pydantic import BaseModel, ConfigDict, Field, StrictBool from k1link.fleet.registry import FleetRegistry from k1link.fleet.trust import PairingError @@ -51,6 +51,42 @@ class AddRequest(BaseModel): router = APIRouter(prefix="/api/v1/fleet", tags=["fleet"]) +class BoardLayoutChange(BaseModel): + model_config = ConfigDict(extra="forbid") + section: Literal["computer", "settings", "devices"] + open: StrictBool + + +@router.get("/{vehicle_id}/board-layout") +def board_layout_read(vehicle_id: str, response: Response, + fleet: Annotated[FleetRegistry, Depends(local_operator)]): + from k1link.fleet.board_layout import read + response.headers["Cache-Control"] = "no-store" + try: + with fleet.lock: + fleet.find(vehicle_id) + return read(fleet.root, vehicle_id) + except PairingError as error: + raise HTTPException(404, str(error)) from None + except (OSError, ValueError): + raise HTTPException(500, "Не удалось прочитать раскладку аппарата.") from None + + +@router.patch("/{vehicle_id}/board-layout") +def board_layout_patch(vehicle_id: str, body: BoardLayoutChange, response: Response, + fleet: Annotated[FleetRegistry, Depends(local_operator)]): + from k1link.fleet.board_layout import update + response.headers["Cache-Control"] = "no-store" + try: + with fleet.lock: + fleet.find(vehicle_id) + return update(fleet.root, vehicle_id, body.section, body.open) + except PairingError as error: + raise HTTPException(404, str(error)) from None + except (OSError, ValueError): + raise HTTPException(500, "Не удалось сохранить раскладку аппарата.") from None + + @router.get("/{vehicle_id}/monitor") def board_monitor(vehicle_id: str, response: Response, fleet: Annotated[FleetRegistry, Depends(local_operator)], @@ -141,6 +177,30 @@ def sensor_command( raise HTTPException(409, str(error)) from None +@router.get("/{vehicle_id}/devices/{device_id}/configurations") +def vesc_configurations(vehicle_id: str, device_id: str, response: Response, + fleet: Annotated[FleetRegistry, Depends(local_operator)], before: int = 0): + response.headers["Cache-Control"] = "no-store" + try: + with fleet.lock: + node = fleet.find(vehicle_id)["node_id"] + return fleet.vesc_archive.listing(node, device_id, before) + except (PairingError, ValueError): + raise HTTPException(404, "История конфигураций недоступна.") from None + + +@router.get("/{vehicle_id}/devices/{device_id}/configurations/{version_id}") +def vesc_configuration(vehicle_id: str, device_id: str, version_id: str, response: Response, + fleet: Annotated[FleetRegistry, Depends(local_operator)]): + response.headers["Cache-Control"] = "no-store" + try: + with fleet.lock: + node = fleet.find(vehicle_id)["node_id"] + return fleet.vesc_archive.read(node, device_id, version_id) + except (PairingError, ValueError): + raise HTTPException(404, "Версия конфигурации не найдена.") from None + + @router.get("/{vehicle_id}/devices/operations/{operation_id}") def sensor_operation( vehicle_id: str, operation_id: str, fleet: Annotated[FleetRegistry, Depends(local_operator)] diff --git a/tests/fleet/test_pairing.py b/tests/fleet/test_pairing.py index 5e9ea29..3f833d1 100644 --- a/tests/fleet/test_pairing.py +++ b/tests/fleet/test_pairing.py @@ -84,6 +84,25 @@ def cert(row): serialization.Encoding.DER ) +def test_rover_stream_requires_current_pairing_and_binding(setup): + fleet, _, _, _ = setup + public, _ = create(setup) + fleet.advance(public["id"]) + row = fleet.find(public["id"]) + body = {"schema": SCHEMA, "node_id": row["node_id"], + "binding_id": row["binding"]["binding_id"], "relay_id": "a"*32} + certificate = cert(row) + status, result = fleet.receive(certificate, "/v1/node/rover-stream", body) + assert status == 200 + assert result['command'] is None + assert result['control_clock']['instance'] == fleet.rover_control.clock_id + status, _ = fleet.receive(certificate, "/v1/node/rover-stream", {**body, "binding_id": "other"}) + assert status == 410 + row['enrollment'] = 'revoked' + fleet.save(row) + status, _ = fleet.receive(certificate, "/v1/node/rover-stream", body) + assert status == 410 + def test_migrated_heartbeat_preserves_identity_and_old_reply_cannot_reverse(setup): fleet, _, _, _ = setup diff --git a/tests/fleet/test_vesc_archive.py b/tests/fleet/test_vesc_archive.py new file mode 100644 index 0000000..0463b61 --- /dev/null +++ b/tests/fleet/test_vesc_archive.py @@ -0,0 +1,74 @@ +import base64 +import copy +import hashlib +from datetime import UTC, datetime +from uuid import uuid4 + +import pytest + +from k1link.device_plugins.vesc.archive import Archive + + +def backup(): + uid = "01" * 12 + configs = {} + for name, command in (("motor", 14), ("application", 17)): + raw = bytes([command]) + b"test-synthetic-config" + configs[name] = {"encoding": "base64", "payload": base64.b64encode(raw).decode(), + "bytes": len(raw), "sha256": hashlib.sha256(raw).hexdigest(), + "signature_hex": raw[1:5].hex()} + return {"schema": "missioncore.vesc.config-backup/v1", "operation_id": "op_" + uuid4().hex, + "device_id": "vesc_" + hashlib.sha256(("uuid:" + uid).encode()).hexdigest()[:32], + "identity": {"uuid": uid, "version": "6.06"}, "configs": configs, + "observed_at": datetime.now(UTC).isoformat()} + + +def test_immutable_versions_survive_restart_and_do_not_cross_node_scope(tmp_path): + archive = Archive(tmp_path / "archive") + value = backup() + archive.add("node-a", value) + archive.add("node-a", copy.deepcopy(value)) + reopened = Archive(tmp_path / "archive") + assert len(reopened.listing("node-a", value["device_id"])["items"]) == 1 + assert reopened.read("node-a", value["device_id"], value["operation_id"]) == value + assert reopened.listing("node-b", value["device_id"])["items"] == [] + with pytest.raises(ValueError): + reopened.read("node-b", value["device_id"], value["operation_id"]) + changed = copy.deepcopy(value) + changed["observed_at"] = datetime.now(UTC).isoformat() + with pytest.raises(ValueError, match="immutable"): + reopened.add("node-a", changed) + + +def test_corrupt_or_misattributed_payload_is_never_archived(tmp_path): + archive = Archive(tmp_path / "archive") + value = backup() + value["configs"]["motor"]["sha256"] = "0" * 64 + with pytest.raises(ValueError, match="integrity"): + archive.add("a", value) + value = backup() + value["device_id"] = "vesc_" + "0" * 32 + with pytest.raises(ValueError, match="mismatch"): + archive.add("a", value) + assert archive.export("a", 0)["items"] == [] + + +def test_bounded_replication_replays_without_losing_versions_and_paginates(tmp_path): + board, core = Archive(tmp_path / "board"), Archive(tmp_path / "core") + values = [backup() for _ in range(53)] + for value in values: + board.add("local", value) + after = 0 + while True: + batch = board.export("local", after) + assert len(batch["items"]) <= 4 + assert core.receive("paired-node", batch) == batch["next"] + assert core.receive("paired-node", batch) == batch["next"] + if batch["next"] == after: + break + after = batch["next"] + page = core.listing("paired-node", values[0]["device_id"]) + assert len(page["items"]) == 50 and page["next"] + older = core.listing("paired-node", values[0]["device_id"], int(page["next"])) + assert len(older["items"]) == 3 and older["next"] is None + assert len({item["id"] for item in page["items"] + older["items"]}) == 53 From 53818230f900d48e17cefbfcfed9246d9f57c8c6 Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Fri, 25 Sep 2026 16:37:56 +0300 Subject: [PATCH 3/7] feat(node): ship managed environment startup and USB recovery --- AGENTS.md | 18 + .../internal/node/environment-profile.json | 4 +- apps/node-agent/internal/node/presentation.go | 1 + .../50-mission-core-device-prepare.rules | 2 +- apps/node-agent/packaging/build.py | 3 +- apps/node-agent/packaging/build_deb.py | 13 +- .../packaging/build_linux_source.py | 9 +- apps/node-agent/packaging/desktop_startup.py | 30 ++ .../packaging/environment_helper.py | 28 +- .../packaging/install-owner-release | 2 +- .../packaging/install_owner_release.py | 2 +- apps/node-agent/packaging/linux_build_job.py | 4 + .../mission-core-node-autostart.desktop | 10 + .../mission-core-node-usb-startup.service | 35 ++ apps/node-agent/packaging/postinst | 4 + apps/node-agent/packaging/preinst | 13 + apps/node-agent/packaging/prerm | 43 +++ .../packaging/test_desktop_startup.py | 25 ++ .../packaging/test_environment_helper.py | 18 + .../packaging/test_usb_startup_recovery.py | 220 ++++++++++++ apps/node-agent/packaging/usb-startup.json | 1 + .../packaging/usb_startup_recovery.py | 332 ++++++++++++++++++ apps/node-agent/ui/src/main.tsx | 2 +- .../packaging/owner_release_entry.py | 45 ++- .../packaging/test_owner_release_entry.py | 57 +++ 25 files changed, 900 insertions(+), 21 deletions(-) create mode 100644 apps/node-agent/packaging/desktop_startup.py create mode 100644 apps/node-agent/packaging/mission-core-node-autostart.desktop create mode 100644 apps/node-agent/packaging/mission-core-node-usb-startup.service create mode 100644 apps/node-agent/packaging/test_desktop_startup.py create mode 100644 apps/node-agent/packaging/test_usb_startup_recovery.py create mode 100644 apps/node-agent/packaging/usb-startup.json create mode 100644 apps/node-agent/packaging/usb_startup_recovery.py create mode 100644 plugins/insta360-x4/packaging/test_owner_release_entry.py diff --git a/AGENTS.md b/AGENTS.md index eb97e6d..8d8efec 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -62,6 +62,24 @@ and the boundary between Mission Core and vendor-specific integration code. - Synthetic or explicitly redacted fixtures may be committed under `tests/fixtures/`. +## Onboard environment ownership — owner requirement, 2026-09-24 + +- Every onboard OS change belongs to the shipped, versioned installer or the + application's environment/device preparation workflow from the first test. + The operator installs the build and configures it in the application; never + require hand-written service files, USB rules, permission fixes or commands. +- This applies to all Node features, including GUI/service autostart and USB + recovery, not just individual camera drivers. Read-only SSH inspection and + bounded artifact-owned build staging remain allowed. +- Detect the distribution, architecture and required capabilities. Maintain + explicit supported environment profiles; do not claim arbitrary Linux + compatibility from a qualified Ubuntu build. Preserve foreign configuration, + report unsupported features, make preparation repeatable, and ship rollback. +- Do not add USB administration controls or port resets to inventory refresh. + Automatic startup recovery may retry terminal enumeration failures only; + preserve enumerated devices and active companion ports. Device identity and + assignments must survive changes of USB port and tty number. + ## Insta360 and clean-host installation — owner requirement, 2026-09-08 - The current X4 starting point is USB enumeration only. SDK installation, diff --git a/apps/node-agent/internal/node/environment-profile.json b/apps/node-agent/internal/node/environment-profile.json index 0d0a983..21b8b39 100644 --- a/apps/node-agent/internal/node/environment-profile.json +++ b/apps/node-agent/internal/node/environment-profile.json @@ -1,10 +1,12 @@ { "schema": "missioncore.node.environment/v1", - "revision": "ubuntu-24.04-amd64/2", + "revision": "ubuntu-24.04-amd64/3", "steps": [ {"id":"platform","label":"Проверка системы","description":"Операционная система и архитектура БК","requires":[]}, {"id":"packages","label":"Установка системных пакетов","description":"OpenSSH Server и зависимости окружения","requires":["platform"]}, {"id":"node-service","label":"Настройка службы БК","description":"Автозапуск и доступ к системной инвентаризации","requires":["platform"]}, + {"id":"desktop-autostart","label":"Автозапуск приложения","description":"Открытие окна при входе в рабочий стол","requires":["node-service"]}, + {"id":"usb-startup","label":"Обнаружение устройств при загрузке","description":"Автоматическое восстановление незавершённого подключения USB","requires":["platform"]}, {"id":"network-inventory","label":"Получение сетевых настроек","description":"Интерфейсы и назначенные адреса","requires":["node-service"]}, {"id":"usb-inventory","label":"Получение USB-устройств","description":"Оборудование, обнаруженное операционной системой","requires":["node-service"]}, {"id":"ssh-service","label":"Настройка SSH","description":"Запуск сервера и подключение реестра доверенных ключей","requires":["packages","node-service"]}, diff --git a/apps/node-agent/internal/node/presentation.go b/apps/node-agent/internal/node/presentation.go index d2741d8..2cce8a9 100644 --- a/apps/node-agent/internal/node/presentation.go +++ b/apps/node-agent/internal/node/presentation.go @@ -182,6 +182,7 @@ func (p *PresentationStore) save(value PresentationSettings) error { } func (s *Server) presentationRoutes(mux *http.ServeMux) { + s.boardLayoutRoutes(mux) p := s.Presentation mux.HandleFunc("GET /api/presentation/settings", func(w http.ResponseWriter, r *http.Request) { if !s.authorized(w, r) { diff --git a/apps/node-agent/packaging/50-mission-core-device-prepare.rules b/apps/node-agent/packaging/50-mission-core-device-prepare.rules index 59237f8..367c73e 100644 --- a/apps/node-agent/packaging/50-mission-core-device-prepare.rules +++ b/apps/node-agent/packaging/50-mission-core-device-prepare.rules @@ -1,7 +1,7 @@ // An authenticated Node action may start only this fixed model job. polkit.addRule(function(action, subject) { var unit = action.lookup("unit"); - if (subject.user === "mission-core-node" && action.id === "org.freedesktop.systemd1.manage-units" && (unit === "mission-core-node-realsense-prepare.service" || unit === "mission-core-node-insta360-x4-profile.service") && action.lookup("verb") === "start") { + if (subject.user === "mission-core-node" && action.id === "org.freedesktop.systemd1.manage-units" && (unit === "mission-core-node-vesc-prepare.service" || unit === "mission-core-node-realsense-prepare.service" || unit === "mission-core-node-insta360-x4-profile.service") && action.lookup("verb") === "start") { return polkit.Result.YES; } }); diff --git a/apps/node-agent/packaging/build.py b/apps/node-agent/packaging/build.py index 1963f3e..a6c2610 100644 --- a/apps/node-agent/packaging/build.py +++ b/apps/node-agent/packaging/build.py @@ -11,7 +11,7 @@ import sys from build_deb import build, VERSION, BRAND_SHA256 ROOT = Path(__file__).resolve().parents[1] -DG_COMMIT = "8c53f73ee521561a1cc7944a7f7cf113702f40b5" +DG_COMMIT = "8dd9190573d6616024ef01b9b34bf90b72960f44" def guideline_sources(): @@ -36,6 +36,7 @@ def provenance(): "design_guideline_files": guideline_sources(), "shared_sensor_ui_files": {str(p.relative_to(ROOT.parents[1])): hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted((ROOT.parents[1] / "packages/sensor-ui/src").rglob("*")) if p.is_file()}, "shared_spatial_ui_files": {str(p.relative_to(ROOT.parents[1])): hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted((ROOT.parents[1] / "packages/spatial-ui/src").rglob("*")) if p.is_file()}, + "vesc_plugin_files": {str(p.relative_to(ROOT.parents[1])): hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted((ROOT.parents[1] / "plugins/vesc").rglob("*")) if p.is_file() and not any(x in p.relative_to(ROOT.parents[1]).parts for x in ("__pycache__", "build"))}, "k1_frontend_files": {str(p.relative_to(ROOT.parents[1])): hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted((ROOT.parents[1] / "plugins/xgrids-k1/frontend/src").rglob("*")) if p.is_file()}, "toolchain": json.loads((ROOT / "toolchain.json").read_text()), "files": files} diff --git a/apps/node-agent/packaging/build_deb.py b/apps/node-agent/packaging/build_deb.py index 54cccfc..5f53a88 100644 --- a/apps/node-agent/packaging/build_deb.py +++ b/apps/node-agent/packaging/build_deb.py @@ -11,8 +11,8 @@ import sys ROOT = Path(__file__).resolve().parents[1] -BINARY_VERSION = "0.8.21" -VERSION = "0.8.21-3" +BINARY_VERSION = "0.8.45" +VERSION = "0.8.45-1" sys.path.insert(0, str(ROOT.parents[1] / "scripts/packaging")) from debian import package @@ -44,7 +44,7 @@ Architecture: amd64 Maintainer: NODE.DC local build Section: admin Priority: optional -Depends: adduser, systemd (>= 255), python3 (>= 3.12), python3 (<< 3.13), python3-gi, gir1.2-gtk-3.0, gir1.2-webkit2-4.1, pkexec, polkitd, ca-certificates, hicolor-icon-theme, network-manager, iproute2, python3-psycopg2, postgresql-16 (>= 16.15), timescaledb-2-oss-postgresql-16 (= 2.29.2~ubuntu24.04-1615), udev, libc6 (>= 2.35), libstdc++6 (>= 12), libgcc-s1, zlib1g +Depends: adduser, systemd (>= 255), python3 (>= 3.12), python3 (<< 3.13), python3-gi, gir1.2-gtk-3.0, gir1.2-webkit2-4.1, pkexec, polkitd, ca-certificates, hicolor-icon-theme, network-manager, iproute2, python3-psycopg2, postgresql-16 (>= 16.15), timescaledb-2-oss-postgresql-16 (= 2.29.2~ubuntu24.04-1615), udev, usbutils, libc6 (>= 2.39), libstdc++6 (>= 12), libgcc-s1, zlib1g Description: Mission Core onboard computer configuration Local graphical setup, host inventory, SSH access and persistent node identity. """.encode() @@ -66,6 +66,11 @@ Description: Mission Core onboard computer configuration ("tailscale-release.json", "usr/share/mission-core-node/tailscale-release.json", 0o644), ("configure-system", "usr/lib/mission-core-node/configure-system", 0o755), ("environment_helper.py", "usr/lib/mission-core-node/environment_helper.py", 0o644), + ("desktop_startup.py", "usr/lib/mission-core-node/desktop_startup.py", 0o644), + ("mission-core-node-autostart.desktop", "usr/share/mission-core-node/mission-core-node-autostart.desktop", 0o644), + ("usb-startup.json", "usr/share/mission-core-node/usb-startup.json", 0o644), + ("usb_startup_recovery.py", "usr/lib/mission-core-node/usb_startup_recovery.py", 0o644), + ("mission-core-node-usb-startup.service", "usr/lib/systemd/system/mission-core-node-usb-startup.service", 0o644), ("mission-core-node-environment.service", "usr/lib/systemd/system/mission-core-node-environment.service", 0o644), ("60-environment.conf", "usr/share/mission-core-node/60-environment.conf", 0o644), ("setup-monitor", "usr/lib/mission-core-node/setup-monitor", 0o755), @@ -111,6 +116,8 @@ Description: Mission Core onboard computer configuration files.append(("usr/lib/mission-core-node/sdk/missioncore_plugin_sdk/" + str(path.relative_to(sdk)), path.read_bytes(), 0o644)) if (ROOT / "build/provenance.json").exists(): files.append(("usr/share/doc/mission-core-node/provenance.json", (ROOT / "build/provenance.json").read_bytes(), 0o644)) + import runpy + files.extend(runpy.run_path(str(ROOT.parents[1] / "plugins/vesc/packaging/payload.py"))["payload"]()) archive = package(controls, files) destination.parent.mkdir(parents=True, exist_ok=True) destination.write_bytes(archive) diff --git a/apps/node-agent/packaging/build_linux_source.py b/apps/node-agent/packaging/build_linux_source.py index 4c34630..8eb9c0d 100644 --- a/apps/node-agent/packaging/build_linux_source.py +++ b/apps/node-agent/packaging/build_linux_source.py @@ -11,7 +11,7 @@ from pathlib import Path NODE = Path(__file__).resolve().parents[1] REPO = NODE.parents[1] DG = REPO.parent / "NODEDC_DESIGN_GUIDELINE" -DG_COMMIT = "8c53f73ee521561a1cc7944a7f7cf113702f40b5" +DG_COMMIT = "8dd9190573d6616024ef01b9b34bf90b72960f44" def files(root): @@ -73,6 +73,13 @@ def build(qualified, node_only=False): # board, runtime path override or operator compiler dependency is needed. virtual = str(REPO.name + "/apps/node-agent/build/model-packages/" + package_name) entries[virtual] = qualified + native_root = REPO / "plugins/vesc" + native = json.loads((native_root / "packaging/native-runtime.json").read_text()) + native_path = native_root / "build/native-runtime" / native["file"] + native_bytes = native_path.read_bytes() + if len(native_bytes) != native["bytes"] or hashlib.sha256(native_bytes).hexdigest() != native["sha256"]: + raise ValueError("Qualified VESC Tool runtime changed") + entries[REPO.name + "/plugins/vesc/build/native-runtime/" + native["file"]] = native_path metadata = {} for name, path in entries.items(): data = path.read_bytes() diff --git a/apps/node-agent/packaging/desktop_startup.py b/apps/node-agent/packaging/desktop_startup.py new file mode 100644 index 0000000..5913038 --- /dev/null +++ b/apps/node-agent/packaging/desktop_startup.py @@ -0,0 +1,30 @@ +"""Unprivileged XDG startup: wait for Node before opening its ordinary UI.""" +import http.client +import os +import time + + +def wait_for_service(now=time.monotonic, sleep=time.sleep, connection=http.client.HTTPConnection): + deadline = now() + 180 + while now() < deadline: + client = connection('127.0.0.1', 8780, timeout=2) + try: + client.request('GET', '/') + response = client.getresponse() + if response.status == 200: + return True + except (OSError, http.client.HTTPException): + pass + finally: + client.close() + sleep(1) + return False + + +if __name__ == '__main__': + if os.geteuid() == 0: + raise SystemExit('Run in the normal graphical user session') + wait_for_service() + # Gtk.Application retains one window per desktop session. Its ordinary + # polkit authorization and error handling are unchanged. + os.execv('/usr/bin/mission-core-node', ['/usr/bin/mission-core-node']) diff --git a/apps/node-agent/packaging/environment_helper.py b/apps/node-agent/packaging/environment_helper.py index 5c34852..f17f2c6 100644 --- a/apps/node-agent/packaging/environment_helper.py +++ b/apps/node-agent/packaging/environment_helper.py @@ -219,7 +219,33 @@ def tailscale_install(): return "Tailscale установлен; системная служба запущена. Вход проверяется отдельно." -OPERATIONS = {"platform": platform, "packages": packages, "node-service": node_service, "network-inventory": network_inventory, "usb-inventory": usb_inventory, "ssh-service": ssh_service, "tailscale-install": tailscale_install} +def desktop_autostart(): + owned_config(Path('/usr/share/mission-core-node/mission-core-node-autostart.desktop'), + Path('/etc/xdg/autostart/org.nodedc.MissionCoreNode.desktop')) + return "Окно приложения открывается при входе в рабочий стол. Служба БК работает и без входа." + + +def usb_startup(): + # Enabling the next boot is distinct from executing recovery now. This + # workflow never resets devices in a running operator session. + owned_config(Path('/usr/share/mission-core-node/usb-startup.json'), + Path('/etc/mission-core-node/usb-startup.json')) + command(['/usr/bin/systemctl', 'daemon-reload']) + command(['/usr/bin/systemctl', 'enable', 'mission-core-node-usb-startup.service']) + command(['/usr/bin/systemctl', 'is-enabled', 'mission-core-node-usb-startup.service']) + report = json.loads(command(['/usr/bin/python3', '-I', '-B', '/usr/lib/mission-core-node/usb_startup_recovery.py', '--inspect'], timeout=75)) + if report.get('state') != 'inspected': + raise SetupError("Не удалось проверить поддержку восстановления USB. Повторите настройку.") + supported = sum(h.get('individual_power') is True for h in report.get('hubs', [])) + if not supported: + return "Проверка при загрузке включена. Поддержка отдельного переключения USB-портов не подтверждена; они будут пропущены." + return "Восстановление при загрузке включено для поддерживаемых USB-портов. Обнаруженные устройства сохраняют подключение." + + +OPERATIONS = {"platform": platform, "packages": packages, "node-service": node_service, + "desktop-autostart": desktop_autostart, "usb-startup": usb_startup, + "network-inventory": network_inventory, "usb-inventory": usb_inventory, + "ssh-service": ssh_service, "tailscale-install": tailscale_install} def run_steps(profile, operations, save): diff --git a/apps/node-agent/packaging/install-owner-release b/apps/node-agent/packaging/install-owner-release index 31a45e6..d9cafde 100644 --- a/apps/node-agent/packaging/install-owner-release +++ b/apps/node-agent/packaging/install-owner-release @@ -5,7 +5,7 @@ mc_node_release_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) if [ ! -t 0 ]; then exec /usr/bin/gnome-terminal --wait --title="Mission Core Node" -- "$mc_node_release_dir/install" fi -printf '%s\n' 'Mission Core Node' 'Обновление приложения и встроенных пакетов камер на этом Ubuntu-компьютере.' 'Подготовка X4 выполняется затем из списка устройств в Node или Core.' 'Пароль администратора вводится только в этом локальном окне Ubuntu.' +printf '%s\n' 'Mission Core Node' 'Обновление приложения и встроенных драйверов на этом Ubuntu-компьютере.' 'Подготовка VESC и X4 выполняется затем из списка устройств в Node или Core.' 'Пароль администратора вводится только в этом локальном окне Ubuntu.' set +e /usr/bin/sudo /usr/bin/python3 -I "$mc_node_release_dir/install_release.py" 2>&1 | /usr/bin/tee -a "$mc_node_release_dir/install-output.log" mc_node_install_result=${PIPESTATUS[0]} diff --git a/apps/node-agent/packaging/install_owner_release.py b/apps/node-agent/packaging/install_owner_release.py index 386ad8b..7cf86b7 100644 --- a/apps/node-agent/packaging/install_owner_release.py +++ b/apps/node-agent/packaging/install_owner_release.py @@ -351,7 +351,7 @@ def main(): if report["state"] != "complete": raise RuntimeError(report["error"]) print( - "Mission Core Node обновлён. X4 можно подготовить из списка устройств в Node или Core.", + "Mission Core Node обновлён. VESC и X4 можно подготовить из списка устройств в Node или Core.", flush=True, ) diff --git a/apps/node-agent/packaging/linux_build_job.py b/apps/node-agent/packaging/linux_build_job.py index 97770b8..b59c107 100644 --- a/apps/node-agent/packaging/linux_build_job.py +++ b/apps/node-agent/packaging/linux_build_job.py @@ -243,6 +243,10 @@ def main(): sys.path.insert(0, str(node / "packaging")) from build_deb import BINARY_VERSION, VERSION, build + run("node-environment-tests", ["/usr/bin/python3", "-m", "unittest", "test_environment_helper", "test_usb_startup_recovery", "test_desktop_startup", "-v"], cwd=node / "packaging") + run("owner-release-staging-tests", ["/usr/bin/python3", "plugins/insta360-x4/packaging/test_owner_release_entry.py"], cwd=repo) + run("node-usb-unit-validation", ["/usr/bin/systemd-analyze", "verify", str(node / "packaging/mission-core-node-usb-startup.service")], cwd=node) + run("vesc-reader-tests", ["/usr/bin/python3", "-m", "unittest", "discover", "-s", "plugins/vesc/tests", "-v"], cwd=repo) binary = node / "build/node-agent-linux-amd64" run( "node-binary", diff --git a/apps/node-agent/packaging/mission-core-node-autostart.desktop b/apps/node-agent/packaging/mission-core-node-autostart.desktop new file mode 100644 index 0000000..ce1f4d7 --- /dev/null +++ b/apps/node-agent/packaging/mission-core-node-autostart.desktop @@ -0,0 +1,10 @@ +[Desktop Entry] +Version=1.0 +Type=Application +Name=Mission Core Node +Comment=Настройка и диагностика бортового компьютера +TryExec=/usr/bin/mission-core-node +Exec=/usr/bin/python3 -I -B /usr/lib/mission-core-node/desktop_startup.py +Icon=org.nodedc.MissionCoreNode +Terminal=false +StartupNotify=false diff --git a/apps/node-agent/packaging/mission-core-node-usb-startup.service b/apps/node-agent/packaging/mission-core-node-usb-startup.service new file mode 100644 index 0000000..a2700b4 --- /dev/null +++ b/apps/node-agent/packaging/mission-core-node-usb-startup.service @@ -0,0 +1,35 @@ +[Unit] +Description=Mission Core bounded USB startup recovery +Wants=systemd-udev-settle.service +After=systemd-udev-settle.service +Before=mission-core-node.service mission-core-vesc.service +ConditionPathExists=/etc/mission-core-node/usb-startup.json + +[Service] +Type=oneshot +RemainAfterExit=yes +ExecStart=/usr/bin/python3 -I -B /usr/lib/mission-core-node/usb_startup_recovery.py +ExecStopPost=/usr/bin/python3 -I -B /usr/lib/mission-core-node/usb_startup_recovery.py --restore +TimeoutStartSec=130 +TimeoutStopSec=15 +RuntimeDirectory=mission-core-usb-startup +RuntimeDirectoryMode=0755 +RuntimeDirectoryPreserve=yes +UMask=0077 +NoNewPrivileges=yes +PrivateNetwork=yes +ProtectSystem=strict +ProtectHome=yes +ProtectKernelModules=yes +ProtectControlGroups=yes +RestrictSUIDSGID=yes +RestrictAddressFamilies=AF_UNIX AF_NETLINK +CapabilityBoundingSet= +ReadWritePaths=/sys/devices /run/mission-core-usb-startup +DevicePolicy=closed +DeviceAllow=char-usb_device rw +TasksMax=16 +MemoryMax=64M + +[Install] +WantedBy=multi-user.target diff --git a/apps/node-agent/packaging/postinst b/apps/node-agent/packaging/postinst index 0d8a505..c0975e9 100644 --- a/apps/node-agent/packaging/postinst +++ b/apps/node-agent/packaging/postinst @@ -2,6 +2,7 @@ set -eu case "$1" in configure) + /usr/bin/python3 -I /usr/lib/mission-core-vesc/clear_runtime_cache.py if ! getent passwd mission-core-node >/dev/null; then adduser --system --group --home /var/lib/mission-core-node --no-create-home --disabled-login mission-core-node fi @@ -15,6 +16,9 @@ case "$1" in systemctl enable mission-core-node.service systemctl restart mission-core-node.service systemctl try-restart mission-core-realsense.service + if [ -f /var/lib/mission-core-node-profiles/vesc/preparation.json ]; then + systemctl start mission-core-node-vesc-prepare.service + fi if [ -f /run/mission-core-node-k1-upgrade-active ]; then # A jointly upgraded plugin starts itself after its own configuration. # Restore it here only when that package is already configured. diff --git a/apps/node-agent/packaging/preinst b/apps/node-agent/packaging/preinst index 7a1534d..541aad9 100644 --- a/apps/node-agent/packaging/preinst +++ b/apps/node-agent/packaging/preinst @@ -14,10 +14,22 @@ if [ "$1" = install ] || [ "$1" = upgrade ]; then exit 1 fi fi + mc_node_usb_job=$(systemctl show --property=ActiveState --value mission-core-node-usb-startup.service 2>/dev/null || true) + case "$mc_node_usb_job" in + activating|deactivating) echo "Mission Core Node: дождитесь завершения обнаружения USB при загрузке." >&2; exit 1 ;; + esac + if [ -f /run/mission-core-usb-startup/pending.json ]; then + echo "Mission Core Node: восстановление USB ещё не завершило включение порта; пакет сохранён." >&2 + exit 1 + fi mc_node_x4_job=$(systemctl show --property=ActiveState --value mission-core-node-insta360-x4-profile.service 2>/dev/null || true) case "$mc_node_x4_job" in active|activating) echo "Mission Core Node: дождитесь завершения подготовки X4." >&2; exit 1 ;; esac + mc_node_vesc_job=$(systemctl show --property=ActiveState --value mission-core-node-vesc-prepare.service 2>/dev/null || true) + case "$mc_node_vesc_job" in + active|activating) echo "Mission Core Node: дождитесь завершения подготовки VESC." >&2; exit 1 ;; + esac mc_node_device_job=$(systemctl show --property=ActiveState --value mission-core-node-realsense-prepare.service 2>/dev/null || true) case "$mc_node_device_job" in active|activating) echo "Mission Core Node: дождитесь завершения подготовки устройства." >&2; exit 1 ;; @@ -38,6 +50,7 @@ if [ "$1" = install ] || [ "$1" = upgrade ]; then (umask 077; : > /run/mission-core-node-k1-upgrade-active) systemctl stop mission-core-k1.service fi + systemctl stop mission-core-vesc.service 2>/dev/null || true systemctl stop mission-core-node-monitor.service 2>/dev/null || true fi . /etc/os-release diff --git a/apps/node-agent/packaging/prerm b/apps/node-agent/packaging/prerm index 0c9fd9e..754ea7d 100644 --- a/apps/node-agent/packaging/prerm +++ b/apps/node-agent/packaging/prerm @@ -13,10 +13,22 @@ if [ -d /run/systemd/system ]; then exit 1 fi fi + mc_node_usb_job=$(systemctl show --property=ActiveState --value mission-core-node-usb-startup.service 2>/dev/null || true) + case "$mc_node_usb_job" in + activating|deactivating) echo "Mission Core Node: дождитесь завершения обнаружения USB при загрузке." >&2; exit 1 ;; + esac + if [ -f /run/mission-core-usb-startup/pending.json ]; then + echo "Mission Core Node: восстановление USB ещё не завершило включение порта; пакет сохранён." >&2 + exit 1 + fi mc_node_x4_job=$(systemctl show --property=ActiveState --value mission-core-node-insta360-x4-profile.service 2>/dev/null || true) case "$mc_node_x4_job" in active|activating) echo "Mission Core Node: дождитесь завершения подготовки X4." >&2; exit 1 ;; esac + mc_node_vesc_job=$(systemctl show --property=ActiveState --value mission-core-node-vesc-prepare.service 2>/dev/null || true) + case "$mc_node_vesc_job" in + active|activating) echo "Mission Core Node: дождитесь завершения подготовки VESC." >&2; exit 1 ;; + esac mc_node_device_job=$(systemctl show --property=ActiveState --value mission-core-node-realsense-prepare.service 2>/dev/null || true) case "$mc_node_device_job" in active|activating) echo "Mission Core Node: дождитесь завершения подготовки устройства." >&2; exit 1 ;; @@ -30,8 +42,39 @@ if [ -d /run/systemd/system ]; then ;; esac fi +retire_startup_settings() { + for mc_node_owned in /etc/xdg/autostart/org.nodedc.MissionCoreNode.desktop /etc/mission-core-node/usb-startup.json; do + case "$mc_node_owned" in + *.desktop) mc_node_template=/usr/share/mission-core-node/mission-core-node-autostart.desktop ;; + *.json) mc_node_template=/usr/share/mission-core-node/usb-startup.json ;; + esac + if [ ! -L "$mc_node_owned" ] && cmp -s "$mc_node_template" "$mc_node_owned"; then + rm "$mc_node_owned" + fi + done + if [ -d /run/systemd/system ]; then + systemctl disable --now mission-core-node-usb-startup.service + fi +} +# A downgrade removes helpers introduced in 0.8.37. Retire their owned +# configuration first; do not leave an enabled unit or XDG entry dangling. +if [ "$1" = upgrade ] && [ -n "${2:-}" ] && dpkg --compare-versions "$2" lt 0.8.37-1; then + retire_startup_settings +fi +case "$1" in + upgrade|remove|deconfigure) + if [ -d /run/systemd/system ] && [ -f /usr/lib/systemd/system/mission-core-vesc.service ]; then + systemctl disable --now mission-core-vesc.service + fi + ;; +esac case "$1" in remove|deconfigure) + if cmp -s /usr/share/mission-core-node/profiles/vesc/70-mission-core-vesc.rules /etc/udev/rules.d/70-mission-core-vesc.rules; then + rm /etc/udev/rules.d/70-mission-core-vesc.rules + if [ -d /run/systemd/system ]; then udevadm control --reload-rules; fi + fi + retire_startup_settings mc_node_ssh_snippet=/etc/ssh/sshd_config.d/60-mission-core-node.conf if [ -e "$mc_node_ssh_snippet" ]; then if cmp -s /usr/share/mission-core-node/60-mission-core-node.conf "$mc_node_ssh_snippet"; then diff --git a/apps/node-agent/packaging/test_desktop_startup.py b/apps/node-agent/packaging/test_desktop_startup.py new file mode 100644 index 0000000..55c67f4 --- /dev/null +++ b/apps/node-agent/packaging/test_desktop_startup.py @@ -0,0 +1,25 @@ +import unittest +from unittest.mock import Mock +import desktop_startup as startup + + +class DesktopStartupTests(unittest.TestCase): + def test_waits_for_service_without_credentials_and_closes_each_connection(self): + clock = [0] + def sleep(seconds): clock[0] += seconds + client = Mock() + client.getresponse.side_effect = [OSError('not started'), Mock(status=503), Mock(status=200)] + factory = Mock(return_value=client) + self.assertTrue(startup.wait_for_service(lambda: clock[0], sleep, factory)) + self.assertEqual(clock[0], 2) + self.assertEqual(client.close.call_count, 3) + self.assertEqual(client.request.call_args.args, ('GET', '/')) + + def test_stopped_service_does_not_hold_startup_forever(self): + clock = [0] + def sleep(seconds): clock[0] += seconds + client = Mock() + client.request.side_effect = OSError('offline') + self.assertFalse(startup.wait_for_service(lambda: clock[0], sleep, lambda *a, **kw: client)) + self.assertEqual(clock[0], 180) + self.assertEqual(client.close.call_count, 180) diff --git a/apps/node-agent/packaging/test_environment_helper.py b/apps/node-agent/packaging/test_environment_helper.py index acfd543..2a2e2a0 100644 --- a/apps/node-agent/packaging/test_environment_helper.py +++ b/apps/node-agent/packaging/test_environment_helper.py @@ -15,6 +15,24 @@ PROFILE = json.loads((Path(__file__).parents[1] / "internal/node/environment-pro class EnvironmentWorkflowTests(unittest.TestCase): + def test_profile_and_shipped_operations_match(self): + self.assertEqual({s['id'] for s in PROFILE['steps']}, set(helper.OPERATIONS)) + + def test_usb_setup_enables_next_boot_without_resetting_live_devices(self): + def command(argv, **_): + return json.dumps({'state': 'inspected', 'hubs': [{'individual_power': True}]}) if '--inspect' in argv else '' + with patch.object(helper, 'owned_config') as config, patch.object(helper, 'command', side_effect=command) as run: + self.assertIn('включено', helper.usb_startup()) + config.assert_called_once() + for call in run.call_args_list: + self.assertFalse({'--now', 'start', 'restart'} & set(call.args[0])) + self.assertTrue(any('--inspect' in call.args[0] for call in run.call_args_list)) + + def test_autostart_preserves_foreign_configuration_and_does_not_start_a_gui_as_root(self): + with patch.object(helper, 'owned_config', side_effect=helper.SetupError('conflict')), patch.object(helper, 'command') as run: + with self.assertRaises(helper.SetupError): helper.desktop_autostart() + run.assert_not_called() + def test_failure_blocks_dependents_but_inventory_still_runs_and_retry_rechecks(self): saved = [] operations = {item['id']: Mock(return_value='verified') for item in PROFILE['steps']} diff --git a/apps/node-agent/packaging/test_usb_startup_recovery.py b/apps/node-agent/packaging/test_usb_startup_recovery.py new file mode 100644 index 0000000..a498373 --- /dev/null +++ b/apps/node-agent/packaging/test_usb_startup_recovery.py @@ -0,0 +1,220 @@ +"""Synthetic sysfs/journal only: these tests never open a physical USB port.""" +import json +from pathlib import Path +import tempfile +import unittest +from unittest.mock import Mock, patch +import usb_startup_recovery as recovery + + +def event(second, message, transport='kernel'): + return {'__MONOTONIC_TIMESTAMP': str(int(second * 1000000)), + '_TRANSPORT': transport, 'MESSAGE': message} + + +class JournalTests(unittest.TestCase): + def test_only_terminal_boot_failures_with_no_later_connection_are_candidates(self): + records = [event(20, 'usb usb1-port2: unable to enumerate USB device'), + event(18, 'usb usb1-port3: unable to enumerate USB device'), + event(23, 'usb 1-3: new full-speed USB device number 8 using xhci_hcd'), + event(12, 'usb 1-1-port2: unable to enumerate USB device'), + event(65, 'usb usb2-port1: unable to enumerate USB device'), + event(15, 'usb usb2-port3: unable to enumerate USB device', 'stdout'), + event(18, 'usb 1-4: device descriptor read/64, error -71')] + self.assertEqual(recovery.failed_ports(list(reversed(records))), ['1-1-port2', 'usb1-port2']) + + def test_success_or_user_disconnect_invalidates_old_failure(self): + for message in ['New USB device found, idVendor=0000', 'USB disconnect, device number 8']: + self.assertEqual(recovery.failed_ports([ + event(20, 'usb usb1-port2: unable to enumerate USB device'), event(21, 'usb 1-2: ' + message)]), []) + + def test_invalid_port_names_cannot_be_paths(self): + for name in ['../../etc/passwd', 'usb0-port0', 'usb1-port1/disable']: + with self.assertRaises(ValueError): recovery.child_name(name) + self.assertEqual(recovery.child_name('1-2.3-port4'), '1-2.3.4') + + +class SysfsTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + base = Path(self.temp.name) + self.root, self.physical = base/'bus', base/'devices' + self.root.mkdir(); self.physical.mkdir() + self.usb = recovery.USB(self.root, self.physical) + self.ports = [] + for n in (1, 2): + hub = self.physical/f'usb{n}'; hub.mkdir() + for key, value in {'bDeviceClass':'09', 'busnum':str(n), 'devnum':'1'}.items(): + (hub/key).write_text(value) + (self.root/hub.name).symlink_to(hub, target_is_directory=True) + interface = hub/f'{n}-0:1.0'; interface.mkdir() + (self.root/interface.name).symlink_to(interface, target_is_directory=True) + port = interface/f'usb{n}-port2'; port.mkdir() + for key, value in {'state':'not attached', 'disable':'0\n', 'over_current_count':'0', 'connect_type':'unknown'}.items(): + (port/key).write_text(value) + self.ports.append(port) + (self.ports[0]/'peer').symlink_to(self.ports[1], target_is_directory=True) + (self.ports[1]/'peer').symlink_to(self.ports[0], target_is_directory=True) + + def plan(self): + with patch.object(recovery, 'run', return_value=' wHubCharacteristic 0x0009\n'): + return self.usb.plan('usb1-port2') + + def test_individual_power_pair_can_be_disabled_and_restored(self): + entries = self.plan() + self.assertEqual([e['name'] for e in entries], ['usb1-port2', 'usb2-port2']) + for entry in entries: self.usb.write(entry, True) + self.assertTrue(all((p/'disable').read_text() == '1\n' for p in self.ports)) + for entry in reversed(entries): self.usb.write(entry, False) + self.assertTrue(all((p/'disable').read_text() == '0\n' for p in self.ports)) + + def test_connected_companion_blocks_both_ports_before_descriptor_query(self): + (self.ports[1]/'device').symlink_to(self.physical/'camera') + with patch.object(recovery, 'run') as run: + with self.assertRaises(OSError): self.usb.plan('usb1-port2') + run.assert_not_called() + self.assertEqual((self.ports[0]/'disable').read_text(), '0\n') + + def test_non_individual_power_or_missing_descriptor_cannot_reset(self): + for output in ['wHubCharacteristics 0x0000', 'wHubCharacteristics 0x0002', '']: + with self.subTest(output=output), patch.object(recovery, 'run', return_value=output): + with self.assertRaises(OSError): self.usb.plan('usb1-port2') + + def test_internal_disabled_overcurrent_and_mid_enumeration_ports_skipped(self): + for attribute, value in [('connect_type', 'hardwired'), ('disable', '1'), ('over_current_count', '1'), ('state', 'powered')]: + p = self.ports[0]/attribute; original = p.read_text(); p.write_text(value) + with self.subTest(attribute=attribute), self.assertRaises(OSError): self.plan() + p.write_text(original) + + def test_attachment_after_planning_prevents_write(self): + entries = self.plan() + (self.ports[0]/'device').symlink_to(self.physical/'new-device') + with self.assertRaises(OSError): self.usb.write(entries[0], True) + self.assertEqual((self.ports[0]/'disable').read_text(), '0\n') + + def test_hub_replacement_after_planning_prevents_write(self): + entries = self.plan() + (self.physical/'usb1'/'devnum').write_text('4') + with self.assertRaises(OSError): self.usb.write(entries[0], True) + + def test_first_hub_replaced_while_inspecting_companion_invalidates_plan(self): + def inspect(name): + if name == 'usb2-port2': (self.physical/'usb1'/'devnum').write_text('4') + return True + with patch.object(self.usb, 'individual_power', side_effect=inspect): + with self.assertRaises(OSError): self.usb.plan('usb1-port2') + + def test_enabled_port_is_not_written_during_cleanup(self): + entries = self.plan() + with patch.object(recovery.os, 'open', side_effect=AssertionError('No write expected')): + self.usb.write(entries[0], False) + + def test_foreign_companion_path_is_rejected(self): + (self.ports[0]/'peer').unlink() + (self.ports[0]/'peer').symlink_to(self.root) + with self.assertRaises(OSError): self.usb.companions('usb1-port2') + + +class RecoveryTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory(); self.addCleanup(self.temp.cleanup) + self.state = Path(self.temp.name) + self.clock = 30 + self.usb = Mock() + self.entries = [{'name': 'usb1-port2', 'generation': {'address': 1}}, + {'name': 'usb2-port2', 'generation': {'address': 1}}] + self.usb.plan.return_value = self.entries + self.usb.empty.return_value = True + self.usb.generation.return_value = {'address': 1} + self.usb.outcome.return_value = {'idVendor': '0000', 'idProduct': '0001', 'product': 'Synthetic'} + + def sleep(self, seconds): self.clock += seconds + + def run_recovery(self, ports=None): + return recovery.recover(self.usb, self.state, 'boot', ports or ['usb1-port2'], lambda: self.clock, self.sleep) + + def test_pair_is_attempted_only_once_and_restored_before_enumeration_check(self): + result = self.run_recovery(['usb1-port2', 'usb2-port2']) + self.assertEqual(len(result), 1) + self.assertEqual(result[0]['state'], 'enumerated') + self.assertEqual([c.args[1] for c in self.usb.write.call_args_list], [True, True, False, False]) + self.assertFalse((self.state/'pending.json').exists()) + + def test_second_disable_failure_restores_both_and_keeps_failure_detail(self): + def write(entry, disabled): + if disabled and entry['name'] == 'usb2-port2': raise OSError('failed second write') + self.usb.write.side_effect = write + result = self.run_recovery() + self.assertIn('failed second write', result[0]['reason']) + self.assertEqual([c.args[1] for c in self.usb.write.call_args_list], [True, True, False, False]) + self.assertFalse((self.state/'pending.json').exists()) + + def test_termination_during_off_period_restores_ports(self): + def interrupted(_): raise InterruptedError('stop') + result = recovery.recover(self.usb, self.state, 'boot', ['usb1-port2'], lambda: self.clock, interrupted) + self.assertIn('stop', result[0]['reason']) + self.assertFalse((self.state/'pending.json').exists()) + self.assertEqual([c.args[1] for c in self.usb.write.call_args_list], [True, True, False, False]) + + def test_restore_failure_preserves_pending_and_stops_other_ports(self): + def write(_, disabled): + if not disabled: raise OSError('restore failed') + self.usb.write.side_effect = write + result = self.run_recovery(['usb1-port2', 'usb1-port3']) + self.assertEqual(result[0]['state'], 'restore_failed') + self.usb.plan.assert_called_once() + self.assertTrue((self.state/'pending.json').exists()) + self.usb.write.side_effect = None + recovery.restore(self.usb, self.state, 'boot') + self.assertFalse((self.state/'pending.json').exists()) + + def test_slow_planning_cannot_start_a_late_reset(self): + def plan(_): self.clock = 179; return self.entries + self.usb.plan.side_effect = plan + result = self.run_recovery() + self.assertIn('deadline', result[0]['reason']) + self.usb.write.assert_not_called() + + def test_failed_enumeration_has_no_repeated_power_loop(self): + self.usb.outcome.return_value = None + result = self.run_recovery() + self.assertEqual(result[0]['state'], 'retried') + self.assertEqual(self.clock, 39) + self.assertEqual(self.usb.write.call_count, 4) + + def test_previous_boot_pending_state_cannot_address_current_ports(self): + recovery.atomic(self.state/'pending.json', {'boot_id': 'old', 'ports': self.entries}) + with self.assertRaises(OSError): recovery.restore(self.usb, self.state, 'new') + self.usb.write.assert_not_called() + + def test_boot_wait_occurs_before_journal_snapshot_and_second_run_preserves_report(self): + boot_file = self.state/'boot-id'; boot_file.write_text('boot') + self.clock = 5 + def journal(): + self.assertGreaterEqual(self.clock, recovery.MIN_AGE) + return [] + with patch.object(recovery, 'STATE', self.state), patch.object(recovery, 'BOOT_ID', boot_file), \ + patch.object(recovery, 'state_directory'), patch.object(recovery, 'enabled'), \ + patch.object(recovery.os, 'geteuid', return_value=0), patch.object(recovery.sys, 'argv', ['helper']), \ + patch.object(recovery.time, 'monotonic', side_effect=lambda: self.clock), \ + patch.object(recovery.time, 'sleep', side_effect=self.sleep), \ + patch.object(recovery, 'journal', side_effect=journal) as read, patch('builtins.print'): + self.assertEqual(recovery.main(), 0) + first = (self.state/'result.json').read_bytes() + self.assertEqual(recovery.main(), 0) + self.assertEqual((self.state/'result.json').read_bytes(), first) + read.assert_called_once() + + def test_late_service_start_cannot_read_or_reset_ports(self): + boot_file = self.state/'boot-id'; boot_file.write_text('boot') + with patch.object(recovery, 'STATE', self.state), patch.object(recovery, 'BOOT_ID', boot_file), \ + patch.object(recovery, 'state_directory'), patch.object(recovery.os, 'geteuid', return_value=0), \ + patch.object(recovery.sys, 'argv', ['helper']), patch.object(recovery.time, 'monotonic', return_value=200), \ + patch.object(recovery, 'journal') as read, patch.object(recovery, 'recover') as reset, patch('builtins.print'): + self.assertEqual(recovery.main(), 0) + read.assert_not_called(); reset.assert_not_called() + self.assertEqual(json.loads((self.state/'result.json').read_text())['reason'], 'Outside startup window') + + +if __name__ == '__main__': unittest.main() diff --git a/apps/node-agent/packaging/usb-startup.json b/apps/node-agent/packaging/usb-startup.json new file mode 100644 index 0000000..da3b167 --- /dev/null +++ b/apps/node-agent/packaging/usb-startup.json @@ -0,0 +1 @@ +{"schema":"missioncore.node.usb-startup-policy/v1","enabled":true,"mode":"terminal-enumeration-failures"} diff --git a/apps/node-agent/packaging/usb_startup_recovery.py b/apps/node-agent/packaging/usb_startup_recovery.py new file mode 100644 index 0000000..542595c --- /dev/null +++ b/apps/node-agent/packaging/usb_startup_recovery.py @@ -0,0 +1,332 @@ +"""One bounded boot-time retry of failed USB enumeration; no device commands. + +Only root's fixed systemd job may apply. No request supplies a path or command. +Healthy ports (including USB3 companions) and non-individual-power hubs are +excluded. The application still identifies controllers by firmware UUID. +""" +import fcntl +import json +import os +from pathlib import Path +import re +import signal +import stat +import subprocess +import sys +import time + +STATE = Path('/run/mission-core-usb-startup') +BOOT_ID = Path('/proc/sys/kernel/random/boot_id') +POLICY = Path('/etc/mission-core-node/usb-startup.json') +EXPECTED_POLICY = {'schema': 'missioncore.node.usb-startup-policy/v1', 'enabled': True, + 'mode': 'terminal-enumeration-failures'} +BOOT_WINDOW = 180 +FAILURE_WINDOW = 60 +MIN_AGE = 30 +BUDGET = 90 +PORT = re.compile(r'(usb[1-9][0-9]*|[1-9][0-9]*-[1-9][0-9]*(?:\.[1-9][0-9]*)*)-port([1-9][0-9]*)') +FAILURE = re.compile(r'usb ((?:usb[1-9][0-9]*|[1-9][0-9]*-[1-9][0-9]*(?:\.[1-9][0-9]*)*)-port[1-9][0-9]*): unable to enumerate USB device') + + +def child_name(port): + match = PORT.fullmatch(port) + if not match: + raise ValueError('Invalid USB port') + hub, number = match.groups() + return hub[3:] + '-' + number if hub.startswith('usb') else hub + '.' + number + + +def failed_ports(records): + """Ignore failures superseded by a later connection/disconnection event.""" + failures, changes = {}, {} + for entry in sorted(records, key=lambda r: int(r.get('__MONOTONIC_TIMESTAMP', 0))): + if entry.get('_TRANSPORT') != 'kernel': + continue + stamp = int(entry.get('__MONOTONIC_TIMESTAMP', 0)) / 1000000 + message = entry.get('MESSAGE', '') + if not isinstance(message, str): + continue + match = FAILURE.fullmatch(message) + if match and 0 < stamp <= FAILURE_WINDOW: + failures[match[1]] = stamp + match = re.match(r'usb ([0-9]+-[0-9]+(?:\.[0-9]+)*): (?:new |New USB device found|USB disconnect)', message) + if match: + changes[match[1]] = stamp + return [p for p, stamp in sorted(failures.items()) if changes.get(child_name(p), 0) <= stamp] + + +def run(args): + try: + result = subprocess.run(args, capture_output=True, text=True, timeout=5, + env={'PATH': '/usr/sbin:/usr/bin:/sbin:/bin', 'LC_ALL': 'C'}) + except subprocess.SubprocessError as error: + raise OSError('USB inspection command timed out or failed') from error + if result.returncode or len(result.stdout) > 2 * 1024**2: + raise OSError('USB inspection command failed') + return result.stdout + + +def journal(): + raw = run(['/usr/bin/journalctl', '-k', '-b', '0', '--no-pager', '-o', 'json', '-n', '2000', + '--grep=unable to enumerate USB device|new .* USB device|New USB device found|USB disconnect']) + return [json.loads(line) for line in raw.splitlines()] + + +def atomic(path, value): + temporary = path.with_suffix('.tmp') + fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, 'w') as stream: + json.dump(value, stream, sort_keys=True) + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, path) + + +class USB: + def __init__(self, root=Path('/sys/bus/usb/devices'), physical=Path('/sys/devices')): + self.root, self.physical = root, physical.resolve() + + def resolve(self, name): + match = PORT.fullmatch(name) + if not match: + raise ValueError('Invalid port name') + hub = match[1] + interface = hub[3:] + '-0' if hub.startswith('usb') else hub + paths = list(self.root.glob(interface + ':*/' + name)) + if len(paths) != 1: + raise OSError('USB port topology unavailable') + path = paths[0].resolve(strict=True) + if not path.is_relative_to(self.physical) or path.name != name: + raise OSError('USB port outside sysfs devices') + return path + + def generation(self, name): + hub = self.root / PORT.fullmatch(name)[1] + if (hub / 'bDeviceClass').read_text().strip() != '09': + raise OSError('Parent is not a USB hub') + return {'bus': int((hub / 'busnum').read_text()), 'address': int((hub / 'devnum').read_text()), + 'path': str(hub.resolve(strict=True)), 'inode': hub.stat().st_ino} + + def empty(self, name): + p = self.resolve(name) + return (not os.path.lexists(p / 'device') and + (p / 'state').read_text().strip() == 'not attached' and + (p / 'disable').read_text().strip() == '0' and + (p / 'over_current_count').read_text().strip() == '0' and + (p / 'connect_type').read_text().strip() in ('hotplug', 'unknown')) + + def companions(self, name): + p = self.resolve(name) + names = [name] + if os.path.lexists(p / 'peer'): + peer = (p / 'peer').resolve(strict=True) + if not peer.is_relative_to(self.physical) or self.resolve(peer.name) != peer: + raise OSError('USB companion topology changed') + if (peer / 'peer').resolve(strict=True) != p: + raise OSError('USB companion is not reciprocal') + names.append(peer.name) + return names + + def individual_power(self, name): + before = self.generation(name) + raw = run(['/usr/bin/lsusb', '-v', '-s', f"{before['bus']:03}:{before['address']:03}"]) + characteristics = re.findall(r'^\s*wHubCharacteristic[s]?\s+0x([0-9a-fA-F]+)\s*$', raw, re.M) + return (before == self.generation(name) and len(characteristics) == 1 and + int(characteristics[0], 16) & 3 == 1) + + def plan(self, name): + names = self.companions(name) + entries = [{'name': n, 'generation': self.generation(n)} for n in names] + # Test every companion before querying hub descriptors or opening any port. + if not all(self.empty(n) for n in names): + raise OSError('Port or USB companion already attached, disabled, internal or over-current') + if not all(self.individual_power(n) for n in names): + raise OSError('Individual USB port power switching is not confirmed') + if any(self.generation(e['name']) != e['generation'] for e in entries): + raise OSError('USB hub changed during companion inspection') + return entries + + def write(self, entry, disabled): + name = entry['name'] + if self.generation(name) != entry['generation']: + raise OSError('USB hub generation changed') + if disabled and not self.empty(name): + raise OSError('USB port became occupied') + p = self.resolve(name) / 'disable' + # Pending state is durable before the first write. An interrupted or + # rejected first write must not cause a redundant enable on a port + # which has since successfully enumerated. + if not disabled and p.read_text().strip() == '0': + return + fd = os.open(p, os.O_WRONLY | os.O_NOFOLLOW) + try: + if self.generation(name) != entry['generation'] or (disabled and not self.empty(name)): + raise OSError('USB topology changed before write') + if os.write(fd, b'1\n' if disabled else b'0\n') != 2: + raise OSError('Incomplete USB port write') + finally: + os.close(fd) + + def outcome(self, name): + p = self.resolve(name) + if not (p / 'device').exists(): + return None + child = (p / 'device').resolve(strict=True) + if not child.is_relative_to(self.physical): + raise OSError('Unexpected USB child') + return {key: (child / key).read_text().strip() for key in ('idVendor', 'idProduct', 'product')} + + +def restore(usb, state, boot): + p = state / 'pending.json' + if not p.exists(): + return + pending = json.loads(p.read_text()) + if pending['boot_id'] != boot: + raise OSError('Pending recovery belongs to another boot') + errors = [] + for entry in reversed(pending['ports']): + try: + usb.write(entry, False) + except OSError as error: + errors.append(str(error)) + if errors: + raise OSError('; '.join(errors)) + p.unlink() + + +def recover(usb, state, boot, candidates, now=time.monotonic, sleep=time.sleep): + deadline = min(now() + BUDGET, BOOT_WINDOW) + results, processed = [], set() + for name in candidates[:32]: + if name in processed: + continue + item = {'port': name, 'state': 'skipped'} + results.append(item) + if now() + 12 >= deadline: + item['reason'] = 'Boot recovery deadline reached' + break + try: + entries = usb.plan(name) + if now() + 12 >= deadline: + raise OSError('Boot recovery deadline reached during planning') + # Recheck all companions after descriptor reads and before any write. + if not all(usb.empty(e['name']) and usb.generation(e['name']) == e['generation'] for e in entries): + raise OSError('USB port changed during planning') + processed.update(e['name'] for e in entries) + item['ports'] = [e['name'] for e in entries] + atomic(state / 'pending.json', {'boot_id': boot, 'ports': entries}) + try: + for entry in entries: + usb.write(entry, True) + sleep(1) + finally: + restore(usb, state, boot) + item['state'] = 'retried' + until = min(now() + 8, deadline) + while now() < until: + result = usb.outcome(name) + if result: + item.update(state='enumerated', descriptor=result) + break + sleep(0.25) + except (OSError, ValueError) as error: + item['reason'] = str(error) + if (state / 'pending.json').exists(): + item['state'] = 'restore_failed' + break + return results + + +def state_directory(): + STATE.mkdir(mode=0o755, exist_ok=True) + info = STATE.lstat() + if not stat.S_ISDIR(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022: + raise OSError('Untrusted recovery state directory') + + +def enabled(): + info = POLICY.lstat() + if not stat.S_ISREG(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022 or info.st_size > 1024: + raise OSError('Untrusted startup recovery policy') + if json.loads(POLICY.read_text()) != EXPECTED_POLICY: + raise OSError('Startup recovery policy is not supported') + + +def inspect(usb): + hubs = [] + deadline = time.monotonic() + 60 + for p in sorted(usb.root.glob('*')): + if time.monotonic() >= deadline or len(hubs) >= 16: + break + if not re.fullmatch(r'usb[1-9][0-9]*|[1-9][0-9]*-[1-9][0-9]*(?:\.[1-9][0-9]*)*', p.name): + continue + try: + if (p / 'bDeviceClass').read_text().strip() != '09': + continue + hubs.append({'hub': p.name, 'individual_power': usb.individual_power(p.name + '-port1')}) + except OSError as error: + hubs.append({'hub': p.name, 'error': str(error)}) + return hubs + + +def main(): + if os.geteuid() != 0 or sys.argv[1:] not in ([], ['--inspect'], ['--restore']): + raise ValueError('Fixed root-owned startup job only') + mode = sys.argv[1:] or ['apply'] + state_directory() + lock = os.open(STATE / 'lock', os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600) + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + boot = BOOT_ID.read_text().strip() + usb = USB() + if mode == ['--restore']: + try: + restore(usb, STATE, boot) + finally: + os.close(lock) + return 0 + if mode == ['apply'] and (STATE / 'attempted').exists(): + # Preserve the first result, including restore failures, across a later + # daemon/package restart. Recovery is never retriggered by refresh. + try: + restore(usb, STATE, boot) + finally: + os.close(lock) + return 0 + report = {'schema': 'missioncore.node.usb-startup-recovery/v1', 'boot_id': boot, + 'observed_at_unix': time.time(), 'boot_seconds': time.monotonic(), + 'mode': mode[0], 'state': 'skipped', 'results': []} + destination = STATE / ('inspection.json' if mode == ['--inspect'] else 'result.json') + try: + if mode == ['--inspect']: + report['hubs'] = inspect(usb) + report['state'] = 'inspected' + elif time.monotonic() >= BOOT_WINDOW: + report['reason'] = 'Outside startup window' + else: + enabled() + atomic(STATE / 'attempted', {'boot_id': boot}) + restore(usb, STATE, boot) + # udev-settle can return before the hub driver's delayed retries + # give up. Wait before taking the first snapshot, including when + # the journal currently contains no terminal failure yet. + time.sleep(max(0, MIN_AGE - time.monotonic())) + candidates = failed_ports(journal()) + if candidates: + report['results'] = recover(usb, STATE, boot, candidates) + report['state'] = 'complete' + except (OSError, ValueError, subprocess.SubprocessError) as error: + report.update(state='error', reason=str(error)) + finally: + atomic(destination, report) + destination.chmod(0o644) + os.close(lock) + print(json.dumps(report, sort_keys=True)) + return 1 if report['state'] == 'error' or any(r['state'] == 'restore_failed' for r in report['results']) else 0 + + +if __name__ == '__main__': + def interrupted(*_): + raise InterruptedError('Startup recovery interrupted') + signal.signal(signal.SIGTERM, interrupted) + sys.exit(main()) diff --git a/apps/node-agent/ui/src/main.tsx b/apps/node-agent/ui/src/main.tsx index b8d9f51..e8c26e0 100644 --- a/apps/node-agent/ui/src/main.tsx +++ b/apps/node-agent/ui/src/main.tsx @@ -38,7 +38,7 @@ function App() { function openView(id: ViewId) { if(environment.running) return; setAdding(false); setRoot(views.find(item => item.id === id)!.root); workspace.openView(id); } function selectRoot(id: RootId) { const first = roots.find(item => item.id === id)!.first; if (first) openView(first); } const content = !value ? null : workspace.activeView === "environment" ? : workspace.activeView === "overview" ? - : workspace.activeView === "sensors" ? + : workspace.activeView === "sensors" ? openView("environment")} /> : workspace.activeView === "network" ? : workspace.activeView === "usb" ? : workspace.activeView === "core" ? diff --git a/plugins/insta360-x4/packaging/owner_release_entry.py b/plugins/insta360-x4/packaging/owner_release_entry.py index d3a2a1a..548ee61 100644 --- a/plugins/insta360-x4/packaging/owner_release_entry.py +++ b/plugins/insta360-x4/packaging/owner_release_entry.py @@ -7,6 +7,7 @@ import platform import re import subprocess import sys +import tempfile import zipfile from pathlib import Path @@ -24,11 +25,44 @@ PROFILES = { } +def sync_directory(path): + directory = os.open(path, os.O_RDONLY | os.O_DIRECTORY) + try: + os.fsync(directory) + finally: + os.close(directory) + + def private(path): path.mkdir(mode=0o700, exist_ok=True) info = path.lstat() if path.is_symlink() or info.st_uid != os.geteuid() or info.st_mode & 0o077: raise RuntimeError("Release directory is not private and owned") + sync_directory(path.parent) + + +def stage_file(path, data, mode): + """Publish complete, durable installer files before opening the sudo UI.""" + if path.is_symlink(): + raise ValueError("Unexpected release symlink") + if path.exists(): + with path.open("rb") as stream: + if stream.read() != data: + raise ValueError("Existing release was modified") + os.fsync(stream.fileno()) + else: + descriptor, temporary = tempfile.mkstemp(prefix="." + path.name + ".", dir=path.parent) + try: + with os.fdopen(descriptor, "wb") as stream: + os.fchmod(stream.fileno(), mode) + stream.write(data) + stream.flush() + os.fsync(stream.fileno()) + # Do not overwrite another launcher or a modified staged file. + os.link(temporary, path) + finally: + os.unlink(temporary) + sync_directory(path.parent) def main(): @@ -74,16 +108,7 @@ def main(): raise ValueError("Release payload changed") files["release.json"] = raw for name, data in files.items(): - path = folder / name - if path.is_symlink(): - raise ValueError("Unexpected release symlink") - if path.exists(): - if path.read_bytes() != data: - raise ValueError("Existing release was modified") - else: - with path.open("xb") as stream: - stream.write(data) - path.chmod(0o700 if name == "install" else 0o600) + stage_file(folder / name, data, 0o700 if name == "install" else 0o600) print(json.dumps({"release_id": identifier, "directory": str(folder)}), flush=True) if sys.argv[1] == "--plan": result = subprocess.run( diff --git a/plugins/insta360-x4/packaging/test_owner_release_entry.py b/plugins/insta360-x4/packaging/test_owner_release_entry.py new file mode 100644 index 0000000..c8c98cc --- /dev/null +++ b/plugins/insta360-x4/packaging/test_owner_release_entry.py @@ -0,0 +1,57 @@ +"""Installer staging survives interrupted writes without admitting corrupt files.""" + +import importlib.util +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch + +spec = importlib.util.spec_from_file_location( + "owner_release_entry", Path(__file__).with_name("owner_release_entry.py") +) +entry = importlib.util.module_from_spec(spec) +spec.loader.exec_module(entry) + + +class ReleaseStagingTests(unittest.TestCase): + def test_sync_failure_never_publishes_partial_payload(self): + with tempfile.TemporaryDirectory() as directory: + target = Path(directory) / "package.deb" + with patch.object(entry.os, "fsync", side_effect=OSError("disk failure")): + with self.assertRaises(OSError): + entry.stage_file(target, b"complete package", 0o600) + self.assertEqual(list(Path(directory).iterdir()), []) + entry.stage_file(target, b"complete package", 0o600) + self.assertEqual(target.read_bytes(), b"complete package") + self.assertEqual(target.stat().st_mode & 0o777, 0o600) + + def test_valid_staging_can_be_repeated_without_replacing_inode(self): + with tempfile.TemporaryDirectory() as directory: + target = Path(directory) / "install" + entry.stage_file(target, b"installer", 0o700) + inode = target.stat().st_ino + entry.stage_file(target, b"installer", 0o700) + self.assertEqual(target.stat().st_ino, inode) + self.assertEqual(target.stat().st_mode & 0o777, 0o700) + + def test_truncated_existing_file_is_preserved_and_rejected(self): + with tempfile.TemporaryDirectory() as directory: + target = Path(directory) / "package.deb" + target.write_bytes(b"partial") + with self.assertRaisesRegex(ValueError, "modified"): + entry.stage_file(target, b"complete package", 0o600) + self.assertEqual(target.read_bytes(), b"partial") + + def test_symlink_never_changes_its_target(self): + with tempfile.TemporaryDirectory() as directory: + real = Path(directory) / "real" + real.write_bytes(b"keep") + target = Path(directory) / "package.deb" + target.symlink_to(real) + with self.assertRaisesRegex(ValueError, "symlink"): + entry.stage_file(target, b"replacement", 0o600) + self.assertEqual(real.read_bytes(), b"keep") + + +if __name__ == "__main__": + unittest.main() From 63cbb08ea01ffd2959f5081a842d87502f13941b Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Fri, 25 Sep 2026 16:37:56 +0300 Subject: [PATCH 4/7] feat(rover): add drive profiles and leased remote command channel --- apps/node-agent/internal/node/board_layout.go | 151 +++++++++++ .../internal/node/board_layout_test.go | 56 ++++ .../node-agent/internal/node/rover_channel.go | 249 ++++++++++++++++++ .../internal/node/rover_diagnostics.go | 61 +++++ .../internal/node/rover_diagnostics_test.go | 63 +++++ .../internal/node/rover_stream_state.go | 199 ++++++++++++++ .../internal/node/rover_stream_state_test.go | 235 +++++++++++++++++ packages/rover-control/README.md | 107 ++++++++ packages/rover-control/src/authority.ts | 134 ++++++++++ packages/rover-control/src/profile.ts | 72 +++++ packages/sensor-ui/src/BoardSections.tsx | 23 ++ packages/sensor-ui/src/boardLayout.ts | 66 +++++ src/k1link/fleet/board_layout.py | 45 ++++ src/k1link/fleet/rover_control.py | 135 ++++++++++ src/k1link/web/rover_api.py | 40 +++ tests/fleet/test_board_layout.py | 42 +++ tests/fleet/test_rover_control.py | 115 ++++++++ tests/fleet/test_rover_stream_transport.py | 52 ++++ 18 files changed, 1845 insertions(+) create mode 100644 apps/node-agent/internal/node/board_layout.go create mode 100644 apps/node-agent/internal/node/board_layout_test.go create mode 100644 apps/node-agent/internal/node/rover_channel.go create mode 100644 apps/node-agent/internal/node/rover_diagnostics.go create mode 100644 apps/node-agent/internal/node/rover_diagnostics_test.go create mode 100644 apps/node-agent/internal/node/rover_stream_state.go create mode 100644 apps/node-agent/internal/node/rover_stream_state_test.go create mode 100644 packages/rover-control/README.md create mode 100644 packages/rover-control/src/authority.ts create mode 100644 packages/rover-control/src/profile.ts create mode 100644 packages/sensor-ui/src/BoardSections.tsx create mode 100644 packages/sensor-ui/src/boardLayout.ts create mode 100644 src/k1link/fleet/board_layout.py create mode 100644 src/k1link/fleet/rover_control.py create mode 100644 src/k1link/web/rover_api.py create mode 100644 tests/fleet/test_board_layout.py create mode 100644 tests/fleet/test_rover_control.py create mode 100644 tests/fleet/test_rover_stream_transport.py diff --git a/apps/node-agent/internal/node/board_layout.go b/apps/node-agent/internal/node/board_layout.go new file mode 100644 index 0000000..b2d7aaa --- /dev/null +++ b/apps/node-agent/internal/node/board_layout.go @@ -0,0 +1,151 @@ +package node + +import ( + "encoding/json" + "errors" + "io" + "net/http" + "os" + "path/filepath" +) + +const boardLayoutSchema = "missioncore.board-layout/v1" + +var boardSectionIDs = []string{"computer", "settings", "devices"} + +type BoardLayout struct { + Schema string `json:"schema"` + Revision int64 `json:"revision"` + OpenSections []string `json:"open_sections"` +} + +func validBoardSection(id string) bool { + for _, section := range boardSectionIDs { + if id == section { + return true + } + } + return false +} + +func (p *PresentationStore) readBoardLayout() (BoardLayout, error) { + value := BoardLayout{Schema: boardLayoutSchema, OpenSections: append([]string{}, boardSectionIDs...)} + file, err := os.Open(filepath.Join(p.dir, "board-layout.json")) + if errors.Is(err, os.ErrNotExist) { + return value, nil + } + if err != nil { + return BoardLayout{}, err + } + defer file.Close() + d := json.NewDecoder(io.LimitReader(file, 4097)) + d.DisallowUnknownFields() + value = BoardLayout{} + if d.Decode(&value) != nil || d.Decode(new(any)) != io.EOF || value.Schema != boardLayoutSchema || value.Revision < 0 || value.Revision >= 1<<53-1 || value.OpenSections == nil { + return BoardLayout{}, errors.New("invalid board layout") + } + seen := map[string]bool{} + for _, id := range value.OpenSections { + if !validBoardSection(id) || seen[id] { + return BoardLayout{}, errors.New("invalid board section") + } + seen[id] = true + } + return value, nil +} + +func (p *PresentationStore) saveBoardLayout(value BoardLayout) error { + data, err := json.MarshalIndent(value, "", " ") + if err != nil { + return err + } + file, err := os.CreateTemp(p.dir, ".board-layout-*") + if err != nil { + return err + } + defer os.Remove(file.Name()) + if _, err = file.Write(append(data, '\n')); err == nil { + err = file.Sync() + } + closeErr := file.Close() + if err != nil { + return err + } + if closeErr != nil { + return closeErr + } + if err = os.Rename(file.Name(), filepath.Join(p.dir, "board-layout.json")); err != nil { + return err + } + dir, err := os.Open(p.dir) + if err != nil { + return err + } + defer dir.Close() + return dir.Sync() +} + +func (s *Server) boardLayoutRoutes(mux *http.ServeMux) { + p := s.Presentation + mux.HandleFunc("GET /api/presentation/board-layout", func(w http.ResponseWriter, r *http.Request) { + if !s.authorized(w, r) { + return + } + p.mu.Lock() + defer p.mu.Unlock() + value, err := p.readBoardLayout() + if err != nil { + reply(w, 500, map[string]string{"error": "Не удалось прочитать раскладку борта"}) + return + } + reply(w, 200, value) + }) + mux.HandleFunc("PATCH /api/presentation/board-layout", func(w http.ResponseWriter, r *http.Request) { + if !s.authorized(w, r) { + return + } + if r.Header.Get("Content-Type") != "application/json" { + reply(w, 415, map[string]string{"error": "Ожидался JSON"}) + return + } + var change struct { + Section string `json:"section"` + Open *bool `json:"open"` + } + d := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1024)) + d.DisallowUnknownFields() + if d.Decode(&change) != nil || d.Decode(new(any)) != io.EOF || change.Open == nil || !validBoardSection(change.Section) { + reply(w, 400, map[string]string{"error": "Некорректная раскладка борта"}) + return + } + p.mu.Lock() + defer p.mu.Unlock() + value, err := p.readBoardLayout() + if err != nil { + reply(w, 500, map[string]string{"error": "Не удалось прочитать раскладку борта"}) + return + } + next := []string{} + for _, id := range boardSectionIDs { + open := false + for _, saved := range value.OpenSections { + if saved == id { + open = true + } + } + if id == change.Section { + open = *change.Open + } + if open { + next = append(next, id) + } + } + value.OpenSections = next + value.Revision++ + if p.saveBoardLayout(value) != nil { + reply(w, 500, map[string]string{"error": "Не удалось сохранить раскладку борта"}) + return + } + reply(w, 200, value) + }) +} diff --git a/apps/node-agent/internal/node/board_layout_test.go b/apps/node-agent/internal/node/board_layout_test.go new file mode 100644 index 0000000..60e5f6d --- /dev/null +++ b/apps/node-agent/internal/node/board_layout_test.go @@ -0,0 +1,56 @@ +package node + +import ( + "os" + "path/filepath" + "sync" + "testing" +) + +func TestBoardLayoutPersistsEmptyAndConcurrentSectionChanges(t *testing.T) { + s, cookie := presentationServer(t) + var wg sync.WaitGroup + for _, id := range boardSectionIDs { + wg.Add(1) + go func(id string) { + defer wg.Done() + w := call(s, "PATCH", "/api/presentation/board-layout", `{"section":"`+id+`","open":false}`, cookie) + if w.Code != 200 { + t.Error(w.Code, w.Body.String()) + } + }(id) + } + wg.Wait() + value, err := NewPresentationStore(s.Presentation.dir).readBoardLayout() + if err != nil || value.Revision != 3 || len(value.OpenSections) != 0 || value.OpenSections == nil { + t.Fatal(value, err) + } + info, err := os.Stat(filepath.Join(s.Presentation.dir, "board-layout.json")) + if err != nil || info.Mode().Perm() != 0600 { + t.Fatal(info, err) + } + if w := call(s, "GET", "/api/presentation/board-layout", "", nil); w.Code != 401 { + t.Fatal(w.Code) + } +} + +func TestBoardLayoutRejectsInvalidAndPreservesCorruptFile(t *testing.T) { + s, cookie := presentationServer(t) + for _, body := range []string{`{"section":"motor","open":true}`, `{"section":"computer"}`, `{"section":"computer","open":"true"}`, `{"section":"computer","open":true,"extra":0}`} { + if w := call(s, "PATCH", "/api/presentation/board-layout", body, cookie); w.Code != 400 { + t.Fatal(w.Code, w.Body.String()) + } + } + path := filepath.Join(s.Presentation.dir, "board-layout.json") + raw := []byte(`{"schema":"missioncore.board-layout/v1","revision":0,"open_sections":["motor"]}`) + if err := os.WriteFile(path, raw, 0600); err != nil { + t.Fatal(err) + } + if w := call(s, "PATCH", "/api/presentation/board-layout", `{"section":"computer","open":false}`, cookie); w.Code != 500 { + t.Fatal(w.Code) + } + got, _ := os.ReadFile(path) + if string(got) != string(raw) { + t.Fatal("Corrupt file replaced") + } +} diff --git a/apps/node-agent/internal/node/rover_channel.go b/apps/node-agent/internal/node/rover_channel.go new file mode 100644 index 0000000..329b6e2 --- /dev/null +++ b/apps/node-agent/internal/node/rover_channel.go @@ -0,0 +1,249 @@ +package node + +// Commands stream independently of telemetry. Only the local 20 Hz loop may +// deliver the latest unexpired intent to the single VESC owner. +import ( + "bufio" + "bytes" + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "io" + "log" + "net" + "net/http" + "sync" + "time" +) + +func (p *Pairing) roverBinding() *CoreBinding { + p.mu.Lock() + defer p.mu.Unlock() + if p.state.Phase != "paired" || p.state.Binding == nil { + return nil + } + b := *p.state.Binding + return &b +} +func sameRoverBinding(a, b *CoreBinding) bool { + return a != nil && b != nil && a.BindingID == b.BindingID && a.Endpoint == b.Endpoint && a.ClientPEM == b.ClientPEM && a.EndpointRevision == b.EndpointRevision +} +func roverWait(ctx context.Context, delay time.Duration) bool { + if delay < 0 { + delay = 0 + } + select { + case <-ctx.Done(): + return false + case <-time.After(delay): + return true + } +} +func (p *Pairing) roverChannel(ctx context.Context) { + for ctx.Err() == nil { + binding := p.roverBinding() + if binding != nil && p.Sensors != nil { + p.runRoverChannel(ctx, *binding) + } + if !roverWait(ctx, time.Second) { + return + } + } +} +func (p *Pairing) runRoverChannel(parent context.Context, b CoreBinding) { + config, err := bindingTLS(b, p.store.pairingKey()) + if err != nil { + return + } + transport := func() *http.Transport { + return &http.Transport{TLSClientConfig: config, Proxy: nil, + MaxConnsPerHost: 1, MaxIdleConnsPerHost: 1, IdleConnTimeout: 10 * time.Second, + TLSHandshakeTimeout: time.Second, ResponseHeaderTimeout: 2 * time.Second, + DialContext: (&net.Dialer{Timeout: time.Second}).DialContext} + } + telemetry := &http.Client{Transport: transport(), Timeout: 300 * time.Millisecond, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirect forbidden") }} + stream := &http.Client{Transport: transport(), CheckRedirect: telemetry.CheckRedirect} + defer telemetry.CloseIdleConnections() + defer stream.CloseIdleConnections() + random := make([]byte, 16) + if _, err = rand.Read(random); err != nil { + return + } + relay := hex.EncodeToString(random) + id, _ := p.store.Public() + base := map[string]any{"schema": PairSchema, "node_id": id, "binding_id": b.BindingID, + "core_endpoint": b.Endpoint, "endpoint_revision": b.EndpointRevision, "relay_id": relay} + state := newRoverStreamState(time.Now()) + ctx, cancel := context.WithCancel(parent) + var workers sync.WaitGroup + defer func() { cancel(); workers.Wait() }() + workers.Add(2) + go func() { defer workers.Done(); roverTelemetry(ctx, telemetry, b.Endpoint, base, state) }() + go func() { defer workers.Done(); roverCommands(ctx, stream, b.Endpoint, base, state) }() + var model *sensorModel + for i := range sensorModels { + if sensorModels[i].ID == "vesc.controller" { + model = &sensorModels[i] + break + } + } + if model == nil { + return + } + var diagnostic roverDiagnostics + for ctx.Err() == nil && sameRoverBinding(&b, p.roverBinding()) { + select { + case <-state.wake: + default: + } + started := time.Now() + watch, command, stop := state.delivery(started) + frame := roverFrame{} + if command != nil { + frame.Session, _ = command["id"].(string) + frame.Sequence, _ = command["sequence"].(float64) + frame.TTLMS, _ = command["ttl_ms"].(float64) + } + call, done := context.WithTimeout(ctx, 25*time.Millisecond) + result, driverErr := p.Sensors.modelDriver(call, model, "/remote", map[string]any{"watch": watch, "command": command, "relay_id": relay}) + done() + frame.DriverMS = time.Since(started).Milliseconds() + if driverErr != nil { + state.stopStream() + frame.Stage = "driver_transport" + state.delivered(map[string]any{}, 0) + } else { + state.delivered(result, stop) + frame.State, _ = result["state"].(string) + } + diagnostic.record(started, frame) + // New intent and stop signals bypass the periodic watchdog tick. The + // buffered wake channel coalesces arrivals; it never queues commands. + timer := time.NewTimer(max(0, 50*time.Millisecond-time.Since(started))) + select { + case <-ctx.Done(): + case <-state.wake: + case <-timer.C: + } + timer.Stop() + } + // Binding changes and channel shutdown explicitly retire any current intent. + call, done := context.WithTimeout(context.Background(), 25*time.Millisecond) + _, _ = p.Sensors.modelDriver(call, model, "/remote", map[string]any{"watch": false, "command": nil, "relay_id": relay}) + done() +} +func roverTelemetry(ctx context.Context, client *http.Client, endpoint string, base map[string]any, state *roverStreamState) { + var diagnostic roverDiagnostics + for ctx.Err() == nil { + started := time.Now() + snapshot, _ := state.view() + payload := make(map[string]any, len(base)+1) + for k, v := range base { + payload[k] = v + } + payload["rover"] = snapshot + raw, _ := json.Marshal(payload) + req, _ := http.NewRequestWithContext(ctx, "POST", endpoint+"/v1/node/rover", bytes.NewReader(raw)) + req.Header.Set("Content-Type", "application/json") + frame := roverFrame{} + frame.State, _ = snapshot["state"].(string) + if frame.State == "preparing" || frame.State == "ready" || frame.State == "driving" || frame.State == "stopping" { + frame.Session, _ = snapshot["session_id"].(string) + } + response, err := client.Do(req) + if err != nil { + frame.Stage = "telemetry_transport" + } else { + frame.Status = response.StatusCode + var out roverStreamReply + readErr := json.NewDecoder(io.LimitReader(response.Body, 32768)).Decode(&out) + response.Body.Close() + if readErr != nil || response.StatusCode != 200 { + frame.Stage = "telemetry_response" + } else if !state.sampleClock(out.Clock, started, time.Now()) { + frame.Stage = "clock_invalid" + state.stopStream() + } else { + state.setWatch(out.Watch) + } + } + frame.CoreMS = time.Since(started).Milliseconds() + diagnostic.record(started, frame) + _, watch := state.view() + delay := 500 * time.Millisecond + if watch { + delay = 100 * time.Millisecond + } + if !roverWait(ctx, delay-time.Since(started)) { + return + } + } +} +func roverCommands(ctx context.Context, client *http.Client, endpoint string, base map[string]any, state *roverStreamState) { + for ctx.Err() == nil { + _, watch := state.view() + if !watch { + if !roverWait(ctx, 50*time.Millisecond) { + return + } + continue + } + err := roverReadStream(ctx, client, endpoint, base, state) + state.stopStream() + if err != nil && ctx.Err() == nil { + log.Printf("{\"event\":\"rover-command-stream\",\"state\":\"disconnected\"}") + } + if !roverWait(ctx, 250*time.Millisecond) { + return + } + } +} +func roverReadStream(parent context.Context, client *http.Client, endpoint string, base map[string]any, state *roverStreamState) error { + ctx, cancel := context.WithCancel(parent) + defer cancel() + raw, _ := json.Marshal(base) + req, _ := http.NewRequestWithContext(ctx, "POST", endpoint+"/v1/node/rover-stream", bytes.NewReader(raw)) + req.Header.Set("Content-Type", "application/json") + sent := time.Now() + response, err := client.Do(req) + if err != nil { + return err + } + defer response.Body.Close() + if response.StatusCode != 200 { + return errors.New("stream rejected") + } + // The native 200 ms output watchdog is unchanged. A silent stream also + // cancels its network read and retires intent; reconnect never rearms it. + guard := time.AfterFunc(350*time.Millisecond, cancel) + defer guard.Stop() + reader := bufio.NewReaderSize(response.Body, 32768) + first := true + for { + line, err := reader.ReadSlice('\n') + if err != nil { + return err + } + var out roverStreamReply + if json.Unmarshal(line, &out) != nil { + return errors.New("invalid command frame") + } + if first { + if !state.sampleClock(out.Clock, sent, time.Now()) { + return errors.New("invalid stream clock") + } + first = false + } + if !state.accept(out) { + return errors.New("invalid stream intent") + } + if !out.Watch { + return nil + } + if !guard.Reset(350 * time.Millisecond) { + return errors.New("stream deadline") + } + } +} diff --git a/apps/node-agent/internal/node/rover_diagnostics.go b/apps/node-agent/internal/node/rover_diagnostics.go new file mode 100644 index 0000000..aa600df --- /dev/null +++ b/apps/node-agent/internal/node/rover_diagnostics.go @@ -0,0 +1,61 @@ +package node + +// A bounded memory flight recorder. It never stores endpoints, certificates, +// payloads or raw HTTP errors, and never changes admission or lease deadlines. +import ( + "encoding/json" + "log" + "time" +) + +type roverFrame struct { + AtMS int64 `json:"at_ms"` + GapMS int64 `json:"gap_ms"` + BindingMS int64 `json:"binding_ms"` + CoreMS int64 `json:"core_ms"` + DriverMS int64 `json:"driver_ms"` + Status int `json:"http_status"` + Stage string `json:"error_stage,omitempty"` + Session string `json:"session,omitempty"` + Sequence float64 `json:"sequence"` + TTLMS float64 `json:"ttl_ms"` + State string `json:"state"` +} + +type roverDiagnostics struct { + frames []roverFrame + last time.Time + started time.Time + state string + session string + emit func([]byte) +} + +func (d *roverDiagnostics) record(at time.Time, frame roverFrame) { + if d.started.IsZero() { + d.started = at + } + frame.AtMS = at.Sub(d.started).Milliseconds() + if !d.last.IsZero() { + frame.GapMS = at.Sub(d.last).Milliseconds() + } + d.last = at + d.frames = append(d.frames, frame) + if len(d.frames) > 128 { + d.frames = d.frames[len(d.frames)-128:] + } + active := frame.Session != "" || d.session != "" + changed := frame.State != d.state || frame.Session != d.session + if active && (changed || frame.Stage != "" || frame.GapMS >= 200) { + raw, _ := json.Marshal(struct { + Event string `json:"event"` + Frames []roverFrame `json:"frames"` + }{"rover-channel", d.frames}) + if d.emit != nil { + d.emit(raw) + } else { + log.Printf("%s", raw) + } + } + d.state, d.session = frame.State, frame.Session +} diff --git a/apps/node-agent/internal/node/rover_diagnostics_test.go b/apps/node-agent/internal/node/rover_diagnostics_test.go new file mode 100644 index 0000000..20e23a4 --- /dev/null +++ b/apps/node-agent/internal/node/rover_diagnostics_test.go @@ -0,0 +1,63 @@ +package node + +import ( + "encoding/json" + "testing" + "time" +) + +func TestRoverDiagnosticsRetainsCancellationCauseWithoutIdleLogSpam(t *testing.T) { + var events [][]byte + d := roverDiagnostics{emit: func(b []byte) { events = append(events, b) }} + at := time.Unix(100, 0) + for i := 0; i < 200; i++ { + d.record(at.Add(time.Duration(i)*50*time.Millisecond), roverFrame{State: "observing"}) + } + if len(events) != 0 || len(d.frames) != 128 { + t.Fatal("idle must remain bounded and quiet") + } + at = at.Add(11 * time.Second) + d.record(at, roverFrame{Session: "session", Sequence: 1, TTLMS: 350, State: "preparing"}) + d.record(at.Add(100*time.Millisecond), roverFrame{Session: "session", Sequence: 2, TTLMS: 320, State: "preparing"}) + if len(events) != 1 { + t.Fatal("unchanged healthy frames should remain in memory") + } + d.record(at.Add(450*time.Millisecond), roverFrame{CoreMS: 300, Stage: "core_transport", State: "preparing"}) + if len(events) != 2 { + t.Fatal("lost command needs diagnostic evidence") + } + var event struct { + Frames []roverFrame `json:"frames"` + } + if err := json.Unmarshal(events[1], &event); err != nil { + t.Fatal(err) + } + last := event.Frames[len(event.Frames)-1] + if last.Stage != "core_transport" || last.GapMS != 350 || last.CoreMS != 300 || last.Session != "" { + t.Fatal(last) + } + if event.Frames[len(event.Frames)-2].Sequence != 2 { + t.Fatal("last accepted frame lost") + } +} + +func TestRoverDiagnosticsRecordsBindingWaitAndDriverTerminalState(t *testing.T) { + var events [][]byte + d := roverDiagnostics{emit: func(b []byte) { events = append(events, b) }} + at := time.Unix(100, 0) + d.record(at, roverFrame{Session: "session", State: "preparing"}) + d.record(at.Add(500*time.Millisecond), roverFrame{Session: "session", State: "stopped", BindingMS: 400, DriverMS: 2}) + if len(events) != 2 { + t.Fatal("terminal state must flush preceding transport history") + } + var event struct { + Frames []roverFrame `json:"frames"` + } + if err := json.Unmarshal(events[1], &event); err != nil { + t.Fatal(err) + } + last := event.Frames[len(event.Frames)-1] + if last.BindingMS != 400 || last.DriverMS != 2 || last.State != "stopped" { + t.Fatal(last) + } +} diff --git a/apps/node-agent/internal/node/rover_stream_state.go b/apps/node-agent/internal/node/rover_stream_state.go new file mode 100644 index 0000000..692aa86 --- /dev/null +++ b/apps/node-agent/internal/node/rover_stream_state.go @@ -0,0 +1,199 @@ +package node + +import ( + "encoding/hex" + "math" + "sync" + "time" +) + +type roverClock struct { + Instance string `json:"instance"` + MonotonicMS float64 `json:"monotonic_ms"` +} +type roverStreamReply struct { + Watch bool `json:"watch"` + Command map[string]any `json:"command"` + Clock roverClock `json:"control_clock"` +} + +// Clock bounds use the request-send time, never RTT/2 or synchronized wall +// clocks. Server time was sampled after that send, so it gives an upper bound +// on server-minus-local monotonic offset even on an asymmetric network. +type roverStreamState struct { + mu sync.Mutex + origin time.Time + clockID string + upperMS float64 + anchored time.Time + clockSeen time.Time + command map[string]any + watch bool + stopPending bool + stopRevision uint64 + snapshot map[string]any + retired map[string]bool + inhibited bool + wake chan struct{} +} + +func newRoverStreamState(now time.Time) *roverStreamState { + return &roverStreamState{origin: now, stopPending: true, stopRevision: 1, snapshot: map[string]any{}, retired: map[string]bool{}, wake: make(chan struct{}, 1)} +} +func finiteNumber(v any) (float64, bool) { + n, ok := v.(float64) + return n, ok && !math.IsNaN(n) && !math.IsInf(n, 0) +} +func (s *roverStreamState) sampleClock(c roverClock, sent, received time.Time) bool { + if len(c.Instance) != 32 { + return false + } + if _, err := hex.DecodeString(c.Instance); err != nil { + return false + } + if math.IsNaN(c.MonotonicMS) || math.IsInf(c.MonotonicMS, 0) || c.MonotonicMS < 0 || received.Before(sent) { + return false + } + s.mu.Lock() + defer s.mu.Unlock() + upper := c.MonotonicMS - float64(sent.Sub(s.origin).Microseconds())/1000 + 1 + if c.Instance != s.clockID { + s.invalidate() + s.clockID = c.Instance + s.upperMS = upper + s.anchored = received + } else if s.clockSeen.IsZero() || received.Sub(s.clockSeen) > 2*time.Second || upper < s.upperMS+float64(received.Sub(s.anchored).Microseconds())/1e6 { + s.upperMS = upper + s.anchored = received + } + s.clockSeen = received + return true +} +func (s *roverStreamState) accept(reply roverStreamReply) bool { + s.mu.Lock() + defer s.mu.Unlock() + if reply.Clock.Instance != s.clockID || s.clockID == "" { + return false + } + if reply.Command == nil { + if s.command != nil { + s.invalidate() + } + return true + } + command := reply.Command + if len(command) != 6 { + return false + } + for _, k := range []string{"id", "sequence", "left", "right", "settings", "expires_mono_ms"} { + if _, ok := command[k]; !ok { + return false + } + } + expires, ok := finiteNumber(command["expires_mono_ms"]) + if !ok || expires > reply.Clock.MonotonicMS+400.001 { + return false + } + id, ok := command["id"].(string) + if !ok || len(id) != 32 { + return false + } + if _, err := hex.DecodeString(id); err != nil { + return false + } + sequence, ok := finiteNumber(command["sequence"]) + if !ok || sequence < 0 || sequence >= 1<<53 || math.Trunc(sequence) != sequence { + return false + } + if s.inhibited || s.retired[id] { + return true + } + // The native driver independently validates identity, settings and sequence. + if s.stopPending { + s.retire(id) + return true + } + changed := s.command == nil || s.command["id"] != id || s.command["sequence"] != sequence + s.command = command + if changed { + s.notify() + } + return true +} +func (s *roverStreamState) notify() { + select { + case s.wake <- struct{}{}: + default: + } +} +func (s *roverStreamState) stopStream() { + s.mu.Lock() + defer s.mu.Unlock() + s.invalidate() +} +func (s *roverStreamState) retire(id string) { + if len(s.retired) >= 1024 { + s.inhibited = true // Fail closed instead of forgetting interrupted sessions. + return + } + s.retired[id] = true +} +func (s *roverStreamState) invalidate() { + wake := !s.stopPending || s.command != nil + if s.command != nil { + if id, ok := s.command["id"].(string); ok { + s.retire(id) + } + } + s.command = nil + s.stopPending = true + s.stopRevision++ + if wake { + s.notify() + } +} +func (s *roverStreamState) delivery(now time.Time) (bool, map[string]any, uint64) { + s.mu.Lock() + defer s.mu.Unlock() + if s.stopPending { + return s.watch, nil, s.stopRevision + } + if s.command == nil { + return s.watch, nil, 0 + } + if now.Sub(s.clockSeen) > 2*time.Second { + s.invalidate() + return s.watch, nil, s.stopRevision + } + expires, _ := finiteNumber(s.command["expires_mono_ms"]) + // Reserve 25 ms for the private driver RPC and 5 ms plus 1000 ppm for clock + // quantization/rate uncertainty. Expiry is never extended by receipt time. + serverUpper := float64(now.Sub(s.origin).Microseconds())/1000 + s.upperMS + 5 + float64(now.Sub(s.anchored).Microseconds())/1e6 + ttl := math.Min(400, expires-serverUpper-25) + if ttl <= 0 { + s.invalidate() + return s.watch, nil, s.stopRevision + } + out := make(map[string]any, 6) + for k, v := range s.command { + if k != "expires_mono_ms" { + out[k] = v + } + } + out["ttl_ms"] = ttl + return s.watch, out, 0 +} +func (s *roverStreamState) delivered(snapshot map[string]any, stop uint64) { + s.mu.Lock() + defer s.mu.Unlock() + s.snapshot = snapshot + if stop != 0 && stop == s.stopRevision { + s.stopPending = false + } +} +func (s *roverStreamState) view() (map[string]any, bool) { + s.mu.Lock() + defer s.mu.Unlock() + return s.snapshot, s.watch +} +func (s *roverStreamState) setWatch(watch bool) { s.mu.Lock(); s.watch = watch; s.mu.Unlock() } diff --git a/apps/node-agent/internal/node/rover_stream_state_test.go b/apps/node-agent/internal/node/rover_stream_state_test.go new file mode 100644 index 0000000..5948426 --- /dev/null +++ b/apps/node-agent/internal/node/rover_stream_state_test.go @@ -0,0 +1,235 @@ +package node + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "testing" + "time" +) + +const testClockID = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + +func streamIntent(sequence int, serverNow, expires float64) roverStreamReply { + return roverStreamReply{Watch: true, Clock: roverClock{testClockID, serverNow}, Command: map[string]any{ + "id": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "sequence": float64(sequence), "left": float64(1), "right": float64(1), + "settings": map[string]any{"standstill_confirmed": true, "current_a": float64(30), "max_erpm": float64(2000)}, "expires_mono_ms": expires}} +} +func acknowledgeStop(s *roverStreamState, at time.Time) { + _, _, revision := s.delivery(at) + s.delivered(map[string]any{"state": "observing"}, revision) +} +func TestRoverStreamAsymmetricDelayRetainsOriginalExpiry(t *testing.T) { + origin := time.Unix(100, 0) + s := newRoverStreamState(origin) + // Core's clock is +10 seconds. Request took 70 ms outbound and 130 ms + // inbound: dividing RTT in half would be incorrect on this connection. + if !s.sampleClock(roverClock{testClockID, 10070}, origin, origin.Add(200*time.Millisecond)) { + t.Fatal("clock") + } + acknowledgeStop(s, origin.Add(200*time.Millisecond)) + frame := streamIntent(1, 10200, 10600) + if !s.accept(frame) { + t.Fatal("intent") + } + _, command, _ := s.delivery(origin.Add(280 * time.Millisecond)) + if command == nil { + t.Fatal("fresh streamed intent rejected") + } + ttl := command["ttl_ms"].(float64) + if ttl <= 0 || 280+ttl > 600 { + t.Fatal("delay extended original browser deadline", ttl) + } + // Replaying the same frame does not receive a new deadline. + if !s.accept(frame) { + t.Fatal("repeat") + } + _, late, _ := s.delivery(origin.Add(650 * time.Millisecond)) + if late != nil { + t.Fatal("expired frame revived motor intent") + } +} +func TestRoverStreamContinuousInputSurvivesMeasuredRelayJitter(t *testing.T) { + origin := time.Unix(100, 0) + s := newRoverStreamState(origin) + s.sampleClock(roverClock{testClockID, 10050}, origin, origin.Add(150*time.Millisecond)) + acknowledgeStop(s, origin.Add(150*time.Millisecond)) + priorUntil := float64(0) + for i, delay := range []int{60, 90, 45, 110, 80, 50, 100, 60, 90, 50} { + sent := 200 + i*100 + arrival := sent + delay + s.accept(streamIntent(i+1, float64(10000+sent), float64(10400+sent))) + if i > 0 && float64(arrival) >= priorUntil { + t.Fatal("lease gap under measured jitter", i, arrival, priorUntil) + } + _, command, _ := s.delivery(origin.Add(time.Duration(arrival) * time.Millisecond)) + if command == nil { + t.Fatal("fresh command lost", i) + } + priorUntil = float64(arrival) + command["ttl_ms"].(float64) + if priorUntil > float64(sent+400) { + t.Fatal("end-to-end deadline expanded") + } + } +} +func TestRoverStreamDisconnectNeedsAcknowledgedStopBeforeNewFrames(t *testing.T) { + origin := time.Unix(100, 0) + s := newRoverStreamState(origin) + s.sampleClock(roverClock{testClockID, 10000}, origin, origin) + acknowledgeStop(s, origin) + s.accept(streamIntent(1, 10000, 10400)) + s.stopStream() + _, _, oldStop := s.delivery(origin) + s.stopStream() // Another disconnect races the local driver's response. + s.delivered(map[string]any{}, oldStop) + s.accept(streamIntent(2, 10000, 10400)) + _, command, newStop := s.delivery(origin) + if command != nil || newStop == 0 || newStop == oldStop { + t.Fatal("stale ACK removed stop barrier") + } + s.delivered(map[string]any{}, newStop) + _, command, _ = s.delivery(origin) + if command != nil { + t.Fatal("frame received before acknowledged stop was queued") + } +} +func TestRoverStreamClockChangeAndStaleClockDisarm(t *testing.T) { + origin := time.Unix(100, 0) + s := newRoverStreamState(origin) + s.sampleClock(roverClock{testClockID, 10000}, origin, origin) + acknowledgeStop(s, origin) + s.accept(streamIntent(1, 10000, 10400)) + s.sampleClock(roverClock{"cccccccccccccccccccccccccccccccc", 2}, origin, origin) + _, command, stop := s.delivery(origin) + if command != nil || stop == 0 { + t.Fatal("Core restart retained intent") + } + if s.accept(streamIntent(2, 10000, 10400)) { + t.Fatal("old clock accepted") + } + acknowledgeStop(s, origin) + s.sampleClock(roverClock{testClockID, 10000}, origin, origin) + acknowledgeStop(s, origin) + // A fresh-looking frame alone cannot renew the clock calibration. + fresh := streamIntent(3, 13000, 13400) + fresh.Command["id"] = "dddddddddddddddddddddddddddddddd" + s.accept(fresh) + _, command, stop = s.delivery(origin.Add(3 * time.Second)) + if command != nil || stop == 0 { + t.Fatal("stale clock allowed output") + } +} + +func TestRoverStreamUnsentIntentCannotStartAfterReconnect(t *testing.T) { + origin := time.Unix(100, 0) + s := newRoverStreamState(origin) + s.sampleClock(roverClock{testClockID, 10000}, origin, origin) + acknowledgeStop(s, origin) + frame := streamIntent(1, 10000, 10400) + s.accept(frame) + // The network fails before the local driver ever sees this session. + s.stopStream() + acknowledgeStop(s, origin) + s.accept(streamIntent(2, 10010, 10410)) + _, command, _ := s.delivery(origin) + if command != nil { + t.Fatal("undelivered old session started after reconnect") + } + frame.Command["id"] = "dddddddddddddddddddddddddddddddd" + s.accept(frame) + _, command, _ = s.delivery(origin) + if command == nil { + t.Fatal("new explicit session rejected after stop") + } +} + +func TestRoverStreamIntentWakesImmediatelyAndCoalescesWithoutReplayWake(t *testing.T) { + origin := time.Unix(100, 0) + s := newRoverStreamState(origin) + s.sampleClock(roverClock{testClockID, 10000}, origin, origin) + acknowledgeStop(s, origin) + for i := 1; i <= 3; i++ { + s.accept(streamIntent(i, 10000, 10400)) + } + if len(s.wake) != 1 { + t.Fatal("intent notifications must coalesce") + } + <-s.wake + _, command, _ := s.delivery(origin) + if command["sequence"] != float64(3) { + t.Fatal("queued an intermediate command") + } + s.accept(streamIntent(3, 10000, 10400)) + if len(s.wake) != 0 { + t.Fatal("replayed frame woke driver again") + } + s.stopStream() + if len(s.wake) != 1 { + t.Fatal("stop did not wake driver") + } + <-s.wake + s.stopStream() + if len(s.wake) != 0 { + t.Fatal("repeated failure would spin the local loop") + } +} +func TestRoverStreamRejectsExtendedDeadlineAndUnknownCommandFields(t *testing.T) { + origin := time.Unix(100, 0) + s := newRoverStreamState(origin) + s.sampleClock(roverClock{testClockID, 10000}, origin, origin) + acknowledgeStop(s, origin) + if s.accept(streamIntent(1, 10000, 10401)) { + t.Fatal("extended deadline accepted") + } + frame := streamIntent(1, 10000, 10400) + frame.Command["queued"] = true + if s.accept(frame) { + t.Fatal("unknown field accepted") + } + for _, sequence := range []any{map[string]any{}, []any{1}, "1", 1.5, float64(1 << 53)} { + bad := streamIntent(1, 10000, 10400) + bad.Command["sequence"] = sequence + if s.accept(bad) { + t.Fatal("malformed sequence accepted") + } + } +} +func TestRoverStreamSilenceCancelsReadWithoutWaitingForTelemetry(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/x-ndjson") + json.NewEncoder(w).Encode(roverStreamReply{Watch: true, Clock: roverClock{testClockID, 10000}}) + w.(http.Flusher).Flush() + <-r.Context().Done() + })) + defer server.Close() + state := newRoverStreamState(time.Now()) + started := time.Now() + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + if roverReadStream(ctx, server.Client(), server.URL, map[string]any{}, state) == nil { + t.Fatal("silent stream accepted") + } + if time.Since(started) > time.Second { + t.Fatal("silent stream did not cancel its read") + } +} +func TestRoverStreamReadsMultipleFramesOnOneResponse(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/v1/node/rover-stream" { + t.Error("wrong path") + } + w.Header().Set("Content-Type", "application/x-ndjson") + for i := 0; i < 3; i++ { + raw, _ := json.Marshal(roverStreamReply{Watch: i < 2, Clock: roverClock{testClockID, 10000 + float64(i)}}) + fmt.Fprintln(w, string(raw)) + w.(http.Flusher).Flush() + } + })) + defer server.Close() + state := newRoverStreamState(time.Now()) + if err := roverReadStream(context.Background(), server.Client(), server.URL, map[string]any{}, state); err != nil { + t.Fatal(err) + } +} diff --git a/packages/rover-control/README.md b/packages/rover-control/README.md new file mode 100644 index 0000000..8fa845b --- /dev/null +++ b/packages/rover-control/README.md @@ -0,0 +1,107 @@ +# Rover control behaviour prototype + +Status: **offline behavioural reference; no production actuation adapter**. +Requested by the owner while unavailable for physical testing, 2026-09-24. +Neither Core composition nor Node/VESC runtime imports these modules. No new +driver, service, firmware, motor settings or authority capability is installed. + +`src/profile.ts` contains the versioned desired-profile parser, Tank and Arcade +mixers, continuous deadband, linear/squared response, relative output scaling, +and fan-out to any number of UUID-bound motors on both sides. UUIDs must be +unique; a missing side is rejected. `forwardSign` is the verified sign at the +future actuator adapter, not a copy of `m_invert_direction` and not a second +automatic inversion of the current VESC configuration. + +The normalized result has no electrical units. It cannot be sent as amperes, +watts, duty, ERPM or speed without a separately qualified adapter and individual +motor, battery/BMS and braking limits. A profile output scale of 80% is **not** +the owner's proposed 20% safety margin against verified equipment ratings. +The current real RC path is PPM Duty Cycle; this prototype does not change it. + +Arcade uses continuous diamond desaturation, with forward positive and right +yaw positive. For shaped inputs `v` and `r`, the pair is `(v+r, v-r)` multiplied +by `max(abs(v),abs(r))/(abs(v)+abs(r))`, or zero at the origin. This follows the +WPILib ArcadeDriveIK geometry with the steering sign adapted to the UI. +Reverse plus right still requests right yaw; it is not a car steering-wheel +convention, curvature drive, a turn-radius controller or omnidirectional motion. +No VESC Tool calibration algorithm is reproduced. + +References inspected 2026-09-24: + +- [WPILib drive classes](https://docs.wpilib.org/en/stable/docs/software/hardware-apis/motors/wpi-drive-classes.html) +- [ArcadeDriveIK source](https://github.com/wpilibsuite/allwpilib/blob/main/wpilibc/src/main/native/cpp/drive/DifferentialDrive.cpp) + +## Authority model + +`src/authority.ts` is a pure deterministic model. Its output contains **intent** +to stop all drives, revoke the Core epoch, flush queued motion and cancel +autonomous motion tasks; it does not actually stop a motor or cancel a process. +The future actuator must enforce the gate synchronously before asynchronous +task cancellation. RC reception, drive supervision and telemetry must survive. + +Boot, input loss, controller loss, stale/invalid data, a timing gap or Core +command loss enter hold. First RC deflection while Core owns motion consumes +the gesture and revokes the old token. Every assigned input must then be neutral +and every motor must have trusted physical-stop evidence for the full configured +interval. A held first gesture or repeated packet does not qualify. The next +gesture starts RC manual operation. Neutral never resumes the previous Core +task. Reacquisition requires a new explicit, nonreplayed request in neutral. +Old Core commands cannot cross an epoch or process boot identity. + +Policy values are mandatory constructor arguments. The demo uses 100 ms +freshness / 200 ms neutral solely as synthetic fixtures, **not accepted rover +reaction limits**. Use one monotonic clock domain from an authenticated local +producer and a fresh unpredictable boot identity per instance. A token is a +stale-command fence, not authentication or a replacement for access control. +Calls and input types belong to a trusted model harness; this is not a public +network request parser. Run a supervisory tick even when no new input arrives. + +`link.live`, sample acquisition timestamps/sequences and `drive.stopped` must +come from qualified evidence. A fresh USB response with old decoded PPM does +not meet this contract. Zero motor current/duty alone is not physical stop. +The current FW 5.02 input API does not supply all required evidence. In +particular, stop-first independent of Mini needs an enforcement point outside +Mini and coordination of **all** motor controllers. No such qualified mechanism +is claimed by these tests. Receiver failsafe is also still awaiting acceptance. + +Input axes are semantic controls, not invented receiver channels. The mixer for +Tank requires two Y axes; Arcade requires both axes of the selected stick. The +authority policy separately declares all `monitoredAxes`: the demo watches all +four axes, so the other stick also stops Core in Arcade. Missing monitored axes +are rejected, not synthesized as zero; all must return to neutral. The current two +separate receiver-to-VESC PWM outputs do not establish access to those Arcade +axes. The channel map, radio-link semantics and independent mixed RC path remain +hardware integration work. Profile revision or binding changes require a fresh +model initialized in hold, not an in-place live change. + +## Preview and validation + +Use the already installed Control Station toolchain; no new dependencies: + +```sh +cd apps/control-station +node --test test/roverControl.test.mjs +./node_modules/.bin/tsc --project tools/rover-control-preview/tsconfig.json +node tools/rover-control-preview/build.mjs /absolute/artifact/directory +``` + +The self-contained HTML uses canonical Design Guideline components. Its CSP +disables all network connections, and no transport/serial code exists in the +bundle. It is an owner-review artifact, outside production navigation. Browser +storage and JSON export contain a **draft**, never confirmed applied state. +It does not add USB controls, device-specific phantom entities or a runtime +source-selection switch to the product. The synthetic takeover trace is +engineering review content, not a proposed operator control panel. + +Intended product placement remains the existing shared «Настройки борта» section +on Core and Node, between computer details and devices. Alternatives (a new +workspace or separate per-VESC control-mode selectors) would fragment a single +vehicle-wide profile and are not used. Existing `Inspector`, `SettingsCard`, +`InspectorSelectField`, `RangeControl`, `Button`, `StatusBadge` cover the review; +no Design Guideline extensions or new visual primitives were needed. + +Before production integration: verified input mapping and radio failsafe, +independent stop-first actuator mechanism, desired/applied profile storage on +Node with optimistic revision checking, all-member application receipts and +failure recovery, then shared UI and supervised unloaded tests. Do not expose +an enabled Apply button based only on successful model tests. diff --git a/packages/rover-control/src/authority.ts b/packages/rover-control/src/authority.ts new file mode 100644 index 0000000..59dcc27 --- /dev/null +++ b/packages/rover-control/src/authority.ts @@ -0,0 +1,134 @@ +/** Behavioural reference ONLY. Not connected to the current VESC PPM path. */ +import {axisKeys, bounded, mix, parseProfile, type Axes, type ControlProfile, type Sides} from './profile'; + +export interface Sample { value: number; at: number; sequence: number } +export interface DriveEvidence { at: number; healthy: boolean; stopped: boolean } +export interface CoreCommand { + token: string; sequence: number; at: number; expires: number; demand: Sides; +} +export interface Observation { + now: number; + // These are trusted receiver timestamps and link status, NOT USB read times. + link: { state: 'live' | 'lost' | 'unknown'; at: number }; + axes: Partial>; + drives: Record; + command?: CoreCommand; + requestCore?: {owner: 'remote' | 'autonomy'; sequence: number; at: number}; +} +export interface Policy { + maxAgeMs: number; neutralMs: number; maxCommandMs: number; + /** Verified RC controls that can take over, including non-driving stick axes. */ + monitoredAxes: readonly (keyof Axes)[]; +} +export type State = 'hold' | 'rc-ready' | 'rc-manual' | 'core'; +export interface Decision { + state: State; reason: string; demand: Sides; token: string | null; + owner: 'remote' | 'autonomy' | 'rc' | null; + stopAll: boolean; flushMotionQueue: boolean; cancelMotionTasks: boolean; +} +const zero = (): Sides => ({left: 0, right: 0}); + +export class AuthorityModel { + private state: State = 'hold'; + private epoch = 0; + private token: string | null = null; + private owner: Decision['owner'] = null; + private neutralSince: number | null = null; + private lastNow = -Infinity; + private lastCommand = -1; + private lastRequest = -1; + private samples: Partial> = {}; + private readonly profile: ControlProfile; + private readonly motors: string[]; + private readonly policy: Policy; + + constructor(profile: ControlProfile, motors: readonly string[], policy: Policy, private readonly bootId: string) { + this.profile = parseProfile(profile); + this.motors = [...motors]; this.policy = {...policy, monitoredAxes:[...policy.monitoredAxes]}; + if (!bootId || !motors.length || new Set(motors).size !== motors.length || motors.some(id => !id) + || !bounded(policy.maxAgeMs, 1, 10000) || !bounded(policy.neutralMs, 1, 10000) + || !bounded(policy.maxCommandMs, 1, 10000) + || new Set(policy.monitoredAxes).size !== policy.monitoredAxes.length + || policy.monitoredAxes.some(key => !['leftY','rightY','leftX','rightX'].includes(key)) + || axisKeys(this.profile).some(key => !policy.monitoredAxes.includes(key))) throw Error('Invalid authority policy'); + } + private result(reason: string, demand = zero(), revoke = false): Decision { + return {state: this.state, reason, demand, token: this.token, owner: this.owner, + stopAll: this.state === 'hold', flushMotionQueue: revoke, cancelMotionTasks: revoke}; + } + private hold(reason: string): Decision { + const revoke = this.state === 'core'; + if (this.state !== 'hold') this.epoch++; + this.state = 'hold'; this.token = null; this.owner = null; + this.neutralSince = null; this.lastCommand = -1; + return this.result(reason, zero(), revoke); + } + step(input: Observation): Decision { + const now = input.now; + if (!Number.isFinite(now) || now < 0 || now < this.lastNow) return this.hold('clock-invalid'); + const gap = now - this.lastNow; this.lastNow = now; + const fresh = (at: number) => Number.isFinite(at) && at <= now && now - at <= this.policy.maxAgeMs; + const request = input.requestCore; + const newRequest = !!request && Number.isSafeInteger(request.sequence) && request.sequence > this.lastRequest; + // Consume even a premature request: it must never become effective later. + if (newRequest) this.lastRequest = request.sequence; + // A gap cannot count towards continuous observed neutral. + if (gap > this.policy.maxAgeMs) { + const first = gap === Infinity; + if (!first) return this.hold('observation-gap'); + this.neutralSince = null; + } + if (input.link?.state !== 'live' || !fresh(input.link.at)) return this.hold('receiver-unverified'); + const axes = {leftY: 0, rightY: 0, leftX: 0, rightX: 0}; + let neutral = true; + let observedThrough = input.link.at; + const candidates: Partial> = {}; + for (const key of this.policy.monitoredAxes) { + const sample = input.axes[key], prev = this.samples[key]; + if (!sample || !bounded(sample.value, -1, 1) || !fresh(sample.at) + || !Number.isSafeInteger(sample.sequence) || sample.sequence < 0 + || (prev && (sample.sequence < prev.sequence || sample.at < prev.at + || (sample.sequence === prev.sequence && (sample.value !== prev.value || sample.at !== prev.at))))) + return this.hold('axis-invalid'); + candidates[key] = {...sample}; axes[key] = sample.value; + observedThrough = Math.min(observedThrough, sample.at); + neutral &&= Math.abs(sample.value) <= this.profile.deadband; + } + this.samples = candidates; + let stopped = true; + for (const id of this.motors) { + const drive = input.drives[id]; + if (!drive || drive.healthy !== true || !fresh(drive.at)) return this.hold('drive-unverified'); + observedThrough = Math.min(observedThrough, drive.at); + stopped &&= drive.stopped === true; + } + // RC intent is evaluated before any Core command or reacquisition request. + if (this.state === 'core' && !neutral) return this.hold('rc-takeover'); + if (neutral && stopped) this.neutralSince ??= now; + else this.neutralSince = null; + const stableNeutral = this.neutralSince !== null && observedThrough - this.neutralSince >= this.policy.neutralMs; + if (this.state === 'hold') { + if (!stableNeutral) return this.result(stopped ? 'await-neutral' : 'await-stop'); + this.state = 'rc-ready'; this.owner = 'rc'; + // A request queued before reaching neutral cannot acquire Core authority. + return this.result('rc-ready'); + } + if (newRequest && request && fresh(request.at) && this.state !== 'core' && stableNeutral) { + if (!['remote', 'autonomy'].includes(request.owner)) return this.hold('source-invalid'); + this.epoch++; this.token = `${this.bootId}:${this.epoch}:${this.profile.revision}`; + this.owner = request.owner; this.state = 'core'; this.lastCommand = -1; + return this.result('core-granted'); + } + if (this.state === 'core') { + const c = input.command; + if (!c || c.token !== this.token || !Number.isSafeInteger(c.sequence) || c.sequence <= this.lastCommand + || !fresh(c.at) || !Number.isFinite(c.expires) || c.expires <= now + || c.expires - c.at > this.policy.maxCommandMs || c.expires < c.at + || !bounded(c.demand.left, -1, 1) || !bounded(c.demand.right, -1, 1)) return this.hold('core-command-invalid'); + this.lastCommand = c.sequence; + return this.result('core-command', {left: c.demand.left * this.profile.outputScale, right: c.demand.right * this.profile.outputScale}); + } + if (this.state === 'rc-ready' && !neutral) this.state = 'rc-manual'; + return this.result(neutral ? 'rc-neutral' : 'rc-command', mix(this.profile, axes)); + } +} diff --git a/packages/rover-control/src/profile.ts b/packages/rover-control/src/profile.ts new file mode 100644 index 0000000..b5ba470 --- /dev/null +++ b/packages/rover-control/src/profile.ts @@ -0,0 +1,72 @@ +/** Executable profile proposal. Pure calculations; no hardware or transport. */ +export interface ControlProfile { + schema: 'missioncore.rover-control/v1'; + revision: number; + mode: 'tank' | 'arcade'; + stick: 'left' | 'right'; + deadband: number; + response: 'linear' | 'squared'; + outputScale: number; +} +export interface Axes { leftY: number; rightY: number; leftX: number; rightX: number } +export interface Sides { left: number; right: number } +export interface MotorBinding { uuid: string; side: 'left' | 'right'; forwardSign: 1 | -1 } + +export const defaultProfile: Readonly = Object.freeze({ + schema: 'missioncore.rover-control/v1', revision: 0, mode: 'tank', stick: 'right', + deadband: 0.15, response: 'linear', outputScale: 1, +}); +export function bounded(value: unknown, min: number, max: number): value is number { + return typeof value === 'number' && Number.isFinite(value) && value >= min && value <= max; +} +export function parseProfile(value: unknown): ControlProfile { + if (!value || typeof value !== 'object' || Array.isArray(value)) throw Error('Invalid profile'); + const p = value as ControlProfile; + if (Object.keys(p).sort().join() !== Object.keys(defaultProfile).sort().join() + || p.schema !== defaultProfile.schema || !Number.isSafeInteger(p.revision) || p.revision < 0 + || !['tank', 'arcade'].includes(p.mode) || !['left', 'right'].includes(p.stick) + || !['linear', 'squared'].includes(p.response) || !bounded(p.deadband, 0, 0.5) + || !bounded(p.outputScale, 0, 1)) throw Error('Invalid profile'); + return {...p}; +} +export function axisKeys(profile: ControlProfile): (keyof Axes)[] { + return profile.mode === 'tank' ? ['leftY', 'rightY'] + : profile.stick === 'right' ? ['rightY', 'rightX'] : ['leftY', 'leftX']; +} +export function shapeAxis(value: number, profile: ControlProfile): number { + if (!bounded(value, -1, 1)) throw Error('Invalid axis'); + const magnitude = Math.max(0, (Math.abs(value) - profile.deadband) / (1 - profile.deadband)); + return Math.sign(value) * (profile.response === 'squared' ? magnitude * magnitude : magnitude); +} +/** +Y = forward, +X = turn right, including while reversing (yaw convention). + * Arcade diamond desaturation follows the documented WPILib ArcadeDriveIK + * convention, with clockwise steering sign adapted here. Output is normalized + * demand, NOT amps, watts, ERPM, physical velocity, or a guaranteed turn radius. + */ +export function mix(profile: ControlProfile, axes: Axes): Sides { + parseProfile(profile); + for (const key of axisKeys(profile)) if (!bounded(axes[key], -1, 1)) throw Error('Missing or invalid axis'); + let left: number, right: number; + if (profile.mode === 'tank') { + left = shapeAxis(axes.leftY, profile); right = shapeAxis(axes.rightY, profile); + } else { + const throttle = shapeAxis(profile.stick === 'right' ? axes.rightY : axes.leftY, profile); + const turn = shapeAxis(profile.stick === 'right' ? axes.rightX : axes.leftX, profile); + const peak = Math.max(Math.abs(throttle), Math.abs(turn)); + const scale = peak === 0 ? 0 : peak / (Math.abs(throttle) + Math.abs(turn)); + left = (throttle + turn) * scale; right = (throttle - turn) * scale; + } + return {left: left * profile.outputScale || 0, right: right * profile.outputScale || 0}; +} +/** All members of both sides are required, irrespective of 1x1/2x2/6x6. */ +export function motorDemands(sides: Sides, bindings: readonly MotorBinding[]): Record { + if (!bounded(sides.left, -1, 1) || !bounded(sides.right, -1, 1) + || !bindings.some(b => b.side === 'left') || !bindings.some(b => b.side === 'right')) throw Error('Incomplete drive'); + const values: Record = Object.create(null); + for (const b of bindings) { + if (!/^[0-9a-f]{24}$/.test(b.uuid) || b.uuid in values || !['left', 'right'].includes(b.side) + || ![1, -1].includes(b.forwardSign)) throw Error('Invalid motor binding'); + values[b.uuid] = sides[b.side] * b.forwardSign || 0; + } + return values; +} diff --git a/packages/sensor-ui/src/BoardSections.tsx b/packages/sensor-ui/src/BoardSections.tsx new file mode 100644 index 0000000..9f21564 --- /dev/null +++ b/packages/sensor-ui/src/BoardSections.tsx @@ -0,0 +1,23 @@ +import {useEffect,useSyncExternalStore,type ReactNode} from 'react'; +import {Button,Icon,Inspector,LoadingRegion} from '@nodedc/ui-react'; +import type {BoardLayoutStore} from './boardLayout'; + +export interface BoardSectionsProps { + layout:BoardLayoutStore; + computer:ReactNode; + description?:string; +} +export function BoardSections({layout,computer,description,settings,devices}:BoardSectionsProps&{settings:ReactNode;devices:ReactNode}){ + const state=useSyncExternalStore(layout.subscribe,layout.getSnapshot); + useEffect(()=>{void layout.load();},[layout]); + return
    + {state.error&&

    {state.error}

    } + + ,disabled:!state.ready,content:computer}, + {id:'settings',label:'Настройки борта',icon:,disabled:!state.ready,content:settings}, + {id:'devices',label:'Устройства аппарата',icon:,disabled:!state.ready,content:devices}, + ]}/> + +
    ; +} diff --git a/packages/sensor-ui/src/boardLayout.ts b/packages/sensor-ui/src/boardLayout.ts new file mode 100644 index 0000000..c1681ed --- /dev/null +++ b/packages/sensor-ui/src/boardLayout.ts @@ -0,0 +1,66 @@ +export const boardSections = ['computer', 'settings', 'devices'] as const; +export type BoardSection = typeof boardSections[number]; +export interface BoardLayout {schema:'missioncore.board-layout/v1';revision:number;open_sections:BoardSection[]} +export interface BoardLayoutTransport { + read:()=>Promise; + patch:(section:BoardSection,open:boolean)=>Promise; +} +export const defaultBoardLayout:BoardLayout={schema:'missioncore.board-layout/v1',revision:0,open_sections:[...boardSections]}; +type Change={section:BoardSection;open:boolean}; +type Snapshot={value:BoardLayout;ready:boolean;error:string|null;saving:boolean}; +function apply(value:BoardLayout,change:Change):BoardLayout { + const open=new Set(value.open_sections); + if(change.open)open.add(change.section);else open.delete(change.section); + return {...value,open_sections:boardSections.filter(section=>open.has(section))}; +} +function validate(value:BoardLayout):BoardLayout { + if(value.schema!==defaultBoardLayout.schema||!Number.isSafeInteger(value.revision)||value.revision<0|| + !Array.isArray(value.open_sections)||new Set(value.open_sections).size!==value.open_sections.length|| + value.open_sections.some(id=>!boardSections.includes(id)))throw new Error('Не удалось прочитать раскладку блоков.'); + return value; +} +// The queue belongs to the application resource, not a mounted accordion. +// Navigation cannot discard a pending save or let an older reply win a toggle. +export function createBoardLayoutStore(transport:BoardLayoutTransport){ + let saved=defaultBoardLayout; + let snapshot:Snapshot={value:saved,ready:false,error:null,saving:false}; + let pending:Change[]=[]; + let reading:Promise|null=null; + let writing=false; + const listeners=new Set<()=>void>(); + const emit=(patch:Partial={})=>{ + snapshot={...snapshot,...patch,value:pending.reduce(apply,saved),saving:writing||pending.length>0}; + listeners.forEach(listener=>listener()); + }; + const load=():Promise=>{ + if(reading)return reading; + if(writing)return Promise.resolve(); + reading=transport.read().then(value=>{saved=validate(value);emit({ready:true,error:null});}) + .catch(()=>emit({error:'Раскладка блоков не загружена. Повторите подключение.'})) + .finally(()=>{reading=null;}); + return reading; + }; + const flush=async()=>{ + if(writing)return; + writing=true;emit({error:null}); + while(pending.length){ + const change=pending[0]; + try{saved=validate(await transport.patch(change.section,change.open));pending.shift();emit();} + catch{pending=[];emit({error:'Не удалось сохранить раскладку блоков. Изменение отменено.'});break;} + } + writing=false;emit(); + }; + return { + getSnapshot:()=>snapshot, + subscribe:(listener:()=>void)=>{listeners.add(listener);return()=>{listeners.delete(listener);};}, + load, + change:(open:string[])=>{ + if(!snapshot.ready||reading)return; + for(const section of boardSections){ + if(open.includes(section)!==snapshot.value.open_sections.includes(section))pending.push({section,open:open.includes(section)}); + } + emit();void flush(); + }, + }; +} +export type BoardLayoutStore=ReturnType; diff --git a/src/k1link/fleet/board_layout.py b/src/k1link/fleet/board_layout.py new file mode 100644 index 0000000..ad3415b --- /dev/null +++ b/src/k1link/fleet/board_layout.py @@ -0,0 +1,45 @@ +"""Operator presentation only; never transported to a motor controller.""" +import hashlib +import json +from pathlib import Path + +from .trust import atomic_private + +SCHEMA = "missioncore.board-layout/v1" +SECTIONS = ("computer", "settings", "devices") + + +def path(root: Path, vehicle: str) -> Path: + return root / "board-layouts" / (hashlib.sha256(vehicle.encode()).hexdigest() + ".json") + + +def read(root: Path, vehicle: str) -> dict: + target = path(root, vehicle) + if not target.exists(): + return {"schema": SCHEMA, "revision": 0, "open_sections": list(SECTIONS)} + if target.is_symlink() or target.stat().st_size > 4096: + raise ValueError("Invalid layout file") + value = json.loads(target.read_bytes()) + if (not isinstance(value, dict) or set(value) != {"schema", "revision", "open_sections"} + or value["schema"] != SCHEMA or type(value["revision"]) is not int + or not 0 <= value["revision"] < 2**53-1 + or not isinstance(value["open_sections"], list) + or any(item not in SECTIONS for item in value["open_sections"]) + or len(set(value["open_sections"])) != len(value["open_sections"])): + raise ValueError("Invalid layout document") + return value + + +def update(root: Path, vehicle: str, section: str, opened: bool) -> dict: + # Caller holds the fleet writer lock. A patch cannot lose another section. + if section not in SECTIONS or type(opened) is not bool: + raise ValueError("Invalid layout change") + value = read(root, vehicle) + opened_sections = set(value["open_sections"]) + if opened: + opened_sections.add(section) + else: + opened_sections.discard(section) + value.update(revision=value["revision"]+1, open_sections=[s for s in SECTIONS if s in opened_sections]) + atomic_private(path(root, vehicle), (json.dumps(value, indent=2)+"\n").encode()) + return value diff --git a/src/k1link/fleet/rover_control.py b/src/k1link/fleet/rover_control.py new file mode 100644 index 0000000..fd3f5f9 --- /dev/null +++ b/src/k1link/fleet/rover_control.py @@ -0,0 +1,135 @@ +"""Ephemeral operator leases. No motor calls, command queue or persisted motion.""" +from __future__ import annotations + +import copy +import math +import secrets +import threading +import time + + +class RoverControl: + def __init__(self, clock=time.monotonic): + self.clock = clock + self.lock = threading.RLock() + self.changed = threading.Condition(self.lock) + self.boards = {} + self.clock_id = secrets.token_hex(16) + + def _board(self, node): + return self.boards.setdefault(node, {"seen": -1e9, "watch": 0, "snapshot": {}, + "session": None, "relay": None}) + + def view(self, node): + with self.lock: + b = self._board(node) + b["watch"] = self.clock() + 2 + fresh = self.clock() - b["seen"] < 1 + self._expire(b) + return {"fresh": fresh, "snapshot": copy.deepcopy(b["snapshot"]) if fresh else {}, + "controlling": b["session"] is not None} + + def _expire(self, b): + if b["session"] and self.clock() >= b["session"]["until"]: + b["session"] = None + + def arm(self, node, body): + if (set(body) != {"standstill_confirmed", "current_a", "max_erpm"} + or body["standstill_confirmed"] is not True + or type(body["current_a"]) not in (int, float) + or not .5 <= body["current_a"] <= 30 + or type(body["max_erpm"]) not in (int, float) + or not 300 <= body["max_erpm"] <= 3000): + raise ValueError("Подтвердите остановку и выберите допустимые пределы.") + with self.lock: + b = self._board(node) + self._expire(b) + if b["session"]: + raise ValueError("Аппаратом уже управляют. Сначала остановите управление.") + snapshot = b["snapshot"] + if self.clock() - b["seen"] >= 1 or snapshot.get("supported") is not True: + raise ValueError("Канал управления бортом недоступен.") + if snapshot.get("state") in ("preparing", "ready", "driving", "stopping"): + raise ValueError("Дождитесь завершения предыдущего управления.") + identifier = secrets.token_hex(16) + b["session"] = {"id": identifier, "sequence": 0, "until": self.clock()+.4, + "left": 0, "right": 0, "settings": copy.deepcopy(body)} + self.changed.notify_all() + return {"session_id": identifier} + + def command(self, node, body): + if set(body) != {"session_id", "sequence", "left", "right", "stop"}: + raise ValueError("Некорректная команда управления.") + if (type(body["sequence"]) is not int or not 1 <= body["sequence"] < 2**53 + or type(body["stop"]) is not bool + or any(type(body[k]) not in (int,float) or not math.isfinite(body[k]) + or abs(body[k]) > 1 for k in ("left", "right"))): + raise ValueError("Некорректные значения команды.") + with self.lock: + b = self._board(node) + self._expire(b) + s = b["session"] + if not s or not secrets.compare_digest(str(body["session_id"]), s["id"]): + raise ValueError("Управление завершено. Включите его заново.") + if body["sequence"] <= s["sequence"]: + raise ValueError("Устаревшая команда отклонена.") + if body["stop"]: + b["session"] = None + else: + s.update(sequence=body["sequence"], left=body["left"], right=body["right"], + until=self.clock()+.4) + self.changed.notify_all() + return {"accepted_sequence": body["sequence"]} + + def exchange(self, node, body): + """Called only after normal paired-certificate/binding authentication.""" + snapshot = body.get("rover") + relay = body.get("relay_id") + if not isinstance(snapshot, dict) or not isinstance(relay, str) or len(relay) != 32: + raise ValueError("Invalid rover exchange") + with self.lock: + b = self._board(node) + if b["relay"] != relay: + b["session"] = None # No resume after relay restart/rebind. + if b["snapshot"].get("instance") != snapshot.get("instance"): + b["session"] = None # Driver restarts also revoke the browser lease. + b.update(relay=relay, snapshot=copy.deepcopy(snapshot), seen=self.clock()) + self._expire(b) + s = b["session"] + if s and snapshot.get("session_id") == s["id"] and snapshot.get("state") in ( + "stopped", "fault", "receiver"): + b["session"] = s = None + command = None + if s: + command = {k: copy.deepcopy(v) for k,v in s.items() if k != "until"} + command["ttl_ms"] = max(0, min(400, int((s["until"]-self.clock())*1000))) + return {"watch": self.clock() < b["watch"] or s is not None, "command": command, + "control_clock": self._clock()} + + def _clock(self): + return {"instance": self.clock_id, "monotonic_ms": self.clock()*1000} + + def wait_for_intent(self, node, relay, previous, timeout=.05): + """Wake on a new intent, including updates between write and wait.""" + previous = previous or {} + def changed(): + board = self._board(node) + current = (board["session"] if board["relay"] == relay else None) or {} + return (current.get("id"), current.get("sequence")) != (previous.get("id"), previous.get("sequence")) + with self.changed: + self.changed.wait_for(changed, timeout) + + def stream(self, node, relay): + """Latest intent only. Telemetry round trips never pace command delivery.""" + with self.lock: + b = self._board(node) + self._expire(b) + if self.clock() - b["seen"] >= 1: + b["session"] = None + s = b["session"] if b["relay"] == relay else None + command = None + if s: + command = {k: copy.deepcopy(v) for k,v in s.items() if k != "until"} + command["expires_mono_ms"] = s["until"]*1000 + return {"watch": self.clock() < b["watch"] or s is not None, + "command": command, "control_clock": self._clock()} diff --git a/src/k1link/web/rover_api.py b/src/k1link/web/rover_api.py new file mode 100644 index 0000000..edd4988 --- /dev/null +++ b/src/k1link/web/rover_api.py @@ -0,0 +1,40 @@ +"""Local operator BFF for the paired Node's bounded control channel.""" +from typing import Annotated +from fastapi import APIRouter, Depends, HTTPException, Response +from k1link.fleet.registry import FleetRegistry +from k1link.fleet.trust import PairingError +from .fleet_api import local_operator + +router = APIRouter(prefix="/api/v1/fleet", tags=["fleet"]) + +def node(fleet, vehicle): + with fleet.lock: + row = fleet.find(vehicle) + if row["enrollment"] != "paired": + raise ValueError("Борт не привязан.") + return row["node_id"] + +@router.get("/{vehicle_id}/rover") +def rover_state(vehicle_id: str, response: Response, + fleet: Annotated[FleetRegistry, Depends(local_operator)]): + response.headers["Cache-Control"] = "no-store" + try: + return fleet.rover_control.view(node(fleet, vehicle_id)) + except (ValueError, PairingError) as error: + raise HTTPException(409, str(error)) from None + +@router.post("/{vehicle_id}/rover/arm") +def rover_arm(vehicle_id: str, body: dict, + fleet: Annotated[FleetRegistry, Depends(local_operator)]): + try: + return fleet.rover_control.arm(node(fleet, vehicle_id), body) + except (ValueError, PairingError) as error: + raise HTTPException(409, str(error)) from None + +@router.post("/{vehicle_id}/rover/command") +def rover_command(vehicle_id: str, body: dict, + fleet: Annotated[FleetRegistry, Depends(local_operator)]): + try: + return fleet.rover_control.command(node(fleet, vehicle_id), body) + except (ValueError, PairingError) as error: + raise HTTPException(409, str(error)) from None diff --git a/tests/fleet/test_board_layout.py b/tests/fleet/test_board_layout.py new file mode 100644 index 0000000..5e50780 --- /dev/null +++ b/tests/fleet/test_board_layout.py @@ -0,0 +1,42 @@ +import json +import threading +from types import SimpleNamespace + +from fastapi import FastAPI +from fastapi.testclient import TestClient +import pytest + +from k1link.fleet import board_layout +from k1link.fleet.trust import PairingError +from k1link.web.fleet_api import router, local_operator + + +def test_layout_api_persists_empty_and_isolates_vehicles(tmp_path): + app = FastAPI() + app.include_router(router) + def find(identifier): + if identifier not in ("rover-a", "rover-b"): + raise PairingError("Unknown") + fleet = SimpleNamespace(root=tmp_path, lock=threading.RLock(), find=find) + app.dependency_overrides[local_operator] = lambda: fleet + client = TestClient(app) + for section in board_layout.SECTIONS: + response = client.patch('/api/v1/fleet/rover-a/board-layout', json={"section": section, "open": False}) + assert response.status_code == 200 + assert client.get('/api/v1/fleet/rover-a/board-layout').json()['open_sections'] == [] + assert client.get('/api/v1/fleet/rover-b/board-layout').json()['open_sections'] == list(board_layout.SECTIONS) + assert board_layout.read(tmp_path, 'rover-a')['revision'] == 3 + assert board_layout.path(tmp_path, 'rover-a').stat().st_mode & 0o777 == 0o600 + for body in ({"section":"motor","open":True},{"section":"computer","open":"true"},{"section":"computer","open":True,"extra":0}): + assert client.patch('/api/v1/fleet/rover-a/board-layout', json=body).status_code == 422 + assert client.get('/api/v1/fleet/missing/board-layout').status_code == 404 + + +def test_corrupt_layout_is_preserved(tmp_path): + board_layout.update(tmp_path, "a", "computer", False) + target = board_layout.path(tmp_path, "a") + raw = json.dumps({"schema":board_layout.SCHEMA,"revision":3,"open_sections":["motor"]}) + target.write_text(raw) + with pytest.raises(ValueError): + board_layout.update(tmp_path, "a", "devices", False) + assert target.read_text() == raw diff --git a/tests/fleet/test_rover_control.py b/tests/fleet/test_rover_control.py new file mode 100644 index 0000000..a535114 --- /dev/null +++ b/tests/fleet/test_rover_control.py @@ -0,0 +1,115 @@ +import pytest +from k1link.fleet.rover_control import RoverControl + +@pytest.fixture +def hub(): + now=[10.] + h=RoverControl(lambda:now[0]) + h.exchange('node',{'relay_id':'a'*32,'rover':{'supported':True,'instance':'driver','state':'observing'}}) + return h,now + +def arm(h): + return h.arm('node',{'standstill_confirmed':True,'current_a':30,'max_erpm':2000})['session_id'] + +def cmd(id,seq=1,**kw): + return {'session_id':id,'sequence':seq,'left':1,'right':1,'stop':False,**kw} + +def exchange(h,**kw): + return h.exchange('node',{'relay_id':'a'*32,'rover':{'supported':True,'instance':'driver',**kw}}) + +def test_expired_browser_cannot_be_revived_by_late_packet(hub): + h,now=hub;id=arm(h);h.command('node',cmd(id));now[0]+=.401 + assert exchange(h)['command'] is None + with pytest.raises(ValueError):h.command('node',cmd(id,2)) + +def test_sequence_stop_and_single_owner(hub): + h,_=hub;id=arm(h) + with pytest.raises(ValueError):arm(h) + h.command('node',cmd(id,2)) + with pytest.raises(ValueError):h.command('node',cmd(id,1)) + assert exchange(h)['command']['sequence']==2 + h.command('node',cmd(id,3,stop=True)) + with pytest.raises(ValueError):h.command('node',cmd(id,4)) + assert exchange(h)['command'] is None + +@pytest.mark.parametrize('snapshot',[{'state':'receiver'},{'state':'fault'},{'instance':'new-driver'}]) +def test_takeover_fault_or_driver_restart_revokes(hub,snapshot): + h,_=hub;id=arm(h) + assert exchange(h,session_id=id,**snapshot)['command'] is None + +def test_relay_restart_and_cross_board_do_not_inherit_authority(hub): + h,_=hub;id=arm(h) + with pytest.raises(ValueError):h.command('other',cmd(id)) + assert h.exchange('node',{'relay_id':'b'*32,'rover':{}})['command'] is None + +@pytest.mark.parametrize('value',[True,float('nan'),float('inf'),1.01,-1.01,'1']) +def test_invalid_demand_cannot_refresh(hub,value): + h,_=hub;id=arm(h) + with pytest.raises(ValueError):h.command('node',cmd(id,left=value)) + +def test_stale_telemetry_is_unavailable_and_arm_requires_current_board(hub): + h,now=hub;now[0]+=1.1 + assert h.view('node')['snapshot']=={} + with pytest.raises(ValueError):arm(h) + +def test_stream_keeps_absolute_deadline_and_never_renews_held_frame(hub): + h, now = hub + identifier = arm(h) + h.command('node', cmd(identifier, 1)) + first = h.stream('node', 'a'*32) + now[0] += .2 + repeated = h.stream('node', 'a'*32) + assert repeated['command'] == first['command'] + assert repeated['control_clock']['monotonic_ms'] > first['control_clock']['monotonic_ms'] + assert first['command']['expires_mono_ms'] == pytest.approx(10400) + now[0] += .201 + assert h.stream('node', 'a'*32)['command'] is None + with pytest.raises(ValueError): h.command('node', cmd(identifier, 2)) + +def test_stream_delivers_new_intent_without_waiting_for_telemetry(hub): + h, now = hub + identifier = arm(h) + h.command('node', cmd(identifier, 1)) + h.command('node', cmd(identifier, 2, left=-1)) + assert h.stream('node', 'a'*32)['command']['left'] == -1 + assert h.stream('node', 'b'*32)['command'] is None + h.command('node', cmd(identifier, 3, stop=True)) + assert h.stream('node', 'a'*32)['command'] is None + +def test_new_core_has_distinct_clock_epoch(hub): + h, _ = hub + assert h.stream('node', 'a'*32)['control_clock']['instance'] != RoverControl().clock_id + +def test_stream_retires_control_if_return_telemetry_is_lost(hub): + h, now = hub + identifier = arm(h) + for seq in range(1, 13): + h.command('node', cmd(identifier, seq)) + now[0] += .09 + assert h.stream('node', 'a'*32)['command'] is None + with pytest.raises(ValueError): h.command('node', cmd(identifier, 13)) + +def test_intent_wait_wakes_on_update_and_does_not_miss_prior_update(hub): + import threading + from unittest.mock import patch + h, _ = hub + identifier = arm(h) + previous = h.stream('node', 'a'*32)['command'] + entered, done = threading.Event(), threading.Event() + def waiter(): + entered.set() + h.wait_for_intent('node', 'a'*32, previous, timeout=2) + done.set() + worker = threading.Thread(target=waiter) + worker.start() + assert entered.wait(1) + h.command('node', cmd(identifier, 1)) + assert done.wait(.5), 'new intent waited for the periodic keepalive' + worker.join(2) + # A command arriving after socket write but before wait must not be lost. + with patch.object(h.changed, 'wait', side_effect=AssertionError('missed prior update')): + h.wait_for_intent('node', 'a'*32, previous, timeout=2) + latest = h.stream('node', 'a'*32)['command'] + h.command('node', cmd(identifier, 2, stop=True)) + with patch.object(h.changed, 'wait', side_effect=AssertionError('missed stop')): + h.wait_for_intent('node', 'a'*32, latest, timeout=2) diff --git a/tests/fleet/test_rover_stream_transport.py b/tests/fleet/test_rover_stream_transport.py new file mode 100644 index 0000000..56e23a6 --- /dev/null +++ b/tests/fleet/test_rover_stream_transport.py @@ -0,0 +1,52 @@ +"""Exercise HTTP framing and per-frame binding checks without a real board.""" +import http.client +import json +import threading +import time +from http.server import ThreadingHTTPServer +from types import SimpleNamespace + +from k1link.fleet.transport import NodeChannelHandler + + +def test_stream_rechecks_binding_and_closes_when_revoked(): + calls = [] + + def receive(certificate, path, body, *, address): + calls.append((certificate, path, body, address)) + if len(calls) == 3: + return 410, {"error": "Binding revoked"} + return 200, {"watch": True, "command": {"sequence": len(calls)}} + + class Handler(NodeChannelHandler): + def setup(self): + super().setup() + # Only TLS certificate extraction is substituted. HTTP reads, + # writes, streaming, loop and reauthentication use production code. + self.connection = SimpleNamespace(getpeercert=lambda **_: b"synthetic-cert") + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + server.address = "127.0.0.1" + server.registry = SimpleNamespace(receive=receive, stop=threading.Event(), + rover_control=SimpleNamespace(wait_for_intent=lambda *_: time.sleep(.01))) + worker = threading.Thread(target=server.serve_forever, daemon=True) + worker.start() + client = http.client.HTTPConnection(*server.server_address, timeout=2) + try: + body = {"relay_id": "a" * 32, "node_id": "synthetic-node"} + client.request("POST", "/v1/node/rover-stream", json.dumps(body), + {"Content-Type": "application/json"}) + response = client.getresponse() + assert response.status == 200 + assert response.getheader("Content-Type") == "application/x-ndjson" + assert response.getheader("Content-Length") is None + frames = [json.loads(line) for line in response.read().splitlines()] + assert [frame["command"]["sequence"] for frame in frames] == [1, 2] + assert len(calls) == 3 + assert all(call == (b"synthetic-cert", "/v1/node/rover-stream", body, "127.0.0.1") for call in calls) + finally: + client.close() + server.shutdown() + server.server_close() + worker.join(timeout=2) + assert not worker.is_alive() From 6d772b29fedd550f9fc9f761002272db3c0eb2f7 Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Fri, 25 Sep 2026 16:37:57 +0300 Subject: [PATCH 5/7] feat(control-station): add rover scene telemetry and guarded keyboard control --- .../public/rover-scene/dcd006-v020.glb | 3 + .../public/rover-scene/dcd006-v020.json | 39 + .../public/rover-scene/environment-map.png | Bin 0 -> 256580 bytes apps/control-station/src/App.tsx | 2 +- .../src/components/rover/RoverTelemetry.tsx | 25 + .../src/components/rover/RoverView.tsx | 70 + .../rover/playcanvas/PROVENANCE.json | 16 + .../rover/playcanvas/PlayCanvasViewer.tsx | 2043 +++++++++++++++++ .../rover/playcanvas/playcanvasPostFx.ts | 393 ++++ .../components/rover/playcanvas/sceneTree.ts | 20 + .../src/components/rover/rover.css | 20 + .../src/composition/devicePlugins.ts | 3 +- .../src/core/fleet/boardLayout.ts | 13 + .../src/core/fleet/roverHoldInput.ts | 66 + .../src/core/fleet/roverInput.ts | 20 + .../src/core/fleet/sensorTransport.ts | 1 + .../src/core/fleet/useRoverControl.ts | 79 + .../src/workspaces/Workspaces.tsx | 2 +- .../src/workspaces/fleet/VehicleSensors.tsx | 8 +- .../workspaces/fleet/VehiclesWorkspace.tsx | 16 +- .../observation/BoardObservationCenter.tsx | 18 +- .../fleet/observation/ObservationDeck.tsx | 4 +- .../control-station/test/boardLayout.test.mjs | 57 + .../test/roverControl.test.mjs | 157 ++ .../test/roverControlFocus.test.mjs | 49 + .../test/roverControlStartup.test.mjs | 49 + .../test/roverHoldInput.test.mjs | 85 + apps/control-station/test/roverInput.test.mjs | 23 + apps/control-station/test/vescUi.test.mjs | 70 + .../tools/rover-control-preview/build.mjs | 18 + .../tools/rover-control-preview/main.tsx | 69 + .../tools/rover-control-preview/preview.css | 16 + .../tools/rover-control-preview/trace.ts | 38 + .../tools/rover-control-preview/tsconfig.json | 5 + tools/rover-scene/export_rover.py | 49 + tools/rover-scene/inspect_model.py | 11 + 36 files changed, 3536 insertions(+), 21 deletions(-) create mode 100644 apps/control-station/public/rover-scene/dcd006-v020.glb create mode 100644 apps/control-station/public/rover-scene/dcd006-v020.json create mode 100644 apps/control-station/public/rover-scene/environment-map.png create mode 100644 apps/control-station/src/components/rover/RoverTelemetry.tsx create mode 100644 apps/control-station/src/components/rover/RoverView.tsx create mode 100644 apps/control-station/src/components/rover/playcanvas/PROVENANCE.json create mode 100644 apps/control-station/src/components/rover/playcanvas/PlayCanvasViewer.tsx create mode 100644 apps/control-station/src/components/rover/playcanvas/playcanvasPostFx.ts create mode 100644 apps/control-station/src/components/rover/playcanvas/sceneTree.ts create mode 100644 apps/control-station/src/components/rover/rover.css create mode 100644 apps/control-station/src/core/fleet/boardLayout.ts create mode 100644 apps/control-station/src/core/fleet/roverHoldInput.ts create mode 100644 apps/control-station/src/core/fleet/roverInput.ts create mode 100644 apps/control-station/src/core/fleet/useRoverControl.ts create mode 100644 apps/control-station/test/boardLayout.test.mjs create mode 100644 apps/control-station/test/roverControl.test.mjs create mode 100644 apps/control-station/test/roverControlFocus.test.mjs create mode 100644 apps/control-station/test/roverControlStartup.test.mjs create mode 100644 apps/control-station/test/roverHoldInput.test.mjs create mode 100644 apps/control-station/test/roverInput.test.mjs create mode 100644 apps/control-station/test/vescUi.test.mjs create mode 100644 apps/control-station/tools/rover-control-preview/build.mjs create mode 100644 apps/control-station/tools/rover-control-preview/main.tsx create mode 100644 apps/control-station/tools/rover-control-preview/preview.css create mode 100644 apps/control-station/tools/rover-control-preview/trace.ts create mode 100644 apps/control-station/tools/rover-control-preview/tsconfig.json create mode 100644 tools/rover-scene/export_rover.py create mode 100644 tools/rover-scene/inspect_model.py diff --git a/apps/control-station/public/rover-scene/dcd006-v020.glb b/apps/control-station/public/rover-scene/dcd006-v020.glb new file mode 100644 index 0000000..068a892 --- /dev/null +++ b/apps/control-station/public/rover-scene/dcd006-v020.glb @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:15f17f5b5b014e0f65273aa1565b7fb8e46381ca389a3c3d3ca89a32806bfb79 +size 54960576 diff --git a/apps/control-station/public/rover-scene/dcd006-v020.json b/apps/control-station/public/rover-scene/dcd006-v020.json new file mode 100644 index 0000000..f14fdb4 --- /dev/null +++ b/apps/control-station/public/rover-scene/dcd006-v020.json @@ -0,0 +1,39 @@ +{ + "source": "DCD-006_rover_v020.blend", + "source_sha256": "c49a0470974bbe65b4e65b4b5c06cb887730715a1ddfa231b86426fed6de8f79", + "model": "DCD-006 v020 complete rover", + "source_object_count": 1426, + "render_mesh_count": 1, + "original_bounds": [ + [ + -0.527999997138977, + -0.45249998569488525, + 0.0 + ], + [ + 0.6350000500679016, + 0.45249998569488525, + 0.734000027179718 + ] + ], + "dimensions_m": [ + 1.1630001068115234, + 0.9049999713897705, + 0.734000027179718 + ], + "translation_m": [ + -0.05350002646446228, + -0.0, + -0.0 + ], + "glb_bytes": 54960576, + "glb_sha256": "15f17f5b5b014e0f65273aa1565b7fb8e46381ca389a3c3d3ca89a32806bfb79", + "material_source_sha256": "ac50e29fe9fe7ab4012628c52fce30e262e9e0bba4a4d49abe59a90c84391b2e", + "material_rules": { + "metal": 1, + "rubber": 2, + "steel": 6, + "paint": 3 + }, + "source_saved": false +} diff --git a/apps/control-station/public/rover-scene/environment-map.png b/apps/control-station/public/rover-scene/environment-map.png new file mode 100644 index 0000000000000000000000000000000000000000..2b51a5876e824cb16d64c96541a80cba19a126c5 GIT binary patch literal 256580 zcmV)6K*+y|P)b{B?^Syk(?ALn%+{jf0@Y~#N%w*P>!`I|ok5|Hus3{AWQ;M#m^Esy zT5GR;&bi&UL)X3gthK6U%{j(z{2t+}kMSvd>pFVjH@bjtHTz9*eG9tRzrr`VfKO?Y zpIThPx8{7?^@;ewTi&#ZpCZ@#XNDZ%Q;bXamI=Jg>zly@zI7eGzR^&BUC+l)zOZjJ zo}bk9&DvM<4X@m#!8f{;Pduo?Ti!o>D`Y?E3;*A!`hNzlZ}!oIZ$$rZ+cZ99L->@H z^QkDlshf$he^Vp%30}7Zc-P&698UZUZ=gS%t}lE&Mi@RB&-g?xd_#KUr&|{II{JNs z!F^NA{G0sxv~ulJ!QF3Na^Z;!n%QB=Hi+N61He;j4zF)oA)Fp0b)Ak0M-J<{;x#Nx zHN1flEdiSR>%}F@d#nV3FN{%8qI;4!ht=*L;>Z! zFjXhrYg@o@tgditzTN4UVTMv@ z;c%^!!Ci!ZI6zvve=z*R;da9tICeO611EHB_~?VaKb<|cu;gI4jSqN&ON2Z2=6djb z;4OwYYZ3%_?69v>c)gZ$hvWFnirFwX4;g8DLio%k-aY!>fhW!E_1JwVAWsg5Pk5fM zv$f}FUEkhExXqt$+2KxD6<0oE&q&7mPR{96F5n5^hC2p6o)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1+aIZNh&8#S2XrQVz7uP3+5E}>Oepr`ZUkt)yNzVE%Z;LO<(NaRBb zI5LkNeK_tX;iHfOSb`Uds6R9|p86b|y*|TOf{V7rx_7LDcEEk_ANjhrZ6&W^KT>Be zUk{yLu`tJq#LCjGP~BuSq%_jfq2)u@#;cf7cJQ{r`v=41uEVTdUTXh*xzGioWH3tF zbZBk8L`(jS6dP;w0KKAhOFY0wbI`17yi7QGA$2|P7 zagnF$`c7`>*(KFg30mHMj{K^>8Iq6jW%B8hQa%4kh7GoDv4k&ea-mz3jb4(SftO|b zm0l%Meg)le5m9$7IhJg^R^O2Nlx)Q|91kl|b>d~0vu!aOm#xCii1a`9fK3j{<)0J& z!|CBSBDEK+4Jn2C=~PY$Z+95#YD<$+*+pbN6e`liP*lIS8}_xAG?t&Wt>MGvA{LpU z4RQ`v(MHqRk_4^1zOzBJa+7k0` z9(j#cS8%^(odV8~JbsM@S2fx`-%C16s@H-8f!h?gA8nbzO|a|c`YgLiQL$ZFKEQ~|f5eYwe}+Bahjx!ZUL zI$?ftpU3NpZn#5yoeFFl8w7fBOw-~||AoW3&(6tvfLiQ>;t@CQ&t3cZm6ikIs|?*F z{qMt-KY`oCQiPkO#S=|axkJ{P=jQ=G;X|vQf6l7up8v<*vJ-k=ys55j9Z^ATwc-JP yX2hZdR3Vo!-zD$-XJG$K^Kz#C|8}rgctIza63iK`9nb?HUJuoD9+cj8}g4HhH- literal 0 HcmV?d00001 diff --git a/apps/control-station/src/App.tsx b/apps/control-station/src/App.tsx index 30e6c14..08bcc2d 100644 --- a/apps/control-station/src/App.tsx +++ b/apps/control-station/src/App.tsx @@ -822,7 +822,7 @@ export default function App() { /> ) : activeDefinition.kind === "missions" ? (

    - ) : activeDefinition.kind === "vehicles" ? null : activeDefinition.kind === "datasets" ? ( + ) : activeDefinition.kind === "vehicles" ?
    : activeDefinition.kind === "datasets" ? ( Offline evaluation ) : activeDefinition.kind === "lab-archive" ? ( laboratoryAnnotation.control diff --git a/apps/control-station/src/components/rover/RoverTelemetry.tsx b/apps/control-station/src/components/rover/RoverTelemetry.tsx new file mode 100644 index 0000000..482630d --- /dev/null +++ b/apps/control-station/src/components/rover/RoverTelemetry.tsx @@ -0,0 +1,25 @@ +import type {RoverState} from '../../core/fleet/useRoverControl'; +import {drivePositions} from '../../../../../plugins/vesc/frontend/src/model'; +const number=(v:number|undefined,digits=1)=>typeof v==='number'&&Number.isFinite(v)?v.toLocaleString('ru-RU',{maximumFractionDigits:digits}):'—'; +export function RoverTelemetry({state}:{state:RoverState}){ + const devices=state.snapshot.devices??[],profile=state.snapshot.profile; + const positions=drivePositions(profile?.layout??null); + const assigned=Object.entries(profile?.bindings??{}).map(([slot,binding])=>({ + id:binding.device_id,uuid:binding.uuid,label:positions[slot]??slot, + reading:devices.find(d=>d.id===binding.device_id&&d.uuid===binding.uuid), + })); + const readings=[...assigned,...devices.filter(d=>!assigned.some(a=>a.id===d.id&&a.uuid===d.uuid)).map(d=>({...d,reading:d}))]; + return
    + {!state.fresh?

    Нет свежих показаний VESC.

    :!readings.length?

    Получение показаний VESC…

    :readings.map(d=>{ + const fresh=!!d.reading&&d.reading.age_ms<1000,v=fresh?d.reading?.values:undefined; + return
    {d.label}VESC {d.uuid.slice(0,6).toUpperCase()}{!d.reading?' · Нет связи':!fresh?' · Нет свежих данных':''} +
    Ток мотора
    {number(v?.motor_current_a)} А
    +
    Ток батареи
    {number(v?.input_current_a)} А
    +
    Напряжение
    {number(v?.input_voltage_v)} В
    +
    Обороты, ERPM
    {number(v?.erpm,0)}
    +
    Контроллер
    {number(v?.mos_temperature_c)} °C
    +
    Ошибка VESC
    {v?v.fault_code===0?'Нет':String(v.fault_code):'—'}
    +
    ; + })} +
    ; +} diff --git a/apps/control-station/src/components/rover/RoverView.tsx b/apps/control-station/src/components/rover/RoverView.tsx new file mode 100644 index 0000000..7759f4d --- /dev/null +++ b/apps/control-station/src/components/rover/RoverView.tsx @@ -0,0 +1,70 @@ +import {lazy,Suspense,useCallback,useEffect,useRef,useState} from 'react'; +import {createPortal} from 'react-dom'; +import {Button,Icon,IconButton,KeyButton,LoadingRegion,Select,StatusBadge,Switch,TextField,ToastStack,Window} from '@nodedc/ui-react'; +import {keysFor,roverSettings,type RoverMode} from '../../core/fleet/roverInput'; +import {bindRoverHoldInput} from '../../core/fleet/roverHoldInput'; +import type {RoverController} from '../../core/fleet/useRoverControl'; +import type {ObservationHeaderTargets} from '../../../../../packages/sensor-ui/src/observation'; +import './rover.css'; +const Scene=lazy(()=>import('./playcanvas/PlayCanvasViewer')); +const labels:Record={observing:'Наблюдение',preparing:'Подготовка управления',ready:'Управление включено',driving:'Команда движения',receiver:'Управление с пульта',stopping:'Остановка',stopped:'Управление выключено',fault:'Управление остановлено'}; + +export function RoverView({vehicleID,controller:c,header,active}:{vehicleID:string;controller:RoverController;header:ObservationHeaderTargets;active:boolean}){ + const storage=`missioncore.rover-view.v1:${vehicleID}`; + const [settings,setSettings]=useState(()=>{try{return roverSettings(JSON.parse(localStorage.getItem(storage)??'null'));}catch{return roverSettings(null);}}); + const [open,setOpen]=useState(false),[confirmed,setConfirmed]=useState(false),[held,setHeld]=useState>(new Set()); + const [modelState,setModelState]=useState<'loading'|'ready'|'error'>('loading'); + const stage=useRef(null),input=useRef|null>(null); + const stop=useCallback(()=>{input.current?.dispose();input.current=null;c.setInputGuard(null);setHeld(new Set());c.stop();setConfirmed(false);},[c.stop,c.setInputGuard]); + useEffect(()=>{try{localStorage.setItem(storage,JSON.stringify(settings));}catch{}},[storage,settings]); + useEffect(()=>{if(!active)stop();},[active,stop]); + useEffect(()=>{ + if(!c.ready||!active||open||!stage.current)return; + const binding=bindRoverHoldInput(stage.current,settings.mode,{held:setHeld,demand:c.setDemand,pause:c.pauseInput,stop}); + input.current=binding;c.setInputGuard(binding.valid); + return()=>{c.setInputGuard(null);binding.dispose();if(input.current===binding)input.current=null;}; + },[c.ready,active,open,settings.mode,c.setDemand,c.setInputGuard,c.pauseInput,stop]); + const showSettings=()=>{stop();setOpen(true);}; + const preparing=c.pending||(c.armed&&!c.ready); + const availability=c.connecting?'Синхронизация с бортом':!c.state.fresh?'Нет свежих данных с борта':!c.state.snapshot.supported?'Управление на борту недоступно':c.state.controlling&&!c.armed?'Управление уже включено':!c.canArm&&!c.armed?'Завершение предыдущего управления':null; + const tone=preparing||availability?'warning':c.ready?'success':c.state.snapshot.state==='fault'?'warning':'neutral'; + const status=preparing?'Подготовка управления':availability??(labels[c.state.snapshot.state??'']??'Наблюдение'); + return <> + {createPortal(,header.actionsTarget)} + {createPortal(,header.statusTarget)} +
    {if(c.armed&&!e.currentTarget.contains(e.relatedTarget as Node|null))c.pauseInput();}}> + {settings.model==='dcd006-v020'? + + {modelState==='error'&&

    Не удалось загрузить модель ровера.

    } +
    :

    Выберите модель аппарата.

    } +
    {status}
    + {c.ready&&
    +
    + {keysFor(settings.mode).map(code=>{if(!c.ready||!e.isTrusted||e.button!==0)return;e.preventDefault();e.currentTarget.setPointerCapture(e.pointerId);stage.current?.focus();input.current?.pointerDown(e.pointerId,code);}} + onPointerUp={e=>input.current?.pointerUp(e.pointerId)} + onPointerCancel={e=>input.current?.pointerCancel(e.pointerId)} + onLostPointerCapture={e=>input.current?.pointerCancel(e.pointerId)}>{code.slice(3)})} +
    + {settings.mode==='arcade'?'Аркадный':'Танковый'} · пробел — стоп +
    } +
    + {c.armed||c.pending?:} +
    +
    + setOpen(false)} title="Управление ровером" size="md">
    + setSettings(v=>({...v,model}))}/> + setSettings(v=>({...v,currentA:Number(e.target.value)}))}/> + setSettings(v=>({...v,maxErpm:Number(e.target.value)}))}/> + + {availability&&{availability}} +

    Движение — только при удержании клавиш или кнопок. При уходе из окна команда снимается. Команда с пульта прекращает удалённое управление.

    + +
    + + ; +} diff --git a/apps/control-station/src/components/rover/playcanvas/PROVENANCE.json b/apps/control-station/src/components/rover/playcanvas/PROVENANCE.json new file mode 100644 index 0000000..53ba8be --- /dev/null +++ b/apps/control-station/src/components/rover/playcanvas/PROVENANCE.json @@ -0,0 +1,16 @@ +{ + "source": "NodeDC ThreeDAssetNode / PlayCanvasViewer", + "files": { + "PlayCanvasViewer.tsx": "34cd6df2e47a7714288aeb5afb2859b1058eb91dc1819abbf296c6a8937a1533", + "playcanvasPostFx.ts": "91cfb7f8ba821fef14681c6c25a61f430ce25aae65b0f181d359f38e37ccd014", + "sceneTree.ts": "eead378c2402f69e2c68cd1fc2a5ec9028555dced53858c600c599f613dda516", + "environment-map.png": "793f72dce207c1a4d2bdb262610f688bd655a79066298b672b642f228cf7d230" + }, + "adaptations": [ + "Domain asset URL and error/loading callbacks", + "No fallback to a different vehicle", + "Removed unused node-editor type helper; rendering settings unchanged", + "Observe the host pane on resize; preserve responsive canvas CSS sizing", + "Frame the complete rover using the donor 28-degree FOV and current viewport aspect" + ] +} diff --git a/apps/control-station/src/components/rover/playcanvas/PlayCanvasViewer.tsx b/apps/control-station/src/components/rover/playcanvas/PlayCanvasViewer.tsx new file mode 100644 index 0000000..dc639ae --- /dev/null +++ b/apps/control-station/src/components/rover/playcanvas/PlayCanvasViewer.tsx @@ -0,0 +1,2043 @@ +import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import * as pc from 'playcanvas' +import { buildSceneTree } from './sceneTree' +import { mergePostFxDefaults, type PostFxSettings } from './playcanvasPostFx' + +const DEFAULT_MODEL_URL = '' +const PIXELFORMAT_RGBA8 = (pc as any).PIXELFORMAT_RGBA8 ?? 7 +const PIXELFORMAT_111110F = (pc as any).PIXELFORMAT_111110F ?? 18 +const PIXELFORMAT_RGBA16F = (pc as any).PIXELFORMAT_RGBA16F ?? 12 +const PIXELFORMAT_RGBA32F = (pc as any).PIXELFORMAT_RGBA32F ?? 14 + +export type PlayCanvasViewerProps = { + modelUrl: string | null + postFx?: Partial | null + viewportSize?: { width: number; height: number } + onSceneReady?: (api: { app: pc.Application; camera: pc.Entity; modelRoot: pc.Entity }) => void + onSelectionChanged?: (selectedIds: string[]) => void + onSceneGraph?: (tree: ReturnType | null, map?: Map) => void + exposeSceneGraph?: boolean + cameraState?: CameraState | null + cameraResetToken?: number | null + cameraZoomStrength?: number | null + cameraInertiaFactor?: number | null + cameraInertiaTime?: number | null + cameraAutoRotate?: boolean | null + onCameraChange?: (state: CameraState, commit?: boolean) => void + onModelState?: (state: "loading" | "ready" | "error") => void + muteLogs?: boolean +} + +export type CameraState = { + pivot: { x: number; y: number; z: number } + distance: number + azimuthDeg: number + elevationDeg: number +} + +// ------------------------------------------------------------ +// Fallback texture handler +class SimpleTextureHandler { + private gd: pc.GraphicsDevice + constructor(gd: pc.GraphicsDevice) { + this.gd = gd + } + load(url: string, callback: (err: any, data?: any) => void) { + ;(async () => { + const res = await fetch(url) + if (!res.ok) throw new Error(`Failed to fetch texture: ${url} (${res.status})`) + const blob = await res.blob() + const bmp = await createImageBitmap(blob) + callback(null, bmp) + })().catch((e) => callback(e)) + } + open(_url: string, data: ImageBitmap) { + const tex = new pc.Texture(this.gd, { + mipmaps: true, + } as any) + // ImageBitmap is supported by the pinned PlayCanvas runtime. + tex.setSource(data as unknown as HTMLImageElement) + return tex + } + patch() {} +} + +function ensureTextureHandler(app: pc.Application) { + try { + if (!app?.graphicsDevice) return + + const fallback = new SimpleTextureHandler(app.graphicsDevice) + const textureCtor = (pc as any).TextureHandler + const buildNative = () => { + if (!textureCtor) return null + try { return new textureCtor(app.graphicsDevice, (app as any).assets) } catch {} + try { return new textureCtor(app.graphicsDevice) } catch {} + try { return new textureCtor(app) } catch {} + return null + } + const nativeHandler = buildNative() + const handler = nativeHandler || fallback + const candidates: any[] = [] + if ((app as any)?.loader) candidates.push((app as any).loader) + if ((app as any)?.assets?.loader) candidates.push((app as any).assets.loader) + if ((app as any)?.assets?._loader) candidates.push((app as any).assets._loader) + if ((app as any)?.assets) candidates.push((app as any).assets) + + for (const loader of candidates) { + if (!loader) continue + + const hasGet = typeof loader.getHandler === 'function' + const hasAdd = typeof loader.addHandler === 'function' + + if (!hasGet || !hasAdd) { + if (loader._handlers && !loader._handlers.texture) { + loader._handlers.texture = handler + } + continue + } + + if (!loader.getHandler('texture')) { + try { loader.addHandler('texture', handler) } catch {} + } + if (loader._handlers && !loader._handlers.texture) { + loader._handlers.texture = handler + } + } + } catch (e) { + console.warn('[PlayCanvasViewer] Failed to register fallback texture handler', e) + } +} + +// ------------------------------------------------------------ +// Environment / HDR helpers +function destroyTexture(texture: pc.Texture | null) { + if (!texture) return + try { texture.destroy?.() } catch {} +} + +function createGradientEquirectTexture( + app: pc.Application, + colorA: string, + colorB: string, + size = 256 +): pc.Texture | null { + try { + const gd: any = (app as any).graphicsDevice ?? (app as any).device + if (!gd || !(pc as any).Texture) return null + + const width = size * 2 + const height = size + const canvas = document.createElement('canvas') + canvas.width = width + canvas.height = height + const ctx = canvas.getContext('2d') + if (!ctx) return null + + const grad = ctx.createLinearGradient(0, 0, width, 0) + grad.addColorStop(0, colorA) + grad.addColorStop(1, colorB) + ctx.fillStyle = grad + ctx.fillRect(0, 0, width, height) + + const tex = new pc.Texture(gd, { + width, + height, + mipmaps: true, + format: (pc as any).PIXELFORMAT_RGBA8 ?? undefined, + addressU: pc.ADDRESS_CLAMP_TO_EDGE, + addressV: pc.ADDRESS_CLAMP_TO_EDGE, + } as any) + + if ((pc as any).TEXTUREPROJECTION_EQUIRECT) { + ;(tex as any).projection = (pc as any).TEXTUREPROJECTION_EQUIRECT + } + + tex.setSource(canvas) + return tex + } catch (e) { + console.warn('[PlayCanvasViewer] Failed to create gradient equirect texture', e) + return null + } +} + +function generateSkyboxResources( + app: pc.Application, + colorA: string, + colorB: string +): { + source: pc.Texture | null + lightingSource: pc.Texture | null + cubemap: pc.Texture | null + atlas: pc.Texture | null +} { + const source = createGradientEquirectTexture(app, colorA, colorB) + if (!source) return { source: null, lightingSource: null, cubemap: null, atlas: null } + + try { + const env: any = (pc as any).EnvLighting + if (!env?.generateLightingSource || !env?.generateAtlas) { + return { source, lightingSource: null, cubemap: null, atlas: null } + } + + const lightingSource = env.generateLightingSource(source, { size: 128 }) + const atlas = env.generateAtlas(lightingSource) + const cubemap = env.generateSkyboxCubemap + ? env.generateSkyboxCubemap(source, 128) + : lightingSource + + return { source, lightingSource, cubemap, atlas } + } catch (e) { + console.warn('[PlayCanvasViewer] Failed to generate skybox resources', e) + return { source, lightingSource: null, cubemap: null, atlas: null } + } +} + +function applySceneEnvironment( + app: pc.Application, + opts: { + envAtlas: pc.Texture | null + skybox: pc.Texture | null + intensity: number + mip: number + rotationDeg: number + } +) { + const scene: any = app.scene + if (!scene) return + + scene.envAtlas = opts.envAtlas || null + scene.skybox = opts.skybox || null + if (typeof scene.skyboxIntensity === 'number') scene.skyboxIntensity = opts.intensity + if (typeof scene.skyboxMip === 'number') scene.skyboxMip = opts.mip + + const rotRad = (opts.rotationDeg * Math.PI) / 180 + try { + if (scene.skyboxRotation && (pc as any).Quat) { + const q = new (pc as any).Quat() + q.setFromEulerAngles(0, opts.rotationDeg, 0) + scene.skyboxRotation = q + } else if (typeof scene.setSkyboxRotation === 'function') { + scene.setSkyboxRotation(0, rotRad, 0) + } + } catch {} +} + +function clamp01(v: number) { + return Math.max(0, Math.min(1, v)) +} + +function toneMapColor(x: number, mode: number) { + const v = Math.max(0, x) + switch (mode) { + case 1: { + const A = 0.15 + const B = 0.50 + const C = 0.10 + const D = 0.20 + const E = 0.02 + const F = 0.30 + const num = v * (A * v + C * B) + D * E + const den = v * (A * v + B) + D * F + return clamp01(num / den - E / F) + } + case 2: { + const t = Math.max(0, v - 0.004) + return clamp01((t * (6.2 * t + 0.5)) / (t * (6.2 * t + 1.7) + 0.06)) + } + case 3: + case 4: { + return clamp01((v * (2.51 * v + 0.03)) / (v * (2.43 * v + 0.59) + 0.14)) + } + case 5: { + return clamp01(v / (1 + v)) + } + case 0: + default: + return clamp01(v) + } +} + +function applyMaterialEnvOverride( + app: pc.Application, + opts: { + enabled: boolean + envAtlas: pc.Texture | null + cubeMap: pc.Texture | null + useSkybox?: boolean + reflectivityScale?: number | null + } +) { + const anyApp = app as any + const store: WeakMap = + anyApp.__ENV_OVERRIDE_STORE__ ?? + (anyApp.__ENV_OVERRIDE_STORE__ = new WeakMap()) + + const setMat = (mat: any) => { + if (!mat || typeof mat !== 'object') return + + if (!store.has(mat)) { + store.set(mat, { + envAtlas: mat.envAtlas ?? null, + cubeMap: mat.cubeMap ?? null, + useSkybox: typeof mat.useSkybox === 'boolean' ? mat.useSkybox : undefined, + reflectivity: typeof mat.reflectivity === 'number' ? mat.reflectivity : undefined, + }) + } + + if (!opts.enabled) { + const prev = store.get(mat) + if (prev) { + mat.envAtlas = prev.envAtlas ?? null + mat.cubeMap = prev.cubeMap ?? null + if (typeof prev.useSkybox === 'boolean') mat.useSkybox = prev.useSkybox + if (typeof prev.reflectivity === 'number') mat.reflectivity = prev.reflectivity + mat.update?.() + } + return + } + + mat.envAtlas = opts.envAtlas ?? null + mat.cubeMap = opts.cubeMap ?? null + if (typeof opts.useSkybox === 'boolean') mat.useSkybox = opts.useSkybox + if (typeof opts.reflectivityScale === 'number') { + const base = store.get(mat)?.reflectivity + if (typeof base === 'number') { + mat.reflectivity = Math.max(0, Math.min(1, base * opts.reflectivityScale)) + } + } + mat.update?.() + } + + const traverse = (e: pc.Entity) => { + const r = (e as any).render + if (r?.meshInstances?.length) { + for (const mi of r.meshInstances) setMat(mi.material) + } + + const m = (e as any).model + if (m?.meshInstances?.length) { + for (const mi of m.meshInstances) setMat(mi.material) + } + + for (const c of e.children ?? []) if (c instanceof pc.Entity) traverse(c) + } + + const modelRoot = app.root.findByName('ModelRoot') as pc.Entity | null + traverse(modelRoot ?? app.root) +} + +function resolveShadowType(type: string) { + const anyPc: any = pc + switch (type) { + case 'vsm32': + return anyPc.SHADOW_VSM_32F ?? anyPc.SHADOW_VSM32 ?? anyPc.SHADOW_VSM_16F ?? pc.SHADOW_VSM_16F + case 'pcf1': + return anyPc.SHADOW_PCF1 ?? pc.SHADOW_PCF1 + case 'pcf3': + return anyPc.SHADOW_PCF3 ?? pc.SHADOW_PCF3 + case 'vsm16': + default: + return anyPc.SHADOW_VSM_16F ?? anyPc.SHADOW_VSM16 ?? pc.SHADOW_VSM_16F + } +} + +function applyLightAngles(entity: pc.Entity | null, azimuthDeg: number, elevationDeg: number) { + if (!entity) return + entity.setLocalEulerAngles(elevationDeg, azimuthDeg, 0) +} + +type ColorInput = string | { r: number; g: number; b: number; a?: number } | pc.Color | null | undefined + +function toColor(value: ColorInput, fallback?: pc.Color): pc.Color { + if (value instanceof pc.Color) { + return new pc.Color(value.r, value.g, value.b, value.a) + } + if (value && typeof value === 'object') { + const r = Number((value as any).r) + const g = Number((value as any).g) + const b = Number((value as any).b) + const a = Number.isFinite((value as any).a) ? Number((value as any).a) : 1 + if (Number.isFinite(r) && Number.isFinite(g) && Number.isFinite(b)) { + return new pc.Color( + Math.max(0, Math.min(1, r)), + Math.max(0, Math.min(1, g)), + Math.max(0, Math.min(1, b)), + Math.max(0, Math.min(1, a)) + ) + } + } + if (typeof value === 'string') { + const hex = value.trim() + const full = /^#?([0-9a-f]{6})$/i.exec(hex) + const short = /^#?([0-9a-f]{3})$/i.exec(hex) + if (full) { + const n = parseInt(full[1], 16) + const r = ((n >> 16) & 255) / 255 + const g = ((n >> 8) & 255) / 255 + const b = (n & 255) / 255 + return new pc.Color(r, g, b) + } + if (short) { + const s = short[1] + const n = parseInt(`${s[0]}${s[0]}${s[1]}${s[1]}${s[2]}${s[2]}`, 16) + const r = ((n >> 16) & 255) / 255 + const g = ((n >> 8) & 255) / 255 + const b = (n & 255) / 255 + return new pc.Color(r, g, b) + } + } + return fallback ? new pc.Color(fallback.r, fallback.g, fallback.b, fallback.a) : new pc.Color(0, 0, 0) +} + +function setWireframeForScene(app: pc.Application, enabled: boolean) { + const renders = app.root.findComponents('render') as any[] + for (const r of renders) { + const meshInstances = r?.meshInstances ?? [] + for (const mi of meshInstances) { + const mat = mi.material as any + if (mat && 'wireframe' in mat) { + mat.wireframe = enabled + mat.update?.() + } + } + } +} + +function collectMeshInstances(entity: pc.Entity | null, out: any[] = []): any[] { + if (!entity) return out + const render = (entity as any).render + const model = (entity as any).model + if (render?.meshInstances?.length) out.push(...render.meshInstances) + if (model?.meshInstances?.length) out.push(...model.meshInstances) + for (const child of entity.children ?? []) collectMeshInstances(child as any, out) + return out +} + +function disableInvalidMeshes(root: pc.Entity | null) { + if (!root) return + const meshInstances = collectMeshInstances(root) + meshInstances.forEach((mi: any) => { + const mesh = mi?.mesh + const vb = mesh?.vertexBuffer + const numVertices = vb?.numVertices ?? 0 + if (!mesh || !numVertices) return + const hasIndex = Array.isArray(mesh.indexBuffer) ? mesh.indexBuffer.length > 0 : !!mesh.indexBuffer + if (!hasIndex) return + try { + const indices: number[] = [] + const count = mesh.getIndices(indices) + if (!count || !indices.length) return + let maxIndex = -1 + for (let i = 0; i < count; i += 1) { + const v = indices[i] ?? -1 + if (v > maxIndex) maxIndex = v + } + if (maxIndex >= numVertices) { + mi.visible = false + // eslint-disable-next-line no-console + console.warn('[PlayCanvasViewer] Disabled mesh with invalid indices', { + numVertices, + maxIndex, + mesh: mesh?.name, + }) + } + } catch {} + }) +} + +function computeAabb(entity: pc.Entity): pc.BoundingBox | null { + const renders = entity.findComponents('render') as any[] + if (!renders?.length) return null + + let out: pc.BoundingBox | null = null + for (const r of renders) { + const meshInstances = r?.meshInstances ?? [] + for (const mi of meshInstances) { + const aabb = mi?.aabb as pc.BoundingBox | undefined + if (!aabb) continue + if (!out) out = aabb.clone() + else out.add(aabb) + } + } + return out +} + +type OrbitOptions = { + pivot: pc.Vec3 + distance: number + minDistance: number + maxDistance: number + zoomStrength?: number + minElevationDeg?: number + maxElevationDeg?: number + inertiaFactor?: number + inertiaTime?: number + initialAzimuthDeg?: number + initialElevationDeg?: number + autoRotate?: boolean + autoRotateSpeed?: number + autoRotateDelay?: number + autoRotateFade?: number + autoRotatePitchSpeed?: number + autoRotatePitchAmount?: number + onChange?: (state: CameraState, commit: boolean) => void +} + +type OrbitController = { + setPivot(v: pc.Vec3): void + setDistance(d: number): void + setZoomStrength(value?: number | null): void + setInertiaFactor(value?: number | null): void + setInertiaTime(value?: number | null): void + setAutoRotate(value?: boolean | null): void + setState(state: CameraState): void + getState(): CameraState + destroy(): void +} + +function makeOrbitController(app: pc.Application, cameraEntity: pc.Entity, opts: OrbitOptions): OrbitController { + const canvas = app.graphicsDevice.canvas as HTMLCanvasElement + + let pivot = opts.pivot.clone() + let distance = opts.distance + let azimuth = ((opts.initialAzimuthDeg ?? 45) * Math.PI) / 180 + let elevation = ((opts.initialElevationDeg ?? 25) * Math.PI) / 180 + + let targetAzimuth = azimuth + let targetElevation = elevation + let targetDistance = distance + + const minEl = ((opts.minElevationDeg ?? 5) * Math.PI) / 180 + const maxEl = ((opts.maxElevationDeg ?? 89) * Math.PI) / 180 + + let dragging = false + let panning = false + let lastX = 0 + let lastY = 0 + let idleTime = 0 + let wheelCommitTimer: number | null = null + + const toDeg = (rad: number) => (rad * 180) / Math.PI + const toRad = (deg: number) => (deg * Math.PI) / 180 + const clampZoom = (value?: number | null) => { + const n = Number(value) + if (!Number.isFinite(n)) return 0.04 + return Math.max(0.001, Math.min(0.5, n)) + } + const clampInertia = (value?: number | null) => { + const n = Number(value) + if (!Number.isFinite(n)) return 0 + return Math.max(0, Math.min(1, n)) + } + const clampInertiaTime = (value?: number | null) => { + const n = Number(value) + if (!Number.isFinite(n)) return 0.05 + return Math.max(0.02, Math.min(10, n)) + } + let zoomStrength = clampZoom(opts.zoomStrength) + let inertia = clampInertia(opts.inertiaFactor) + let inertiaTime = clampInertiaTime(opts.inertiaTime) + let autoRotate = opts.autoRotate !== false + + const snapshot = (useTarget = true): CameraState => ({ + pivot: { x: pivot.x, y: pivot.y, z: pivot.z }, + distance: useTarget ? targetDistance : distance, + azimuthDeg: toDeg(useTarget ? targetAzimuth : azimuth), + elevationDeg: toDeg(useTarget ? targetElevation : elevation), + }) + + const emitChange = (commit: boolean) => { + if (!opts.onChange) return + opts.onChange(snapshot(true), commit) + } + + const updateCamera = (dt = 0) => { + if (autoRotate && !dragging && !panning) { + idleTime += dt + const delay = Math.max(0, opts.autoRotateDelay ?? 0) + if (idleTime > delay) { + const t = idleTime - delay + const fadeTime = Math.max(0.001, opts.autoRotateFade ?? 0.001) + const x = t / fadeTime + const fade = x <= 0 ? 0 : x >= 1 ? 1 : 0.5 * Math.sin((x - 0.5) * Math.PI) + 0.5 + const speed = ((opts.autoRotateSpeed ?? 0) * Math.PI) / 180 + const pitchSpeed = Number(opts.autoRotatePitchSpeed ?? 0) + const pitchAmount = ((opts.autoRotatePitchAmount ?? 0) * Math.PI) / 180 + targetAzimuth += speed * fade * dt + if (pitchSpeed && pitchAmount) { + targetElevation += Math.sin(t * pitchSpeed) * fade * dt * pitchAmount + } + } + } + + targetElevation = Math.max(minEl, Math.min(maxEl, targetElevation)) + targetDistance = Math.max(opts.minDistance, Math.min(opts.maxDistance, targetDistance)) + + const step = dt > 0 ? dt : 1 / 60 + const timeFactor = inertiaTime > 0 ? 1 - Math.exp(-step / inertiaTime) : 1 + const smooth = inertia <= 0 ? 1 : (1 - inertia) + inertia * timeFactor + + azimuth += (targetAzimuth - azimuth) * smooth + elevation += (targetElevation - elevation) * smooth + distance += (targetDistance - distance) * smooth + + const x = pivot.x + distance * Math.cos(elevation) * Math.sin(azimuth) + const y = pivot.y + distance * Math.sin(elevation) + const z = pivot.z + distance * Math.cos(elevation) * Math.cos(azimuth) + + cameraEntity.setPosition(x, y, z) + cameraEntity.lookAt(pivot) + } + + const onMouseDown = (e: MouseEvent) => { + if (e.button === 0) dragging = true + if (e.button === 2) panning = true + lastX = e.clientX + lastY = e.clientY + idleTime = 0 + } + + const onMouseMove = (e: MouseEvent) => { + if (!dragging && !panning) return + const dx = e.clientX - lastX + const dy = e.clientY - lastY + lastX = e.clientX + lastY = e.clientY + idleTime = 0 + + if (dragging) { + targetAzimuth -= dx * 0.005 + targetElevation -= dy * 0.005 + } else if (panning) { + const s = distance * 0.0018 + const right = cameraEntity.right.clone().mulScalar(-dx * s) + const up = cameraEntity.up.clone().mulScalar(dy * s) + pivot = pivot.add(right).add(up) + } + updateCamera(0) + emitChange(false) + } + + const onMouseUp = () => { + dragging = false + panning = false + idleTime = 0 + emitChange(true) + } + + const onWheel = (e: WheelEvent) => { + idleTime = 0 + const dir = Math.sign(e.deltaY) + if (dir) targetDistance *= 1 + dir * zoomStrength + updateCamera(0) + emitChange(false) + if (wheelCommitTimer) window.clearTimeout(wheelCommitTimer) + wheelCommitTimer = window.setTimeout(() => { + wheelCommitTimer = null + emitChange(true) + }, 180) + } + + const onContextMenu = (e: Event) => e.preventDefault() + + canvas.addEventListener('mousedown', onMouseDown) + window.addEventListener('mousemove', onMouseMove) + window.addEventListener('mouseup', onMouseUp) + canvas.addEventListener('wheel', onWheel, { passive: true }) + canvas.addEventListener('contextmenu', onContextMenu) + + app.on('update', updateCamera as any) + updateCamera(0) + + const api: OrbitController = { + setPivot(v: pc.Vec3) { + pivot = v.clone() + updateCamera() + }, + setDistance(d: number) { + targetDistance = d + updateCamera() + }, + setZoomStrength(value?: number | null) { + zoomStrength = clampZoom(value) + }, + setInertiaFactor(value?: number | null) { + inertia = clampInertia(value) + }, + setInertiaTime(value?: number | null) { + inertiaTime = clampInertiaTime(value) + }, + setAutoRotate(value?: boolean | null) { + autoRotate = value !== false + if (!autoRotate) idleTime = 0 + }, + setState(state: CameraState) { + if (!state) return + const nextPivot = state.pivot || { x: 0, y: 0, z: 0 } + pivot = new pc.Vec3( + Number(nextPivot.x) || 0, + Number(nextPivot.y) || 0, + Number(nextPivot.z) || 0, + ) + const nextAz = toRad(Number(state.azimuthDeg) || 0) + const nextEl = toRad(Number(state.elevationDeg) || 0) + azimuth = nextAz + elevation = nextEl + targetAzimuth = nextAz + targetElevation = nextEl + const nextDistance = Number(state.distance) || distance + distance = nextDistance + targetDistance = nextDistance + updateCamera(0) + }, + getState() { + return snapshot(true) + }, + destroy() { + canvas.removeEventListener('mousedown', onMouseDown) + window.removeEventListener('mousemove', onMouseMove) + window.removeEventListener('mouseup', onMouseUp) + canvas.removeEventListener('wheel', onWheel as any) + canvas.removeEventListener('contextmenu', onContextMenu) + app.off('update', updateCamera) + if (wheelCommitTimer) window.clearTimeout(wheelCommitTimer) + }, + } + + ;(app as any).__orbit = api + return api +} + +type RenderOverrides = { renderFormats: number[]; samples: number } + +function resolveRenderOverrides(fx: PostFxSettings, device: pc.GraphicsDevice | null): RenderOverrides { + const maxSamples = Number.isFinite((device as any)?.maxSamples) ? Number((device as any).maxSamples) : 1 + const rawSamples = Number(fx.rendering.samples) + let samples = Number.isFinite(rawSamples) ? Math.round(rawSamples) : 1 + samples = Math.max(1, samples || 1) + samples = Math.min(samples, Math.max(1, maxSamples)) + const originalSamples = samples + const forceSingleSample = samples > 1 + if (forceSingleSample) samples = 1 + + const primary = Number(fx.rendering.renderFormat) + if (primary === PIXELFORMAT_RGBA8) { + return { renderFormats: [PIXELFORMAT_RGBA8], samples } + } + + const candidates = [ + primary, + fx.rendering.renderFormatFallback0, + fx.rendering.renderFormatFallback1, + ] + + const canUseFormat = (fmt: number, sampleCount: number) => { + if (!device) return fmt !== PIXELFORMAT_RGBA8 + if (fmt === PIXELFORMAT_111110F) return !!(device as any).textureRG11B10Renderable + if (fmt === PIXELFORMAT_RGBA16F) return !!(device as any).textureHalfFloatRenderable + if (fmt === PIXELFORMAT_RGBA32F) { + const floatRenderable = !!(device as any).textureFloatRenderable + const floatFilterable = (device as any).textureFloatFilterable !== false + if (!floatRenderable || !floatFilterable) return false + if ((device as any).isWebGPU && sampleCount > 1) return false + return true + } + return fmt !== PIXELFORMAT_RGBA8 + } + + const buildFormats = (sampleCount: number) => { + const list: number[] = [] + for (const candidate of candidates) { + const fmt = Number(candidate) + if (!Number.isFinite(fmt)) continue + if (!canUseFormat(fmt, sampleCount)) continue + if (!list.includes(fmt)) list.push(fmt) + } + return list + } + + let renderFormats = buildFormats(samples) + if (!renderFormats.length && samples > 1) { + const singleSampleFormats = buildFormats(1) + if (singleSampleFormats.length) { + samples = 1 + renderFormats = singleSampleFormats + } + } + if (samples > 1 && renderFormats.length > 0) { + samples = 1 + } + if (!renderFormats.length) { + samples = forceSingleSample ? 1 : originalSamples + renderFormats = [PIXELFORMAT_RGBA8] + } + + return { renderFormats, samples } +} + +function applyPostFx( + frame: any, + fx: PostFxSettings, + lutTexture: pc.Texture | null, + overrides?: RenderOverrides +) { + if (!frame) return + + if (frame.rendering) { + if (Array.isArray(frame.rendering.renderFormats)) { + const formats = Array.isArray(overrides?.renderFormats) ? overrides?.renderFormats : (() => { + const list: number[] = [] + if (Number.isFinite(fx.rendering.renderFormat)) list.push(fx.rendering.renderFormat) + if (Number.isFinite(fx.rendering.renderFormatFallback0)) list.push(fx.rendering.renderFormatFallback0) + if (Number.isFinite(fx.rendering.renderFormatFallback1)) list.push(fx.rendering.renderFormatFallback1) + return list + })() + if (formats.length) { + frame.rendering.renderFormats.length = 0 + frame.rendering.renderFormats.push(...formats) + } + } else if (Array.isArray(overrides?.renderFormats) && overrides?.renderFormats.length) { + const fmt = overrides.renderFormats[0] + if (Number.isFinite(fmt)) frame.rendering.renderFormat = fmt + } + if (typeof frame.rendering.stencil === 'boolean') { + frame.rendering.stencil = !!fx.rendering.stencil + } + frame.rendering.renderTargetScale = fx.rendering.renderTargetScale + frame.rendering.samples = Number.isFinite(overrides?.samples) ? Number(overrides?.samples) : fx.rendering.samples + frame.rendering.sceneColorMap = true + frame.rendering.sceneDepthMap = !!fx.rendering.sceneDepthMap + frame.rendering.toneMapping = fx.rendering.toneMapping + frame.rendering.sharpness = fx.rendering.sharpness + } + + if (frame.ssao) { + frame.ssao.type = fx.ssao.type + frame.ssao.blurEnabled = !!fx.ssao.blurEnabled + if (fx.ssao.type !== 'none') { + frame.ssao.intensity = fx.ssao.intensity + frame.ssao.radius = fx.ssao.radius + frame.ssao.samples = fx.ssao.samples + frame.ssao.power = fx.ssao.power + frame.ssao.minAngle = fx.ssao.minAngle + frame.ssao.scale = fx.ssao.scale + } + } + + if (frame.bloom) { + const enabled = !!fx.bloom.enabled + frame.bloom.enabled = enabled + frame.bloom.intensity = enabled ? fx.bloom.intensity : 0 + if (enabled) { + const blurLevel = + Number.isFinite((fx.bloom as any).lastMipLevel) + ? Number((fx.bloom as any).lastMipLevel) + : Number((fx.bloom as any).blurLevel) + if (Number.isFinite(blurLevel)) frame.bloom.blurLevel = blurLevel + } + } + + if (frame.grading) { + frame.grading.enabled = !!fx.grading.enabled + if (fx.grading.enabled) { + frame.grading.brightness = fx.grading.brightness + frame.grading.contrast = fx.grading.contrast + frame.grading.saturation = fx.grading.saturation + const c = toColor(fx.grading.tint) + frame.grading.tint?.copy?.(c) ?? (frame.grading.tint = c) + } + } + + if (frame.colorLUT) { + frame.colorLUT.texture = lutTexture || null + frame.colorLUT.intensity = fx.lut.intensity + } + + if (frame.vignette) { + const enabled = !!fx.vignette.enabled + frame.vignette.enabled = enabled + frame.vignette.intensity = enabled ? fx.vignette.intensity : 0 + if (enabled) { + frame.vignette.inner = fx.vignette.inner + frame.vignette.outer = fx.vignette.outer + frame.vignette.curvature = fx.vignette.curvature + const c = toColor(fx.vignette.color) + frame.vignette.color?.copy?.(c) ?? (frame.vignette.color = c) + } + } + + if (frame.taa) { + frame.taa.enabled = !!fx.taa.enabled + if (fx.taa.enabled) frame.taa.jitter = fx.taa.jitter + } + + if (frame.fringing) { + const enabled = !!fx.chromaticAberration.enabled + frame.fringing.enabled = enabled + frame.fringing.intensity = enabled ? fx.chromaticAberration.intensity : 0 + } + + frame.update?.() +} + +export default function PlayCanvasViewer({ + modelUrl, + postFx, + viewportSize, + onSceneReady, + onSelectionChanged, + onSceneGraph, + exposeSceneGraph = false, + cameraState, + cameraResetToken, + cameraZoomStrength, + cameraInertiaFactor, + cameraInertiaTime, + cameraAutoRotate, + onCameraChange, + muteLogs = false, + onModelState, +}: PlayCanvasViewerProps) { + const canvasRef = useRef(null) + const appRef = useRef(null) + const cameraEntityRef = useRef(null) + const cameraFrameRef = useRef(null) + const modelAssetRef = useRef(null) + const envAtlasRef = useRef(null) + const envAtlasImageRef = useRef(null) + const envAtlasAdjustKeyRef = useRef(null) + const skyboxSourceRef = useRef(null) + const skyboxLightingSourceRef = useRef(null) + const skyboxCubemapRef = useRef(null) + const skyboxAtlasRef = useRef(null) + const lutTextureRef = useRef(null) + const directionalLightRef = useRef(null) + const shadowCatcherRef = useRef(null) + const shadowCatcherLightRef = useRef(null) + const shadowCatcherPlaneRef = useRef(null) + const gridEntityRef = useRef(null) + const gridMaterialRef = useRef(null) + const sceneMapRef = useRef>(new Map()) + const loadTokenRef = useRef(0) + const cameraStateRef = useRef(null) + const onCameraChangeRef = useRef(null) + const logWarn = useCallback((...args: any[]) => { if (!muteLogs) console.warn(...args) }, [muteLogs]) + const logError = useCallback((...args: any[]) => { if (!muteLogs) console.error(...args) }, [muteLogs]) + const [appReady, setAppReady] = useState(false) + const [envAtlasVersion, setEnvAtlasVersion] = useState(0) + const [skyboxVersion, setSkyboxVersion] = useState(0) + const [modelVersion, setModelVersion] = useState(0) + + const fx = useMemo(() => mergePostFxDefaults(postFx), [postFx]) + + useEffect(() => { + cameraStateRef.current = cameraState ?? null + }, [cameraState]) + + useEffect(() => { + onCameraChangeRef.current = onCameraChange ?? null + }, [onCameraChange]) + + const resizeCanvas = React.useCallback((width?: number, height?: number) => { + const canvas = canvasRef.current + const inst = appRef.current + if (!canvas || !inst) return + const w = Math.max(1, Math.round(width ?? canvas.parentElement?.clientWidth ?? canvas.clientWidth)) + const h = Math.max(1, Math.round(height ?? canvas.parentElement?.clientHeight ?? canvas.clientHeight)) + if (canvas.width !== w) canvas.width = w + if (canvas.height !== h) canvas.height = h + try { + if (inst.resizeCanvas.length >= 2) { + inst.resizeCanvas(w, h) + } else { + inst.resizeCanvas() + } + } catch {} + // PlayCanvas writes fixed pixel CSS sizes; the hosted pane remains fluid. + canvas.style.width = '100%' + canvas.style.height = '100%' + const model = inst.root.findByName('Model') as pc.Entity | null + const bounds = model ? computeAabb(model) : null + const orbit = (inst as any).__orbit as OrbitController | undefined + if (bounds && orbit) { + const vertical = (cameraEntityRef.current?.camera?.fov ?? 28) * Math.PI / 360 + const horizontal = Math.atan(Math.tan(vertical) * w / h) + orbit.setDistance(Math.max(1.8, bounds.halfExtents.length() / Math.sin(Math.min(vertical, horizontal)) * 1.1)) + } + }, []) + + useEffect(() => { + const canvas = canvasRef.current + if (!canvas) return + + const app = new pc.Application(canvas, { + mouse: new pc.Mouse(canvas), + touch: new pc.TouchDevice(canvas), + keyboard: new pc.Keyboard(window), + }) + + appRef.current = app + + app.setCanvasFillMode((pc as any).FILLMODE_NONE ?? pc.FILLMODE_NONE) + app.setCanvasResolution(pc.RESOLUTION_AUTO) + app.scene.exposure = 1.0 + const renderOverrides = resolveRenderOverrides(fx, (app as any).graphicsDevice ?? (app as any).device ?? null) + + const ensureHandler = (type: string, Ctor: any) => { + const loaderAny: any = (app as any).loader + if (!loaderAny || !Ctor) return + + try { + if (typeof loaderAny.getHandler === 'function' && loaderAny.getHandler(type)) return + } catch {} + + const tryCreate = () => { + try { return new Ctor((app as any).graphicsDevice ?? (app as any).device ?? app) } catch {} + try { return new Ctor(app) } catch {} + try { return new Ctor((app as any).graphicsDevice, (app as any).assets) } catch {} + try { return new Ctor((app as any).graphicsDevice, (app as any).assets, (app as any).loader) } catch {} + return null + } + + const handler = tryCreate() + if (!handler) return + + try { + loaderAny.addHandler(type, handler) + } catch (e) { + logWarn(`[PlayCanvasViewer] Failed to register handler ${type}`, e) + } + } + + ensureHandler('texture', (pc as any).TextureHandler) + ensureHandler('container', (pc as any).ContainerHandler) + ensureTextureHandler(app) + + const modelRoot = new pc.Entity('ModelRoot') + app.root.addChild(modelRoot) + + app.scene.ambientLight = new pc.Color(0, 0, 0) + + const camera = new pc.Entity('Camera') + camera.addComponent('camera', { + clearColor: toColor(fx.rendering.backgroundColor), + fov: 28, + farClip: 500, + nearClip: 0.05, + }) + app.root.addChild(camera) + cameraEntityRef.current = camera + + try { + const CameraFrameCtor: any = (pc as any).CameraFrame + if (CameraFrameCtor) { + const cf = new CameraFrameCtor(app, camera.camera) + cameraFrameRef.current = cf + applyPostFx(cf, fx, lutTextureRef.current, renderOverrides) + try { cf.update?.() } catch {} + } + } catch (e) { + logWarn('[PlayCanvasViewer] CameraFrame init failed:', e) + cameraFrameRef.current = null + } + + const cam = camera.camera! + ;(cam as any).gammaCorrection = pc.GAMMA_SRGB + ;(cam as any).toneMapping = fx.rendering.toneMapping + + if (typeof (cam as any).requestSceneColorMap === 'function') { + ;(cam as any).requestSceneColorMap(true) + } + if (typeof (cam as any).requestSceneDepthMap === 'function') { + ;(cam as any).requestSceneDepthMap(true) + } + if (Array.isArray((cam as any).layers) && !(cam as any).layers.includes(pc.LAYERID_DEPTH)) { + ;(cam as any).layers = [...(cam as any).layers, pc.LAYERID_DEPTH] + } + + const initialCamera = cameraStateRef.current + const orbit = makeOrbitController(app, camera, { + pivot: initialCamera + ? new pc.Vec3( + Number(initialCamera.pivot?.x) || 0, + Number(initialCamera.pivot?.y) || 0, + Number(initialCamera.pivot?.z) || 0, + ) + : new pc.Vec3(0, 0, 0), + distance: Number(initialCamera?.distance) || 6, + minDistance: 0.05, + maxDistance: 500, + minElevationDeg: 5, + maxElevationDeg: 90, + initialAzimuthDeg: Number.isFinite(initialCamera?.azimuthDeg) ? Number(initialCamera?.azimuthDeg) : 45, + initialElevationDeg: Number.isFinite(initialCamera?.elevationDeg) ? Number(initialCamera?.elevationDeg) : 10, + autoRotate: cameraAutoRotate !== false, + autoRotateSpeed: 4, + autoRotateDelay: 4, + autoRotateFade: 5, + autoRotatePitchSpeed: 0, + autoRotatePitchAmount: 1, + zoomStrength: cameraZoomStrength ?? undefined, + inertiaFactor: cameraInertiaFactor ?? undefined, + inertiaTime: cameraInertiaTime ?? undefined, + onChange: (state, commit) => { + onCameraChangeRef.current?.(state, commit) + }, + }) + + const directionalLight = new pc.Entity('DirectionalLight') + directionalLight.addComponent('light', { + type: 'directional', + }) + app.root.addChild(directionalLight) + directionalLightRef.current = directionalLight + + const gridEntity = new pc.Entity('Grid') + gridEntity.addComponent('render', { castShadows: false }) + const gridMaterial = new pc.ShaderMaterial({ + uniqueName: 'grid-shader', + vertexGLSL: ` + attribute vec3 vertex_position; + attribute vec2 aUv0; + + uniform mat4 matrix_model; + uniform mat4 matrix_viewProjection; + + varying vec2 uv0; + + void main(void) { + gl_Position = matrix_viewProjection * matrix_model * vec4(vertex_position, 1.0); + uv0 = aUv0; + } +`, + fragmentGLSL: ` + uniform vec2 uHalfExtents; + uniform vec3 uColorX; + uniform vec3 uColorZ; + uniform vec3 uColorMain; + uniform float uAlphaX; + uniform float uAlphaZ; + uniform float uAlphaMain; + uniform int uResolution; + uniform vec3 uDotColor; + uniform float uDotAlpha; + uniform float uDotSize; + uniform vec3 uCrossColor; + uniform float uCrossAlpha; + uniform float uCrossLength; + uniform float uCrossWidth; + uniform float uFadeStart; + uniform float uFadeEnd; + + varying vec2 uv0; + + // https://bgolus.medium.com/the-best-darn-grid-shader-yet-727f9278b9d8#1e7c + float pristineGrid(in vec2 uv, in vec2 ddx, in vec2 ddy, vec2 lineWidth) { + vec2 uvDeriv = vec2(length(vec2(ddx.x, ddy.x)), length(vec2(ddx.y, ddy.y))); + bvec2 invertLine = bvec2(lineWidth.x > 0.5, lineWidth.y > 0.5); + vec2 targetWidth = vec2( + invertLine.x ? 1.0 - lineWidth.x : lineWidth.x, + invertLine.y ? 1.0 - lineWidth.y : lineWidth.y + ); + vec2 drawWidth = clamp(targetWidth, uvDeriv, vec2(0.5)); + vec2 lineAA = uvDeriv * 1.5; + vec2 gridUV = abs(fract(uv) * 2.0 - 1.0); + gridUV.x = invertLine.x ? gridUV.x : 1.0 - gridUV.x; + gridUV.y = invertLine.y ? gridUV.y : 1.0 - gridUV.y; + vec2 grid2 = smoothstep(drawWidth + lineAA, drawWidth - lineAA, gridUV); + + grid2 *= clamp(targetWidth / drawWidth, 0.0, 1.0); + grid2 = mix(grid2, targetWidth, clamp(uvDeriv * 2.0 - 1.0, 0.0, 1.0)); + grid2.x = invertLine.x ? 1.0 - grid2.x : grid2.x; + grid2.y = invertLine.y ? 1.0 - grid2.y : grid2.y; + + return mix(grid2.x, 1.0, grid2.y); + } + + float dotMask(vec2 levelPos, float radius) { + if (radius <= 0.0) { + return 0.0; + } + vec2 dist = min(fract(levelPos), 1.0 - fract(levelPos)); + float d = length(dist); + float aa = max(fwidth(levelPos.x), fwidth(levelPos.y)); + return 1.0 - smoothstep(radius - aa, radius + aa, d); + } + + float crossMask(vec2 levelPos, float halfLen, float halfWidth) { + if (halfLen <= 0.0 || halfWidth <= 0.0) { + return 0.0; + } + vec2 dist = min(fract(levelPos), 1.0 - fract(levelPos)); + float dx = dist.x; + float dy = dist.y; + float aa = max(fwidth(levelPos.x), fwidth(levelPos.y)); + float hor = (1.0 - smoothstep(halfWidth - aa, halfWidth + aa, dy)) * + (1.0 - smoothstep(halfLen - aa, halfLen + aa, dx)); + float ver = (1.0 - smoothstep(halfWidth - aa, halfWidth + aa, dx)) * + (1.0 - smoothstep(halfLen - aa, halfLen + aa, dy)); + return max(hor, ver); + } + + void main(void) { + vec2 uv = uv0; + + vec2 pos = (uv * 2.0 - 1.0) * uHalfExtents; + vec2 ddx = dFdx(pos); + vec2 ddy = dFdy(pos); + + float epsilon = 1.0 / 255.0; + float res = float(uResolution); + + vec2 levelPos; + float levelSize; + float levelAlpha; + vec3 baseColor = vec3(0.0); + float baseAlpha = 0.0; + float hasBase = 0.0; + + levelPos = pos * 0.1; + levelSize = 2.0 / 1000.0; + levelAlpha = pristineGrid(levelPos, ddx * 0.1, ddy * 0.1, vec2(levelSize)); + if (levelAlpha > epsilon) { + vec3 color; + float alphaMul = uAlphaMain; + if (abs(levelPos.x) < levelSize) { + if (abs(levelPos.y) < levelSize) { + color = vec3(1.0); + } else { + color = uColorZ; + alphaMul = uAlphaZ; + } + } else if (abs(levelPos.y) < levelSize) { + color = uColorX; + alphaMul = uAlphaX; + } else { + color = uColorMain; + } + baseColor = color; + baseAlpha = levelAlpha * alphaMul; + hasBase = 1.0; + } + + if (hasBase < 0.5 && res >= 1.0) { + levelPos = pos; + levelSize = 1.0 / 100.0; + levelAlpha = pristineGrid(levelPos, ddx, ddy, vec2(levelSize)); + if (levelAlpha > epsilon) { + baseColor = uColorMain; + baseAlpha = levelAlpha * uAlphaMain; + hasBase = 1.0; + } + } + + if (hasBase < 0.5 && res >= 2.0) { + levelPos = pos * 10.0; + levelSize = 1.0 / 100.0; + levelAlpha = pristineGrid(levelPos, ddx * 10.0, ddy * 10.0, vec2(levelSize)); + if (levelAlpha > epsilon) { + baseColor = uColorMain; + baseAlpha = levelAlpha * uAlphaMain; + hasBase = 1.0; + } + } + + float dotRadius = max(0.0, uDotSize) * 0.5; + float crossHalfLen = max(0.0, uCrossLength) * 0.5; + float crossHalfWidth = max(0.0, uCrossWidth) * 0.5; + float dotMaskAll = 0.0; + float crossMaskAll = 0.0; + + if (res >= 1.0) { + levelPos = pos; + dotMaskAll = dotMask(levelPos, dotRadius); + crossMaskAll = crossMask(levelPos, crossHalfLen, crossHalfWidth); + } + + vec3 outColor = baseColor; + float outAlpha = baseAlpha; + float dotAlpha = clamp(uDotAlpha, 0.0, 1.0) * dotMaskAll; + float crossAlpha = clamp(uCrossAlpha, 0.0, 1.0) * crossMaskAll; + float fadeStart = max(0.0, uFadeStart); + float fadeEnd = max(0.0, uFadeEnd); + float fade = 1.0; + if (fadeEnd > fadeStart && fadeEnd > 0.0) { + float d = length(pos); + fade = 1.0 - smoothstep(fadeStart, fadeEnd, d); + } + outAlpha *= fade; + dotAlpha *= fade; + crossAlpha *= fade; + if (dotAlpha > 0.0) { + outColor = mix(outColor, uDotColor, dotAlpha); + outAlpha = max(outAlpha, dotAlpha); + } + if (crossAlpha > 0.0) { + outColor = mix(outColor, uCrossColor, crossAlpha); + outAlpha = max(outAlpha, crossAlpha); + } + + if (outAlpha <= epsilon) { + discard; + } + gl_FragColor = vec4(outColor, outAlpha); + } +`, + attributes: { + vertex_position: (pc as any).SEMANTIC_POSITION ?? pc.SEMANTIC_POSITION, + aUv0: (pc as any).SEMANTIC_TEXCOORD0 ?? pc.SEMANTIC_TEXCOORD0, + }, + }) + gridMaterial.blendType = pc.BLEND_NORMAL + gridMaterial.cull = pc.CULLFACE_NONE + gridMaterial.update() + const gridMesh = pc.Mesh.fromGeometry(app.graphicsDevice, new pc.PlaneGeometry()) + const gridMeshInstance = new pc.MeshInstance(gridMesh, gridMaterial) + gridEntity.render!.meshInstances = [gridMeshInstance] + gridEntity.setLocalScale(1000, 1, 1000) + gridEntity.setLocalPosition(0, 0, 0) + gridMaterial.setParameter('uColorX', [1, 0.3, 0.3]) + gridMaterial.setParameter('uColorZ', [0.3, 0.3, 1]) + gridMaterial.setParameter('uColorMain', [0.9, 0.9, 0.9]) + gridMaterial.setParameter('uAlphaX', 1) + gridMaterial.setParameter('uAlphaZ', 1) + gridMaterial.setParameter('uAlphaMain', 1) + gridMaterial.setParameter('uDotColor', [1, 1, 1]) + gridMaterial.setParameter('uDotAlpha', 0) + gridMaterial.setParameter('uDotSize', 0) + gridMaterial.setParameter('uCrossColor', [1, 1, 1]) + gridMaterial.setParameter('uCrossAlpha', 0) + gridMaterial.setParameter('uCrossLength', 0) + gridMaterial.setParameter('uCrossWidth', 0) + gridMaterial.setParameter('uFadeStart', 0) + gridMaterial.setParameter('uFadeEnd', 0) + gridMaterial.setParameter('uResolution', 2) + const gridHalfExtents = new pc.Vec2(500, 500) + gridMaterial.setParameter('uHalfExtents', [gridHalfExtents.x, gridHalfExtents.y]) + gridMaterial.update() + app.root.addChild(gridEntity) + gridEntityRef.current = gridEntity + gridMaterialRef.current = gridMaterial + + const updateGridHalfExtents = () => { + const scale = gridEntity.getLocalScale() + const half = new pc.Vec2(scale.x / 2, scale.z / 2) + if (gridHalfExtents.distance(half) > 0.001) { + gridHalfExtents.copy(half) + gridMaterial.setParameter('uHalfExtents', [gridHalfExtents.x, gridHalfExtents.y]) + gridMaterial.update() + } + } + app.on('prerender', updateGridHalfExtents) + + const shadowCatcher = new pc.Entity('ShadowCatcher') + shadowCatcherRef.current = shadowCatcher + shadowCatcher.setLocalPosition(0, fx.shadowCatcher.yOffset, 0) + + const shadowLight = new pc.Entity('ShadowCatcherLight') + shadowLight.addComponent('light', { + type: 'directional', + castShadows: true, + shadowUpdateMode: pc.SHADOWUPDATE_REALTIME, + }) + shadowCatcherLightRef.current = shadowLight + shadowCatcher.addChild(shadowLight) + + const shadowPlane = new pc.Entity('ShadowCatcherGeometry') + const shadowMat = new pc.StandardMaterial() + shadowMat.blendType = pc.BLEND_MULTIPLICATIVE + shadowMat.shadowCatcher = true + shadowMat.useSkybox = false + shadowMat.depthWrite = false + shadowMat.diffuse.set(0, 0, 0) + shadowMat.specular.set(0, 0, 0) + shadowMat.update() + shadowPlane.addComponent('render', { type: 'plane', castShadows: false, material: shadowMat }) + shadowPlane.setLocalScale(fx.shadowCatcher.size, 1, fx.shadowCatcher.size) + shadowCatcherPlaneRef.current = shadowPlane + shadowPlane.render?.meshInstances?.forEach((mi: any) => { + mi.drawOrder = -1 + mi.material = shadowMat + }) + shadowCatcher.addChild(shadowPlane) + app.root.addChild(shadowCatcher) + + let started = false + try { + app.start() + started = true + } catch (err) { + logError('[PlayCanvasViewer] App start failed:', err) + } + + if (!started) { + try { app.destroy() } catch {} + appRef.current = null + return () => {} + } + + setAppReady(true) + + try { + const atlasUrl = '/rover-scene/environment-map.png' + const asset = new pc.Asset( + 'envAtlas_default', + 'texture', + { url: atlasUrl }, + { + type: 'rgbp', + addressu: 'clamp', + addressv: 'clamp', + mipmaps: false, + } as any + ) + app.assets.add(asset) + app.assets.load(asset) + + asset.ready(() => { + envAtlasRef.current = asset.resource as any + ;(async () => { + try { + const res = await fetch(atlasUrl) + if (!res.ok) throw new Error(`Failed to fetch ${atlasUrl} (${res.status})`) + const blob = await res.blob() + const bmp = await createImageBitmap(blob) + envAtlasImageRef.current = bmp + } catch (err) { + try { + const img = new Image() + img.src = atlasUrl + await new Promise((resolve, reject) => { + img.onload = () => resolve() + img.onerror = () => reject(new Error('Failed to load env atlas image')) + }) + envAtlasImageRef.current = img + } catch (fallbackErr) { + logWarn('[PlayCanvasViewer] Failed to load env atlas image', fallbackErr) + } + } finally { + setEnvAtlasVersion((v) => v + 1) + } + })() + }) + } catch (e) { + logWarn('[PlayCanvasViewer] Failed to init default environment-map.png', e) + } + + onSceneReady?.({ app, camera, modelRoot }) + + const ro = new ResizeObserver(() => resizeCanvas()) + ro.observe(canvas.parentElement ?? canvas) + resizeCanvas() + + return () => { + try { ro.disconnect() } catch {} + orbit.destroy() + cameraEntityRef.current = null + directionalLightRef.current = null + shadowCatcherRef.current = null + shadowCatcherLightRef.current = null + shadowCatcherPlaneRef.current = null + try { cameraFrameRef.current?.destroy?.() } catch {} + try { lutTextureRef.current?.destroy?.() } catch {} + destroyTexture(envAtlasRef.current) + destroyTexture(skyboxSourceRef.current) + destroyTexture(skyboxLightingSourceRef.current) + destroyTexture(skyboxCubemapRef.current) + destroyTexture(skyboxAtlasRef.current) + envAtlasImageRef.current = null + try { app.off('prerender', updateGridHalfExtents) } catch {} + try { gridMaterial.destroy?.() } catch {} + try { shadowMat.destroy?.() } catch {} + + app.destroy() + appRef.current = null + modelAssetRef.current = null + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []) + + useEffect(() => { + if (!viewportSize) return + const w = Math.max(1, Math.round(viewportSize.width)) + const h = Math.max(1, Math.round(viewportSize.height)) + const id = window.requestAnimationFrame(() => resizeCanvas(w, h)) + return () => window.cancelAnimationFrame(id) + }, [viewportSize?.width, viewportSize?.height, resizeCanvas]) + + const resolvedUrl = modelUrl || DEFAULT_MODEL_URL + + useEffect(() => { + const app = appRef.current + if (!app || !resolvedUrl) return + const modelRoot = app.root.findByName('ModelRoot') as pc.Entity | null + if (!modelRoot) return + + let cancelled = false + + const loadGlb = async (url: string) => { + const loadToken = ++loadTokenRef.current + let asset: pc.Asset | null = null + try { + if (!app?.assets) return + + const prevAsset = modelAssetRef.current + const prevChildren = modelRoot.children.slice() + + ensureTextureHandler(app) + + asset = new pc.Asset('model', 'container', { url }) + app.assets.add(asset) + + const loadedAsset = asset + await new Promise((resolve, reject) => { + loadedAsset.ready(() => resolve()) + loadedAsset.on('error', (err: unknown) => reject(err)) + app.assets.load(loadedAsset) + }) + + if (cancelled || loadTokenRef.current !== loadToken) { + try { + if (asset) { + app.assets.remove(asset) + asset.unload?.() + } + } catch {} + return + } + + prevChildren.forEach((c) => c.destroy()) + if (prevAsset) { + try { + app.assets.remove(prevAsset) + prevAsset.unload?.() + } catch {} + } + if (!asset) return + modelAssetRef.current = asset + const resource = asset.resource as any + const entity: pc.Entity = resource.instantiateRenderEntity() + entity.name = 'Model' + modelRoot.addChild(entity) + disableInvalidMeshes(entity) + + const orbit = (app as any).__orbit as OrbitController | undefined + const aabb = computeAabb(entity) + if (orbit && aabb && !cameraStateRef.current) { + orbit.setPivot(aabb.center.clone()) + const cam = cameraEntityRef.current?.camera + const vertical = (cam?.fov ?? 28) * Math.PI / 360 + const horizontal = Math.atan(Math.tan(vertical) * (cam?.aspectRatio ?? 1)) + orbit.setDistance(Math.max(1.8, aabb.halfExtents.length() / Math.sin(Math.min(vertical, horizontal)) * 1.1)) + } + + if (exposeSceneGraph || onSceneGraph) { + const map = new Map() + sceneMapRef.current = map + const graphRoot = modelRoot ?? app.root + const tree = buildSceneTree(graphRoot, map) + onSceneGraph?.(tree, map) + } + setModelVersion((v) => v + 1) + onModelState?.("ready") + } catch (e) { + logError('[PlayCanvasViewer] Failed to load model:', e) + if (!cancelled && asset && app?.assets) { + try { + app.assets.remove(asset) + asset.unload?.() + } catch {} + } + if (!cancelled) onModelState?.("error") + } + } + + onModelState?.("loading") + loadGlb(resolvedUrl) + + return () => { + cancelled = true + } + }, [resolvedUrl, exposeSceneGraph, onSceneGraph]) + + useEffect(() => { + if (!appReady || !cameraState) return + const app = appRef.current + if (!app) return + const orbit = (app as any).__orbit as OrbitController | undefined + if (!orbit) return + orbit.setState(cameraState) + }, [appReady, cameraState]) + + useEffect(() => { + if (!appReady) return + const app = appRef.current + if (!app) return + const orbit = (app as any).__orbit as OrbitController | undefined + if (!orbit) return + orbit.setZoomStrength(cameraZoomStrength ?? undefined) + }, [appReady, cameraZoomStrength]) + + useEffect(() => { + if (!appReady) return + const app = appRef.current + if (!app) return + const orbit = (app as any).__orbit as OrbitController | undefined + if (!orbit) return + orbit.setInertiaFactor(cameraInertiaFactor ?? undefined) + }, [appReady, cameraInertiaFactor]) + + useEffect(() => { + if (!appReady) return + const app = appRef.current + if (!app) return + const orbit = (app as any).__orbit as OrbitController | undefined + if (!orbit) return + orbit.setInertiaTime(cameraInertiaTime ?? undefined) + }, [appReady, cameraInertiaTime]) + + useEffect(() => { + if (!appReady) return + const app = appRef.current + if (!app) return + const orbit = (app as any).__orbit as OrbitController | undefined + if (!orbit) return + orbit.setAutoRotate(cameraAutoRotate ?? undefined) + }, [appReady, cameraAutoRotate]) + useEffect(() => { + if (!appReady || !cameraResetToken) return + const app = appRef.current + if (!app) return + const orbit = (app as any).__orbit as OrbitController | undefined + if (!orbit) return + const modelRoot = app.root.findByName('ModelRoot') as pc.Entity | null + if (!modelRoot) return + const modelEntity = (modelRoot as any).findByName?.('Model') as pc.Entity | null + const aabb = computeAabb(modelEntity || modelRoot) + if (!aabb) return + orbit.setState({ + pivot: { x: aabb.center.x, y: aabb.center.y, z: aabb.center.z }, + distance: Math.max(1.8, aabb.halfExtents.length() * 2.5), + azimuthDeg: 45, + elevationDeg: 10, + }) + }, [appReady, cameraResetToken, modelVersion]) + + useEffect(() => { + const app = appRef.current + if (!app) return + const camEnt = app.root.findByName('Camera') as pc.Entity | null + const cam = camEnt?.camera as any + if (cam) cam.clearColor = toColor(fx.rendering.backgroundColor) + }, [fx.rendering.backgroundColor]) + + useEffect(() => { + const grid = gridEntityRef.current + const mat = gridMaterialRef.current + if (!grid || !mat) return + + const gridVisible = !!fx.grid.enabled || !!fx.grid.dotsEnabled || !!fx.grid.crossEnabled + grid.enabled = gridVisible + const cX = toColor(fx.grid.colorX) + const cZ = toColor(fx.grid.colorZ) + const cMain = toColor(fx.grid.colorMain) + const dotColor = toColor(fx.grid.dotsColor) + const crossColor = toColor(fx.grid.crossColor) + mat.setParameter('uColorX', [cX.r, cX.g, cX.b]) + mat.setParameter('uColorZ', [cZ.r, cZ.g, cZ.b]) + mat.setParameter('uColorMain', [cMain.r, cMain.g, cMain.b]) + const linesEnabled = !!fx.grid.enabled + mat.setParameter('uAlphaX', linesEnabled ? clamp01(fx.grid.alphaX) : 0) + mat.setParameter('uAlphaZ', linesEnabled ? clamp01(fx.grid.alphaZ) : 0) + mat.setParameter('uAlphaMain', linesEnabled ? clamp01(fx.grid.alphaMain) : 0) + mat.setParameter('uDotColor', [dotColor.r, dotColor.g, dotColor.b]) + mat.setParameter('uDotAlpha', fx.grid.dotsEnabled ? clamp01(fx.grid.dotsAlpha) : 0) + mat.setParameter('uDotSize', Math.max(0, Number(fx.grid.dotsDiameter) || 0)) + mat.setParameter('uCrossColor', [crossColor.r, crossColor.g, crossColor.b]) + mat.setParameter('uCrossAlpha', fx.grid.crossEnabled ? clamp01(fx.grid.crossAlpha) : 0) + mat.setParameter('uCrossLength', Math.max(0, Number(fx.grid.crossLength) || 0)) + mat.setParameter('uCrossWidth', Math.max(0, Number(fx.grid.crossWidth) || 0)) + mat.setParameter('uFadeStart', Math.max(0, Number(fx.grid.fadeStart) || 0)) + mat.setParameter('uFadeEnd', Math.max(0, Number(fx.grid.fadeEnd) || 0)) + mat.update() + }, [ + fx.grid.enabled, + fx.grid.colorX, + fx.grid.colorZ, + fx.grid.colorMain, + fx.grid.alphaX, + fx.grid.alphaZ, + fx.grid.alphaMain, + fx.grid.dotsEnabled, + fx.grid.dotsColor, + fx.grid.dotsAlpha, + fx.grid.dotsDiameter, + fx.grid.crossEnabled, + fx.grid.crossColor, + fx.grid.crossAlpha, + fx.grid.crossLength, + fx.grid.crossWidth, + fx.grid.fadeStart, + fx.grid.fadeEnd, + ]) + + useEffect(() => { + const cam = cameraEntityRef.current?.camera as any + if (cam) cam.toneMapping = fx.rendering.toneMapping + }, [fx.rendering.toneMapping]) + + useEffect(() => { + const app = appRef.current + if (!app) return + setWireframeForScene(app, fx.rendering.wireframe) + }, [fx.rendering.wireframe]) + + useEffect(() => { + const frame: any = cameraFrameRef.current + if (!frame) return + const overrides = resolveRenderOverrides(fx, appRef.current?.graphicsDevice ?? null) + applyPostFx(frame, fx, lutTextureRef.current, overrides) + }, [fx]) + + useEffect(() => { + const app = appRef.current + if (!app) return + if (fx.lighting) { + app.scene.exposure = fx.lighting.exposure + } + }, [fx.lighting?.exposure]) + + useEffect(() => { + const app = appRef.current + if (!app) return + + const scene: any = app.scene + const fogType = fx.rendering.fog + const fogValue = + fogType === 'linear' ? pc.FOG_LINEAR : + fogType === 'exp' ? pc.FOG_EXP : + fogType === 'exp2' ? pc.FOG_EXP2 : + pc.FOG_NONE + + const fog = scene?.fog + if (fog && typeof fog === 'object') { + fog.type = fogValue + const fogColor = toColor(fx.rendering.fogColor) + if (fog.color?.copy) fog.color.copy(fogColor) + else fog.color = fogColor + + if (Number.isFinite(fx.rendering.fogDensity)) { + fog.density = fx.rendering.fogDensity + } + + const range = fx.rendering.fogRange + const start = Number.isFinite(fx.rendering.fogStart) ? fx.rendering.fogStart : (Array.isArray(range) ? range[0] : undefined) + const end = Number.isFinite(fx.rendering.fogEnd) ? fx.rendering.fogEnd : (Array.isArray(range) ? range[1] : undefined) + if (Number.isFinite(start)) fog.start = start + if (Number.isFinite(end)) fog.end = end + } else { + scene.fog = fogValue + + const fogColor = toColor(fx.rendering.fogColor) + if (scene.fogColor?.copy) scene.fogColor.copy(fogColor) + else scene.fogColor = fogColor + + if (Number.isFinite(fx.rendering.fogDensity)) { + scene.fogDensity = fx.rendering.fogDensity + } + + const range = fx.rendering.fogRange + const start = Number.isFinite(fx.rendering.fogStart) ? fx.rendering.fogStart : (Array.isArray(range) ? range[0] : undefined) + const end = Number.isFinite(fx.rendering.fogEnd) ? fx.rendering.fogEnd : (Array.isArray(range) ? range[1] : undefined) + if (Number.isFinite(start)) scene.fogStart = start + if (Number.isFinite(end)) scene.fogEnd = end + } + }, [ + fx.rendering.fog, + fx.rendering.fogColor, + fx.rendering.fogDensity, + fx.rendering.fogRange, + fx.rendering.fogStart, + fx.rendering.fogEnd, + ]) + + useEffect(() => { + const app = appRef.current + if (!app || !appReady) return + + const next = generateSkyboxResources(app, fx.skybox.colorA, fx.skybox.colorB) + if (!next.source && !next.cubemap && !next.atlas) return + + destroyTexture(skyboxSourceRef.current) + destroyTexture(skyboxLightingSourceRef.current) + destroyTexture(skyboxCubemapRef.current) + destroyTexture(skyboxAtlasRef.current) + + skyboxSourceRef.current = next.source + skyboxLightingSourceRef.current = next.lightingSource + skyboxCubemapRef.current = next.cubemap + skyboxAtlasRef.current = next.atlas + setSkyboxVersion((v) => v + 1) + }, [appReady, fx.skybox.colorA, fx.skybox.colorB]) + + useEffect(() => { + const app = appRef.current + if (!app || !appReady) return + + if (envAtlasRef.current && envAtlasImageRef.current) { + const key = [ + fx.envAtlas.brightness, + fx.envAtlas.contrast, + fx.envAtlas.saturation, + fx.envAtlas.toneMapping, + ].join('|') + if (envAtlasAdjustKeyRef.current !== key) { + envAtlasAdjustKeyRef.current = key + const base = envAtlasImageRef.current + const width = + 'width' in base + ? (base as ImageBitmap).width + : (base as HTMLImageElement).naturalWidth + const height = + 'height' in base + ? (base as ImageBitmap).height + : (base as HTMLImageElement).naturalHeight + const canvas = document.createElement('canvas') + canvas.width = width + canvas.height = height + const ctx = canvas.getContext('2d') + if (ctx) { + ctx.drawImage(base as any, 0, 0, width, height) + const img = ctx.getImageData(0, 0, width, height) + const data = img.data + const brightness = fx.envAtlas.brightness + const contrast = fx.envAtlas.contrast + const saturation = fx.envAtlas.saturation + const tone = fx.envAtlas.toneMapping + const neutral = + Math.abs(brightness - 1) < 0.0001 && + Math.abs(contrast - 1) < 0.0001 && + Math.abs(saturation - 1) < 0.0001 && + Math.abs(tone) < 0.0001 + + if (!neutral) { + for (let i = 0; i < data.length; i += 4) { + let r = data[i] / 255 + let g = data[i + 1] / 255 + let b = data[i + 2] / 255 + + r *= brightness + g *= brightness + b *= brightness + + r = (r - 0.5) * contrast + 0.5 + g = (g - 0.5) * contrast + 0.5 + b = (b - 0.5) * contrast + 0.5 + + const l = r * 0.2126 + g * 0.7152 + b * 0.0722 + r = l + (r - l) * saturation + g = l + (g - l) * saturation + b = l + (b - l) * saturation + + r = toneMapColor(r, tone) + g = toneMapColor(g, tone) + b = toneMapColor(b, tone) + + data[i] = Math.round(clamp01(r) * 255) + data[i + 1] = Math.round(clamp01(g) * 255) + data[i + 2] = Math.round(clamp01(b) * 255) + } + ctx.putImageData(img, 0, 0) + } + envAtlasRef.current.setSource(canvas as any) + } + } + } + + const atlasTex = envAtlasRef.current + const skyboxAtlas = skyboxAtlasRef.current + const skyboxCube = skyboxCubemapRef.current + + const atlasActive = !!fx.envAtlas.enabled + const skyboxActive = !atlasActive && !!fx.skybox.enabled + + let intensity = 0 + let mip = 0 + let rotation = 0 + + let sceneEnvAtlas: pc.Texture | null = null + let sceneSkybox: pc.Texture | null = null + let overrideEnvAtlas: pc.Texture | null = null + let overrideUseSkybox: boolean | undefined = false + let overrideReflectivityScale = 1 + let overrideEnabled = true + + if (atlasActive) { + const backgroundOn = !!fx.envAtlas.background && !!atlasTex + const reflectionOn = !!fx.envAtlas.reflection && !!atlasTex + + intensity = fx.envAtlas.intensity * (fx.lighting?.skyBoxIntensity ?? 1) + mip = fx.envAtlas.mip + rotation = fx.envAtlas.rotation + + const reflectionIntensity = fx.envAtlas.reflectionIntensity * (fx.lighting?.skyBoxIntensity ?? 1) + overrideReflectivityScale = reflectionIntensity + + if (backgroundOn) sceneEnvAtlas = atlasTex + overrideEnvAtlas = reflectionOn ? atlasTex : null + } else if (skyboxActive) { + const backgroundOn = !!fx.skybox.background && !!skyboxCube + const reflectionOn = !!fx.skybox.reflection && !!skyboxAtlas + + intensity = fx.skybox.intensity * (fx.lighting?.skyBoxIntensity ?? 1) + mip = fx.skybox.mip + rotation = fx.skybox.rotation + + const reflectionIntensity = fx.skybox.reflectionIntensity * (fx.lighting?.skyBoxIntensity ?? 1) + overrideReflectivityScale = reflectionIntensity + + if (backgroundOn) sceneSkybox = skyboxCube + if (backgroundOn) sceneEnvAtlas = skyboxAtlas + overrideEnvAtlas = reflectionOn ? skyboxAtlas : null + } else { + overrideEnvAtlas = null + overrideReflectivityScale = 1 + } + + applySceneEnvironment(app, { + envAtlas: sceneEnvAtlas, + skybox: sceneSkybox, + intensity, + mip, + rotationDeg: rotation, + }) + + applyMaterialEnvOverride(app, { + enabled: overrideEnabled, + envAtlas: overrideEnvAtlas, + cubeMap: null, + useSkybox: overrideUseSkybox, + reflectivityScale: overrideReflectivityScale, + }) + }, [ + appReady, + envAtlasVersion, + skyboxVersion, + modelVersion, + fx.envAtlas.enabled, + fx.envAtlas.background, + fx.envAtlas.reflection, + fx.envAtlas.intensity, + fx.envAtlas.reflectionIntensity, + fx.envAtlas.brightness, + fx.envAtlas.contrast, + fx.envAtlas.saturation, + fx.envAtlas.toneMapping, + fx.envAtlas.mip, + fx.envAtlas.rotation, + fx.skybox.enabled, + fx.skybox.background, + fx.skybox.reflection, + fx.skybox.intensity, + fx.skybox.reflectionIntensity, + fx.skybox.mip, + fx.skybox.rotation, + fx.lighting?.skyBoxIntensity, + ]) + + useEffect(() => { + const lightEntity = directionalLightRef.current + if (!lightEntity) return + + lightEntity.enabled = !!fx.directionalLight.enabled + applyLightAngles(lightEntity, fx.directionalLight.azimuth, fx.directionalLight.elevation) + + const light = (lightEntity as any).light + if (!light) return + + light.color?.copy?.(toColor(fx.directionalLight.color)) + light.intensity = fx.directionalLight.intensity + light.castShadows = !!fx.directionalLight.castShadows + light.shadowIntensity = fx.directionalLight.shadowIntensity + light.shadowDistance = fx.directionalLight.shadowDistance + light.shadowResolution = fx.directionalLight.shadowResolution + light.shadowBias = fx.directionalLight.shadowBias + light.normalOffsetBias = fx.directionalLight.normalOffsetBias + light.shadowType = resolveShadowType(fx.directionalLight.shadowType) + light.vsmBlurSize = fx.directionalLight.vsmBlurSize + if (light.castShadows && typeof light.shadowUpdateMode === 'number') { + light.shadowUpdateMode = pc.SHADOWUPDATE_REALTIME + } + }, [ + fx.directionalLight.enabled, + fx.directionalLight.color, + fx.directionalLight.intensity, + fx.directionalLight.azimuth, + fx.directionalLight.elevation, + fx.directionalLight.castShadows, + fx.directionalLight.shadowIntensity, + fx.directionalLight.shadowDistance, + fx.directionalLight.shadowResolution, + fx.directionalLight.shadowBias, + fx.directionalLight.normalOffsetBias, + fx.directionalLight.shadowType, + fx.directionalLight.vsmBlurSize, + ]) + + useEffect(() => { + const catcher = shadowCatcherRef.current + const lightEntity = shadowCatcherLightRef.current + const planeEntity = shadowCatcherPlaneRef.current + if (!catcher || !lightEntity || !planeEntity) return + + catcher.enabled = !!fx.shadowCatcher.enabled + catcher.setLocalPosition(0, fx.shadowCatcher.yOffset, 0) + planeEntity.setLocalScale(fx.shadowCatcher.size, 1, fx.shadowCatcher.size) + applyLightAngles(lightEntity, fx.shadowCatcher.lightAzimuth, fx.shadowCatcher.lightElevation) + + const light = (lightEntity as any).light + if (!light) return + + light.color?.copy?.(toColor(fx.shadowCatcher.lightColor)) + light.intensity = fx.shadowCatcher.lightIntensity + light.castShadows = true + light.shadowIntensity = fx.shadowCatcher.shadowIntensity + light.shadowDistance = fx.shadowCatcher.shadowDistance + light.shadowResolution = fx.shadowCatcher.shadowResolution + light.shadowBias = fx.shadowCatcher.shadowBias + light.normalOffsetBias = fx.shadowCatcher.normalOffsetBias + light.shadowType = resolveShadowType(fx.shadowCatcher.shadowType) + light.vsmBlurSize = fx.shadowCatcher.vsmBlurSize + if (typeof light.shadowUpdateMode === 'number') { + light.shadowUpdateMode = pc.SHADOWUPDATE_REALTIME + } + }, [ + fx.shadowCatcher.enabled, + fx.shadowCatcher.size, + fx.shadowCatcher.yOffset, + fx.shadowCatcher.lightIntensity, + fx.shadowCatcher.lightColor, + fx.shadowCatcher.lightAzimuth, + fx.shadowCatcher.lightElevation, + fx.shadowCatcher.shadowIntensity, + fx.shadowCatcher.shadowDistance, + fx.shadowCatcher.shadowResolution, + fx.shadowCatcher.shadowBias, + fx.shadowCatcher.normalOffsetBias, + fx.shadowCatcher.shadowType, + fx.shadowCatcher.vsmBlurSize, + ]) + + // reflection overrides are managed in the environment effect above + + useEffect(() => { + if (!onSelectionChanged) return + onSelectionChanged([]) + }, [onSelectionChanged]) + + return ( +
    + +
    + ) +} diff --git a/apps/control-station/src/components/rover/playcanvas/playcanvasPostFx.ts b/apps/control-station/src/components/rover/playcanvas/playcanvasPostFx.ts new file mode 100644 index 0000000..053e745 --- /dev/null +++ b/apps/control-station/src/components/rover/playcanvas/playcanvasPostFx.ts @@ -0,0 +1,393 @@ + +export type PostFxSettings = { + lighting: { + exposure: number + skyBoxIntensity: number + } + envAtlas: { + enabled: boolean + background: boolean + reflection: boolean + intensity: number + reflectionIntensity: number + brightness: number + contrast: number + saturation: number + toneMapping: number + mip: number + rotation: number + } + skybox: { + enabled: boolean + background: boolean + reflection: boolean + intensity: number + reflectionIntensity: number + mip: number + rotation: number + colorA: string + colorB: string + } + rendering: { + backgroundColor: string + wireframe: boolean + renderFormat: number + renderFormatFallback0: number + renderFormatFallback1: number + stencil: boolean + renderTargetScale: number + samples: number + sharpness: number + toneMapping: number + sceneColorMap: boolean + sceneDepthMap: boolean + fog: 'none' | 'linear' | 'exp' | 'exp2' + fogColor: string + fogRange: [number, number] + fogDensity: number + fogStart: number + fogEnd: number + } + grid: { + enabled: boolean + colorX: string + colorZ: string + colorMain: string + alphaX: number + alphaZ: number + alphaMain: number + dotsEnabled: boolean + dotsColor: string + dotsAlpha: number + dotsDiameter: number + crossEnabled: boolean + crossColor: string + crossAlpha: number + crossLength: number + crossWidth: number + fadeStart: number + fadeEnd: number + } + ssao: { + type: 'none' | 'lighting' | 'combine' + blurEnabled: boolean + intensity: number + radius: number + samples: number + power: number + minAngle: number + scale: number + } + bloom: { + enabled: boolean + intensity: number + lastMipLevel: number + } + chromaticAberration: { + enabled: boolean + intensity: number + } + taa: { + enabled: boolean + jitter: number + } + grading: { + enabled: boolean + brightness: number + contrast: number + saturation: number + tint: string + } + lut: { + intensity: number + textureUrl?: string | null + } + vignette: { + enabled: boolean + intensity: number + inner: number + outer: number + curvature: number + color: string + } + directionalLight: { + enabled: boolean + color: string + intensity: number + azimuth: number + elevation: number + castShadows: boolean + shadowIntensity: number + shadowDistance: number + shadowResolution: number + shadowBias: number + normalOffsetBias: number + shadowType: 'vsm16' | 'vsm32' | 'pcf1' | 'pcf3' + vsmBlurSize: number + } + shadowCatcher: { + enabled: boolean + size: number + yOffset: number + lightIntensity: number + lightColor: string + lightAzimuth: number + lightElevation: number + shadowIntensity: number + shadowDistance: number + shadowResolution: number + shadowBias: number + normalOffsetBias: number + shadowType: 'vsm16' | 'vsm32' | 'pcf1' | 'pcf3' + vsmBlurSize: number + } +} + +export const DEFAULT_POSTFX: PostFxSettings = { + lighting: { + exposure: 1.21, + skyBoxIntensity: 0.86, + }, + envAtlas: { + enabled: true, + background: false, + reflection: true, + intensity: 0.76, + reflectionIntensity: 0.6, + brightness: 1.65, + contrast: 1, + saturation: 1, + toneMapping: 0, + mip: 1, + rotation: 247, + }, + skybox: { + enabled: false, + background: false, + reflection: true, + intensity: 0.62, + reflectionIntensity: 1, + mip: 0, + rotation: 0, + colorA: '#c5bfbf', + colorB: '#c7bcbc', + }, + rendering: { + backgroundColor: '#111113', + wireframe: false, + renderFormat: 18, + renderFormatFallback0: 12, + renderFormatFallback1: 14, + stencil: false, + renderTargetScale: 1, + samples: 4, + sharpness: 0, + toneMapping: 4, + sceneColorMap: false, + sceneDepthMap: false, + fog: 'exp', + fogColor: '#dcc2ff', + fogRange: [0, 100], + fogDensity: 0.008, + fogStart: 0, + fogEnd: 100, + }, + grid: { + enabled: true, + colorX: '#ffffff', + colorZ: '#ffffff', + colorMain: '#7a3cff', + alphaX: 0.18, + alphaZ: 0.18, + alphaMain: 0.6, + dotsEnabled: false, + dotsColor: '#ffffff', + dotsAlpha: 0.5, + dotsDiameter: 0.06, + crossEnabled: false, + crossColor: '#ffffff', + crossAlpha: 0.5, + crossLength: 0.5, + crossWidth: 0.06, + fadeStart: 0, + fadeEnd: 0, + }, + ssao: { + type: 'none', + blurEnabled: true, + intensity: 0.5, + radius: 30, + samples: 12, + power: 6, + minAngle: 10, + scale: 1, + }, + bloom: { + enabled: true, + intensity: 0.03, + lastMipLevel: 4, + }, + chromaticAberration: { + enabled: true, + intensity: 30, + }, + taa: { + enabled: false, + jitter: 1, + }, + grading: { + enabled: true, + brightness: 0.837, + contrast: 1.1, + saturation: 1.126, + tint: '#ffffff', + }, + lut: { + intensity: 1, + textureUrl: null, + }, + vignette: { + enabled: true, + intensity: 1, + inner: 0.25, + outer: 1.52, + curvature: 0.78, + color: '#000000', + }, + directionalLight: { + enabled: true, + color: '#ffffff', + intensity: 0.4, + azimuth: 0, + elevation: 0, + castShadows: false, + shadowIntensity: 0.5, + shadowDistance: 16, + shadowResolution: 1024, + shadowBias: 0, + normalOffsetBias: 0, + shadowType: 'vsm16', + vsmBlurSize: 8, + }, + shadowCatcher: { + enabled: true, + size: 9, + yOffset: 0.001, + lightIntensity: 0.3, + lightColor: '#ffffff', + lightAzimuth: 20, + lightElevation: 60, + shadowIntensity: 0.29, + shadowDistance: 16, + shadowResolution: 2048, + shadowBias: 0, + normalOffsetBias: 0, + shadowType: 'vsm16', + vsmBlurSize: 8, + }, +} + +function isObject(value: any): value is Record { + return !!value && typeof value === 'object' && !Array.isArray(value) +} + +export function mergePostFxDefaults(raw?: Partial | null): PostFxSettings { + if (!raw) return JSON.parse(JSON.stringify(DEFAULT_POSTFX)) as PostFxSettings + + const out: any = JSON.parse(JSON.stringify(DEFAULT_POSTFX)) + const merge = (target: any, source: any) => { + if (!isObject(source)) return + for (const [key, value] of Object.entries(source)) { + if (isObject(value)) { + if (!isObject(target[key])) target[key] = {} + merge(target[key], value) + } else { + target[key] = value + } + } + } + merge(out, raw) + + const legacy: any = raw as any + if (legacy?.hdrLight) { + const src = legacy.hdrLight + const env = legacy?.envAtlas ?? {} + if (env?.enabled === undefined && typeof src.enabled === 'boolean') out.envAtlas.enabled = src.enabled + if (env?.background === undefined && typeof src.showSkybox === 'boolean') out.envAtlas.background = src.showSkybox + if (env?.intensity === undefined && typeof src.intensity === 'number') out.envAtlas.intensity = src.intensity + if (env?.mip === undefined && typeof src.mip === 'number') out.envAtlas.mip = src.mip + if (env?.rotation === undefined && typeof src.rotation === 'number') out.envAtlas.rotation = src.rotation + } + if (legacy?.hdrReflection && (legacy?.envAtlas?.reflection === undefined)) { + if (typeof legacy.hdrReflection.enabled === 'boolean') { + out.envAtlas.reflection = legacy.hdrReflection.enabled + } + } + if (out.envAtlas && typeof out.envAtlas.reflectionIntensity !== 'number') { + out.envAtlas.reflectionIntensity = out.envAtlas.intensity + } + if (out.envAtlas && typeof out.envAtlas.brightness !== 'number') { + out.envAtlas.brightness = 1 + } + if (out.envAtlas && typeof out.envAtlas.contrast !== 'number') { + out.envAtlas.contrast = 1 + } + if (out.envAtlas && typeof out.envAtlas.saturation !== 'number') { + out.envAtlas.saturation = 1 + } + if (out.envAtlas && typeof out.envAtlas.toneMapping !== 'number') { + out.envAtlas.toneMapping = 0 + } + if (out.skybox && typeof out.skybox.reflectionIntensity !== 'number') { + out.skybox.reflectionIntensity = out.skybox.intensity + } + if (out.grid && typeof out.grid.enabled !== 'boolean') { + out.grid.enabled = DEFAULT_POSTFX.grid.enabled + } + if (out.grid && typeof out.grid.colorX !== 'string') { + out.grid.colorX = DEFAULT_POSTFX.grid.colorX + } + if (out.grid && typeof out.grid.colorZ !== 'string') { + out.grid.colorZ = DEFAULT_POSTFX.grid.colorZ + } + if (out.grid && typeof out.grid.colorMain !== 'string') { + out.grid.colorMain = DEFAULT_POSTFX.grid.colorMain + } + if (out.grid && typeof out.grid.alphaX !== 'number') { + out.grid.alphaX = DEFAULT_POSTFX.grid.alphaX + } + if (out.grid && typeof out.grid.alphaZ !== 'number') { + out.grid.alphaZ = DEFAULT_POSTFX.grid.alphaZ + } + if (out.grid && typeof out.grid.alphaMain !== 'number') { + out.grid.alphaMain = DEFAULT_POSTFX.grid.alphaMain + } + if (out.grid && typeof out.grid.dotsEnabled !== 'boolean') { + out.grid.dotsEnabled = DEFAULT_POSTFX.grid.dotsEnabled + } + if (out.grid && typeof out.grid.dotsColor !== 'string') { + out.grid.dotsColor = DEFAULT_POSTFX.grid.dotsColor + } + if (out.grid && typeof out.grid.dotsAlpha !== 'number') { + out.grid.dotsAlpha = DEFAULT_POSTFX.grid.dotsAlpha + } + if (out.grid && typeof out.grid.dotsDiameter !== 'number') { + out.grid.dotsDiameter = DEFAULT_POSTFX.grid.dotsDiameter + } + if (out.grid && typeof out.grid.crossEnabled !== 'boolean') { + out.grid.crossEnabled = DEFAULT_POSTFX.grid.crossEnabled + } + if (out.grid && typeof out.grid.crossColor !== 'string') { + out.grid.crossColor = DEFAULT_POSTFX.grid.crossColor + } + if (out.grid && typeof out.grid.crossAlpha !== 'number') { + out.grid.crossAlpha = DEFAULT_POSTFX.grid.crossAlpha + } + if (out.grid && typeof out.grid.crossLength !== 'number') { + out.grid.crossLength = DEFAULT_POSTFX.grid.crossLength + } + if (out.grid && typeof out.grid.crossWidth !== 'number') { + out.grid.crossWidth = DEFAULT_POSTFX.grid.crossWidth + } + return out as PostFxSettings +} diff --git a/apps/control-station/src/components/rover/playcanvas/sceneTree.ts b/apps/control-station/src/components/rover/playcanvas/sceneTree.ts new file mode 100644 index 0000000..dacdf59 --- /dev/null +++ b/apps/control-station/src/components/rover/playcanvas/sceneTree.ts @@ -0,0 +1,20 @@ +import type * as pc from 'playcanvas' + +export type SceneTreeNode = { + id: string + name: string + enabled: boolean + children: SceneTreeNode[] +} + +export function buildSceneTree(root: pc.GraphNode, map: Map): SceneTreeNode { + const id = String((root as any).getGuid?.() ?? (root as any)._guid ?? root.name) + const children = (root.children || []).map((c) => buildSceneTree(c, map)) + map.set(id, root as pc.Entity) + return { + id, + name: root.name || 'Entity', + enabled: root.enabled !== false, + children, + } +} diff --git a/apps/control-station/src/components/rover/rover.css b/apps/control-station/src/components/rover/rover.css new file mode 100644 index 0000000..a8d3263 --- /dev/null +++ b/apps/control-station/src/components/rover/rover.css @@ -0,0 +1,20 @@ +.rover-view { position:relative; height:100%; min-height:200px; overflow:hidden; container-type:inline-size; } +.rover-view:focus-visible { outline:2px solid var(--nodedc-text-secondary); outline-offset:-2px; } +.rover-view .rover-view__scene { position:absolute; inset:0; } +.rover-view__empty { display:grid; place-content:center; height:100%; text-align:center; font-size:var(--nodedc-font-size-sm); color:var(--nodedc-text-muted); } +.rover-view__status { position:absolute; top:var(--nodedc-space-3); left:var(--nodedc-space-3); } +.rover-view__controls { position:absolute; right:var(--nodedc-space-3); bottom:var(--nodedc-space-3); display:flex; flex-direction:column; gap:var(--nodedc-space-2); align-items:center; } +.rover-view__controls > span { font-size:var(--nodedc-font-size-xs); color:var(--nodedc-text-secondary); } +.rover-keys { display:grid; gap:var(--nodedc-space-1); grid-template-columns:repeat(3,46px); } +.rover-key-KeyW { grid-column:2; }.rover-key-KeyA { grid-column:1; grid-row:2; }.rover-key-KeyS { grid-column:2; grid-row:2; }.rover-key-KeyD { grid-column:3; grid-row:2; } +.rover-key-KeyQ { grid-column:1; }.rover-key-KeyE { grid-column:3; } +.rover-view__authority { position:absolute; left:var(--nodedc-space-3); bottom:var(--nodedc-space-3); } +@container (max-width: 380px) { + .rover-view__authority { top:48px; bottom:auto; } +} +.rover-settings { display:flex; flex-direction:column; gap:var(--nodedc-space-3); } +.rover-settings p { font-size:var(--nodedc-font-size-sm); color:var(--nodedc-text-secondary); } +.rover-telemetry { height:100%; overflow:auto; padding:var(--nodedc-space-3); display:flex; flex-wrap:wrap; align-content:start; gap:var(--nodedc-space-4); font-size:var(--nodedc-font-size-sm); } +.rover-telemetry section { flex:1; min-width:170px; }.rover-telemetry section > span { display:block; color:var(--nodedc-text-muted); font-size:var(--nodedc-font-size-xs); margin-top:var(--nodedc-space-1); } +.rover-telemetry dl { display:grid; gap:var(--nodedc-space-1); margin-bottom:0; }.rover-telemetry dl > div { display:flex; justify-content:space-between; gap:var(--nodedc-space-3); } +.rover-telemetry dt { color:var(--nodedc-text-secondary); }.rover-telemetry dd { margin:0; font-variant-numeric:tabular-nums; } diff --git a/apps/control-station/src/composition/devicePlugins.ts b/apps/control-station/src/composition/devicePlugins.ts index 2091dcb..c242a83 100644 --- a/apps/control-station/src/composition/devicePlugins.ts +++ b/apps/control-station/src/composition/devicePlugins.ts @@ -1,3 +1,4 @@ +import {vescSensorUi} from '../../../../plugins/vesc/frontend/src/plugin'; import type { DeviceUiPlugin } from "../core/device-plugins/contracts"; import { xgridsK1Plugin } from "@xgrids-k1/frontend/plugin"; import {insta360X4SensorUi} from '../../../../plugins/insta360-x4/frontend/src/plugin'; @@ -10,4 +11,4 @@ export const installedDevicePlugins: readonly DeviceUiPlugin[] = Object.freeze([ // Node-executed camera controls use the existing sensor contribution contract; // they do not register a desktop capture/AI runtime or a new product workspace. -export const installedNodeSensorContributions = Object.freeze([insta360X4SensorUi]); +export const installedNodeSensorContributions = Object.freeze([insta360X4SensorUi,vescSensorUi]); diff --git a/apps/control-station/src/core/fleet/boardLayout.ts b/apps/control-station/src/core/fleet/boardLayout.ts new file mode 100644 index 0000000..309eb83 --- /dev/null +++ b/apps/control-station/src/core/fleet/boardLayout.ts @@ -0,0 +1,13 @@ +import {createBoardLayoutStore,type BoardLayoutStore} from '../../../../../packages/sensor-ui/src/boardLayout'; +import {fleetRequest} from './useFleet'; + +const layouts=new Map(); +export function boardLayout(vehicleID:string):BoardLayoutStore { + let layout=layouts.get(vehicleID); + if(!layout){ + const path=`/${encodeURIComponent(vehicleID)}/board-layout`; + layout=createBoardLayoutStore({read:()=>fleetRequest(path),patch:(section,open)=>fleetRequest(path,'PATCH',{section,open})}); + layouts.set(vehicleID,layout); + } + return layout; +} diff --git a/apps/control-station/src/core/fleet/roverHoldInput.ts b/apps/control-station/src/core/fleet/roverHoldInput.ts new file mode 100644 index 0000000..7ebd75c --- /dev/null +++ b/apps/control-station/src/core/fleet/roverHoldInput.ts @@ -0,0 +1,66 @@ +import {keyDemand,keysFor,type Demand,type RoverMode} from './roverInput'; + +// The network heartbeat is not evidence that a physical key is still held. +// Allow the initial OS repeat delay, then require continuing keyboard evidence. +export const firstKeyLeaseMs=1000,repeatKeyLeaseMs=300; +export function bindRoverHoldInput(scope:HTMLElement,mode:RoverMode,callbacks:{ + held:(keys:Set)=>void;demand:(value:Demand)=>void;pause:()=>void;stop:()=>void; +},now:()=>number=()=>performance.now()){ + const doc=scope.ownerDocument,win=doc.defaultView!; + const keyboard=new Set(),pointers=new Map(); + let deadline=0,closed=false,suspended=false; + const clear=()=>{keyboard.clear();pointers.clear();deadline=0;callbacks.held(new Set());}; + const pause=()=>{if(closed||suspended)return;suspended=true;clear();callbacks.pause();}; + const stop=()=>{if(closed)return;closed=true;clear();callbacks.stop();}; + const focused=()=>!doc.hidden&&doc.hasFocus()&&scope.contains(doc.activeElement); + const valid=()=>{ + if(closed)return false; + if(!focused()||(keyboard.size>0&&now()>=deadline)){pause();return false;} + return true; + }; + const publish=()=>{const held=new Set([...keyboard,...pointers.values()]);callbacks.held(held);callbacks.demand(keyDemand(mode,held));}; + const down=(e:KeyboardEvent)=>{ + if(!e.isTrusted||closed)return; + if(e.code==='Space'||e.code==='Escape'){e.preventDefault();stop();return;} + if(e.altKey||e.ctrlKey||e.metaKey){pause();return;} + if(!keysFor(mode).includes(e.code)||!valid())return; + if((e.target as HTMLElement)?.closest('input,textarea,select,[role=dialog],[role=listbox]')){pause();return;} + // A repeat delivered after focus returns cannot become a fresh press. + if(e.repeat&&!keyboard.has(e.code))return; + e.preventDefault();suspended=false;keyboard.add(e.code); + deadline=now()+(e.repeat?repeatKeyLeaseMs:firstKeyLeaseMs);publish(); + }; + const up=(e:KeyboardEvent)=>{ + if(!e.isTrusted||closed||!keyboard.delete(e.code))return; + e.preventDefault();if(!keyboard.size)deadline=0;publish(); + }; + const blur=(e:Event)=>{if(e.target===win)pause();}; + const focusOut=(e:FocusEvent)=>{if(scope.contains(e.target as Node)&&!scope.contains(e.relatedTarget as Node|null))pause();}; + const focusIn=()=>{if(!focused())pause();}; + const hidden=()=>{if(doc.hidden)pause();}; + const outside=(e:Event)=>{if(!scope.contains(e.target as Node))pause();}; + const pointerUp=(e:PointerEvent)=>{if(!closed&&pointers.delete(e.pointerId))publish();}; + const pointerCancel=(e:PointerEvent)=>{if(pointers.has(e.pointerId))pause();}; + win.addEventListener('keydown',down,true);win.addEventListener('keyup',up,true); + win.addEventListener('blur',blur,true);win.addEventListener('pagehide',stop); + doc.addEventListener('focusout',focusOut,true);doc.addEventListener('focusin',focusIn,true); + doc.addEventListener('visibilitychange',hidden);doc.addEventListener('pointerdown',outside,true); + doc.addEventListener('pointerup',pointerUp,true);doc.addEventListener('pointercancel',pointerCancel,true); + doc.addEventListener('contextmenu',pause,true); + const timer=win.setInterval(valid,50); + return { + valid, + pointerDown(id:number,code:string){if(valid()){suspended=false;pointers.set(id,code);publish();}}, + pointerUp(id:number){if(!closed&&pointers.delete(id))publish();}, + pointerCancel(id:number){if(pointers.has(id))pause();}, + dispose(){ + closed=true;clear();callbacks.demand({left:0,right:0});win.clearInterval(timer); + win.removeEventListener('keydown',down,true);win.removeEventListener('keyup',up,true); + win.removeEventListener('blur',blur,true);win.removeEventListener('pagehide',stop); + doc.removeEventListener('focusout',focusOut,true);doc.removeEventListener('focusin',focusIn,true); + doc.removeEventListener('visibilitychange',hidden);doc.removeEventListener('pointerdown',outside,true); + doc.removeEventListener('pointerup',pointerUp,true);doc.removeEventListener('pointercancel',pointerCancel,true); + doc.removeEventListener('contextmenu',pause,true); + }, + }; +} diff --git a/apps/control-station/src/core/fleet/roverInput.ts b/apps/control-station/src/core/fleet/roverInput.ts new file mode 100644 index 0000000..547d1f3 --- /dev/null +++ b/apps/control-station/src/core/fleet/roverInput.ts @@ -0,0 +1,20 @@ +export type RoverMode='arcade'|'tank'; +export type Demand={left:number;right:number}; +export const keysFor=(mode:RoverMode)=>mode==='arcade'?['KeyW','KeyA','KeyS','KeyD']:['KeyQ','KeyE','KeyA','KeyD']; +export function keyDemand(mode:RoverMode,held:ReadonlySet):Demand { + const axis=(positive:string,negative:string)=>Number(held.has(positive))-Number(held.has(negative)); + if(mode==='tank')return {left:axis('KeyQ','KeyA'),right:axis('KeyE','KeyD')}; + const forward=axis('KeyW','KeyS'),turn=axis('KeyD','KeyA'); + const scale=Math.max(1,Math.abs(forward)+Math.abs(turn)); + return {left:(forward+turn)/scale,right:(forward-turn)/scale}; +} +export const defaultRoverSettings={version:1,mode:'arcade' as RoverMode,currentA:30,maxErpm:2000,model:''}; +export function roverSettings(value:unknown):typeof defaultRoverSettings { + const v=value as Partial|null; + return {...defaultRoverSettings,...(v?.version===1?{ + mode:v.mode==='tank'?'tank':'arcade', + currentA:typeof v.currentA==='number'&&Number.isFinite(v.currentA)?Math.max(.5,Math.min(30,v.currentA)):30, + maxErpm:typeof v.maxErpm==='number'&&Number.isFinite(v.maxErpm)?Math.max(300,Math.min(3000,v.maxErpm)):2000, + model:v.model==='dcd006-v020'?v.model:'', + }:{} )}; +} diff --git a/apps/control-station/src/core/fleet/sensorTransport.ts b/apps/control-station/src/core/fleet/sensorTransport.ts index 9ee8749..d557b97 100644 --- a/apps/control-station/src/core/fleet/sensorTransport.ts +++ b/apps/control-station/src/core/fleet/sensorTransport.ts @@ -9,6 +9,7 @@ export function createFleetSensorTransport(vehicleID:string):SensorTransport { return {...value.sensor_state,fresh:value.connectivity==='online'&&value.enrollment==='paired'}; }; return { + configurationArchive:{list:(device,before)=>fleetRequest(`${path}/${encodeURIComponent(device)}/configurations${before?'?before='+encodeURIComponent(before):''}`),read:(device,version)=>fleetRequest(`${path}/${encodeURIComponent(device)}/configurations/${encodeURIComponent(version)}`)}, enrollment:{state:()=>fleetRequest(`${path}/enrollment`),submit:value=>fleetRequest(`${path}/enrollment/operations`,'POST',value),operation:id=>fleetRequest(`${path}/enrollment/operations/${encodeURIComponent(id)}`)}, inventory:async()=>inventory(await fleetRequest()), subscribe:(receive,unavailable)=>{const events=new EventSource('/api/v1/fleet/events');events.onmessage=e=>{try{receive(inventory(JSON.parse(e.data)));}catch{unavailable();}};events.onerror=unavailable;return()=>events.close();}, diff --git a/apps/control-station/src/core/fleet/useRoverControl.ts b/apps/control-station/src/core/fleet/useRoverControl.ts new file mode 100644 index 0000000..a8a8ad1 --- /dev/null +++ b/apps/control-station/src/core/fleet/useRoverControl.ts @@ -0,0 +1,79 @@ +import {useCallback,useEffect,useRef,useState} from 'react'; +import type {Demand} from './roverInput'; + +export interface RoverReading { + id:string;uuid:string;slot:string|null;label:string;age_ms:number; + values:{motor_current_a:number;input_current_a:number;input_voltage_v:number;erpm:number;duty:number;mos_temperature_c:number;fault_code:number}; +} +export interface RoverState { + fresh:boolean;controlling:boolean; + snapshot:{supported?:boolean;instance?:string;state?:string;session_id?:string|null;message?:string|null;devices?:RoverReading[]; + profile?:{layout:null|'1x1'|'2x2';bindings:Record}}; +} +const empty:RoverState={fresh:false,controlling:false,snapshot:{}}; +async function request(url:string,body?:unknown,keepalive=false):Promise{ + const response=await fetch(url,{method:body?'POST':'GET',headers:body?{'Content-Type':'application/json'}:undefined, + body:body?JSON.stringify(body):undefined,cache:'no-store',signal:AbortSignal.timeout(body?350:1000),keepalive}); + const result=await response.json(); + if(!response.ok)throw new Error(typeof result.detail==='string'?result.detail:'Канал управления недоступен.'); + return result; +} +export function useRoverControl(vehicleID:string,visible:boolean){ + const url=`/api/v1/fleet/${encodeURIComponent(vehicleID)}/rover`; + const [state,setState]=useState(empty),[armed,setArmed]=useState(false),[pending,setPending]=useState(false),[error,setError]=useState(null); + const [connecting,setConnecting]=useState(true),armPending=useRef(false); + const session=useRef(null),seq=useRef(0),demand=useRef({left:0,right:0}),sending=useRef(false),generation=useRef(0); + const inputGuard=useRef<(()=>boolean)|null>(null); + const setInputGuard=useCallback((guard:(()=>boolean)|null)=>{inputGuard.current=guard;},[]); + const stop=useCallback(()=>{ + generation.current++;armPending.current=false;const id=session.current;session.current=null;demand.current={left:0,right:0};setArmed(false);setPending(false); + if(id)void request(url+'/command',{session_id:id,sequence:++seq.current,left:0,right:0,stop:true},true).catch(()=>{}); + },[url]); + const send=useCallback(async()=>{ + const id=session.current;if(!id)return; + // Check on every heartbeat, even when a previous request is still pending. + const inputValid=(demand.current.left===0&&demand.current.right===0)||inputGuard.current?.(); + if(document.hidden||!document.hasFocus()||!inputValid)demand.current={left:0,right:0}; + if(sending.current)return; + sending.current=true; + try{await request(url+'/command',{session_id:id,sequence:++seq.current,...demand.current,stop:false});} + catch(e){if(session.current===id){stop();setError(e instanceof Error?e.message:'Команда не подтверждена.');}} + finally{sending.current=false;} + },[url,stop]); + const setDemand=useCallback((next:Demand)=>{demand.current=next;void send();},[send]); + const pauseInput=useCallback(()=>{demand.current={left:0,right:0};void send();},[send]); + const arm=useCallback(async(currentA:number,maxErpm:number)=>{ + if(session.current||armPending.current)return false;const g=++generation.current;armPending.current=true;setError(null);setPending(true); + try{ + const result=await request<{session_id:string}>(url+'/arm',{standstill_confirmed:true,current_a:currentA,max_erpm:maxErpm}); + if(g!==generation.current){void request(url+'/command',{session_id:result.session_id,sequence:1,left:0,right:0,stop:true},true).catch(()=>{});return false;} + // Retire every read started before this acknowledgement, including reads + // begun while POST /arm was pending. They describe the previous authority. + generation.current++;armPending.current=false;setPending(false); + seq.current=0;demand.current={left:0,right:0};session.current=result.session_id;setArmed(true);void send(); + return true; + }catch(e){if(g===generation.current)setError(e instanceof Error?e.message:'Не удалось включить управление.');return false;} + finally{if(g===generation.current){armPending.current=false;setPending(false);}} + },[url,send]); + useEffect(()=>{ + if(!visible){stop();setState(empty);setConnecting(false);return;} + let alive=true,busy=false,lastFault='';const started=performance.now();setConnecting(true); + const poll=async()=>{ + if(busy)return;busy=true;const before=generation.current; + try{const value=await request(url);if(alive&&before===generation.current){setState(value); + setConnecting(!value.fresh&&performance.now()-started<2000); + if(session.current&&(!value.fresh||!value.controlling)){stop();} + const fault=value.snapshot.state==='fault'?value.snapshot.message??'':''; + if(fault&&lastFault!==fault){lastFault=fault;setError(fault);} + }}catch{if(alive&&before===generation.current){setState(empty);setConnecting(false);if(session.current)stop();}}finally{busy=false;} + }; + void poll();const timer=setInterval(()=>void poll(),200),heartbeat=setInterval(()=>void send(),100); + const blur=()=>pauseInput(),hidden=()=>{if(document.hidden)pauseInput();}; + window.addEventListener('blur',blur);window.addEventListener('pagehide',stop);document.addEventListener('visibilitychange',hidden); + return()=>{alive=false;clearInterval(timer);clearInterval(heartbeat);window.removeEventListener('blur',blur);window.removeEventListener('pagehide',stop);document.removeEventListener('visibilitychange',hidden);stop();}; + },[url,visible,stop,send,pauseInput]); + const ready=armed&&state.fresh&&state.snapshot.session_id===session.current&&['ready','driving'].includes(state.snapshot.state??''); + const canArm=state.fresh&&state.snapshot.supported===true&&!state.controlling&&!['preparing','ready','driving','stopping'].includes(state.snapshot.state??''); + return {state,armed,pending,error,connecting,canArm,arm,stop,pauseInput,setDemand,setInputGuard,ready,clearError:()=>setError(null)}; +} +export type RoverController=ReturnType; diff --git a/apps/control-station/src/workspaces/Workspaces.tsx b/apps/control-station/src/workspaces/Workspaces.tsx index 8733927..6f79938 100644 --- a/apps/control-station/src/workspaces/Workspaces.tsx +++ b/apps/control-station/src/workspaces/Workspaces.tsx @@ -431,7 +431,7 @@ export function WorkspaceRenderer(props: WorkspaceRendererProps) { case "missions": return ; case "vehicles": - return ; + return ; case "catalog": return ; case "contour-health": diff --git a/apps/control-station/src/workspaces/fleet/VehicleSensors.tsx b/apps/control-station/src/workspaces/fleet/VehicleSensors.tsx index 10bcd75..10a64c0 100644 --- a/apps/control-station/src/workspaces/fleet/VehicleSensors.tsx +++ b/apps/control-station/src/workspaces/fleet/VehicleSensors.tsx @@ -1,11 +1,13 @@ -import {useMemo} from 'react'; +import {useMemo,type ReactNode} from 'react'; +import {boardLayout} from '../../core/fleet/boardLayout'; import {useDevicePluginHost} from '../../core/device-plugins/DevicePluginHost'; import {createIsolatedRerunHost} from '../../components/rerun/isolatedRerunHost'; import {SensorWorkspace} from '../../../../../packages/sensor-ui/src/SensorWorkspace'; import {createFleetSensorTransport} from '../../core/fleet/sensorTransport'; -export function VehicleSensors({vehicleID,enabled,onDetailChange}:{vehicleID:string;enabled:boolean;onDetailChange:(open:boolean)=>void}){ +export function VehicleSensors({vehicleID,enabled,computer,description}:{vehicleID:string;enabled:boolean;computer:ReactNode;description:string}){ const {registry}=useDevicePluginHost(); const sensorContributions=registry.sensorContributions; + const layout=useMemo(()=>boardLayout(vehicleID),[vehicleID]); const transport=useMemo(()=>createFleetSensorTransport(vehicleID),[vehicleID]); - return ; + return ; } diff --git a/apps/control-station/src/workspaces/fleet/VehiclesWorkspace.tsx b/apps/control-station/src/workspaces/fleet/VehiclesWorkspace.tsx index 9bde6da..9668bcd 100644 --- a/apps/control-station/src/workspaces/fleet/VehiclesWorkspace.tsx +++ b/apps/control-station/src/workspaces/fleet/VehiclesWorkspace.tsx @@ -10,7 +10,7 @@ const platforms = [{ value: "ugv", label: "Наземный (UGV)" }, { value: " const platformLabel = (value: string) => platforms.find(item => item.value === value)?.label ?? value; function statusLabel(item: Vehicle) { return item.enrollment === "pending" ? "Подтверждаем привязку" : item.enrollment === "revoked" ? "Доверие отозвано" : item.enrollment === "failed" ? "Привязка не завершена" : item.connectivity === "online" ? "В сети" : "Нет связи"; } -export function VehiclesWorkspace({ createRequest = 0 }: { createRequest?: number }) { +export function VehiclesWorkspace({ createRequest = 0, headerToolsHost }: { createRequest?: number; headerToolsHost?: HTMLElement|null }) { const fleet = useFleet(); const [adding, setAdding] = useState(false); const [code, setCode] = useState(""); @@ -20,7 +20,6 @@ export function VehiclesWorkspace({ createRequest = 0 }: { createRequest?: numbe const [pending, setPending] = useState(false); const [error, setError] = useState(""); const [selected, setSelected] = useState(null); - const [sensorOpen, setSensorOpen] = useState(false); const [monitorOpen,setMonitorOpen]=useState(false); const [observationOpen,setObservationOpen]=useState(false); const [revoking, setRevoking] = useState(null); @@ -44,25 +43,24 @@ export function VehiclesWorkspace({ createRequest = 0 }: { createRequest?: numbe finally { setPending(false); } } const detail = fleet.items?.find(item => item.id === selected); - if(detail&&observationOpen)return {setObservationOpen(false);setSensorOpen(false);}}/>; + if(detail&&observationOpen)return {setObservationOpen(false);setSelected(null);}} configure={()=>setObservationOpen(false)} headerToolsHost={headerToolsHost}/>; if(detail&&monitorOpen)return setMonitorOpen(false)}/>; return
    {fleet.error &&

    {fleet.error}

    } {!adding && error &&

    {error}

    } {detail ? <> -
    - {!sensorOpen && {fleet.error ? "Нет свежих данных" : statusLabel(detail)}}> +
    + {fleet.error ? "Нет свежих данных" : statusLabel(detail)}}> {detail.notice &&

    {detail.notice}

    }
    Бортовой компьютер
    {detail.node_id}
    Последняя связь
    {detail.last_seen ? new Date(detail.last_seen * 1000).toLocaleString("ru-RU") : "Соединение ещё не получено"}
    {detail.host && <>
    Имя БК в системе
    {detail.host.hostname}
    Операционная система
    {detail.host.os}
    Архитектура
    {detail.host.architecture}
    Процессоры
    {detail.host.cpus}
    Память
    {detail.host.memory_kib ? `${(detail.host.memory_kib / 1024 / 1024).toFixed(1)} ГиБ` : "Нет сведений"}
    }
    - + {detail.enrollment !== "revoked" && }
    -
    } - - : !fleet.items ? : fleet.items.length === 0 ? : {fleet.items.map(item =>
  • } title={item.name} description={`${platformLabel(item.platform)} · бортовой компьютер`} status={{fleet.error ? "Нет свежих данных" : statusLabel(item)}} actions={<> setSelected(item.id)}> {setSelected(item.id);setObservationOpen(true);}}>} />
  • )}
    } + }/> + : !fleet.items ? : fleet.items.length === 0 ? : {fleet.items.map(item =>
  • } title={item.name} description={`${platformLabel(item.platform)} · бортовой компьютер`} status={{fleet.error ? "Нет свежих данных" : statusLabel(item)}} actions={<> setSelected(item.id)}> {setSelected(item.id);setObservationOpen(true);}}>} />
  • )}
    } {preview ? : }}>
    setLayout(current=>({...current,layers:{...current.layers,[source.key]:value}}))} variant="inline"/>} - {source.key!=='map'&&{setFocused(source.key);setLayersOpen(true);}}>} + {source.deviceID&&{setFocused(source.key);setLayersOpen(true);}}>} setFull(value=>value===source.key?null:source.key)}> setVisible(source.key,false)}>
    @@ -63,6 +69,8 @@ export function BoardObservationCenter({vehicleID,name,enabled,back}:{vehicleID: {groups.map(({device,views,Session})=>visible.some(key=>views.some(view=>key===observationKey(device.id,view.id)))&&({id:view.id,layer:layerFor(observationKey(device.id,view.id),view),target:media.current.get(observationKey(device.id,view.id))!,...headers.current.get(observationKey(device.id,view.id))!}))}/>)} {visible.includes('map')&&createPortal(,media.current.get('map')!,'map-session')} + {visible.includes('rover')&&createPortal(,media.current.get('rover')!,'rover-session')} + {visible.includes('telemetry')&&createPortal(,media.current.get('telemetry')!,'telemetry-session')} setLayersOpen(false)} title={active?active.view.label:'Доступные слои'} size="md">
    {!active&&({value:String(i),label:`Окно ${i+1}`}))} onChange={value=>setLayout(current=>moveObservation(current,ids,id,ids[Number(value)]))}/>
    ;})} diff --git a/apps/control-station/src/workspaces/fleet/observation/ObservationDeck.tsx b/apps/control-station/src/workspaces/fleet/observation/ObservationDeck.tsx index 4575e4e..ee52e85 100644 --- a/apps/control-station/src/workspaces/fleet/observation/ObservationDeck.tsx +++ b/apps/control-station/src/workspaces/fleet/observation/ObservationDeck.tsx @@ -11,6 +11,8 @@ export function ObservationMount({element,className='observation-mount'}:{elemen export function ObservationDeck({ids,mounts,layout,onSplit,depth=0}:{ids:string[];mounts:Map;layout:ObservationLayout;onSplit:(key:string,value:number)=>void;depth?:number}){ if(!ids.length)return null; if(ids.length===1)return ; - const mid=Math.ceil(ids.length/2),key=JSON.stringify(ids),orientation=layout.arrangement==='rows'?'horizontal':layout.arrangement==='columns'?'vertical':depth%2?'horizontal':'vertical'; + const defaultColumns=depth===0&&layout.arrangement==='auto'&&!layout.order.some(id=>id==='rover'||id==='telemetry')&&ids.some(id=>!['map','rover','telemetry'].includes(id)); + const cameraCount=ids.filter(id=>!['map','rover','telemetry'].includes(id)).length; + const mid=defaultColumns&&cameraCountonSplit(key,value)} separatorLabel="Изменить размеры окон" primary={} secondary={}/>; } diff --git a/apps/control-station/test/boardLayout.test.mjs b/apps/control-station/test/boardLayout.test.mjs new file mode 100644 index 0000000..e99a342 --- /dev/null +++ b/apps/control-station/test/boardLayout.test.mjs @@ -0,0 +1,57 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; +import ts from 'typescript'; +const code=ts.transpileModule(readFileSync(new URL('../../../packages/sensor-ui/src/boardLayout.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022}}).outputText; +const {createBoardLayoutStore,defaultBoardLayout}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64')); +const tick=()=>new Promise(resolve=>setImmediate(resolve)); +function server(){ + let value=structuredClone(defaultBoardLayout);const calls=[]; + return {calls,read:async()=>structuredClone(value),patch:async(section,open)=>{ + calls.push({section,open});await tick(); + value={...value,revision:value.revision+1,open_sections:defaultBoardLayout.open_sections.filter(id=>id===section?open:value.open_sections.includes(id))}; + return structuredClone(value); + }}; +} +test('rapid toggles persist after navigation and preserve all-closed state',async()=>{ + const api=server();const store=createBoardLayoutStore(api);await store.load(); + const unsubscribe=store.subscribe(()=>{}); + store.change(['settings','devices']);store.change(['devices']);store.change([]); + unsubscribe(); + while(store.getSnapshot().saving)await tick(); + const reopened=createBoardLayoutStore(api);await reopened.load(); + assert.deepEqual(reopened.getSnapshot().value.open_sections,[]); + assert.equal(api.calls.length,3); +}); +test('a later toggle wins while an older patch is still in flight',async()=>{ + const api=server();const store=createBoardLayoutStore(api);await store.load(); + store.change(['settings','devices']);store.change(['computer','settings','devices']); + while(store.getSnapshot().saving)await tick(); + assert.deepEqual((await api.read()).open_sections,defaultBoardLayout.open_sections); +}); +test('different vehicles and simultaneous section changes do not clobber one another',async()=>{ + const api=server(),other=server();const a=createBoardLayoutStore(api),b=createBoardLayoutStore(api),c=createBoardLayoutStore(other); + await Promise.all([a.load(),b.load(),c.load()]); + a.change(['settings','devices']);b.change(['computer','devices']); + while(a.getSnapshot().saving||b.getSnapshot().saving)await tick(); + assert.deepEqual((await api.read()).open_sections,['devices']); + assert.deepEqual(c.getSnapshot().value.open_sections,defaultBoardLayout.open_sections); +}); +test('failed save reports failure, rolls back, and explicit reload recovers',async()=>{ + const api=server();let fail=true; + const store=createBoardLayoutStore({...api,patch:(...args)=>fail?Promise.reject(new Error('offline')):api.patch(...args)}); + await store.load();store.change([]); + while(store.getSnapshot().saving)await tick(); + assert.ok(store.getSnapshot().error); + assert.deepEqual(store.getSnapshot().value.open_sections,defaultBoardLayout.open_sections); + fail=false;await store.load();store.change(['devices']); + while(store.getSnapshot().saving)await tick(); + assert.equal(store.getSnapshot().error,null); + assert.deepEqual((await api.read()).open_sections,['devices']); +}); +test('invalid layout cannot overwrite stored preferences',async()=>{ + let writes=0; + const store=createBoardLayoutStore({read:async()=>({...defaultBoardLayout,open_sections:['motor-start']}),patch:async()=>{writes++;return defaultBoardLayout;}}); + await store.load();store.change([]); + assert.equal(store.getSnapshot().ready,false);assert.ok(store.getSnapshot().error);assert.equal(writes,0); +}); diff --git a/apps/control-station/test/roverControl.test.mjs b/apps/control-station/test/roverControl.test.mjs new file mode 100644 index 0000000..3dcdd28 --- /dev/null +++ b/apps/control-station/test/roverControl.test.mjs @@ -0,0 +1,157 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {build} from 'esbuild'; + +async function moduleAt(path) { + const result = await build({entryPoints:[new URL(path,import.meta.url).pathname],bundle:true,write:false,format:'esm',platform:'node'}); + return import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64')); +} +const {defaultProfile:base,mix,motorDemands,parseProfile}=await moduleAt('../../../packages/rover-control/src/profile.ts'); +const {AuthorityModel}=await moduleAt('../../../packages/rover-control/src/authority.ts'); +const axes=(leftY=0,rightY=0,leftX=0,rightX=0)=>({leftY,rightY,leftX,rightX}); +const profile={...base,deadband:0}; +const arcade={...profile,mode:'arcade'}; +const policy={maxAgeMs:100,neutralMs:200,maxCommandMs:100,monitoredAxes:['leftY','rightY','leftX','rightX']}; +const motors=['a','b','c','d']; +function frame(now,values=axes(),extra={}) { + return {now,link:{state:'live',at:now}, + axes:Object.fromEntries(Object.entries(values).map(([key,value])=>[key,{value,at:now,sequence:now}])), + drives:Object.fromEntries(motors.map(id=>[id,{at:now,healthy:true,stopped:true}])),...extra}; +} +function ready(p=base) { + const model=new AuthorityModel(p,motors,policy,'boot-A'); + for(let t=0;t<=200;t+=50)model.step(frame(t)); + return model; +} +function core() { + const model=ready(); + const {token}=model.step(frame(250,axes(),{requestCore:{owner:'autonomy',sequence:1,at:250}})); + assert.ok(token);return {model,token}; +} +const command=(token,at,sequence=0)=>({token,at,expires:at+75,sequence,demand:{left:.5,right:.5}}); + +test('tank keeps the two motor sides independent, including reversal',()=>{ + assert.deepEqual(mix(profile,axes(.8,-.4)),{left:.8,right:-.4}); + assert.deepEqual(mix(profile,axes(0,.4)),{left:0,right:.4}); +}); +test('arcade cardinal, diagonal and reverse vectors preserve yaw sign',()=>{ + for(const [y,x,left,right] of [[0,0,0,0],[1,0,1,1],[-1,0,-1,-1],[0,1,1,-1],[0,-1,-1,1],[1,1,1,0],[1,-1,0,1],[-1,1,0,-1],[-1,-1,-1,0]]) + assert.deepEqual(mix(arcade,axes(0,y,0,x)),{left,right}); + assert.deepEqual(mix(arcade,axes(0,.5,0,.5)),{left:.5,right:0}); +}); +test('selected stick defines the axes, not the number or position of motors',()=>{ + assert.deepEqual(mix({...arcade,stick:'left'},axes(.5,-1,.5,-1)),{left:.5,right:0}); +}); +test('deadband is continuous and rescaled; response and output scale are separate',()=>{ + assert.deepEqual(mix(base,axes(-.064,.074)),{left:0,right:0}); + assert.deepEqual(mix({...profile,deadband:.2,response:'squared',outputScale:.5},axes(.6,-1)),{left:.12499999999999997,right:-.5}); + assert.ok(Math.abs(mix(base,axes(.150001)).left)<.000002); +}); +test('every point in the input square stays bounded and changes sign symmetrically',()=>{ + for(let i=-20;i<=20;i++)for(let j=-20;j<=20;j++){ + const a=mix({...arcade,outputScale:.8},axes(0,i/20,0,j/20)); + const b=mix({...arcade,outputScale:.8},axes(0,-i/20,0,-j/20)); + assert.ok(Math.abs(a.left)<=.8+1e-12 && Math.abs(a.right)<=.8+1e-12); + assert.ok(Math.abs(a.left+b.left)<1e-12 && Math.abs(a.right+b.right)<1e-12); + } +}); +test('profile JSON rejects unknown fields, malformed numbers and unknown schema',()=>{ + assert.deepEqual(parseProfile(JSON.parse(JSON.stringify(base))),base); + for(const bad of [null,[],{...base,schema:'future'},{...base,revision:1.5},{...base,revision:-1},{...base,deadband:NaN},{...base,outputScale:1.1},{...base,writeVesc:true}])assert.throws(()=>parseProfile(bad)); + for(const value of [NaN,Infinity,1.01,undefined])assert.throws(()=>mix(profile,{...axes(),leftY:value})); +}); +test('2, 4 and 10 motors route by identity and explicit direction, never USB position',()=>{ + for(const n of [2,4,10]){ + const bindings=Array.from({length:n},(_,i)=>({uuid:i.toString(16).padStart(24,'0'),side:imotorDemands({left:1,right:1},[b])); + assert.throws(()=>motorDemands({left:1,right:1},[b,{...b,side:'right'}])); +}); +test('boot with held stick never permits motion; stable stopped neutral required',()=>{ + const model=new AuthorityModel(base,motors,policy,'boot'); + for(let t=0;t<1000;t+=50){const d=model.step(frame(t,axes(1)));assert.equal(d.state,'hold');assert.deepEqual(d.demand,{left:0,right:0});} + for(let t=1000;t<1200;t+=50)assert.equal(model.step(frame(t)).state,'hold'); + assert.equal(model.step(frame(1200)).state,'rc-ready'); + assert.equal(model.step(frame(1250,axes(1))).state,'rc-manual'); +}); +test('first RC gesture stops Core immediately, held packets never count as second gesture',()=>{ + const {model,token}=core(); + assert.equal(model.step(frame(300,axes(),{command:command(token,300)})).state,'core'); + const first=model.step(frame(350,axes(.5),{command:command(token,350,1)})); + assert.equal(first.reason,'rc-takeover');assert.ok(first.stopAll&&first.flushMotionQueue&&first.cancelMotionTasks); + for(let t=400;t<1500;t+=50)assert.deepEqual(model.step(frame(t,axes(.5))).demand,{left:0,right:0}); + for(let t=1500;t<=1700;t+=50)model.step(frame(t)); + const second=model.step(frame(1750,axes(.5))); + assert.equal(second.state,'rc-manual');assert.ok(second.demand.left>0); + assert.equal(model.step(frame(1800)).state,'rc-manual'); + assert.equal(model.step(frame(1850,axes(0,.5),{command:command(token,1850,2)})).state,'rc-manual'); +}); +test('neutral of one channel or a single moving member never completes rearming',()=>{ + for(const kind of ['axis','drive']){ + const {model}=core();model.step(frame(300,axes(1))); + for(let t=350;t<=1500;t+=50){const f=frame(t,kind==='axis'?axes(0,.2):axes());if(kind==='drive')f.drives.d.stopped=false;assert.equal(model.step(f).state,'hold');} + } +}); +test('loss of any of four controllers stops all sides and invalidates Core',()=>{ + for(const id of motors){const {model,token}=core();const f=frame(300,axes(),{command:command(token,300)});delete f.drives[id];const d=model.step(f);assert.equal(d.reason,'drive-unverified');assert.ok(d.cancelMotionTasks);assert.deepEqual(d.demand,{left:0,right:0});} +}); +test('unknown/lost radio cannot be treated as neutral even with fresh zero PWM reads',()=>{ + for(const state of ['lost','unknown']){const {model,token}=core();const d=model.step(frame(300,axes(),{link:{state,at:300},command:command(token,300)}));assert.equal(d.reason,'receiver-unverified');assert.ok(d.stopAll);} +}); +test('old decoded PPM, future samples, modified repeats and sequence rollback are rejected',()=>{ + for(const patch of [{at:0},{at:351},{sequence:249},{value:.4,at:250,sequence:250},{value:NaN}]){ + const {model}=core();const f=frame(350);Object.assign(f.axes.leftY,patch);assert.equal(model.step(f).reason,'axis-invalid'); + } +}); +test('one repeated neutral sample cannot qualify stable neutral',()=>{ + const model=new AuthorityModel(base,motors,{...policy,neutralMs:50},'boot'); + model.step(frame(0));const f=frame(50);f.axes.leftY={at:0,sequence:0,value:0}; + assert.equal(model.step(f).state,'hold'); +}); +test('receiver reconnect while held stays stopped until neutral and a new gesture',()=>{ + const model=ready();model.step(frame(250,axes(.5)));model.step(frame(300,axes(),{link:{state:'lost',at:300}})); + for(let t=350;t<1000;t+=50)assert.equal(model.step(frame(t,axes(.5))).state,'hold'); + for(let t=1000;t<=1200;t+=50)model.step(frame(t)); + assert.equal(model.step(frame(1250,axes(.5))).state,'rc-manual'); +}); +test('Core expiry/replay/wrong boot token/missing commands all require rearming',()=>{ + for(const change of [c=>({...c,expires:300}),c=>({...c,expires:500}),c=>({...c,token:'old-boot:1'}),()=>undefined,c=>({...c,demand:{left:Infinity,right:0}})]){ + const {model,token}=core();assert.equal(model.step(frame(300,axes(),{command:change(command(token,300))})).reason,'core-command-invalid'); + } + const {model,token}=core();model.step(frame(300,axes(),{command:command(token,300,1)})); + assert.equal(model.step(frame(350,axes(),{command:command(token,350,1)})).reason,'core-command-invalid'); +}); +test('clock rewind and missing observation interval cannot bypass the stop gate',()=>{ + for(const time of [249,500,NaN]){const {model,token}=core();const d=model.step(frame(time,axes(),{command:command(token,time)}));assert.equal(d.state,'hold');assert.ok(d.cancelMotionTasks);} +}); +test('premature or replayed Core request does not acquire authority after neutral',()=>{ + const model=new AuthorityModel(base,motors,policy,'boot'); + for(let t=0;t<=300;t+=50){const d=model.step(frame(t,axes(),{requestCore:{owner:'remote',sequence:1,at:t}}));assert.notEqual(d.state,'core');} + assert.equal(model.step(frame(350,axes(),{requestCore:{owner:'remote',sequence:2,at:350}})).state,'core'); +}); +test('reboot cannot restore authority from serialized profile or old grant',()=>{ + const {token}=core(), model=ready(); + assert.equal(model.step(frame(250,axes(),{command:command(token,250)})).state,'rc-ready'); + const next=new AuthorityModel(base,motors,policy,'boot-B'); + for(let t=0;t<=200;t+=50)next.step(frame(t)); + const grant=next.step(frame(250,axes(),{requestCore:{owner:'remote',sequence:1,at:250}})); + assert.notEqual(grant.token,token); + assert.equal(next.step(frame(300,axes(),{command:command(token,300)})).state,'hold'); +}); +test('profile limits do not mask RC takeover intent at zero output scale',()=>{ + const model=ready({...base,outputScale:0});const grant=model.step(frame(250,axes(),{requestCore:{owner:'remote',sequence:1,at:250}})); + assert.ok(grant.token);assert.equal(model.step(frame(300,axes(.5))).reason,'rc-takeover'); +}); + +test('non-driving stick still takes over in Arcade and every monitored axis must return',()=>{ + const model=ready({...base,mode:'arcade',stick:'right'}); + model.step(frame(250,axes(),{requestCore:{owner:'autonomy',sequence:1,at:250}})); + assert.equal(model.step(frame(300,axes(.5))).reason,'rc-takeover'); + for(let t=350;t<800;t+=50)assert.equal(model.step(frame(t,axes(0,0,.5))).state,'hold'); + const f=frame(800);delete f.axes.leftX;assert.equal(model.step(f).reason,'axis-invalid'); + assert.throws(()=>new AuthorityModel(base,motors,{...policy,monitoredAxes:['leftY']},'boot')); +}); diff --git a/apps/control-station/test/roverControlFocus.test.mjs b/apps/control-station/test/roverControlFocus.test.mjs new file mode 100644 index 0000000..c3fd7a7 --- /dev/null +++ b/apps/control-station/test/roverControlFocus.test.mjs @@ -0,0 +1,49 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {build} from 'esbuild'; +const result=await build({entryPoints:[new URL('../src/core/fleet/useRoverControl.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm',plugins:[{name:'hook-fixture',setup(b){ + b.onResolve({filter:/^react$/},()=>({path:'react',namespace:'fixture'})); + b.onLoad({filter:/.*/,namespace:'fixture'},()=>({contents:`export const useRef=v=>({current:v});export const useState=v=>[v,()=>{}];export const useCallback=f=>f;export const useEffect=f=>globalThis.roverEffects.push(f);`})); +}}]}); +const {useRoverControl}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64')); +const flush=()=>new Promise(resolve=>setImmediate(resolve)); +async function fixture(run){ + const originals=Object.fromEntries(['window','document','fetch','roverEffects','setInterval','clearInterval'].map(k=>[k,globalThis[k]])); + let focus=true,hidden=false;const calls=[],timers=[];globalThis.roverEffects=[]; + globalThis.window={addEventListener(){},removeEventListener(){}}; + globalThis.document={get hidden(){return hidden;},hasFocus:()=>focus,addEventListener(){},removeEventListener(){}}; + globalThis.setInterval=(f,ms)=>{const timer={f,ms};timers.push(timer);return timer;};globalThis.clearInterval=()=>{}; + globalThis.fetch=async(url,init)=>{const body=init.body?JSON.parse(init.body):null;calls.push({url,body});return {ok:true,json:async()=>url.endsWith('/arm')?{session_id:'fixture-session'}:{fresh:true,controlling:true,snapshot:{state:'ready'}}};}; + const c=useRoverControl('fixture',true);const cleanup=globalThis.roverEffects.map(f=>f()); + try{await flush();await c.arm(30,2000);await flush();await run({c,calls,timers,blur:()=>{focus=false;},focus:()=>{focus=true;},hide:()=>{hidden=true;}});} + finally{cleanup.forEach(f=>f?.());await flush();for(const [key,value]of Object.entries(originals)){if(value===undefined)delete globalThis[key];else globalThis[key]=value;}} +} +test('command heartbeat sends neutral on lost blur, keeps session, and accepts new focused input',async()=>fixture(async f=>{ + f.c.setInputGuard(()=>true);f.c.setDemand({left:1,right:-1});await flush(); + assert.equal(f.calls.at(-1).body.left,1);f.blur();f.timers.find(t=>t.ms===100).f();await flush(); + assert.equal(f.calls.at(-1).body.stop,false);assert.equal(f.calls.at(-1).body.left,0); + f.c.setDemand({left:1,right:1});await flush();assert.equal(f.calls.at(-1).body.left,0); + f.focus();f.timers.find(t=>t.ms===100).f();await flush();assert.equal(f.calls.at(-1).body.left,0); + f.c.setDemand({left:1,right:1});await flush();assert.equal(f.calls.at(-1).body.left,1); + assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,1); +})); +test('expired physical input prevents heartbeat from renewing remembered demand',async()=>fixture(async f=>{ + let valid=true;f.c.setInputGuard(()=>valid);f.c.setDemand({left:1,right:-1});await flush();valid=false; + f.timers.find(t=>t.ms===100).f();await flush();assert.equal(f.calls.at(-1).body.stop,false); +})); +test('no registered input scope cannot issue motion',async()=>fixture(async f=>{ + f.c.setDemand({left:1,right:1});await flush();assert.equal(f.calls.at(-1).body.stop,false); + assert.equal(f.calls.some(x=>x.body?.left===1),false); +})); +test('hidden document sends only neutral without a visibility event',async()=>fixture(async f=>{ + f.c.setInputGuard(()=>true);f.hide();f.c.setDemand({left:1,right:1});await flush(); + assert.equal(f.calls.at(-1).body.stop,false);assert.equal(f.calls.some(x=>x.body?.left===1),false); +})); + +test('explicit pause clears demand without revoking session; explicit stop still revokes it',async()=>fixture(async f=>{ + f.c.setInputGuard(()=>true);f.c.setDemand({left:1,right:-1});await flush();f.c.pauseInput();await flush(); + assert.equal(f.calls.at(-1).body.stop,false);assert.equal(f.calls.at(-1).body.left,0); + f.c.setDemand({left:1,right:1});await flush();assert.equal(f.calls.at(-1).body.left,1); + f.c.stop();await flush();assert.equal(f.calls.at(-1).body.stop,true); + const count=f.calls.length;f.c.setDemand({left:1,right:1});await flush();assert.equal(f.calls.length,count); +})); diff --git a/apps/control-station/test/roverControlStartup.test.mjs b/apps/control-station/test/roverControlStartup.test.mjs new file mode 100644 index 0000000..05b371e --- /dev/null +++ b/apps/control-station/test/roverControlStartup.test.mjs @@ -0,0 +1,49 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {build} from 'esbuild'; +const result=await build({entryPoints:[new URL('../src/core/fleet/useRoverControl.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm',plugins:[{name:'hook-fixture',setup(b){ + b.onResolve({filter:/^react$/},()=>({path:'react',namespace:'fixture'})); + b.onLoad({filter:/.*/,namespace:'fixture'},()=>({contents:`export const useRef=v=>({current:v});export const useState=v=>[v,()=>{}];export const useCallback=f=>f;export const useEffect=f=>globalThis.roverEffects.push(f);`})); +}}]}); +const {useRoverControl}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64')); +const flush=()=>new Promise(resolve=>setImmediate(resolve)); +const deferred=()=>{let resolve;const promise=new Promise(r=>resolve=r);return {promise,resolve};}; +const response=value=>({ok:true,json:async()=>value}); +const idle={fresh:true,controlling:false,snapshot:{supported:true,state:'observing'}}; +async function fixture(run){ + const originals=Object.fromEntries(['window','document','fetch','roverEffects','setInterval','clearInterval'].map(k=>[k,globalThis[k]])); + const calls=[],timers=[];globalThis.roverEffects=[]; + globalThis.window={addEventListener(){},removeEventListener(){}};globalThis.document={hidden:false,hasFocus:()=>true,addEventListener(){},removeEventListener(){}}; + globalThis.setInterval=(f,ms)=>{timers.push({f,ms});return timers.length;};globalThis.clearInterval=()=>{}; + let armResponse=null,nextPoll=null; + globalThis.fetch=async(url,init)=>{const body=init.body?JSON.parse(init.body):null;calls.push({url,body}); + if(url.endsWith('/arm'))return armResponse?armResponse.promise:response({session_id:'new-session'}); + if(!body)return nextPoll?nextPoll.promise:response(idle); + return response({accepted_sequence:body.sequence}); + }; + const c=useRoverControl('fixture',true),cleanup=globalThis.roverEffects.map(f=>f()); + try{await flush();await run({c,calls,poll:()=>timers.find(t=>t.ms===200).f(),heartbeat:()=>timers.find(t=>t.ms===100).f(),delayArm:()=>armResponse=deferred(),delayPoll:()=>nextPoll=deferred()});} + finally{cleanup.forEach(f=>f?.());await flush();for(const [key,value]of Object.entries(originals)){if(value===undefined)delete globalThis[key];else globalThis[key]=value;}} +} +test('idle poll begun during pending arm cannot revoke newly acknowledged session',async()=>fixture(async f=>{ + const a=f.delayArm();const arming=f.c.arm(30,2000);const p=f.delayPoll();f.poll(); + a.resolve(response({session_id:'new-session'}));assert.equal(await arming,true);await flush(); + p.resolve(response(idle));await flush();f.heartbeat();await flush(); + assert.equal(f.calls.filter(x=>x.body?.stop===true).length,0,'old idle poll revoked the new session'); + assert.equal(f.calls.at(-1).body.session_id,'new-session'); +})); +test('failed poll begun during pending arm cannot revoke newly acknowledged session',async()=>fixture(async f=>{ + const a=f.delayArm();const arming=f.c.arm(30,2000);const p=f.delayPoll();f.poll(); + a.resolve(response({session_id:'new-session'}));assert.equal(await arming,true);await flush(); + p.resolve({ok:false,json:async()=>({detail:'stale read failure'})});await flush(); + assert.equal(f.calls.filter(x=>x.body?.stop===true).length,0,'old failed poll revoked the new session'); +})); +test('a current poll still revokes control when server reports lease lost',async()=>fixture(async f=>{ + assert.equal(await f.c.arm(30,2000),true);await flush();f.poll();await flush(); + assert.equal(f.calls.at(-1).body.stop,true); +})); +test('duplicate arm clicks while request pending create exactly one lease request',async()=>fixture(async f=>{ + const a=f.delayArm();const first=f.c.arm(30,2000),second=f.c.arm(30,2000); + a.resolve(response({session_id:'new-session'}));await Promise.all([first,second]);await flush(); + assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,1); +})); diff --git a/apps/control-station/test/roverHoldInput.test.mjs b/apps/control-station/test/roverHoldInput.test.mjs new file mode 100644 index 0000000..5b2af77 --- /dev/null +++ b/apps/control-station/test/roverHoldInput.test.mjs @@ -0,0 +1,85 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {build} from 'esbuild'; +const result=await build({entryPoints:[new URL('../src/core/fleet/roverHoldInput.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'}); +const {bindRoverHoldInput}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64')); +class Events { + listeners=new Map();timers=new Map();next=0; + addEventListener(type,fn){if(!this.listeners.has(type))this.listeners.set(type,new Set());this.listeners.get(type).add(fn);} + removeEventListener(type,fn){this.listeners.get(type)?.delete(fn);} + emit(type,detail={}){const e={target:this,isTrusted:true,preventDefault(){},...detail};for(const fn of [...(this.listeners.get(type)??[])])fn(e);} + setInterval(fn){const id=++this.next;this.timers.set(id,fn);return id;} + clearInterval(id){this.timers.delete(id);} + tick(){for(const fn of this.timers.values())fn();} +} +function fixture(mode='arcade'){ + let time=0,focus=true;const win=new Events(),doc=new Events();doc.defaultView=win;doc.hidden=false;doc.hasFocus=()=>focus; + const scope={ownerDocument:doc,closest:()=>null},child={closest:()=>null};scope.contains=x=>x===scope||x===child;doc.activeElement=scope; + const states=[],demands=[];let stops=0,pauses=0; + const binding=bindRoverHoldInput(scope,mode,{held:k=>states.push([...k]),demand:d=>demands.push(d),stop:()=>stops++,pause:()=>{pauses++;demands.push({left:0,right:0});}},()=>time); + const key=(code,repeat=false)=>win.emit('keydown',{code,repeat,target:scope}); + return {win,doc,scope,child,binding,states,demands,key,stops:()=>stops,pauses:()=>pauses,advance:ms=>{time+=ms;win.tick();},loseFocus:()=>{focus=false;},restoreFocus:()=>{focus=true;},up:code=>win.emit('keyup',{code,target:scope})}; +} +test('blur clears D, ignores a late repeat, but accepts a fresh press without rearming',()=>{ + const f=fixture();f.key('KeyD');assert.deepEqual(f.demands.at(-1),{left:1,right:-1}); + f.win.emit('blur');assert.equal(f.pauses(),1);assert.equal(f.stops(),0);assert.deepEqual(f.states.at(-1),[]); + assert.deepEqual(f.demands.at(-1),{left:0,right:0});const count=f.demands.length; + f.key('KeyD',true);assert.equal(f.demands.length,count); + f.key('KeyW');assert.deepEqual(f.demands.at(-1),{left:1,right:1});assert.equal(f.binding.valid(),true);f.binding.dispose(); +}); +test('heartbeat validity catches missing blur event using document focus',()=>{ + const f=fixture();f.key('KeyD');f.loseFocus();assert.equal(f.binding.valid(),false);assert.equal(f.pauses(),1); + f.restoreFocus();assert.equal(f.binding.valid(),true);f.binding.dispose(); +}); +test('focus polling catches missing event or moving to another control',()=>{ + const f=fixture();f.key('KeyW');f.doc.activeElement={};f.advance(50);assert.equal(f.pauses(),1);f.binding.dispose(); +}); +test('lost keyup AND missing focus notifications still expire repeated D',()=>{ + const f=fixture();f.key('KeyD');f.advance(500);f.key('KeyD',true);f.advance(299);assert.equal(f.pauses(),0); + f.advance(1);assert.equal(f.pauses(),1);assert.deepEqual(f.states.at(-1),[]);f.key('KeyD',true);assert.equal(f.pauses(),1);f.binding.dispose(); +}); +test('first press allows OS repeat delay but never an indefinite hold',()=>{ + const f=fixture();f.key('KeyW');f.advance(999);assert.equal(f.pauses(),0);f.advance(1);assert.equal(f.pauses(),1);f.binding.dispose(); +}); +test('continuous repeat renews hold; keyup immediately sends neutral',()=>{ + const f=fixture();f.key('KeyW');f.advance(600); + for(let i=0;i<30;i++){f.key('KeyW',true);f.advance(100);} + assert.equal(f.pauses(),0);f.up('KeyW');assert.deepEqual(f.demands.at(-1),{left:0,right:0});f.advance(1200);assert.equal(f.pauses(),0);f.binding.dispose(); +}); +test('diagonal input survives single-key OS repeat; release recomputes demand',()=>{ + const f=fixture();f.key('KeyW');f.key('KeyA'); + for(let i=0;i<20;i++){f.key('KeyA',true);f.advance(100);} + assert.equal(f.pauses(),0);assert.deepEqual(f.demands.at(-1),{left:0,right:1}); + f.up('KeyA');assert.deepEqual(f.demands.at(-1),{left:1,right:1});f.up('KeyW');f.binding.dispose(); +}); +test('repeat without a fresh press and untrusted events never command motion',()=>{ + const f=fixture();f.key('KeyD',true);f.win.emit('keydown',{code:'KeyW',isTrusted:false,target:f.scope});assert.equal(f.demands.length,0);f.binding.dispose(); +}); +test('focus inside the view is allowed; leaving or hiding it stops',()=>{ + for(const event of ['focusout','visibilitychange','pagehide','outside']){ + const f=fixture();f.key('KeyW');f.doc.emit('focusout',{target:f.scope,relatedTarget:f.child});assert.equal(f.pauses(),0); + if(event==='focusout')f.doc.emit(event,{target:f.scope,relatedTarget:null}); + else if(event==='visibilitychange'){f.doc.hidden=true;f.doc.emit(event);} + else if(event==='pagehide')f.win.emit(event); + else f.doc.emit('pointerdown',{target:{}}); + assert.equal(event==='pagehide'?f.stops():f.pauses(),1,event);f.binding.dispose(); + } +}); +test('pointer capture lost or cancelled releases every input',()=>{ + for(const mode of ['arcade','tank']){ + const f=fixture(mode);f.binding.pointerDown(1,mode==='arcade'?'KeyW':'KeyQ');f.binding.pointerCancel(1); + assert.equal(f.pauses(),1);assert.deepEqual(f.states.at(-1),[]);f.binding.dispose(); + } +}); +test('document pointerup releases even if button handler does not receive it',()=>{ + const f=fixture();f.binding.pointerDown(1,'KeyD');f.doc.emit('pointerup',{pointerId:1});assert.deepEqual(f.demands.at(-1),{left:0,right:0});assert.equal(f.pauses(),0);f.binding.dispose(); +}); +test('modifier shortcuts pause; cleanup removes listeners, timer and held demand',()=>{ + const f=fixture();f.key('KeyD');f.win.emit('keydown',{code:'Tab',metaKey:true,target:f.scope});assert.equal(f.pauses(),1);f.binding.dispose(); + assert.deepEqual(f.demands.at(-1),{left:0,right:0});assert.equal(f.win.timers.size,0); + assert.equal([...f.win.listeners.values(),...f.doc.listeners.values()].reduce((sum,x)=>sum+x.size,0),0); +}); + +test('Space and Escape remain explicit session stops',()=>{ + for(const code of ['Space','Escape']){const f=fixture();f.key('KeyW');f.key(code);assert.equal(f.stops(),1);assert.equal(f.binding.valid(),false);f.binding.dispose();} +}); diff --git a/apps/control-station/test/roverInput.test.mjs b/apps/control-station/test/roverInput.test.mjs new file mode 100644 index 0000000..f1d41f0 --- /dev/null +++ b/apps/control-station/test/roverInput.test.mjs @@ -0,0 +1,23 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {build} from 'esbuild'; +const result=await build({entryPoints:[new URL('../src/core/fleet/roverInput.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'}); +const {keyDemand,roverSettings}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64')); +const keys=(...k)=>new Set(k.map(v=>'Key'+v)); +test('arcade mixes directions and opposite keys cancel',()=>{ + assert.deepEqual(keyDemand('arcade',keys('W')),{left:1,right:1}); + assert.deepEqual(keyDemand('arcade',keys('A')),{left:-1,right:1}); + assert.deepEqual(keyDemand('arcade',keys('W','A')),{left:0,right:1}); + assert.deepEqual(keyDemand('arcade',keys('W','S','A','D')),{left:0,right:0}); +}); +test('tank sides and backwards remain independent',()=>{ + assert.deepEqual(keyDemand('tank',keys('Q','D')),{left:1,right:-1}); + assert.deepEqual(keyDemand('tank',keys('A','D')),{left:-1,right:-1}); + assert.deepEqual(keyDemand('tank',keys('Q','A')),{left:0,right:0}); +}); +test('invalid stored settings never grant motion or invalid limits',()=>{ + assert.equal(roverSettings({version:1,currentA:Infinity}).currentA,30); + assert.equal(roverSettings({version:1,maxErpm:999999}).maxErpm,3000); + assert.equal(roverSettings({version:1,model:'https://other/model.glb'}).model,''); + assert.deepEqual(keyDemand('arcade',new Set()),{left:0,right:0}); +}); diff --git a/apps/control-station/test/vescUi.test.mjs b/apps/control-station/test/vescUi.test.mjs new file mode 100644 index 0000000..b599a23 --- /dev/null +++ b/apps/control-station/test/vescUi.test.mjs @@ -0,0 +1,70 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; +import ts from 'typescript'; + +const source=readFileSync(new URL('../../../plugins/vesc/frontend/src/model.ts',import.meta.url),'utf8'); +const code=ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText; +const {vescLabel,testInput,speedInput,rotationResult,driveTestIds}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64')); +const controller={online:true,prepared:true,verified:true,vesc_status:{identity:{uuid:'synthetic'},readable:true}}; + +test('speed mode requires board capability and reports measured rotation time',()=>{ + assert.ok(speedInput('1200',undefined).error); + const bounds={min_erpm:300,max_erpm:3000,duration_basis:'measured_speed'}; + assert.equal(speedInput('1200',bounds).error,null); + for(const value of ['', 'NaN','299','3001'])assert.ok(speedInput(value,bounds).error); + const text=rotationResult({outcome:'stopped',rotation_s:2.5,release_confirmed:true,limits_restored:true}); + assert.match(text,/2,5 с/); + assert.match(text,/Проверка остановлена/); + assert.doesNotMatch(text,/время вращения набрано/); +}); + +test('USB discovery and model preparation never claim a verified VESC',()=>{ + assert.equal(vescLabel({...controller,prepared:false},true).label,'Требуется подготовка'); + assert.equal(vescLabel({...controller,vesc_status:{identity:null,readable:false}},true).tone,'warning'); +}); +test('fresh read capability is distinct from unsupported firmware and offline state',()=>{ + assert.equal(vescLabel(controller,true).label,'Готов к чтению'); + assert.equal(vescLabel(controller,false).label,'Нет связи'); + assert.equal(vescLabel({...controller,online:false},true).label,'Нет связи'); + assert.equal(vescLabel({...controller,vesc_status:{identity:{uuid:'synthetic'},readable:false}},true).label,'Прошивка не поддерживается'); +}); + +test('test fields accept entered values only inside the board capability bounds',()=>{ + const bounds={min_current_a:0.5,max_current_a:5,min_duration_s:0.5,max_duration_s:10}; + assert.equal(testInput('3.7','7.2',bounds).valid,true); + assert.equal(testInput('5','10',bounds).valid,true); + for(const [amps,seconds] of [['','5'],['5',''],['60','10'],['5','11'],['NaN','1'],['Infinity','1']])assert.equal(testInput(amps,seconds,bounds).valid,false); + assert.equal(testInput('2','1.5',undefined).valid,false); + const overlong=testInput('5','15',bounds); + assert.equal(overlong.valid,false); + assert.equal(overlong.currentError,null); + assert.equal(overlong.durationError,'Длительность должна быть от 0,5 до 10 с.'); + assert.equal(testInput('5','10',bounds).durationError,null); +}); + +// Capabilities come from the installed board: a newer Core must retain old bounds. +test('extended board accepts 30 A / 30 s without changing older board bounds',()=>{ + const old={min_current_a:0.5,max_current_a:5,min_duration_s:0.5,max_duration_s:10}; + const expanded={...old,max_current_a:30,max_duration_s:30,continuous_current:true}; + assert.equal(testInput('30','30',expanded).valid,true); + assert.equal(testInput('30.1','30',expanded).valid,false); + assert.equal(testInput('30','30.1',expanded).valid,false); + assert.equal(testInput('30','30',old).valid,false); +}); + + +test('group spin requires a complete unique profile containing the selected controller',()=>{ + const profile={layout:'1x1',revision:3,bindings:{'left.1':{device_id:'left',uuid:'a'},'right.1':{device_id:'right',uuid:'b'}}}; + assert.deepEqual(driveTestIds(profile,'left'),['left','right']); + assert.deepEqual(driveTestIds(profile,'unassigned'),[]); + assert.deepEqual(driveTestIds({...profile,bindings:{'left.1':profile.bindings['left.1']}},'left'),[]); + assert.deepEqual(driveTestIds({...profile,bindings:{...profile.bindings,'right.1':profile.bindings['left.1']}},'left'),[]); + assert.deepEqual(driveTestIds(undefined,'left'),[]); +}); + +test('four-wheel profile preserves front and rear membership for common testing',()=>{ + const ids=['lf','lr','rf','rr']; + const bindings=Object.fromEntries(['left.1','left.2','right.1','right.2'].map((slot,i)=>[slot,{device_id:ids[i],uuid:ids[i]}])); + assert.deepEqual(driveTestIds({layout:'2x2',revision:4,bindings},'rf'),ids); +}); diff --git a/apps/control-station/tools/rover-control-preview/build.mjs b/apps/control-station/tools/rover-control-preview/build.mjs new file mode 100644 index 0000000..aa32ec2 --- /dev/null +++ b/apps/control-station/tools/rover-control-preview/build.mjs @@ -0,0 +1,18 @@ +import {build} from 'esbuild'; +import {mkdir,writeFile} from 'node:fs/promises'; +import {fileURLToPath} from 'node:url'; +import {resolve,join} from 'node:path'; + +const root=fileURLToPath(new URL('.',import.meta.url)); +const destination=process.argv[2]; +if(!destination)throw Error('Pass an artifact output directory; no server is started.'); +const result=await build({entryPoints:[join(root,'main.tsx')],bundle:true,write:false,minify:true, + format:'iife',platform:'browser',jsx:'automatic',outfile:'preview.js',define:{'process.env.NODE_ENV':'"production"'}, + alias:{'@nodedc/ui-react':resolve(root,'../../node_modules/@nodedc/ui-react/dist/index.js')}, + nodePaths:[resolve(root,'../../node_modules')],logLevel:'warning'}); +const js=result.outputFiles.find(f=>f.path.endsWith('.js')).text.replaceAll('f.path.endsWith('.css')).text.replaceAll('Mission Core · Профили управления · Прототип
    `; +await writeFile(join(destination,'rover-control-preview.html'),html); +console.log(JSON.stringify({artifact:join(destination,'rover-control-preview.html'),bytes:Buffer.byteLength(html),network:'disabled by CSP',hardware:'no adapter'})); diff --git a/apps/control-station/tools/rover-control-preview/main.tsx b/apps/control-station/tools/rover-control-preview/main.tsx new file mode 100644 index 0000000..ab36fa7 --- /dev/null +++ b/apps/control-station/tools/rover-control-preview/main.tsx @@ -0,0 +1,69 @@ +import {useState} from 'react'; +import {createRoot} from 'react-dom/client'; +import {Button,Inspector,InspectorSelectField,RangeControl,SettingsCard,StatusBadge} from '@nodedc/ui-react'; +import '@nodedc/ui-core/styles.css'; +import {defaultProfile,mix,parseProfile,type Axes,type ControlProfile} from '../../../../packages/rover-control/src/profile'; +import {trace} from './trace'; +import './preview.css'; + +const emptyAxes:Axes={leftY:0,rightY:0,leftX:0,rightX:0}; +const percent=(n:number)=>`${Math.round(n*100)}%`; +const states={'hold':'Остановка / ожидание нейтрали','rc-ready':'Пульт готов','rc-manual':'Ручное управление','core':'Mission Core'}; +const storageKey='missioncore.rover-control-preview.v1'; +function load():ControlProfile { + try{const raw=localStorage.getItem(storageKey);return raw?parseProfile(JSON.parse(raw)):{...defaultProfile};} + catch{return {...defaultProfile};} +} +function App(){ + const [profile,setProfile]=useState(load); + const [axes,setAxes]=useState(emptyAxes); + const [open,setOpen]=useState(['settings','preview']); + const [saved,setSaved]=useState(''); + const [light,setLight]=useState(false); + const change=(patch:Partial)=>{ + setProfile(parseProfile({...profile,...patch,revision:profile.revision+1}));setAxes(emptyAxes);setSaved(''); + }; + const result=mix(profile,axes); + const y=profile.mode==='tank'?'leftY':profile.stick==='right'?'rightY':'leftY'; + const x=profile.mode==='tank'?'rightY':profile.stick==='right'?'rightX':'leftX'; + const field=(key:keyof Axes,label:string)=>setAxes({...axes,[key]:value})}/>; + function save(){ + try{localStorage.setItem(storageKey,JSON.stringify(profile));setSaved('Черновик сохранён в этом браузере.');} + catch{setSaved('Браузер не сохранил черновик. Используйте скачивание JSON.');} + } + function download(){ + const url=URL.createObjectURL(new Blob([JSON.stringify(profile,null,2)+'\n'],{type:'application/json'})); + const a=document.createElement('a');a.href=url;a.download='rover-control-draft.json';a.click(); + setTimeout(()=>URL.revokeObjectURL(url),1000); + } + return
    +

    MISSION CORE · ПРОТОТИП

    Настройки управления ровером

    +

    Интерактивный макет без подключения к роверу. Все значения ниже — расчёт на экране; кнопки не обращаются к борту и VESC.

    + + change({mode})}/> + {profile.mode==='arcade'&&change({stick})}/>} +

    {profile.mode==='tank'?'Левый рычаг управляет левой стороной, правый — правой.':'Вперёд/назад задаёт движение; влево/вправо — поворот, включая разворот на месте. При движении назад знак поворота корпуса сохраняется.'}

    + change({response})}/> + change({deadband})}/> + change({outputScale})}/> +

    Масштаб команды — относительный отклик рычага. Он не задаёт амперы, ватты или паспортный предел двигателя.

    +
    + {saved&&

    {saved}

    } + }, + {id:'preview',label:'Проверка профиля на экране',content: + {field(y,profile.mode==='tank'?'Левый рычаг · вперёд / назад':'Движение · вперёд / назад')} + {field(x,profile.mode==='tank'?'Правый рычаг · вперёд / назад':'Поворот · влево / вправо')} +
    +
    {(['left','right'] as const).map(side=>
    {side==='left'?'Левая сторона':'Правая сторона'}{percent(result[side])}{result[side]===0?'Нейтраль':result[side]>0?'Вперёд':'Назад'}
    )}
    +

    Команда стороны распространяется на все назначенные ей моторы: два, четыре, шесть и более. Связь — по UUID, а направление проверяется отдельно для каждого мотора.

    +
    }, + {id:'takeover',label:'Перехват пультом · проверка сценария',content: +
    {trace(profile).map(({label,decision},i)=>
    {i+1}. {label}{states[decision.state]}{percent(decision.demand.left)} / {percent(decision.demand.right)}
    )}
    +

    Первый жест отменяет допуск и очередь Mission Core. Новый допуск требует явного действия: нейтраль и восстановление связи не возобновляют автономную задачу.

    +
    }, + ]}/> +
    ; +} +document.documentElement.dataset.nodedcTheme='dark'; +createRoot(document.getElementById('root')!).render(); diff --git a/apps/control-station/tools/rover-control-preview/preview.css b/apps/control-station/tools/rover-control-preview/preview.css new file mode 100644 index 0000000..6a26ea5 --- /dev/null +++ b/apps/control-station/tools/rover-control-preview/preview.css @@ -0,0 +1,16 @@ +/* Domain composition only; all controls come from the Design Guideline. */ +body { margin:0; background:var(--nodedc-canvas); color:var(--nodedc-text-primary); font-family:var(--nodedc-font-family); font-size:var(--nodedc-font-size-md); } +main { max-width:960px; margin:0 auto; padding:32px 24px 64px; } +main>header { display:flex; align-items:center; justify-content:space-between; gap:24px; margin-bottom:24px; } +h1 { font-size:var(--nodedc-font-size-title); font-weight:600; margin:8px 0; } +p { font-size:var(--nodedc-font-size-sm); line-height:1.6; color:var(--nodedc-text-secondary); } +main>header p { font-size:var(--nodedc-font-size-xs); } +.notice { margin-bottom:24px; } +.actions { display:flex; flex-wrap:wrap; gap:12px; margin:16px 0; } +.demands { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:24px; margin:24px 0; } +.demands>div { display:flex; flex-direction:column; gap:8px; } +.demands strong { font-size:var(--nodedc-font-size-lg); font-variant-numeric:tabular-nums; } +.demands span { font-size:var(--nodedc-font-size-sm); } +.trace { display:grid; gap:20px; } +.trace-row { display:grid; grid-template-columns:minmax(0,1fr) 250px 100px; align-items:center; gap:16px; font-size:var(--nodedc-font-size-sm); } +@media (max-width:720px) { main {padding:20px 12px 40px;} .trace-row {grid-template-columns:1fr;} } diff --git a/apps/control-station/tools/rover-control-preview/trace.ts b/apps/control-station/tools/rover-control-preview/trace.ts new file mode 100644 index 0000000..ee8765b --- /dev/null +++ b/apps/control-station/tools/rover-control-preview/trace.ts @@ -0,0 +1,38 @@ +import {AuthorityModel, type Decision} from '../../../../packages/rover-control/src/authority'; +import {type ControlProfile} from '../../../../packages/rover-control/src/profile'; + +/** Synthetic event replay, with no wall clock, I/O, timers or hardware adapter. */ +export function trace(profile: ControlProfile): {label: string; decision: Decision}[] { + const model = new AuthorityModel(profile, ['left', 'right'], { + maxAgeMs:100, neutralMs:200, maxCommandMs:100, monitoredAxes:['leftY','rightY','leftX','rightX'], + }, 'preview'); + const rows: {label:string;decision:Decision}[] = []; + let now = -50, token = ''; + function step(value=0, link: 'live'|'lost'='live', core=false, request=false) { + now+=50; + const axes = {leftY:0,rightY:0,leftX:0,rightX:0}; + axes[profile.mode==='tank'?'leftY':profile.stick==='left'?'leftY':'rightY']=value; + return model.step({now, link:{state:link,at:now}, + axes:Object.fromEntries(Object.entries(axes).map(([key,v])=>[key,{value:v,at:now,sequence:now}])), + drives:{left:{healthy:true,stopped:value===0,at:now},right:{healthy:true,stopped:value===0,at:now}}, + requestCore:request?{owner:'autonomy',at:now,sequence:1}:undefined, + command:core?{token,at:now,expires:now+75,sequence:now,demand:{left:.4,right:.4}}:undefined, + }); + } + const add=(label:string,decision:Decision)=>rows.push({label,decision}); + for(let i=0;i<5;i++)step(); + const grant=step(0,'live',false,true);token=grant.token??''; + add('Mission Core получил явный допуск',grant); + add('Автономная команда движения',step(0,'live',true)); + add('Первое отклонение рычага',step(.8,'live',true)); + for(let i=0;i<20;i++)step(.8); + add('Тот же рычаг удерживается',step(.8)); + add('Остановка подтверждена, оба рычага отпущены',step()); + for(let i=0;i<3;i++)step(); + add('Непрерывная нейтраль подтверждена',step()); + add('Второе отклонение — ручное движение',step(.8)); + add('Запоздавшая команда прежней задачи',step(.8,'live',true)); + add('Радиосвязь потеряна',step(0,'lost')); + add('Связь вернулась с отклонённым рычагом',step(.8)); + return rows; +} diff --git a/apps/control-station/tools/rover-control-preview/tsconfig.json b/apps/control-station/tools/rover-control-preview/tsconfig.json new file mode 100644 index 0000000..f19d0c0 --- /dev/null +++ b/apps/control-station/tools/rover-control-preview/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends":"../../tsconfig.app.json", + "compilerOptions":{"incremental":false,"tsBuildInfoFile":null}, + "include":["*.tsx","*.ts","../../../../packages/rover-control/src/*.ts"] +} diff --git a/tools/rover-scene/export_rover.py b/tools/rover-scene/export_rover.py new file mode 100644 index 0000000..401ef69 --- /dev/null +++ b/tools/rover-scene/export_rover.py @@ -0,0 +1,49 @@ +"""Immutable-source evaluated geometry export, owner-selected complete v020.""" +import bpy,json,hashlib,struct +from pathlib import Path +from mathutils import Vector,Matrix +root=Path.cwd();source=Path(bpy.data.filepath) +donor=root.parent/'NODEDC_ENGINE_INFRA/nodedc-source/public/3dassetnode/model.glb' +with donor.open('rb') as f: + f.read(12);n,t=struct.unpack(' Date: Fri, 25 Sep 2026 16:37:57 +0300 Subject: [PATCH 6/7] fix(core): serialize planning reports outside the control event loop --- src/k1link/web/planning_live_api.py | 25 ++++++++-- tests/test_planning_active_response.py | 69 ++++++++++++++++++++++++++ 2 files changed, 91 insertions(+), 3 deletions(-) create mode 100644 tests/test_planning_active_response.py diff --git a/src/k1link/web/planning_live_api.py b/src/k1link/web/planning_live_api.py index 0682444..510fc85 100644 --- a/src/k1link/web/planning_live_api.py +++ b/src/k1link/web/planning_live_api.py @@ -1,9 +1,11 @@ """Planning-profile preparation and preview; never an acquisition endpoint.""" +import gzip from typing import Literal from uuid import UUID -from fastapi import APIRouter, HTTPException, Query, Response +from fastapi import APIRouter, HTTPException, Query, Request, Response +from fastapi.responses import JSONResponse from pydantic import BaseModel, ConfigDict, Field from starlette.concurrency import run_in_threadpool @@ -47,8 +49,25 @@ def build_planning_live_router(service): raise HTTPException(409, str(exc)) from exc @router.get("/active") - async def active(): - return await call(service.get) + async def active(request: Request): + accepts_gzip = "gzip" in request.headers.get("accept-encoding", "") + + def encoded(): + # A completed report can contain megabytes of numerical evidence. + # Returning its dict sends it through FastAPI's recursive encoder + # and gzip on the event loop, delaying unrelated control requests. + # Keep the exact JSON contract, but finish both operations here. + response = JSONResponse(service.get(), headers={"Cache-Control": "no-store"}) + if accepts_gzip and len(response.body) >= 1024: + return Response( + gzip.compress(response.body, compresslevel=5, mtime=0), + media_type="application/json", + headers={"Content-Encoding": "gzip", "Vary": "Accept-Encoding", + "Cache-Control": "no-store"}, + ) + return response + + return await call(encoded) @router.get("") async def history(): diff --git a/tests/test_planning_active_response.py b/tests/test_planning_active_response.py new file mode 100644 index 0000000..d2d7833 --- /dev/null +++ b/tests/test_planning_active_response.py @@ -0,0 +1,69 @@ +"""Periodic planning reports must not serialize/compress on the ASGI loop.""" +import threading +from types import SimpleNamespace + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from k1link.web import planning_live_api +from k1link.web.response_compression import ResponseCompressionMiddleware + + +@pytest.mark.parametrize("encoding", ["gzip", "identity"]) +def test_active_report_keeps_content_and_encodes_off_loop(monkeypatch, encoding): + document = {"state": "completed", "evidence": [{"label": "Проверка", "x": 1.25}] * 50} + calls = [] + original_json = planning_live_api.JSONResponse + original_compress = planning_live_api.gzip.compress + + class RecordedJSON(original_json): + def render(self, content): + calls.append(("json", threading.get_ident())) + return super().render(content) + + def compress(*args, **kwargs): + calls.append(("gzip", threading.get_ident())) + return original_compress(*args, **kwargs) + + monkeypatch.setattr(planning_live_api, "JSONResponse", RecordedJSON) + monkeypatch.setattr(planning_live_api.gzip, "compress", compress) + app = FastAPI() + app.include_router(planning_live_api.build_planning_live_router(SimpleNamespace(get=lambda: document))) + app.add_middleware(ResponseCompressionMiddleware) + + @app.get("/loop-thread") + async def loop_thread(): + return threading.get_ident() + + with TestClient(app) as client: + loop_id = client.get("/loop-thread").json() + result = client.get("/api/v1/mission-planner/live-tests/active", headers={"Accept-Encoding": encoding}) + assert result.status_code == 200 + assert result.json() == document # Includes HTTP decompression; no double gzip. + assert result.headers["cache-control"] == "no-store" + assert result.headers["content-type"] == "application/json" + assert [name for name, _ in calls] == (["json", "gzip"] if encoding == "gzip" else ["json"]) + assert all(thread != loop_id for _, thread in calls) + if encoding == "gzip": + assert result.headers["content-encoding"] == "gzip" + assert result.headers["vary"] == "Accept-Encoding" + else: + assert "content-encoding" not in result.headers + + +def test_active_report_retains_empty_and_failure_contract(): + service = SimpleNamespace(get=lambda: None) + app = FastAPI() + app.include_router(planning_live_api.build_planning_live_router(service)) + with TestClient(app) as client: + result = client.get("/api/v1/mission-planner/live-tests/active") + assert result.status_code == 200 and result.json() is None + + def fail(): + raise RuntimeError("synthetic unavailable report") + + service.get = fail + result = client.get("/api/v1/mission-planner/live-tests/active") + assert result.status_code == 409 + assert result.json() == {"detail": "synthetic unavailable report"} From 6bbbd5bf7db894e8e2237192a03a931d95214d81 Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Fri, 25 Sep 2026 16:39:19 +0300 Subject: [PATCH 7/7] docs(rover): record calibration control acceptance and operating boundaries --- ...7_PRODUCT_UI_AND_LAB_PRESENTATION_CANON.md | 14 + ...9-23_ROVER_006_VESC_IMPLEMENTATION_PLAN.md | 331 +++ docs/node/17_VESC_INSTALLATION_LEDGER.md | 2244 +++++++++++++++++ docs/node/18_VESC_TOOL_NATIVE_BACKEND.md | 176 ++ docs/node/19_VESC_OPERATOR_CALIBRATION.md | 99 + docs/node/20_VESC_POWER_LIMITS_PLAN.md | 145 ++ docs/node/21_STARTUP_AND_USB_RECOVERY.md | 95 + docs/node/22_BOARD_SETTINGS_SURFACE.md | 37 + docs/node/23_ROVER_CONTROL_PROFILES.md | 595 +++++ docs/node/24_RC_FAILSAFE_ACCEPTANCE.md | 247 ++ .../node/25_OBSERVATION_AND_REMOTE_CONTROL.md | 545 ++++ docs/runbooks/ROVER_006_ENGINEERING_ACCESS.md | 75 + 12 files changed, 4603 insertions(+) create mode 100644 docs/handoff/2026-09-23_ROVER_006_VESC_IMPLEMENTATION_PLAN.md create mode 100644 docs/node/17_VESC_INSTALLATION_LEDGER.md create mode 100644 docs/node/18_VESC_TOOL_NATIVE_BACKEND.md create mode 100644 docs/node/19_VESC_OPERATOR_CALIBRATION.md create mode 100644 docs/node/20_VESC_POWER_LIMITS_PLAN.md create mode 100644 docs/node/21_STARTUP_AND_USB_RECOVERY.md create mode 100644 docs/node/22_BOARD_SETTINGS_SURFACE.md create mode 100644 docs/node/23_ROVER_CONTROL_PROFILES.md create mode 100644 docs/node/24_RC_FAILSAFE_ACCEPTANCE.md create mode 100644 docs/node/25_OBSERVATION_AND_REMOTE_CONTROL.md create mode 100644 docs/runbooks/ROVER_006_ENGINEERING_ACCESS.md diff --git a/docs/17_PRODUCT_UI_AND_LAB_PRESENTATION_CANON.md b/docs/17_PRODUCT_UI_AND_LAB_PRESENTATION_CANON.md index 3294f4e..7913136 100644 --- a/docs/17_PRODUCT_UI_AND_LAB_PRESENTATION_CANON.md +++ b/docs/17_PRODUCT_UI_AND_LAB_PRESENTATION_CANON.md @@ -353,3 +353,17 @@ Before A3 or any subsequent LAB UI change: 7. visually inspect normal and expanded modes at representative viewport sizes. 8. verify every bounded `ENNResult.tsx` uses the v1 summary and result components without raw canonical report markup. + + +## Hardware synchronization feedback — owner requirement, 2026-09-25 + +When an operator action must wait for equipment synchronization, preparation +or completion of a previous operation, show its current phase next to the +action using canonical status components. Do not silently disable the entry +point or present an unexplained frozen control. Keep settings accessible; +gate the actual hardware action on readiness and explain the reason. +A busy phase uses the canonical warning status; confirmed readiness alone +uses success. Missing/stale data or failure must say so, never imply endless +active synchronization. Status follows real lifecycle responses, not a timer +that pretends completion. This is an application-wide interaction requirement; +other equipment workflows need their own lifecycle verification. diff --git a/docs/handoff/2026-09-23_ROVER_006_VESC_IMPLEMENTATION_PLAN.md b/docs/handoff/2026-09-23_ROVER_006_VESC_IMPLEMENTATION_PLAN.md new file mode 100644 index 0000000..1ca152c --- /dev/null +++ b/docs/handoff/2026-09-23_ROVER_006_VESC_IMPLEMENTATION_PLAN.md @@ -0,0 +1,331 @@ +# Rover 006 — VESC: аудит кода и план реализации + +Исторический план, составленный до реализации 23 сентября 2026. Текущий статус +см. `../node/17_VESC_INSTALLATION_LEDGER.md` и MISSIONCOR-84. + +Результат первоначального аудита — исследование, свежий read-only +baseline и план. Плагин ещё не реализован; конфиги контроллеров не прочитаны, +моторы не запускались. Исторические команды и планы приложенного документа +рассматривались как источники, а не как поручения на исполнение. + +## 1. Целевой пользовательский результат + +После подключения контроллеров к USB бортового Mac Mini они появляются в +«Устройствах» Node и в «Парк → Rover 006 → Устройства» основного Core. +В карточке выбранного контроллера есть вход **«VESC Tool»**. Через него доступны +настройка, диагностика, калибровка и остальные применимые функции Tool. +Исполнение принадлежит борту; обе UI используют одну реализацию предметного +интерфейса и одни операции. Полнота Tool остаётся целевым требованием, +первый read-only выпуск является отдельным промежуточным результатом. + +Ближайшая физическая задача — разобраться с потерей оборотов одного мотора. +Слова владельца о левом канале остаются предположением до сопоставления. +Предыдущие наблюдения: плавный старт возможен, резкий может давать короткий +рывок и остановку; конфигурация, датчики и управление — приоритетная ветка +диагностики. Причина пока не измерена. + +## 2. Что проверено сейчас + +| Объект | Факт 23.09 | Ограничение | +| --- | --- | --- | +| Core | Канонический localhost:8000 отвечает; Rover 006 paired/online | Не означает доступность каждого устройства | +| SSH | Вход `dcsudo` с существующим персональным ключом работает | Старая запись `nodedc-edge` использовала `ndcsudo`; sudo не проверялся и не нужен для чтения | +| Борт | Ubuntu 24.04.4, kernel 7.0.0-31-generic, i7-3615QM, 4 ядра/8 потоков | CPU поддерживает AVX, но AVX2 в полученном наборе флагов нет | +| Память/диск | Около 8 GB RAM, около 6.3 GiB available; swap не занят; root 457 GiB, свободно 381 GiB | Это короткий idle-срез, не совместная нагрузочная приёмка | +| Установка | Node 0.8.21-3, K1 0.1.14, X4 0.1.3-9 | Старый Node README с 0.6.11 не является installed baseline | +| Службы | Node, K1, X4 broker, D455, monitor, PostgreSQL active/running, NRestarts=0 в проверенном наборе | Активный драйвер не доказывает подключение камеры | +| База | PostgreSQL 16, cluster `ndcmonitor` online; Timescale 2.29.2 установлен | База системного мониторинга, не готовый motor recorder | +| Реплика мониторинга | available/fresh=true, storage=ready, backlog=0; sample interval 1 s | Срез около 11:02 UTC; полевая задержка управления не измерена | +| USB контроллеров | Два кандидата `0483:5740`, ChibiOS/RT Virtual COM Port, cdc_acm, два ttyACM | USB-дескриптор ещё не доказательство HW/FW VESC | +| Identity | У двух кандидатов одинаковый USB serial; одна конфликтующая by-id ссылка | Нельзя использовать USB serial, by-id, tty или порядок включения как постоянную личность | +| Права | tty принадлежат root:dialout, 0660; dcsudo не имеет read/write | Права будущего runtime поставляются профилем модели | +| Конкурирующий опрос | ModemManager active; кандидаты имеют ID_MM_CANDIDATE=1 | Не доказано, что он уже посылал команды; нужен адресный udev ignore при подготовке модели | +| Камеры | D455/X4 в свежем paired inventory offline | Сохранность их потоков под VESC-нагрузкой сейчас проверить нельзя | + +Портов serial не открывали; firmware/UUID, моторные и application configs, +CAN/RC topology и физические стороны остаются неизвестными. VESC Tool не найден +через проверенное имя `vesc_tool` в PATH; это не полный поиск всех установок. + +Подробный путь доступа: [ROVER_006_ENGINEERING_ACCESS.md](../runbooks/ROVER_006_ENGINEERING_ACCESS.md). +Raw fleet/monitor snapshots и приватный SSH-профиль находятся вне Git в +операторском `outputs/rover-006-vesc-context-20260923`. + +## 3. Источники и границы исследования + +Прочитаны основной актуальный срез и VESC-handoff приложенного документа, +профильные Node/SDK/UI материалы и релевантная история приложений. Большой +архив планировщика/Rerun использован для контекста владельцев; повторной +квалификации всех старых экспериментов не выполнялось. + +Через прямой Ops MCP получены живые проекты/контекст/карточки, в том числе +MISSIONCOR-84, 76, 77, 50, 5, 2, и история комментариев 76/77/84; изучен +архив ROBOT2B-5. Профильная карта — +[MISSIONCOR-84](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-84), Node — +[MISSIONCOR-76](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-76). +Поиск GPIO в других четырёх доступных Ops-проектах совпадений не вернул; +среди полученных Mission Core/ROBOT2B карточек подтверждённой схемы GPIO +для этого привода не найдено. Это пробел найденных источников, не утверждение +об отсутствии такой схемы вообще. USB достаточно для первого этапа; +GPIO/UART/RC/аварийная цепь требуют конкретной аппаратной схемы до motor tests. + +Основная кодовая база: `NODEDC_MISSION_CORE_m5_observatory`, HEAD `2e5d525`. +Соседние base/node checkout остаются detached `76dc9f1`. В main есть чужая +незавершённая работа SIM/AI polygon и service recovery. Для реализации нужен +отдельный checkout от проверенного commit; не включать эти изменения в пакет. + +Design Guideline прочитан по реестрам и документации, текущий HEAD +`8dd9190573d6616024ef01b9b34bf90b72960f44`, рабочее дерево чистое в проверке. +Node build_linux_source.py закреплён на `8c53f73...` и отклоняет другой HEAD. +Перед выпуском выбрать проверенную ревизию DG и квалифицировать её в сборке; +не снимать проверку и не брать случайные локальные dist. + +## 4. Реальные точки расширения + +| Код | Что уже есть | Что нужно VESC | +| --- | --- | --- | +| `apps/node-agent/internal/node/sensor_models.go` | Registry, model actions, отдельные IPC sockets, USB discovery, provisional identity при дублях | Новый model profile; разделение attachment и protocol UUID; discovery двух плат с одинаковым USB serial | +| `sensors.go` | Durable fsync journal, dedup, action allowlist, deadline, unknown после restart, local API | Точные VESC actions и параметры; проверка session непосредственно в адаптере; bounded результаты; не прятать моторные функции за camera `start`/`option` | +| `sensor_preparation.go` | Профиль на модель и проверка отдельного экземпляра, shared preparation job | Device-neutral подписи и безопасная identity verification. Нельзя трактовать `verify` как motor detection | +| `sensor_events.go` | udev events, coalescing, полные SSE snapshots | Reconnect создаёт новый session; stale GUI не получает authority над новым контроллером | +| `pairing_transport.go` | mTLS heartbeat, commands/results/acks; периодический tick 5 s и пробуждение от событий | Существующий путь для service operations; отдельная доставка частой telemetry и будущего realtime control | +| `src/k1link/fleet/sensors.py` | Проверки pairing/freshness/session, очередь, receipts, ограниченные payloads | Добавить явные actions; не превращать whitelist в arbitrary protocol passthrough | +| `packages/plugin-sdk/.../v0alpha2` | Identity/session, safety/idempotency policies, commands/events | Использовать существующие contracts; motor authority/lease и конфиг revision оформить узким дополнением | +| `packages/sensor-ui` | Общий SensorWorkspace, transport, Detail contribution, status/preparation | VESC Detail в том же slot; camera-specific поля/подписи нормализовать ровно там, где нужно | +| `apps/node-agent/ui/src/NodeSensors.tsx` | Локальная композиция общих plugins | Зарегистрировать ту же VESC contribution | +| `apps/control-station/src/core/fleet/sensorTransport.ts` и composition | Remote adapter общего UI | Повторно использовать; новая предметная логика в plugin, не App.tsx | +| `plugins/insta360-x4/runtime/operations.py` | fsync receipt до физического действия, отсутствие replay, readback settings | Проверенный пример lifecycle, но motor safety проектируется отдельно | +| Node monitor/storage и fleet monitor replica | 1 s host samples → Timescale → bounded Core replica | Не использовать этот период как осциллограф или контур stop; моторная сессия пишет данные на борту с собственной частотой | + +В этих действующих реестрах и каталогах VESC runtime отсутствует. Архитектурные +документы старого этапа местами описывают gRPC как целевой вариант; текущая +проверенная реализация использует JSON HTTP/Unix sockets и HTTPS heartbeat. + +## 5. Интеграция VESC Tool + +Для аудита закреплён официальный upstream: +[`dc53c658cbb89a947246034f7a00149cf79abdfc`](https://github.com/vedderb/vesc_tool/tree/dc53c658cbb89a947246034f7a00149cf79abdfc). +Сохранены 17 исходных файлов с SHA-256. Этот snapshot объявляет **7.01, +test version 1**; это исследовательская точка, не автоматически выбранный +production release для неизвестной firmware наших плат. + +Исходники показывают: + +- `main.cpp`: CLI умеет конкретные чтения/записи config, выбор port/CAN, + offscreen и TCP. Это не готовый полный web API. +- `vescinterface.cpp`: autoconnect обходит serial ports и заканчивает поиск + на первом ответе. Для инвентаризации двух плат нужен наш ограниченный поиск. +- `commands.cpp`/`datatypes.h`: FW response содержит version, HW name, UUID + и дополнительные признаки; набор полей зависит от ответа. HW name нельзя + автоматически считать точной коммерческой моделью платы. +- `configparams.cpp`/`utility.cpp`: schema выбирается по firmware, сериализация + использует signature. Парсить конфиг произвольной новой firmware старой + схемой и затем сохранять его нельзя. +- `packet.cpp`: length/framing/CRC и размер пакета ограничены. Нужны tests на + fragmented/combined/corrupt packets и truncation полей ответа. +- `tcpserversimple.h`: default bind — все адреса. Штатный TCP server нельзя + просто включить как удалённый продуктовый интерфейс. +- `setupwizardmotor.cpp`: wizard содержит реальные записи конфигурации по + ходу шагов. Его запуск/отмена не являются только локальным редактированием. + +### Сравнение реализаций + +| Вариант | Польза | Цена/ограничение | +| --- | --- | --- | +| Официальный Qt Tool + локальный launcher и трансляция его окна в Core | Самый прямой путь к исходному GUI и широкому набору функций | Новый remote-app runtime, конкуренция ввода двух UI, Qt UI вне DG, передача port ownership; интерфейс сам умеет опасные команды | +| Собственный минимальный protocol adapter | Быстрое read-only discovery/telemetry | Поддержка всех конфигов/wizards потребует дублирования большого firmware-specific слоя | +| Бортовой service plugin с переиспользованием закреплённого upstream protocol/config engine + общий React UI | Наш UI, один owner, применимые функции Tool расширяются без второй модели состояния | Требуется проверить headless сборку/зависимости и адаптировать операции; полного готового API нет | + +**Рекомендация:** третий вариант как целевая архитектура. Первый технический +spike проверяет сборку и выделение engine без desktop UI; fallback на +ограниченный собственный reader допустим для первого чтения, но не отменяет +требование функционального паритета. Оригинальный Tool полезен как инструмент +сравнения с эксклюзивной передачей владения портом. В текущем плане нельзя +объявить «все функции готовы», открыв только несколько полей или удалённое окно. + +Нужно отдельно различать паритет функций и показ неизменённого Qt GUI. Здесь +принято рабочее предположение из запроса про наш интерфейс и DG: единая +предметная UI внутри Mission Core. Если нужен именно исходный Qt GUI, меняется +способ его доставки, а не требование единственного hardware owner. + +Upstream содержит GPL-3.0-or-later notices и отдельные правила бренда. При +упаковке выбранного кода/бинарника проверить состав, notices, исходники и +название распространяемого продукта. Этот аудит не делает юридического вывода +о допустимости конкретного способа распространения. + +## 6. Runtime и модель данных + +```mermaid +flowchart TD + L[Node UI: Устройства → VESC Tool] --> N[Node API и журнал операций] + R[Core: Парк → Rover 006 → VESC Tool] --> C[Core fleet API] + C -->|Существующее pairing и mTLS| N + N --> V[VESC plugin на борту: owner и арбитраж] + V --> U[USB attachment → protocol UUID → controller/channel] + U --> M[Мотор и подтверждённая роль] + V --> D[Конфиги, telemetry и diagnostic session на борту] + D --> C +``` + +Предлагаемый bounded каталог `plugins/vesc/`: `runtime/`, `frontend/`, +`profiles/`, `packaging/`, `tests/`, upstream lock/notice manifest. +Названия здесь — план, каталог ещё не создан. + +Один service владеет serial. Открывает только подтверждённые candidates; +проверяет отсутствие конкурирующего владельца и сохраняет связь порта с +attachment generation. До FW query attachment имеет provisional identity. +После ответа UUID связывается со стабильным controller instance. Смена порта +не меняет подтверждённый UUID; USB/CAN aliases одной платы не создают двойник. +Неоднозначный protocol UUID оставляет устройство без write authority. + +Особенно важно для текущих двух плат: общий Node discovery уже считает +duplicate USB serial неинициализируемым. Нельзя просто добавить VID/PID: +обе кнопки подготовки окажутся заблокированы. Нужен отдельный безопасный путь +подготовки модели/identity query для provisional attachments; он разрешает +только ограниченное чтение личности. Общую защиту камер не ослаблять. + +Role Left/Right и metadata мотора хранятся отдельно от UUID. Отключение владельцем +одного USB при обесточенном приводе может сопоставить плату с кабелем; это само +по себе не доказывает, какой мотор подключён к её силовым выходам. Сопоставление +по проводке/маркировке предпочтительно; активный тест — отдельная операция. + +Конфиг имеет исходный blob, decoded fields, firmware/schema signature, hash, +revision и timestamp. Запись использует ожидаемую revision и свежий session, +сохраняет before/after, выполняет readback. Потеря ACK даёт unknown и +reconciliation, а не слепой retry. + +Калибровка — бортовая операция с этапами, результатом и явно проверенной +семантикой отмены. HTTP timeout не доказывает прекращение электрического +измерения. Motor control дополнительно требует одного владельца управления, +локального watchdog, известных timeout/stop свойств firmware и арбитража RC. +Точные токи/обороты/частота не выбираются до hardware baseline. + +## 7. Полнота функций и порядок включения + +| Группа Tool | Предметный результат | Этап и условие | +| --- | --- | --- | +| Discovery, FW/HW/UUID, USB/CAN topology | Независимые экземпляры и совместимость | Первый read-only slice | +| Live values, faults, decoded PPM/ADC/Chuk input | Напряжение, токи, ERPM, температура, вход, timeout/kill flags по поддержке FW | Первый read-only slice; измерить реальную частоту | +| Motor/app/custom configs, backup/export, сравнение | Полный применимый набор параметров по schema, неизменяемый backup | Read-only до первой записи | +| Import, defaults, apply/restore | Предпросмотр diff и проверенный readback | После identity, backup и compatibility; restore/defaults — записи | +| FOC/BLDC/DC setup, R/L/flux, Hall/encoder | Калибровочный workflow с результатом | Активный допуск на конкретный мотор; один шаг может подавать ток | +| App/input setup, direction, limits | Настройка RC/ADC/UART/CAN по реальной схеме | Сначала прочитать существующий input/timeout/RC ownership | +| Duty/current/brake/RPM/position, motor tests | Управляемый стендовый опыт | Быстрый бортовой контур; не heartbeat 5 s | +| Samples, logging, plotting | Синхронная диагностическая запись реакции | Bounded board recorder; сводки через Core | +| Firmware/bootloader/recovery | Exact-HW image, версия, progress и recovery | Отдельная поздняя ветка; не «обновить на всякий случай» | +| CAN forwarding/multi-controller setup | Явный target и topology | Никаких автоматических detect-all/broadcast writes | +| Terminal, Lisp/QML/packages, custom application | Сервисные функции выбранного устройства | Отдельный maintenance scope; чтение кода и его выполнение различаются | +| BMS, IMU, power switch, NRF/GPD и расширения | Применимые к конкретному hardware возможности | Capability-driven; отсутствие аппаратуры не маскировать как готовую функцию | + +Перед реализацией широкой сервисной поверхности матрица уточняется по страницам +выбранного релиза Tool и реальной HW/FW. Для каждого пункта фиксируются: +supported/unsupported/not-implemented, операция, side effects, schema, +readback, cancel/recovery и аппаратная приёмка. Старые настройки firmware +не переименовываются в поддержанные только ради единого красивого UI. + +## 8. UI brief и Design Guideline + +Задача оператора: выбрать конкретный контроллер, понять состояние, настроить +его и проверить итог. Первичная сущность — выбранный controller/channel; +мотор и роль — связанный контекст. Вход из существующего списка устройств. + +Выбран **plugin Detail slot** общего `SensorWorkspace`, с текстовой кнопкой +«VESC Tool» в карточке. Внутри — обзор/диагностика, параметры и сервисные +операции, основанные на capabilities. Нового root или LAB не требуется. +Длинный motor workflow остаётся полноценным detail-view; компактный editor +может использовать существующий `FeatureSettingsWindow`. + +Альтернатива отдельного глобального workspace создаёт второй вход к тем же +устройствам и отрывает инструмент от адресной identity. Модальное окно на весь +долгий workflow неудобно для контроля результата и закрытия/recovery. +Показ исходного Qt GUI — иной вариант интеграции, описанный выше. + +Уже есть `ResourceRow/List`, `Button/IconButton`, `StatusBadge`, +`SettingsCard`, `Window`, `FeatureSettingsWindow`, `SegmentedControl`, +`TextField`, `Select`, `RangeControl`, `ConfirmationModal`, `ProgressBar`, +`LoadingRegion`, `ToastStack`. Подходящие существующие icons: settings, +activity, network, download, upload, refresh, alert, eye, play/stop. +Отдельной motor-icon в просмотренном registry нет; новая не нужна для первого +slice. Domain graph/plot остаётся кодом плагина с этими controls. + +`RangeControl.min/max` ограничивает drag, но не всякий ручной ввод: для токов +и других bounded величин нужны `exactValueBounds` и серверная валидация. +Safety check нельзя делегировать только форме. + +Состояния: поиск; не обнаружено; найден кандидат; требуется подготовка; +чтение личности; unsupported/ambiguous; готов к чтению; fault; занят; +операция выполняется; outcome unknown; связь потеряна. Свежесть контроллера +проверяется отдельно от online борта. Браузер не принимает unknown за failed +и не предлагает повтор опасного действия как универсальное восстановление. + +Это новое доменное содержимое существующей принятой list/detail композиции. +Изменения global navigation и новые общие визуальные сущности не предлагаются. + +## 9. Упаковка с первого бортового опыта + +Versioned пакет/profile устанавливает бинарник, pinned зависимости, отдельного +непривилегированного service user, Unix socket для Node, systemd limits, +узкие udev rules доступа и ModemManager ignore для квалифицированного профиля. +Не добавлять весь Node или пользователя в общий dialout, не делать chmod 666, +не отключать ModemManager глобально. Runtime не должен читать произвольные tty. + +Node сохраняет `PrivateDevices=yes`; аппаратные права принадлежат отдельному +адаптеру. Verify после установки означает protocol identity/read capability, +а не автокалибровку. Package qualification: повторная установка, конфликт +портов, rollback бинарника при сохранении data/backup, холодный старт и чистая +Ubuntu. Компилятор/Qt dev packages не становятся скрытым требованием runtime. + +## 10. Реализация по проверяемым результатам + +1. **Контракт и build spike.** Изолированный checkout, выбранный upstream + release/commit, DG pin, headless engine build, firmware schema closure; + synthetic packets, IPC/action contracts. Никакого доступа к моторам. +2. **Discovery на борту и две UI.** Поставляемый profile, два кандидата с + одинаковым USB serial, FW/UUID handshake, session transitions, одна + VESC contribution в Node/Core. Итог — оба контроллера видны независимо. +3. **Read-only сервисная поверхность.** Версии/capabilities, telemetry, + faults/input, motor/app/custom backups и semantic diff. Это первый полезный + завершённый выпуск; статусы неподдержанной FW честные. +4. **Диагностика проблемного канала.** Сначала сравнить конфиги, затем на + подготовленном стенде записать плавный/резкий старт по конкретному сценарию. + Сопоставить command/input, ERPM, currents, voltage, fault и timeout. Выбрать + измеренную гипотезу; рабочий конфиг не копировать целиком. +5. **Адресная настройка/калибровка.** Backup, effect preview, необходимые + ограничения hardware, исключение конкурирующего управления, конкретная + операция, cancel/recovery, readback и повтор исходного теста. +6. **Остальная матрица Tool.** Дополнять функции вместе с соответствующей + упаковкой и аппаратными критериями; FW/terminal/scripts выделены по эффекту. + +До физического теста требуются аппаратные факты о моторах/датчиках/питании, +проводке RC/CAN и доступном аварийном останове. Выбор «левый/правый» владельцем +выполняется позже; он не блокирует initial inventory. + +## 11. Приёмка и тесты + +- Parser: CRC, partial/multiple packets, неверные длины/концы, timeout, + несовместимая FW/config signature, отсутствующие optional fields. +- Identity: одинаковые USB serial, пустой/дублированный UUID, два независимых + контроллера, unplug/replug/reorder, замена платы, USB/CAN duplicate alias. +- Operations: общий local/remote journal, stale session, conflict/lease, + crash до/после dispatch, unknown outcome, readback mismatch, отсутствие + повторного исполнения после reconnect и reboot. +- Packaging: clean Ubuntu, narrow permissions, targeted ModemManager rule, + занятый port, idempotency/rollback, pinned binaries/firmware schemas/DG. +- UI: обе поверхности на одном экземпляре, одинаковые capabilities/results, + empty/offline/fault/unknown, сохранение draft, keyboard/Escape/expand, без + новых local controls или моторной логики в App.tsx. +- Hardware: версии и backup обеих плат; измеренный fault/поведение; + отдельная проверка stop/timeout на стенде до ручного управления. +- Совместная работа: вернуть реальные D455/X4/K1 в согласованный сценарий и + измерить ресурсы/USB/latency вместе с VESC. Их текущий offline не считается + успешной regression-проверкой. + +Проверки кода выполнять последовательно с учётом памяти операторского Mac. +Текущая задача не меняла runtime-код, поэтому тесты/сборки приложения не +запускались. HTTP/SSH/API чтения и анализ исходников не являются калибровкой. + +## 12. Следующее конкретное действие + +Реализовать и упаковать **двухэкземплярное VESC discovery + read-only identity, +config backup и общую detail-поверхность**. Первый бортовой запуск обязан +учесть уже обнаруженный duplicate USB serial. Это снимает неизвестность +HW/FW и даёт основание выбирать реальную настройку проблемного мотора. diff --git a/docs/node/17_VESC_INSTALLATION_LEDGER.md b/docs/node/17_VESC_INSTALLATION_LEDGER.md new file mode 100644 index 0000000..2324229 --- /dev/null +++ b/docs/node/17_VESC_INSTALLATION_LEDGER.md @@ -0,0 +1,2244 @@ +# Rover 006 — VESC integration ledger + +This ledger records actual execution separately from pending qualification. +Private evidence is in the operator's `outputs/rover-006-vesc-context-20260923` +directory. Raw configurations, device UUIDs, SSH material and photographs are +not repository fixtures. The current Ops record is MISSIONCOR-84. + +2026-09-25: the owner-requested consolidated configuration passport is now +[MISSIONCOR-85 — Гусеничный ровер Node 006](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-85). +It contains current hardware, both full decoded controller configurations, +radio settings, experiment outcomes and outstanding checkers. MISSIONCOR-84 +remains the historical integration task. Direct MCP readback verified all 35 +blocks; no controller changes or powered experiments were performed to publish +the passport. Owner deferred the one-stick/Tank–Arcade work and retained the +existing two-stick radio control. + +## 2026-09-23 — first deployed reader + +Node **0.8.22-1**, VESC plugin **0.1.0**, DG revision +`8dd9190573d6616024ef01b9b34bf90b72960f44` installed on Ubuntu 24.04.4 amd64. +The owner entered sudo in the Mini's local installer window. SSH authentication +already worked as `dcsudo`; no SSH/VPN/sudo-policy repair was needed. + +| Artifact | SHA-256 | +| --- | --- | +| Node package | `64e121fd3d12e94675def1284c5977a4e63a3d3e3ebab888b6b8ccab040136b7` | +| Source artifact b6dbe696a8c3182281e16553 | `bfed06700a1b8059db7c840851fab5a224e6eb0c6cdf8f4b68d000086964b184` | +| Owner installer 3955580c7d0b29c90c151ea9 | `fd9ca5eb473fcbf5618cecf76adff95b4f90d65a2a4150b5c0c432810e64d9e3` | + +Install completed 11:55:10 UTC; model preparation completed about 11:56 UTC. +Node, K1, RealSense and monitor services remained active; X4 package remained +0.1.3-9. This does not qualify live camera operation: camera inventory was offline. + +The shipped preparation profile creates a dedicated service identity and exact +USB rule, mode 0660, with a device-specific ModemManager exclusion. It never +adds the desktop user to dialout or disables ModemManager globally. The service +has no network access or Linux capabilities. Serial ownership uses flock, +TIOCEXCL and USB attachment-generation checks. No raw TCP gateway is exposed. + +Both controllers reported hardware 75_300_R2 / firmware 5.02. Distinct protocol +UUIDs disambiguated duplicated USB serials. Core successfully requested live +telemetry and durable raw motor/application backups through paired Node. +At rest, both reported about 50 V, fault 0 and ERPM 0. Motor temperature +−72.9°C on both is implausible and is not proof of a particular broken contact. + +Exact official 5.02 schemas matched both signatures and consumed every byte. +Both controllers use FOC Hall Sensors. The 151 serialized motor parameters +differ only in direction inversion. Existing current limits are motor ±60 A +and battery ±55 A; these are readback values, not verified motor nameplate limits. + +The owner unplugged the presumed left USB; USB1-2 / CAN74 disappeared and +returned, while USB1-3 / CAN111 stayed connected. **Rotation has not yet +confirmed physical sides.** The owner photograph identifies FlySky FS-iA6B; +CH3 is reported as left candidate and CH2 right candidate. The receiver stays +connected, transmitter off. One Hall connector pin is broken; its exact +function is unknown. The rig is raised, track removed, and the owner authorized +bounded motor tests through the product interface. + +## Native VESC Tool engineering build + +Official stable Tool 7.00 commit `01d5f10901116c311e3fb84d5a1541f663d3ce20`; +source archive SHA-256 +`4565ecec4e41e094bcc43127a51970e810aa9080a9d7c025af64632bfd4c0189`. +Versioned `plugins/vesc/packaging/tool_build.py` builds as an unprivileged user +under MemoryMax=3G, CPUQuota=150%, TasksMax=256. Signed Ubuntu packages are +downloaded/extracted into private staging, never installed system-wide. +Already-installed OpenGL runtime files used by the linker have recorded hashes. + +Early attempts failed on stale APT indexes, then private include/library paths. +Profile d1797bf1152f59ee14012ed5 resumed the recorded compile staging and linked +successfully; `--version` reported `7.00-0+`. Binary SHA-256: +`d68bd760918dd5c1f11f5133f6c236749c7004391d46298953341c0b67e40c40`. +This is an engineering build, not clean-host runtime dependency qualification. +It has not opened either controller. Native Tool serial handoff and calibration +integration remain pending; a Detail button is not evidence of full Tool parity. + +## Node 0.8.23-1 / plugin 0.2.0 — pending board installation + +Source artifact f1a42096c12295d29c9a736d SHA-256: +`995297d2f1070e0c13a5b11fd6da91c022aff0c5058c6bf5546c5b4e78b138cf`. +It is building and undergoing synthetic qualification on the Mini. No motor +command has been sent at this ledger entry. First motor experiment must append +its operation receipt, outcome, operator observation and before/after evidence. + +Changes: + +- Private immutable SQLite archive in both Node plugin and Core; preserve every + version, replay-safe replication scoped by pairing, ACK only after durable + Core storage. Existing backup files migrate on startup. Offline retrieval is + independent of transient operation receipts. No restore action is exposed. +- Shared history UI lists/paginates versions and requests JSON downloads. + Core displays an original backup; API content equals the original receipt. + IAB's download event did not fire, so browser file delivery is not yet accepted. +- A fixed raised-rig pulse selects one UUID/session, requires both peers, + exact supported firmware/config schema, one second neutral PPM, telemetry + bounds and durable backups. Commanded current is 2 A for at most 1.5 seconds. + No firmware/config write or variable current API is introduced. +- Per-controller volatile app-output leases expire after 250 ms. CAN forwarding + is false; peer current is zero. Expiry restores the existing PPM handling. + PPM pulses reset the firmware global timeout even while output is paused, + so a USB heartbeat timeout alone would be insufficient. Exact firmware source + audited: `vedderb/bldc` commit `3f670137e27e6e383fa79c50cc6b1fa85aab1554`. +- Non-neutral RC input latches further test requests until explicit release + after neutral. This test-session guard is not a continuous production RC / + remote / autonomous arbiter. Neutral PPM cannot prove radio-link availability. + +Validation before installation: 17 synthetic VESC tests including RC takeover, +partial lease failure and no physical replay; 37 fleet tests; Go Node package +and scoped archive ACK test; Core typecheck, 905 unit tests and production build. +The canonical Core 8000 was restarted through its existing managed helper and +health accepted. Its panel uses DG components; real pulse remains disabled until +the Node capability arrives. Linux qualification and physical failsafe acceptance +must be recorded separately. + +Rollback uses the prior qualified Node owner artifact after stopping any active +test. Configuration archives and original raw backup files remain on disk. +Do not replay an uncertain motor operation; inspect actual hardware state first. + + +### Final qualification after queued-stop correction + +The initial qualified 0.8.23 candidate f1a42096c12295d29c9a736d was not +installed. Review found that a Stop arriving before a queued pulse started +could be cleared by that start. The final runtime records cancellation time +and clears the event only for a newer request under the same lock; an added +fault-injection test covers the ordering. All 18 VESC tests passed on Ubuntu. + +Final source ID: `25ccd797bc91fceab43ba3db`, SHA-256 +`60fa8a151395e8e50617beec33752111152b3acb28cd2c5cfad5b6bc454fa75c`. +Final Node0.8.23-1 package: 168446728 bytes, SHA-256 +`b7be1efd9b404e3b54f43e73fab38d5e4207a1f50a80ab28b1b842284d90badf`. +Qualified result archive SHA-256 +`274aa43a64c781ce7fcc010dc332907f9b4679b0427f71b9cd27b68449fb2eea`. +DG, Node UI, Go, VESC synthetic tests and binary build all completed. +Installation and real motor execution are still pending this entry. + +Final owner installer `3b474f082a4c5af545dffda2`, SHA-256 +`e5f296bba8edcb0b6d681442214f326333d513cb5c0a215fa156669bf4ae0424`, +was opened in the Mini local session after APT plan showed exactly one Node +upgrade, zero new packages and zero removals. No password is collected by SSH +or chat. The older candidate e196a44ce00c150e5dc37311 must not be installed. + + +## 2026-09-23 — 0.8.23-1 installed, stale bytecode rejected by Node + +Owner installer `3b474f082a4c5af545dffda2` completed at 13:02:48 UTC +(run `6189de4765744a259b5a06776f6ee98f`). Package version and services updated, +but the VESC runtime imported version 0.1.0 from old timestamp-based bytecode +although its installed source declared 0.2.0. Deterministic package mtimes and +same-size source edits allowed Python to accept the old cache; `-B` disables +cache writes, not reads. Node's exact plugin-version check correctly rejected +that inventory. No test-current command was sent. This was not accepted as a +working hardware upgrade. Private before/after evidence remains outside Git. + +The next package, Node 0.8.24-1 / VESC 0.2.1, owns removal of generated +`__pycache__` directories below its fixed installed payload path in postinst, +before preparation/service start. Root preparation also disables new bytecode +writes. No ad-hoc root cleanup was performed on the board. The regression test +reproduces the old cache acceptance, clears it twice, verifies new imports and +preserves an unrelated evidence file. Backups live outside the payload. + +## 2026-09-23 — variable controller count and per-controller identification + +Owner clarified that each board can have 1, 6, 10 or more motors/controllers. +Discovery now admits up to 128 USB candidates per board, retaining UUID-based +identity and independent attachment sessions. The same device detail on Node +and Core offers a 2 A identification pulse with 1.5/5/10 second limits. The +existing editable device name supports Left 1, Left 2, Right 3 or arbitrary +owner labels; no fixed left/right enum or second motor registry was added. + +The request includes all live controller sessions on that board. Before any +current, the service verifies the exact attachment set, identity, configuration, +CAN peers and neutral receiver input, archiving both configurations of every +controller. It checks receiver channels and target telemetry while controlling +each app-output lease separately. Non-selected controllers receive zero current. +Slow cycles, hotplug, unmanaged CAN peers and ambiguous sessions abort the test. +The operation's 60-second deadline includes preflight, and the 1.5/5/10-second +current limit starts on the board. These controls are for an unloaded raised +rig, not general vehicle driving or a completed continuous RC arbiter. + +Local synthetic validation: 24 VESC tests passed, including 1/6/10 controllers, +target-only current, durable backups, hotplug, unmanaged CAN peer on a second +controller, slow cycles, stop-before-start, RC latch and bytecode upgrade. +Physical ten-controller capacity and motor calibration remain unverified. + + +## 2026-09-23 — 0.8.24-1 hardware inventory accepted; CAN preflight timed out + +Qualified source `0492e295535837afdf9ddcca` completed at 13:21:57 UTC in +224.35 s, peak memory 2,596,036,608 bytes. Package SHA-256: +`c254ad7dfaea236ae6d65186f00055a745169a11799063df2bd8cb44d53c779a`. +Owner release `6a2be7c817798c981fa6b1c8` installed successfully at +13:24:46 UTC (run `e766b308543e4312856f13c7077c83ad`). VESC service is active +with zero restarts and a read-only isolated import confirms VERSION 0.2.1. +Node/Core again expose exactly two verified UUID controllers, not the two +provisional USB rows plus one prior offline UUID seen during the failed upgrade. +The old row was the same left-candidate controller, not a third physical unit. +No identity records or backups were deleted to hide it. + +Core passed architecture checks, typecheck, 906 unit tests and production build; +its managed restart passed health acceptance. In-app UI shows the two matching +controllers and the 1.5/5/10 second selector; Escape closes the selector. +A single 1.5-second test was requested through the Core UI at 13:26:35 UTC, +operation `op_8d8f5ee7ae0c4510b584839350b41b3d`. Preflight archived both +controllers at 13:26:40, then returned an error after the first 4-second CAN +query. The motor loop was never entered: no app-output lease or current +command was sent. Both configurations remain unchanged. Core archive API +returns the original and new version for each controller. Browser file-save +handoff remains unverified; backend version retrieval is accepted. + +Firmware CAN ping waits up to 5 ms for transmission and 10 ms for a response +per address, plus scheduler/mutex delay; 255 addresses can exceed our former +4-second cap. Node 0.8.24-2 extends only that read deadline to 8 seconds and +adds `vesc.can.read` for direct, bounded topology inspection without any motor +command. Failure is now reported specifically as CAN preflight without torque. +Synthetic validation: 26 tests passed. Source `292106d05d5e1ff5ecb866f9` is +being qualified; motor watchdog/lease and current limits remain unchanged. +Separate `vesc.input.read` through Core returned level0/pulse0 on both channels. +Physical side identification and calibration have not yet been achieved. + + +## 2026-09-23 — 0.8.24-2 installed; first real identification pulse + +Source `292106d05d5e1ff5ecb866f9` qualified at 13:34:47 UTC in 224.19 s. +Package SHA-256 `9f54423216163917c52c6b627205dbe3a24b69f6d4f1d606aa59e489d0e02c4d`. +Owner release `7b4545754e703e7a64ee88bb` installed at 13:37:05 UTC, +run `4dde4c0992164fafb1828a91c402a8b7`. Node and device services were +active with zero restarts. Both CAN read operations completed in approximately +4.26 seconds with no responding peer IDs. No firmware/configuration was written. + +The owner had the rig raised, a track removed and the transmitter off with its +receiver connected. Core UI operation `op_dded265e82b54e3181a194a67868d6e6` +sent a bounded 2 A / 1.5 s pulse to the selected left-candidate controller. +Both configurations were archived first. Twenty-one samples showed peak 2.23 A +and 442 ERPM, with only three net versus 33 absolute tachometer steps: jitter +was observed, not demonstrated sustained rotation. The owner heard rustling +and could not identify which motor moved. Physical side remains unconfirmed. +Both zero-current commands were sent and subsequent telemetry confirmed +current release; both controllers reported fault zero. The old duration-boundary +receipt label incorrectly said stopped; the next revision separates duration +expiry from user Stop. Private raw receipts and identities remain outside Git. + +## 2026-09-23 — 0.8.25-1 candidate: test fields and user drive assignment + +Owner requested numeric current/time fields and eventually 30 A / 30 s. That +higher-power run has not been performed: manufacturer, motor and battery/BMS +ratings are unknown, and the initial pulse did not show steady rotation. +The next identification increment admits 0.5–5 A / 0.5–10 s, with board-side +validation, electrical-speed coasting above 2 A and all prior preflight guards. +These are software test bounds, not claimed hardware maximum ratings. + +Owner clarified exactly two current profiles: 1×1 (left/right) and 2×2 (left +front/left rear/right front/right rear). A shared existing VESC detail card +assigns UUID controllers to those positions. Assignment is board-owned metadata, +uses revision conflict checks, persists across service restart and never sends +motor commands. Occupied positions cannot be overwritten; shrinking requires +explicitly removing rear assignments. No real controller has yet been assigned. +This entry records implementation intent; package/UI/hardware acceptance below +must be recorded separately after execution. + +0.8.25-1 source `edfc5911070cab9c863cddcf` completed all 15 Linux qualification +stages at 14:00:34 UTC in 222.18 s, peak memory 2,955,657,216 bytes. +Package SHA-256 `e3e69718507ed921f24844409829a9af429df7d571a7faea8e42c3c91e81aa06`. +Owner release `5ff7b2b657fdce16bebd5ff4`, SHA-256 +`db0ec4003ec6cc3cadcb076ff45c170e8c6c281e1878539191d1fe82295bfe4f`, +was opened locally after an APT plan of one Node upgrade / zero new / zero +removed packages. At this entry it awaits the owner's local sudo input. +Core passed typecheck, 907 unit tests, 11 Python archive/boundary checks and +production build; managed restart reports health accepted. New controls are +visible and correctly disabled against the older board's missing capabilities. + + +## 2026-09-23 — 0.8.25-1 installed; two 5 A observations + +The owner completed local sudo. Install run `a980576ffb984a85b192a929a2517002` +finished at 14:26:27 UTC in 16.57 seconds; Node and VESC services are active, +Node package is 0.8.25-1 and inventory has both verified UUIDs, new capabilities +and an empty drive assignment profile. X4 package remains 0.1.3-9. + +The owner's screenshot used 5 A / 15 s, outside the admitted 10-second limit, +so the disabled Start was correct but its explanation was inadequate. After +changing to 10 seconds, the owner ran operation +`op_99d89bd76df44885816855293f1cb02e` at 14:40:12 UTC on the left candidate. +It completed by duration, 146 samples, peak current 5.65 A, median 5.00 A, peak +283 ERPM and median zero. From about one second onward, speed was zero and +reported position stayed near 126 degrees; no speed-coasting occurred. Owner +reports no visible rotation. Both releases confirmed, fault zero. Do not +interpret completed operation as confirmed rotation or a confirmed physical side. + +A comparison UI operation `op_523ee78a7f92441094257f05a5784a1f` on the other +controller at approximately 14:44 UTC requested the same 5 A / 10 s. It stopped +very early on a telemetry bound. Only two pre-limit samples were retained, +showing 0 then 177 ERPM; subsequent released telemetry showed 79 ERPM and +0.26 A. Both zero commands and current release confirmed, faults zero. The +triggering sample was not preserved by 0.2.2, so the exact exceeded metric +cannot be inferred from this receipt. No config/firmware writes occurred. + +Node 0.8.26-1 / VESC 0.2.3 candidate keeps every existing bound unchanged, +preserves the triggering sample before validation, and returns measured field +and bounds in the result and UI error. Shared numeric fields explain invalid +input; the action area explains missing rig confirmation, unavailable connection +and in-progress execution. New synthetic checks reproduce a PWM-bound stop, +confirm no further current command and require release of all controllers. + +Owner visually confirmed the second controller as the right motor and clarified +that visible movement lasted 2–3 seconds. This does not mean the requested +10-second pulse completed. Core UI saved layout 1×1 / right.1 (revision1) on +the board; both inventory entries project that same profile and the device row +now displays Right. The left candidate remains unassigned. + +The shared input-feedback fix is live in Core. Browser QA reproduced 15s and +showed the explicit allowed-duration message, then verified Start enabled for +5A/10s plus rig confirmation; removing confirmation disabled it with an explicit +reason. This form-only QA did not request a motor operation. Core passed +architecture/typecheck/907unit tests/production build. Runtime candidate0.2.3 +passed34synthetic tests; source f89d904ec9e71348c2db95e1 is being qualified. + +0.8.26-1 qualification completed all15stages at14:53:20UTC in225.17s, +peak2,695,626,752bytes. Package SHA-256 +`eab7e24ec36d89793544480c8c5ce4675dee6c503c811ecc33ad9b7be57f30e8`. +Owner release `dbea4df7e0eb5ec8664a18a5`, SHA-256 +`f2aa50f54ff0c3607f26b8d50e616a588d86b6b39315c9ece624003670c83326`, +was opened locally after one Node upgrade / zero new / zero removed plan. +At this entry installation awaits local sudo; no new diagnostic motor test +has been run. Existing current, duration and telemetry bounds are unchanged. + + +## 2026-09-23 — 0.8.26 installed; exact right-channel stop identified + +Install run9d8e1c601bf0414795bf287d3bd80b87 completed14:56:46UTC in16.54s. +Node/VESC active,0restarts; right.1 assignment persisted across upgrade. +UI operation op_e6885c4f552f4bd59a7d46dc08f188f1 at approximately15:08UTC +requested5A/10s on the confirmed right motor. The third sample at0.245s +reported801ERPM,4.84A,duty0.091. The test stopped at the unchanged800ERPM +bound (duty also exceeded0.08); the exact offending sample and metric are now +retained. Both zero-current commands and release confirmed; faults zero. +This demonstrates an overly abrupt current step for the intended low-speed +identification mode, not a completed10s run or a VESC firmware fault. + +0.8.27-1 / VESC0.2.4 candidate starts/resumes at0.5A and ramps toward the +entered current ceiling at approximately1A/s. Soft coasting now applies at +all current settings and triggers at200ERPM or4%PWM; resume requires both +speed<=100ERPM and|PWM|<=2%. Existing hard telemetry, current, duration, +lease, RC and topology bounds are retained. No config/firmware writes added. +The board advertises the ramp capability so the shared UI describes it only +when installed.36synthetic tests passed, including ramp progression, duty +coasting before a speed edge, restart ramp and prior stop/failsafe regressions. +This is not completed speed control or hardware acceptance of the new ramp. + +0.8.27-1 source fb29a802d53507678e906cc3 passed all15Linux stages at15:19:04UTC +in224.38s, peak2,877,997,056bytes. Package SHA-256 +`baed463408c7ffb0242506668c6b0f5b465e5f161ffbef5f1053f3406f346494`. +Owner release ec6eb256586fd8454e0f0d5e, SHA-256 +`be0fc5ada98656d075dd1dd1d00c019053371bbeba32bf66299c04067f01d743`, +opened locally after one Node upgrade/zero new/zero removed plan. At this +entry it awaits local sudo. Ramp hardware behavior is not yet qualified. +Core architecture/typecheck/907unit tests/build passed; final browser check +of ramp description awaits the installed board capability. + +## 2026-09-23 — 0.8.27 installed; coordinated right-motor observation + +Install run `1e0183d2ba1341d29f1c637c3ecaaef6` completed at 15:22:30 UTC +in 16.55 seconds. Node/VESC are active with zero restarts; the right.1 binding +and profile revision1 survived the upgrade. Core displays the installed ramp +capability. X4 remains 0.1.3-9. No firmware or controller configuration writes +were performed. + +The first attempt `op_607dd0d63339449086dfb2676b068826` exceeded the +120 ms cycle deadline before taking an app-output lease or sending torque. +One announced retry, `op_2af7955abede4bedaed05f2b2a0e4651`, completed its +10-second command loop: 143 samples, last offset9.9887s, peak564ERPM, +peak3.60A, maximum command3.655A, no hard-bound violation, release confirmed +on both controllers and faults zero. It includes repeated soft coasting and +does not qualify continuous rotation. The owner subsequently clarified that +he had stepped away and missed this run; his earlier impression of near-zero +motion is not a complete physical observation. + +The owner now requires explicit coordination for every powered experiment: +wait for a fresh ready-and-observing reply, announce the target and parameters, +and explain the preparation delay. Do not automatically repeat a motor test. +After the owner replied ready, the Core UI launched exactly one right-motor +5A-ceiling/10s operation `op_2e93a47e94f840e9a99a0fb207145cc4` at +15:35:13.885UTC. Configuration backups preceded torque. The owner saw the +RIGHT motor move approximately10degrees, pause, then move another10degrees; +these were two small movements, not two full revolutions. + +The receipt contains99samples and stops at offset6.8856s on880ERPM against +the unchanged800ERPM hard bound. Peak current3.39A, maximum command3.452A; +29net/31absolute electrical tachometer steps. Current first ramps until3.151s, +is set to zero at3.220s, and resumes from0.5A at3.497s. The second ramp is +released at6.811s; the next sample crosses the hard bound even though the +previous command was already zero. These two acceleration/coasting episodes +match the owner's two movements, although there is no synchronized video. +The pause/restart behavior is introduced by our identification governor and +must not be used to diagnose a hardware fault in the right motor. A zero-current +command allows coasting; it does not guarantee an immediate zero-speed sample. +Final readback: both currents0A, left0ERPM, right13ERPM, faults zero; +release_confirmed=true. Raw receipts with UTC/monotonic offsets, hashes and +operator corrections are retained privately outside Git. + +The right physical assignment is confirmed again. Left rotation, Hall wiring, +motor calibration and native Tool runtime integration remain unqualified. +No limit increase or further powered test follows automatically from this run. + + +## 2026-09-23 — 0.8.28-1 candidate: owner-requested 30 A / 30 s controls + +The owner explicitly requests an editable range up to30A and30seconds, and +clarifies LEFT is problematic while RIGHT works normally from RC. Earlier +right-channel stepping was produced by our identification governor; do not +transfer the fault hypothesis to the right motor. The current ready-to-observe +reply precedes a code/build/install change, so a fresh coordinated launch is +required after installation rather than an unattended deferred motor start. + +VESC0.2.5 candidate keeps the existing fields and advertises new capabilities. +It ramps0.5A→entered ceiling at2A/s and removes the200ERPM/4%PWM coast/restart +cycle. It ends the operation at6000ERPM or25%PWM, or lower configured bounds; +no automatic restart follows a limit. Above5A,2seconds without continuing +reported movement aborts. Fault,20–60V,65°C FET limit, RC latch, per-controller +250ms leases, full backups and attachment checks remain. These software limits +are not a claim about nameplate ratings or clean calibration. No motor or +firmware configuration is changed. + +Synthetic acceptance:39VESC tests pass, including30A/30s with continuing +simulated movement and bounded receipt, no artificial pause at880ERPM, stalled +high-current shutdown, speed-only/no-tachometer rejection, configured limits, +and prior RC/Stop/topology/release regression cases. This candidate has not +been installed or physically tested at this ledger entry. + + +0.8.28-1 source9a125d01aad00711f03165df completed all15 Linux qualification +stages at15:53:11UTC in226.07s, peak2,701,422,592bytes. Package SHA256 +`002178109f807a411cac37c0be71ad22e32fa5cee3c0bd76e5a5df3f0aadbb40`. +Owner release265e96b1a910aaf23a221568, SHA256 +`34f8a43374b3639b7e8b90d15d38067816a101b93f30ad57b41eb0e50faad5b1`, +opened locally after one Node upgrade/zero new/zero removed plan. At this entry +installation awaits the owner's local Ubuntu authentication. Core passed +architecture/typecheck/908unit tests/production build; browser shows the new +shared component against the old board's correctly retained5A/10s capability. +No new motor command was sent during development, build or form inspection. + + +0.8.28-1 installed:run43a4b512c687491fbfa41abd382e99df completed at +15:55:04UTC in16.47s. Node/VESC active with0restarts; X4 remains0.1.3-9. +Both Core inventory entries advertise VESC0.2.5 and30A/30s capabilities. +Browser form accepted30/30 with rig confirmation off and no start; it was +then set to5A/30s on the left candidate. The right assignment survives. +No powered0.2.5 operation has run at this entry: a fresh ready-and-observing +reply was requested after installation. The installed max range is accepted; +hardware behavior at the expanded limits remains unqualified. + + +## 2026-09-23 — coordinated 30 A / 30 s request on the left candidate + +After installation the owner declined5A/30s, explicitly selected30A/30s and +repeated the request. The announced target was the left-candidate VESC; the +owner was observing. Core UI operation `op_1cadeb2c861b434e9bba93c5d8a7e5e5` +was requested at15:57:42.612UTC. Both configurations were archived before +current. The result at15:58:03.230UTC contains67samples, last monotonic offset +4.705856s. Actual peak current8.70A, maximum successfully sent command8.763A; +ERPM remained0, net/absolute tachometer delta0, reported phase126degrees stayed +constant. The2-second no-motion guard above5A ended the run. Neither the new +speed nor PWM bound triggered. Do not claim30A were reached or30s completed. + +The owner heard a click but reported no physical movement at all. This matches +the measured lack of movement, and is distinct from the old governor's two +right-motor steps. Zero current commands reached both controllers; final +readback target0.33A/0ERPM/duty0, peer0A/0ERPM/duty0, faults zero; +release_confirmed=true. Raw receipt SHA256 +`9003459550d44c38644c86f0660b82505ef7c35f153076506fe7bb531d7d1354`. +The raw receipt, experiment manifest, UTC/monotonic timing and operator note +remain private. No configuration/firmware write or automatic retry followed. + +The editable30A/30s range is installed and browser-verified. Actual sustained +rotation at these values, left-side visual motion identification, Hall wiring, +calibration and native Tool runtime are not accepted by this stopped test. + + +## 2026-09-23 — owner comparison exposes duration/control-mode mismatch + +Owner independently ran30A/30s on right and left. Right operation +`op_144e051172474f86a9df3841c4578a70` (16:03:05.982UTC) stopped at2.404s +on26.1%PWM against our25%limit, not a VESC fault.34samples, maxcommand4.573A, +peakmeasured6.08A, peak4568ERPM. The owner saw approximately one revolution +and a short visible run. Release confirmed, subsequent0.22A/1371ERPM is +coasting rather than evidence of continued torque; the later peer snapshot +is0A/0ERPM. Left operation `op_c67e68008b89401ab74895d71c7c66d8` +(16:04:42.076UTC) again stopped by no-motion guard at4.707s:67samples, +peak8.69A/maxcommand8.748A, ERPM0. Owner heard a click without movement. +Both release checks passed, faults0. No new agent motor command was sent. + +The owner correctly identifies that the UI's current/time fields do not deliver +his intended sustained rotation test.30A is a ramp ceiling,30s an upper bound, +and the software governor can end a healthy motor's acceleration far earlier. +Merely increasing current/duration limits did not implement speed holding. +A dedicated timed speed-control workflow and actual calibration must not be +represented as complete by this limited current test. The VESC Tool entry still +opens a partial custom adapter, not the full native tool or calibration wizard. +Do not use the right software-limit stop as a right-motor fault or treat the +left symptom alone as proof of a specific Hall wiring/calibration failure. +Owner priority remains actual calibration, using the upstream functionality; +exact native-tool ownership/runtime integration remains outstanding. + + +### 2026-09-23 — 0.8.29 / VESC 0.3.0 implementation, not yet installed + +Owner correction: duration means observed rotation after acceleration, not an +upper bound on a torque command. Added native speed PID, explicit speed/current +ceiling/rotation-time fields, measured hold timer, startup/lost-speed deadlines, +and volatile motor-current scaling with durable restoration and full readback. +No flash changes. Original settings cannot be overwritten after an independent +configuration change. This addresses the prior right-motor PWM guard stop by +controlling speed instead of repeatedly increasing torque. + +Added firmware-native Hall measurement (5 A, about 12 s) as the first calibration +step for the problematic left motor. Audited pinned FW 5.02 source: Hall detect +locks ordinary controls and temporarily changes the timeout; it is not software +interruptible. The separate UI acknowledgement describes physical power cut. +The table is measured only, never auto-applied. Unknown completion blocks new +powered operations. Full VESC Tool desktop integration and R/L/flux application +are not represented as complete; the entry is renamed “Настройка VESC”. + +Local synthetic runtime checks: 51 passed, including motion-time accounting, +stationary tachometer, interrupted rotation, lost configuration ACK, restoration +after interruption, external-change protection, RC preemption and Hall timeout. +Fleet archive checks: 3 passed. Hardware commands in this implementation stage: +none. Installation and physical calibration remain pending. + +### 2026-09-23 — withhold 0.8.29; use the actual native VESC Tool engine + +Owner rejected expanding a separate custom calibration implementation. The +required architecture is upstream VESC Tool on the board, controlled through +Mission Core's own local and paired UI. Source `d6178c84997c585bf06be65e` +completed Linux qualification (15 stages, 230.34 s). The 0.8.29-1 package SHA256 +is `a87fad59ca02b5bffca3960442ed140f46d2581366ce82a45861aa2f03ca481b`. +Owner artifact `1d8868618ed467ccdb330ed4` was planned only, never launched. +This release is withheld; do not interpret its successful build or newer Core +fields as an installed/calibrated hardware runtime. Board package remains +0.8.28-1 and both Node/VESC services remain active. + +Versioned native proof `6d56d1dc847c63a0dc5cbfb2`, artifact SHA256 +`01df98dfdb044d503532d1dc3b0cb61bffcf62a13e72a07b9ebff86c22b3de4e`, +completed at17:03:45UTC in7.48s under an unprivileged MemoryMax=3GiB/CPUQuota=200% +user scope. Only a C++ entry point was compiled, linked to286 unchanged objects +from the previously attested Tool7.00 build. Binary SHA256 +`58d3e1441507d4e50bfdd5ca2e342e8dce4ceed2dcbf411fa05856b5352e68ff`. +No system package, service, serial port or controller setting was touched. + +Both actual archived controller configurations pass native FW5.02 negotiation, +binary decode/re-encode equality, native XML export/import comparison and the +upstream legacy power-loss compatibility correction. For each archive, corrupt +hash, unsupported firmware, bad native signature and truncated input are rejected: +10 acceptance checks total.162 motor and149 application schema entries are +exported, including upstream non-serialized UI/schema entries. Native XML rounds +floating point text and is not byte-identical after conversion; original binary +backups remain authoritative. This is offline engine qualification only. + +Files: `plugins/vesc/native/offline_main.cpp`, +`plugins/vesc/packaging/native_probe.py`, `build_native_probe.py`, README and +`docs/node/18_VESC_TOOL_NATIVE_BACKEND.md`. Raw archives, native JSON/XML exports, +object hashes, failed-build diagnostics and the complete report stay private. +The initial prototype's too-strict XML byte comparison was corrected to use +upstream `checkDifference`; native binary comparison remains exact. A later +compile caught a private Utility API; final code uses the public native +serializer to validate fixed-size FW5.02 payloads. No upstream files changed. + +Battery identification no longer blocks motor-only diagnosis. Owner photos +identify UNITE BM1418HQF family on one motor; approximately500W is an unconfirmed +owner recollection. Keep existing battery protections while using actual native +motor procedures. The full wizard must not recalculate cutoffs from stale saved +3S/6Ah metadata. See the native engine document for two-controller topology, +canonical procedure, sensorless fallback, remaining runtime/installer work and +physical acceptance boundaries. No calibration or powered test ran here. + +### 2026-09-23 — 0.8.30 / VESC 0.4.0 native runtime candidate + +Continued from offline qualification to a real process adapter. Native engine +`9bebad9670b6db63099578aa` links the same unchanged Tool 7.00 objects. One +VescInterface owns each exact, exclusively locked CDC ACM attachment; firmware +negotiation, configuration serialization, serial commands and Hall measurement +use upstream C++. `Utility::measureHallFocBlocking` is invoked unchanged. +Configuration reads must reproduce the received bytes through native ConfigParams. +The Python layer owns session authorization, operation receipts, RC leases, +backup history and measured-duration policy; it no longer opens serial ports. + +The engine is packaged with its Qt/offscreen and ELF dependency closure. Only +the Ubuntu 24.04 glibc family remains a host prerequisite. Native bundle SHA256 +`3987527298f472ced6ec85d7460eec5a47d27872836ce96cbdaae02ec25d7bb7`, +50,344,426 bytes; executable SHA256 +`26a8df1c04d9246ae91e60363309dfbc1fd127717b53fadb5b0460a8c92a1e5a`. +Includes upstream license/source reference, adapter source and distribution +notices. Hashes are checked during payload construction and by an offline +self-check under the service account before profile activation. System packages +were not installed to prepare the dependency closure. Clean-image acceptance +and real USB ownership remain separate from this prepared-host offline proof. + +Eleven native acceptance checks passed (two original archives and four negative +cases for each, plus disconnected-engine rejection of powered/unknown methods). +Sixty synthetic runtime tests passed, including subprocess response identity, +lost ACK, process exit, stale session, changed attachment, malformed response, +blocked write, no replay, original limits recovery and real rotation timing. +Service limits become 512 MiB / 64 tasks for the parent plus native device owners. +This is a resource ceiling, not an assertion of arbitrary-device capacity. + +Touched native engine/config export, native_link.py, service.py, Hall timing, +packaging/native_bundle.py/native_probe.py/native-runtime.json/native_check.py, +Node source/payload builder, model version and installer preparation. Source +artifact `ab73ffcf92d894e67f8cffa8` is being qualified for Node 0.8.30-1. At this +entry no new runtime has been installed and no powered experiment has run. + + +### 2026-09-23 — 0.8.30 installed; first actual upstream Hall result + +All 15 Node Linux qualification jobs passed in 248.88 s, peak 2,637,553,664 bytes. +Node 0.8.30-1 package SHA256 +`f3f2ac7c6af8e8aff7c11192c4c97375d50fe4f2e8b1daa2030cd2b8ec174950`. +Owner release `66a702a23b5dfb61d2a18417` APT plan upgraded only Node. The owner +authenticated in the local Ubuntu window; installation completed 17:42:44 UTC +in 18.44 s. VESC profile 0.4.0 offline integrity/engine check passed under the +service account, both USB profiles applied, service active with zero restarts. +Both native processes identify Tool 7.00 and the exact pinned commit, recognize +FW 5.02 and enable its upstream compatibility correction. Both motor/application +readbacks through the shared Core UI match original archived hashes exactly. +History replication remains available. No controller settings changed at install. + +After fresh owner observation/raised-rig/radio-off/physical-cut confirmation, +Core UI started one left-candidate native Hall measurement at 17:50:56 UTC. +Procedure completed 17:51:20 UTC; actual native cycle 12.38 s, 118 samples, +no communication issues. Result: firmware_success=false, measured table +[255,174,255,120,255,22,255,63], observed states [1,3,5,7] rather than six. +All observed state codes have their least significant Hall bit high. This is +consistent with one non-switching Hall input, not proof of which physical pin +or whether the cause is wiring, sensor or incomplete physical sweep. Owner +subsequently reported no visible physical movement. Peak reported motor current +3.18 A with requested Hall current 5 A; reported tacho changed. This is not a +steady-rotation test or a successful calibration. Original motor configuration +restored byte-for-byte; both devices report 0 A / 0 ERPM / fault 0 afterwards. +No table was applied and no automatic repeat ran. Raw receipt, UUIDs, sessions +and backup IDs remain in private evidence. + +### 2026-09-23 — full native FOC transaction, Node 0.8.31 / profile 0.5.0 + +The owner confirms raised rig, removed track and transmitter off; retain those +facts without repeated questions. Coordinate actual observation after long builds. +The shared UI calls unchanged pinned `Utility::detectAllFoc(false, ...)`, including +upstream Commands' FW 5.02 power-loss correction. Actual battery current limits +and FOC startup parameters are preserved. Invalid 3S/6Ah metadata is not used to +derive cutoffs. Heating budget is explicitly 10–150 W, initially 50 W, not motor +nameplate power. Firmware selects its measurement currents; the separate spin +test's 30 A bound does not cap this non-interruptible firmware cycle. + +This initial profile requires independent USB with no CAN peers because upstream +Utility broadcasts application-output disable even with detect_can=false. +All connected devices are backed up and checked before launch. A durable pending +marker prevents replay after uncertain completion/restart. Python polls only +native procedure status during the cycle and never overrides its lease. Native +completion accepts only documented calibration field changes, restores appconf's +CAN status side effect, retains the lower of detected and prior motor current +limits, and verifies exact write/readback. Known failed detection restores its +known original motor settings; unexpected changes are not blindly overwritten. +Both target and peers are archived/verified after completion. Uncertain results +block further motion. UI distinguishes sensorless fallback from healthy Halls. + +67 Python transaction/fault-injection tests passed; architecture/typecheck and +908 UI tests passed. Native artifact `47c2efc6fe16229c500655ce` compiled against +the same 286 upstream objects and passed 11 archive/negative/disconnected checks +without USB use. At this entry 0.8.31 is not installed and full FOC has not run. +Physical left startup, right baseline, sustained rotation and replicated final +histories remain required acceptance work. + +### 2026-09-23 — 0.8.31 installed; successful native left calibration + +Node 0.8.31-1 completed all 15 Linux qualification jobs in 248.56 s. Package +SHA256 `2cf96e817872edb2b161e383b502ed4eecbe0beb75a76ecf13122f226dae7ca3`; +owner release `09f05ab9303fc2a4610d484d` upgraded only Node. Owner authenticated; +installation took 17.72 s. Both native USB owners returned, profile 0.5.0 active. +The owner freshly confirmed observation; the shared Core UI started LEFT-only +native FOC at 18:22:27 UTC with 50 W heating budget. Native completion/readback +finished 18:23:08 UTC, cycle 29.68 s, code 0 / Success / Sensorless. Detected +R=21.3572 mOhm, L=21.6031 uH, flux=12.0932 mWb, motor limits +/-34.2135 A. +Receiver/battery settings and the right configuration were verified unchanged; +both before/after histories replicated to Core. Owner observed LEFT smooth +acceleration and 2–3 s rotation without catching. This was the flux measurement, +not the separate sustained-rotation acceptance test. Broken Hall pin is not +repaired; low-speed/loaded startup remains unaccepted. + +The operator transport was interrupted during this cycle. On reconnection, +Mini uptime proved no reboot; the locally completed receipt arrived without +replay. Tailscale relay ping succeeded and SSH resumed. Ops HTTP/MCP was already +unreachable before the cycle with the task host route matching DHCP gateway; +no VPN/routes/firewall settings were changed. + +The native result/configuration were accepted, but the outer release check +latched: its first GET_VALUES returned 3.67 A accumulated average over the +entire unpolled native cycle, despite duty=0. FW 5.02 commands.c explicitly uses +mc_interface_read_reset_avg_motor_current(). Fresh Core UI read at 18:28:18 UTC +confirmed 0 A, 0 ERPM, duty=0, fault=0. Preserve the original receipt faithfully. + +Profile 0.5.1 / Node 0.8.31-2 drains that accumulation and samples a fresh bounded +interval after release. The existing explicit neutral-return action can reconcile +only a completed, config-verified archived native result with exact live UUID, +all-peer config equality, neutral input and fresh idle values. It writes recovery +evidence and clears only its completed pending marker, without any calibration, +torque or configuration replay. Unknown completion or changed config stays +blocked. 71 fault-injection tests pass, including the actual averaging failure, +explicit recovery, changed-config rejection and unknown-completion rejection. +At this entry 0.8.31-2 is awaiting qualification/installation; sustained rotation +has not yet been run. + + +### 2026-09-23 — 0.8.31-2 installed; completed calibration recovered + +All 15 Linux qualification jobs passed in 250.69 s; 71 Python runtime tests and +909 active-Core UI tests passed, with architecture/typecheck and production build. +Source artifact `25dc6ae93ea5038f0bec4bf4`; Node package SHA256 +`cc9f023b4519f65158c7244e4f0b66b1fd38ce1180600f84be87bbb6c6fba1de`. +Owner release `192e63bb2f7992ddcf38399f` upgraded only Node after local Ubuntu +authentication. Installation completed in 18.32 s; UI ready, VESC service active +and both USB identities returned on profile 0.5.1. Native Tool bundle unchanged. + +At 18:45:03 UTC the shared Core UI invoked explicit neutral-return recovery. +At 18:45:19 it completed with authority ready, calibration_replayed=false, +configuration_verified=true and release_confirmed=true. Both controllers had +fresh 0 A / 0 ERPM / duty 0 / fault 0. The original FOC receipt was preserved; +its completed configuration was reconciled without motor/configuration replay. +The owner then freshly confirmed watching LEFT for one 2000 ERPM / 30 A limit / +30 s measured-rotation test. That test is recorded separately below on completion. + + +### 2026-09-23 — LEFT sustained-rotation acceptance + +With fresh owner observation the shared Core UI requested LEFT 2000 ERPM, +30 A temporary current ceiling and 30 s measured rotation at 18:46:16 UTC. +Completed 18:47:04 UTC with outcome duration, rotation_s=30.0574, no limit +violation, release_confirmed=true and limits_restored=true. 354 samples retained; +311 holding samples ranged 1978–2012 ERPM (mean 1998.77), 2.50–2.75 A motor +current (mean 2.615), duty 0.107–0.113, fault 0 throughout. Hold began after +4.24 s acceleration/settling; total motion-command interval was 34.29 s. +Right remained at 0 A / 0 ERPM. Final left release sample had 0.1 A / 69 ERPM +while coasting, not a claim of instantaneous mechanical stop. + +Owner confirms smooth acceleration, stable visible rotation for approximately +30 s and modest sprocket speed. This accepts the unloaded sustained-rotation +path after native calibration. It does not accept loaded startup or the original +abrupt-transmitter-demand scenario. Only LEFT has been calibrated at this point; +RIGHT still retains its original configuration. No automatic repeat was started. +Ops MCP remained unreachable on a fresh check; evidence is retained locally. + + +### 2026-09-23 — RIGHT native calibration accepted; first speed trial interrupted + +After fresh owner observation, Core UI started RIGHT native FOC at 18:52:55 UTC +with the same 50 W heating budget. Finished 18:53:37 UTC, native elapsed 28.35 s, +code 1 / Success / Hall Sensors; configuration_verified=true, release_confirmed +and overall success=true, issues empty. Detected R=21.1167 mOhm, L=21.3738 uH, +flux=11.9471 mWb, motor limits +/-34.4078 A. Hall table becomes +[255,166,98,131,34,1,66,255]. Both after-state snapshots show 0 A / 0 ERPM / +fault 0. All four before/after archives were fetched from Core. Exact decoded +comparison finds 14 right motor calibration fields changed; application and +battery fields unchanged. Left motor/application bytes remain unchanged. Owner +observed the expected short spin and later tiny positioning steps, then confirmed +understanding that this was the calibration cycle. + +The separate 2000 ERPM / 30 A limit / 30 s test at 18:54:28 UTC was interrupted +after 11 acceleration samples (~1.02 s), before speed reached the saved 900 ERPM +PID minimum. No measured hold time accrued. The right native connection closed; +the receipt could not confirm release or temporary-limit restoration immediately. +The durable latch prevented replay; the service later reconnected the same UUID +and recovered temporary limits. No service restart, host reboot or kernel USB +disconnect was observed; exact failed native RPC/cause was not retained, so this +is not attributed to a motor or electrical defect. + +Fresh UI telemetry at 18:55:39 UTC confirmed right 0 A / 0 ERPM / PWM 0 / fault 0. +Explicit neutral-return from Core UI completed 18:57:04 UTC with authority ready. +Both recovery backups match their post-calibration motor/application bytes exactly. +The original interrupted receipt is retained unchanged. After fresh owner +observation, one bounded repeat was admitted; recurring disconnect will require +transport diagnosis before any further powered retry. + + +### 2026-09-23 — RIGHT sustained rotation accepted; common-profile test implementation + +Owner freshly confirmed observing the bounded retry. Core UI requested right +2000 ERPM / 30 A ceiling / 30 s at 18:58:10 UTC. Completed 18:58:59 UTC, +outcome duration, 30.0518 s measured hold, 353 samples, no controller faults or +limit violation. Holding speed 1969–2037 ERPM (mean 2000.322), current +2.07–2.46 A (mean 2.260), controller temperature 30.6–31.2 C. Release and +original-limit restoration confirmed; left remained idle. Owner confirms right +visible motion comparable to left for the same duration. Both motors now have +independent native calibrations and physical unloaded 30 s acceptance. Left is +sensorless; right uses newly measured Hall table. Abrupt RC startup and loaded +operation remain unaccepted; one interrupted right native connection remains +a known observation, not proof that the motor is faulty. + +Owner requests simultaneous comparison and asks whether calibration is available +through the product. Existing per-VESC calibration and history UI demonstrated. +Node 0.8.32 / profile 0.6.0 adds one common `vesc.drive.run` transaction for the +complete assigned 1x1 or 2x2 profile. Placement: existing spin-test SettingsCard, +canonical Select chooses single controller or complete profile; no new root, +workspace, shared visual entity, or duplicated calibration algorithm. Revision, +exact selected membership, live UUID/session, every motor limit and all peer +inputs are checked before motion. Device owners remain upstream VESC Tool. + +Group polling/lease/speed batches run independently per USB owner, joined before +release on any failure. Commands share the ramp/setpoint; the joint 30 s clock +counts only intervals when every motor has confirmed speed and tachometer motion. +Stopping one stops the transaction; RC latches it. Original limits restore only +after zero current and neutral, including after reconnect. No powered command +replay. Receipts retain the original exception separately from cleanup results. +80 synthetic runtime tests pass, including pair/four membership, joint timing, +stationary/lost-speed peer, failed lease, partial limit ACK, RC and stale profile. +At this entry the group feature is not installed or physically accepted. + + +### 2026-09-23 — 0.8.32 qualification and owner installation prepared + +Core architecture/typecheck, 911 UI tests and production build passed sequentially +with adequate local memory headroom. The updated Core remains on canonical 8000. +Browser acceptance confirmed canonical Select and Escape focus restoration, and +correct disabled group option while the board still reports older capabilities. + +Source artifact `5e4945f3ef3a74ffe68d1619`, 411,549,546 bytes, SHA256 +`c5b53209001d8eaa86e56ed5d997224679d429692cddd10b321ec5cd2eec5b99`. +All 15 Linux qualification jobs completed in 255.70 s; peak memory 2,260,582,400 B +inside the unchanged 3 GiB / 150% CPU build envelope. Node 0.8.32-1 package +218,813,236 bytes, SHA256 +`dbef14db5cc78bea27ffd229a5335961cd989ebc89a944bac7a2dc8b7c8a2058`. +Owner release `e72c65f0b91cbbe30655730f`, SHA256 +`c34115038e8fbd1254d53d3277b373e580ea947e5789b220330f43fbd9339157`, +was built exclusively from qualified output. Fresh APT plan upgrades only Node +0.8.31-2 to 0.8.32-1, with no package additions or removals. The canonical +local Ubuntu installer is open awaiting owner authentication. No group motion +or repeat calibration has been performed during this implementation. + + +### 2026-09-23 — 0.8.32 installed; group attempt interrupted by native read timeout + +Owner authenticated the versioned installer; installation completed at +19:19:37 UTC in 17.79 s. Both devices advertised profile 0.6.0 and group capability. +After fresh owner observation confirmation, Core UI started the complete 1x1 +profile at 19:24:54 UTC: 2000 ERPM, 30 A ceiling per motor, 30 s common hold. +Preparation completed, but the native read failed 0.367 s into the command loop, +after only two samples (44.6 and 122.9 ERPM setpoints). Common rotation remained +0 s. Owner reports neither motor moved. No automatic powered retry occurred. + +The native error was `Native query timed out or disconnected`; active-loop read +budget was 60 ms. The Python boundary terminates its native owner after any +unconfirmed query, so subsequent release cannot use that owner. Left zero-current +command was sent; immediate right release/readback were unconfirmed. Original +failure receipt is retained. Explicit UI neutral-return completed 19:26:51 UTC, +both configurations were read and idle/neutral checks passed, original temporary +limits had recovered, authority ready. Neither calibration was replayed. + +No kernel USB disconnect/reset, service restart or board reboot was observed. +Both USB devices remain runtime-active with power/control=on. This rules out an +observed port removal or autosuspend event, not packet loss or electrical noise. +The old error lacks the exact failed query and native elapsed time; cable versus +reply latency cannot be attributed from it. No hardware-fault claim is admitted. + +### 2026-09-23 — read-only latency diagnosis prepared in 0.8.33 / profile 0.6.1 + +Add `vesc.link.check` to the existing per-VESC detail using canonical SettingsCard, +Button and ResourceList. It measures all present, session-matched board VESCs at +the group loop's 10 Hz cadence for 100 cycles, bounded by 25 s and the operation +deadline. Every controller is exclusively locked; only PPM and telemetry queries +are admitted. Nonneutral input or existing motion ends the measurement. It sends +no motor, lease or configuration commands. A separate 500 ms read-only budget +records replies beyond the motor loop's 60 ms cutoff; powered-loop deadlines are +unchanged. No measurement result alone grants motion authority. + +Native RPC records now retain command, deadline, elapsed boundary time, subprocess +and attachment state on failure, plus the last 32 bounded metadata records (no +payload/configuration bytes). Group/single failure receipts retain these records. +The UI no longer equates a missed group reply with a proved physical disconnect. +87 runtime tests pass, including no-write measurement, late-reply statistics, +missing reply identity, nonneutral termination, operation exclusion/idempotency, +stale sessions and stop. Physical transport diagnosis remains pending installation. + + +### 2026-09-23 — 0.8.33 diagnostic package qualified; installer launched + +Architecture/typecheck, 911 UI tests and the Core production build passed. Core +8000 was restarted only after verifying no active motor procedure, and is ready. +Source artifact `edaf094fea23f84985b8cd64`, SHA256 +`f24dbdebb0fb058140a47d9675475a0468b77fa82e71be4a8d9e1d16f3d22acf`. +All 15 Linux jobs passed in 256.98 s, peak 2,252,750,848 B under the unchanged +resource envelope. Node 0.8.33-1 package: 218,816,686 bytes, SHA256 +`e07ea0770f3feb9633b08681a3772e4f814c3e7165f400ca24ccd16cc4994c7e`. +Owner release `b08ab8c46eb5e0d97f049faa`, SHA256 +`843fda4810979c784eb03299b5914bfcb49a663a27a9f82fe867aee4d185e62f`. +APT plan upgrades only Node 0.8.32-1 to 0.8.33-1; no added/removed packages. +The local Ubuntu installer was launched; authentication/install confirmation is +pending. No powered retry occurred. Ops MCP remains unreachable; Ops update is +pending, with the full incident evidence retained privately and this redacted +ledger kept current. + + +### 2026-09-23 — 0.8.33 installed; idle reply latency measured + +After the owner corrected the local Ubuntu keyboard layout, installation +completed at 20:02:50 UTC in 17.91 s. Node is 0.8.33-1, VESC profile 0.6.1, +service active with zero restarts. The initial three rejected password attempts +made no package changes; no authentication bypass or secret handling occurred. + +Core UI `vesc.link.check` read both controllers for 12.324 s with no motor/lease +or configuration commands. All 400 replies arrived; neither device reported +motion/current/fault, and PPM remained neutral. LEFT full-call median 59.07 ms, +p95 79.63 ms, maximum 117.78 ms; RIGHT median 58.49 ms, p95 78.64 ms, maximum +114.23 ms. These are Python-boundary durations, not isolated firmware/USB response +times. Consequently they cannot by themselves prove that the native 60 ms reply +deadline is wrong or explain the earlier native timeout. Both original receipts +and the limitation are retained. No powered retry is authorized by this result. + +CPU quota is unlimited, cgroup throttling counters zero, host load low. Read-only +sysfs timing identifies repeated full-bus discovery in NativeLink.check(): one +scan median 14.65 ms / maximum 18.02 ms; paired scans median 40.28 ms / maximum +41.97 ms. It ran before and after every RPC, unnecessarily scaling with all USB +attachments and contending between controller threads. + +### 2026-09-23 — 0.8.34 / 0.6.2 removes per-request full-bus discovery + +The per-request check now reads only its exact USB path, vendor/product, device +address generation, uniquely matching interface tty and speed. It reads the +address before/after the inspection to reject replacement during the check. +Discovery still enumerates the board; its tty pattern is limited to actual +interfaces rather than driver/subsystem directories. No identity cache or timing +relaxation is introduced. Motor timeouts, stop rules and the native binary are +unchanged. RPC receipts now separate pre-check, request-write, native-response +and post-check durations and preserve the failed stage. + +Read-only execution of the pure sysfs check on Mini (no port open, installation, +motor or configuration commands) measures 2.50 ms median / 2.92 ms maximum for +one target and 5.12 ms median / 6.29 ms maximum for paired targets. 92 runtime +checks pass; seven native-boundary checks also pass after the timing assertions. +Unplug, replaced generation, changed generation during read, duplicate tty, +unrelated driver tty and path traversal are rejected. Installed-operation +acceptance and original timeout attribution remain pending this versioned update. + + +### 2026-09-23 — 0.8.34 package qualified; owner installer launched + +Source `4adfb4f84e097350eaa14102`, SHA256 +`81d00168df5328b82bb887223df69056cd51d5747e0f6a1434f782aee922c108`. +All 15 Linux jobs passed in 256.16 s, peak memory +2,242,736,128 bytes. Node 0.8.34-1 package SHA256 +`58934f48eee0d845d1643eddcbc7f02866310f498b6ccebd9585d29daa2090af`. +Release `229328c79ad99782d788d8b8`, SHA256 +`07a98e6fd3686b23d16a601f46d38bb9ebfe35110c89f3f1105166c669d3f049`. +Fresh plan upgrades only Node 0.8.33-1 to 0.8.34-1, no added/removed packages. +No active motor operation was present when launching the local Ubuntu installer; +owner sudo authentication is pending. UI/native payload and powered timeouts are +unchanged. Ops MCP remains unreachable; this ledger and private evidence retain +the update until the Ops card can be reached. + +### 2026-09-23 — 0.8.34 installed; faster idle reads, powered timeout isolated + +Installation completed 20:17:52 UTC in 18.54 s, all services active with zero +restarts. UI link check at 20:22:28 received all 400 replies in 10.016 s, no +motor commands, faults or motion. Full-call medians LEFT 9.95 ms / RIGHT 9.80 ms, +maxima 19.78 / 21.70 ms. Native-response maxima 1.09 / 1.43 ms; the removed +full-bus checks explain the previous full-call overhead, not the powered fault. + +Owner explicitly observed the next UI group run: 2000 ERPM, 30 A ceiling each, +30 s common rotation. It stopped 0.484 s into initial ramp, after four samples +and a maximum command of 195.81 ERPM. Common rotation 0 s; owner confirms both +motors stayed still. RIGHT command 31 (decoded PPM) failed inside native +exchange after 60.09 ms; Python pre-check was 4.31 ms. Native process was alive +and exact attachment present. Kernel journal has no USB event, service no +restart. This isolates the native reply timeout but does not prove wire/MCU +versus suppressed native transmission. Immediate RIGHT release/readback was +unconfirmed; UI stop followed by explicit neutral recovery completed 20:25:40 +UTC, authority ready and temporary scales restored. No powered retry followed. + +### 2026-09-23 — 0.8.35 / 0.6.3 native exchange diagnostics candidate + +The adapter records bounded metadata around a failed native exchange: requested +command emission, packet transmission, serial bytes-written, decoded incoming +packet IDs, serial error/open/pending-write state and monotonic event times. +No payload contents are recorded. Error details survive the Python fail-closed +boundary; no motor command is retried. Timeout, ramp, current, calibration and +upstream source remain unchanged. Scoped observers and a pending-query guard +are released on normal completion and exception. Build and installation pending. + +### 2026-09-23 — 0.8.35 qualified; local owner installation pending + +Native diagnostic artifact `48f470f0209ccbf97ff77271` passed 11 archive, +negative-input and offline-engine checks in 36.69 s, preserving all 286 upstream +objects. Runtime SHA256 +`cc78c273e025f0738ed79f94d4bc6a70e504f2e7204b1ef694119e6a230b913a`. +Python runtime suite: 93 passed. Source `a661c4ecd4553728ab73d2cc`, SHA256 +`a616faf9f360066c4763fbbdd261c4e0955e5358d1bc45728770ad2016ec4e62`, +verified on Mini. All 15 Linux qualification jobs passed in 256.41 s. +Node 0.8.35-1 package SHA256 +`b95e050e38d347d139e16b37f33bdf2c9d9f9a828a01457d1dae38d4a6971ddc`. +Owner release `4d72eed539c3755b5cb14359`, SHA256 +`1c703adb207ea8373195ad0794905d80ab39941fa35f89e3a468894129936935`. +Fresh plan upgrades only Node 0.8.34-1 to 0.8.35-1; no added or removed packages. +Both VESC were online and inactive before launching the local installer. Ubuntu +owner authentication is pending. The diagnostic change is not a claim that the +missing powered reply is fixed; acceptance requires fresh observation after +installation. Both original calibrated configurations remain in the archive. + +The slow normal rsync transfer completed and matched the canonical source SHA +before a prepared compact transport fallback was needed; the fallback was not +executed on the Mini. The successful upstream Tool report is in build +`d1797bf1152f59ee14012ed5` and points to the qualified source/object tree in +`f611147350b77dfa0006b7d8`; the latter's original report is not successful. +Ops MCP still returns an HTTP transport error; local evidence is retained. + +### 2026-09-23 — 0.8.35 installed; idle native transport accepted + +Owner authenticated locally; installation completed 20:51:39 UTC in 18.44 s. +All steps passed, UI ready, services active and restart counters zero. Installed +engine SHA256 `9d2d6a87032e3c60f2666cadd5d5d1520edac05087e0dcb7a5ac3875f2ace325` +matches the qualified binary; both device sessions report VESC profile 0.6.3. +The first UI read-only check completed 400/400 replies in 10.015 s without +motion, faults or commands. Full RPC maxima LEFT 18.14 ms / RIGHT 20.47 ms; +native response maxima 1.28 / 1.24 ms. Powered diagnostic retry is awaiting the +owner's fresh observation readiness; no powered acceptance is claimed. + +### 2026-09-23 — 0.8.35 powered query emitted; RIGHT reply missing within deadline + +The observed UI group run (2000 ERPM, 30 A ceiling each, 30 s common rotation) +stopped 0.289636 s into its initial ramp. Two samples, common rotation 0 s; +owner confirms both motors remained still. RIGHT GET_VALUES command 4 was +emitted, one six-byte packet was written by QSerialPort at 0.491 ms, with no +decoded incoming packet before the 60 ms configured deadline (59.212 ms +measured by the coarse Qt timer). Port remained open/connected, serial error 0, +no pending output bytes. Python attachment pre-check took 3.802 ms and native +response wait 59.920 ms. The native process and exact USB attachment were alive. +No USB kernel events or service restarts occurred in the retained time window. + +This rules out a suppressed request for this failure. It does not distinguish a +late reply, framing loss, USB transport problem or controller-side delay. +Immediate RIGHT release/readback was unconfirmed; UI stop and explicit neutral +recovery completed at 20:55:37 UTC with authority ready and temporary limits +restored. Original failure receipt remains unchanged. No automatic powered +retry followed. Next discriminating check requested from the owner: interchange +only the two VESC USB plugs at the Mini, verify UUID-to-port mapping read-only, +then coordinate any new powered observation. This physical change is still +pending; neither the USB cable nor controller is declared faulty. + +### 2026-09-23 — first accepted simultaneous rotation after USB relocation + +Owner relocated both USB plugs to two different Mini ports (not a reciprocal +swap). Native UUID identity and the persisted LEFT/RIGHT profile bindings were +preserved automatically. No source, package, calibration, timeout or control +parameter changed between the failed and successful powered attempts. + +The UI idle link check received 400/400 replies in 10.015 s. Full RPC maxima +LEFT 14.93 ms / RIGHT 13.99 ms; native maxima 1.174 / 1.158 ms. The subsequent +owner-observed UI group test started 21:05:15 UTC and completed 21:06:02 UTC: +2000 ERPM, 30 A ceiling per motor, 30.047580 s common rotation, 342 samples +including 301 holding samples. LEFT held 1968–2012 ERPM (mean 1998.67), motor +current 2.48–2.71 A; RIGHT held 1974–2038 ERPM (mean 1999.84), motor current +2.07–2.43 A. Both fault codes stayed zero. Both zero-current releases were +confirmed and original temporary current scales restored. Kernel journal had +no event in the test interval; Node stayed active with zero restarts. + +Owner confirms both motors started together, ran evenly at matching apparent +speed for about 30 s and stopped together. This accepts this simultaneous, +unloaded test. USB relocation/reseating is correlated with the change in +outcome; it does not establish a defective port/cable or long-term transport +reliability. Original abrupt RC startup, loaded drive, damaged Hall wiring and +independent communication-loss torque-off remain separate outstanding checks. +No further automatic motor run followed. Private receipt, owner observation, +identity mapping, statistics and SHA256s are retained in acceptance-035-group.json. + +### 2026-09-23 — owner RC acceptance; follow-up Hall comparison blocked in preflight + +After the accepted common-speed test, the owner reports excellent operation of +both motors from the RC transmitter, in response to the requested gradual and +abrupt-start comparison. This is owner-observed unloaded acceptance; no RC +command/timing telemetry was captured. Working LEFT sensorless and RIGHT Hall +calibrations remain unchanged. + +Owner requested a separate comparison of Hall inputs and explicitly confirmed +transmitter off and observation of both sequential 5 A native measurements. +The LEFT UI request at 21:14:42 UTC failed during preparation, before a new +backup or Hall result. A subsequent ordinary telemetry read also failed. +LEFT then failed identity confirmation and became transport-local/degraded; +RIGHT retained its prior verified session. Linux still enumerated both USB +attachments with unchanged addresses and had no kernel event; both services +remained active with zero restarts. No new Hall procedure or configuration +write is evidenced; no powered retry was issued. Owner was asked whether main +power remained on. The prior LEFT four-state Hall result and RIGHT successful +six-state calibration table remain the available comparison, not new results. +This recurrence means the earlier port relocation cannot be treated as a +confirmed repair of remote transport reliability. + +### 2026-09-23 — USB reconnection retains identity; idle read failures recur + +Owner confirmed both VESC remained powered, unplugged LEFT USB and reconnected +it to the same port. Both native UUIDs and LEFT/RIGHT assignments were verified +again at 21:30 UTC. Linux logged descriptor/address errors (-71) during that +reconnection, then successfully enumerated the device. Those enumeration errors +are a separate observation, not proof of the cause of later missing replies. + +UI read-only link checks at 21:34:17 and 21:51:53 UTC each failed on the first +GET_DECODED_PPM request to both controllers. In both checks, the native adapter +reported an emitted request and six serial bytes written, open/connected port, +no serial error, and zero decoded reply packets within the 500 ms diagnostic +deadline. No motor command or configuration write was sent. Both services +remained active with zero restarts. USB power/control was on, runtime active, +and suspended time zero; both tty devices carried ModemManager ignore flags. + +Automatic native reconnect temporarily restored verified identities, and an +ordinary LEFT telemetry read succeeded at 21:36:57 UTC (50.3 V, PWM zero, +fault zero). A separate UI link-check attempt did not receive confirmation +during a stale board-link interval and is not counted as a completed test. +Identity verification alone therefore does not establish current command-channel +health. Neither USB hardware nor our adapter is exonerated by these observations. + +No additional Hall measurement started. After renewed observation confirmation, +LEFT was again unavailable and its UI action remained disabled. Owner was asked +for one complete power cycle of both controllers with USB also disconnected, +then reconnection to the same ports. That recovery is pending; working motor +calibrations are not changed. The private receipts and kernel journal are +retained under hall-035-*; Ops MCP remains unavailable with an HTTP transport +error, so this update has not been published to the project card. + +### 2026-09-23 — owner requires diagnosis on the running installation + +Owner declined the proposed power cycle and further reconnection. That request +is withdrawn; no board reboot, physical reset, service restart or installation +was performed. Hall comparison remains incomplete. Existing calibration and +the accepted unloaded/RC observations must not be conflated with USB reliability. + +Separate ordinary input reads were submitted through Mission Core's existing +vesc.input.read operation, with no motor/configuration commands. LEFT failed +with the installed generic error. RIGHT completed at 21:59:42 UTC: decoded +level -0.065999, pulse length 1.466 ms. Its accepted application configuration +sets PPM hysteresis to 0.15. FW 5.02 app_ppm.c exposes input_val before applying +utils_deadband, but our host tests used a fixed 0.02 threshold. This is a +confirmed mismatch that can falsely label an input inside the VESC neutral +band as an RC motor command. It does not explain USB query timeouts, and a PPM +value does not establish whether the transmitter's radio link is present. + +Candidate Node 0.8.36-1 / profile 0.6.4 reads each device's admitted PPM band +from configuration for preflight, single/group motion and Hall monitoring. +Recovery rereads/verifies application configuration; missing/invalid bands +block motion. The idle link diagnostic reads application configuration too. +Actual input beyond that device's band still preempts and latches RC authority. +No VESC configuration is changed by this correction. Ordinary and preflight +native errors retain command/stage/transport/history in receipt result.failure; +native traces identify the exact USB attachment. Product errors remain concise. + +99 local synthetic tests passed, including different per-device bands, changed +configuration between operations, active RC preemption, no-write link checks, +failure evidence persistence and idempotency. Existing native Tool binary and +all motor deadlines remain unchanged. Candidate is not installed or accepted +on hardware; preparing it does not authorize restarting the running services. + +The immutable candidate source is `6cd91f87045f3fb2bb8d9f14`, SHA256 +`954f19c2ace4c0186c5a0e96eb2196637481a4818bb871c1d857a86b7492b1ca`. +All 15 bounded Ubuntu build/qualification jobs passed in 276.20 s. Package +0.8.36-1 SHA256 +`ca471e1cfd90eea4e71014b7be020e0a0459fea017668cd657e7e01d9dab05d4`; +owner release `f1d300d6ca0954ba007e7a50`, SHA256 +`f990e5d2a3a1c7a4e2bc8c1f71720c6a9ee6393a8756437645fd9e056ef6171c`. +Only the release's `--plan` ran: APT proposes one Node upgrade, no added/removed +packages. No installer window was launched. Installed Node remains 0.8.35-1; +Node and VESC service PIDs are unchanged and restart counters remain zero. + +Applying this existing Node installer would restart Node/VESC and monitoring, +including its monitoring database, and cycle the configured optional device +services according to preinst/postinst. It is not a restart-free hot patch and +is not described as only a VESC restart. Physical power/USB changes and a Linux +reboot are not part of that update. Owner agreement on software service +interruption is needed before applying under the current no-restart constraint. + +### 2026-09-24 — post-boot absence and power-profile research + +Owner reports board booted and requests a refreshed plan, investigation of +missing VESCs, and explanation of native power profiles. Power-limit changes +are explicitly deferred. SSH works; installed Node remains 0.8.35-1 and both +Node/VESC services are active with zero automatic restarts in this boot. +Read-only Linux inspection finds no VESC USB enumeration and no ttyACM/by-id +ports. Boot logs show descriptor/address failures (-71) on two USB ports; +unidentified devices cannot yet be attributed to a particular VESC. Owner was +asked to confirm present VESC power/cables and any changed connections, without +requesting disconnection/reset. No service restart or controller command ran. + +Core retains one configured offline VESC and serves both controllers' archived +configurations, but the other controller is absent from inventory. Source review +shows the persisted drive profile is exposed only inside live inventory items; +Node's offline registry is updated by explicit preparation, not every verified +discovery. Known-device persistence and independently available drive profiles +therefore need product work separate from USB recovery. Direct SSH reading of +the protected profile file was denied; no permission workaround was attempted. + +The latest confirmed archived configuration has motor limits 34.2135/34.4078 A, +100% acceleration scales, 55 A battery limits per controller and no separate +watt cap. These are historical readbacks, not fresh hardware measurements or +manufacturer-approved ratings. Native profile temporary/permanent semantics, +CAN propagation and per-device readback requirements are documented in +20_VESC_POWER_LIMITS_PLAN.md. No power UI/runtime changes were implemented. +Private boot-20260924-* evidence remains outside Git. Ops MCP still fails at +the instruction call with an HTTP transport error; this update is not in Ops. + +Owner subsequently confirms both VESC USB cables are connected and both motors +work from RC now. First USB enumeration errors appear at boot monotonic 9.124 s, +before VESC process start at 11.111 s and Node at 13.430 s. This separates the +initial boot enumeration failure from current application-driver activity; it +does not identify the failing hardware or exclude USB firmware/host issues. +There are still no ttyACM devices. No reset, movement or configuration change +was issued by the agent during this audit. + +Owner confirms all USB devices were removed and reinserted in different ports +while starting Mini. Audit of installed runtime and udev rules finds no fixed +port requirement: discovery enumerates all USB device paths matching the model, +permissions match descriptors, identity is derived from firmware UUID, and drive +bindings store device_id/UUID. Installed serial.py and drive_profile.py SHA256s +match source exactly. Port/address checks protect one connection generation and +do not determine persistent motor assignment. Three focused synthetic tests +passed; an additional synthetic move of both controllers to different bus, +port and tty names retained both identities and left/right assignments. + +At the latest read-only inspection all four USB2 root ports are active, each +reports zero over-current events, and no VESC tty exists. These attributes do +not certify cable or electrical signal quality. The owner was offered one +controlled USB reconnection into the same current port to distinguish persistent +enumeration failure from boot-time state, with Mini/main VESC power kept on and +no commanded movement. This remains pending explicit owner response under the +previous no-reconnection constraint. No reset or controller command was issued. + + +### 2026-09-24 — owner reconnect and artifact-owned startup changes + +Owner subsequently reconnected USB. Both controllers reappeared without a +service restart: the right instance on ttyACM0/port 1-3, the left on ttyACM1/1-2. +Firmware-derived device identities and the 1x1 profile revision 2 retained both +assignments. Kernel evidence records two enumerations about ten seconds apart; +this is not evidence that one physical reconnection restored both controllers. +Node/VESC remained active with Node NRestarts=0. No motor command was issued. + +Owner requires GUI autostart through the existing environment configuration, +boot-only recovery of failed USB enumeration, no USB control surface and no reset +behind inventory refresh. Owner then extended the artifact-owned OS configuration +rule to all onboard development and Linux environment profiles. The repository +AGENTS.md now records that invariant. + +Candidate Node 0.8.37-1 adds environment profile revision 3, owned XDG autostart, +service-readiness wait, fixed boot USB recovery and individual-hub capability +inspection. Port recovery checks the current boot's terminal kernel errors, +empty port and companion, hub generation and power switching support; it records +pending re-enable before any change and has bounded retries/cleanup. See +21_STARTUP_AND_USB_RECOVERY.md. Neither the USB policy nor autostart is enabled +by copying files manually or by this source edit; the shipped environment setup +owns activation. No warm USB reset, hardware test or reboot has been performed. + +35 focused Python tests passed locally; shell syntax and diff checks passed. +Ubuntu artifact qualification, installation/preparation and cold-boot acceptance +are pending. The board's actual individual-port power capability is still unknown. +Current services and both ttyACM devices remain available. Ops publication remains +blocked by the previously recorded direct-MCP transport failure. + +Pre-install review added a guard and regression for a hub replaced during its +companion descriptor inspection. All 36 focused tests now pass; the first +source snapshot is superseded before any build/install. No runtime change. + + +Ubuntu qualification completed for source 4b32759c1bc19f3c6b64c983 in 253.855 s: +17 jobs passed, including Node UI build/tests, Go race tests, 36 environment / +USB / desktop tests, systemd unit validation (empty stderr), and 99 VESC tests. +Package 0.8.37-1 SHA256: +2171120488a30530e8603a9f8f1a757a7ad65e02138b57a245d5620a28c01e02. +Owner release dbc5e717ee36ebb521f28fa4 SHA256: +06eeff49bda51662c041b25e675be9d6037a5f5a3acf6d27e014a87bfdebc59b. +APT simulation: one Node upgrade from 0.8.35-1, no new packages or removals. +This is prepared-Ubuntu qualification, not clean-image or cold-boot acceptance. + +The release's own --launch opened its local Ubuntu installer. Owner was asked +for the OS sudo prompt in that local window. Installation and the subsequent +in-application environment setup are pending; no arbitrary root command or +manual OS configuration was used. Both controllers were readable and no motor +test was active immediately before opening the installer. Core on 8000 remained +HTTP 200 with one canonical listener; no listener on 8765. Ops MCP was retried +once after the long build preparation interval and still failed at instructions. + + +Owner entered sudo in the artifact's local installer. Readback confirms +0.8.37-1, dpkg `install ok installed`, Node/VESC active/running with NRestarts=0, +and installed USB helper SHA256 identical to the qualified source. Core sees +both original VESC identities, readable=true, test_active=false, profile 1x1 +revision 2 unchanged. No controller configuration or power limit was written. + +Owner ran «Система → Настройка окружения → Сконфигурировать» in the onboard UI. +All nine revision-3 steps completed. App-owned XDG entry and USB policy are +root-owned 0644; the boot recovery unit is enabled, inactive/dead (not executed +in this warm session). Both ttyACM devices remain present. Capability inspection +reported at least one individually switchable hub; exact per-hub inspection is +root-only before the first unit start (preparation umask makes its /run directory +0700; systemd RuntimeDirectoryMode=0755 applies when the unit starts). Do not +infer root-port compatibility from the aggregate preparation status. No manual +permission repair was made. + +Owner asks for the next acceptance step: an orderly full Mini shutdown and +power-on, retaining USB cables and VESC main power, without manually opening +Node or reconnecting devices. Cold-boot recovery, exact root-port capability, +GUI startup and persistent motor assignments remain to be observed. The agent +has not issued a reboot or shutdown command. Ops publication still unavailable. + +## 2026-09-24 — observed restart and board settings UI, Node 0.8.38-1 + +Owner restarted the Mini. A new boot was observed; Node and VESC became active +with NRestarts=0, both original firmware UUIDs were readable, and profile 1x1 +revision 2 retained its left/right assignments despite new port locations. +GNOME reports the MissionCoreNode application scope launched by +gnome-session-binary. The boot recovery result is complete with an empty retry +list: enumeration succeeded without a port reset. Its boot_seconds field is the +job's initial timestamp, before the mandatory wait; services began after the +30-second window. This does not qualify recovery during a real enumeration +failure, individual root-port switching, or the exact physical cold-power +sequence. No agent-initiated reboot, USB reset or motor movement occurred. + +Owner requested three collapsible blocks in the existing vehicle surface and +the onboard device surface. See 22_BOARD_SETTINGS_SURFACE.md. Shared DG Inspector +composition now holds computer information, board settings, and devices. JSON +layout persistence uses independent section patches, separate vehicle files in +Core and the local presentation store in Node. Navigation cannot discard a +pending save. Empty/all-closed layouts, invalid data and concurrent changes are +covered. Inventory lifecycle remains outside the collapsing content. + +The global drive profile and assignments moved out of individual VESC cards. +Changing 1x1/2x2 preserves existing compatible UUID bindings and never commands +motors. New limits.read exposes the native Tool-decoded motor, battery, speed, +watt and duty settings. It is read-only; no hardware ratings, arbitrary reserve, +power write, motor recalibration, or direct OS configuration was introduced. + +Local checks: two API/storage tests, five layout state tests, seven VESC UI +tests, 93 architecture/plugin checks, both TypeScript checks and active Core +production build passed. All 102 VESC synthetic tests passed. Real Core browser +QA confirmed that closing computer/settings survives a full page reload and +reopening the vehicle; both assigned controllers remain visible. The canonical +8000 LaunchAgent was restarted through its exact process group and new health +and layout API were accepted. + +Qualified Ubuntu source ffed12d0fba14f693d52d329 passed all 17 jobs, including +Node build/UI tests, Go race tests, and environment/USB/VESC regressions. +Package 0.8.38-1 SHA256: +cd6fd8bcc2f31f87cad8b406893084ec9d8441bebf555c424c7db5bc66fc2dd6. +Owner release d22b3c002f38c1d842b35526 SHA256: +3cde842b1f96467930460ff19e716574b7236a308322bdd720400701d558f014. +APT plan: upgrade only mission-core-node from 0.8.37-1, no additions/removals. +The artifact-owned local installer was opened and the owner was asked to enter +the Ubuntu sudo prompt. Installation and real limits-read acceptance pending. +Ops direct instructions endpoint was retried and still failed at HTTP transport; +this ledger is local evidence, not a claim of Ops publication. + +Browser QA also confirmed keyboard Enter toggling and persistence of the empty +all-closed layout after reload. The original all-open layout was restored after +the test. The installation check still reports 0.8.37-1; the prepared 0.8.38-1 +installer awaits the owner's local sudo entry, so new Node UI and live limit +readback are not yet accepted. + +Owner entered sudo and 0.8.38-1 installed successfully. Acceptance caught a +release integration defect: the bundled VESC driver declares 0.6.5, while the +Node model registry still required 0.6.4. Node correctly rejected the mismatched +driver snapshot, leaving provisional USB entries instead of the confirmed +controllers. This is an application admission defect, not evidence of USB +failure. No port reset, environment reconfiguration or controller write was +used as a workaround. + +Corrective package 0.8.38-2 aligns the Node registry with the bundled 0.6.5 +driver. A Go regression now reads both bundled driver and preparation metadata +and compares their versions to the Node declaration. Source snapshot +b0af9cd57565e35f41554380 SHA256: +a92d0bc5695624846afe6ab2056c261ca9df8f247611db5f50b2747552fd2e06. +Ubuntu qualification and corrective installation are in progress. + +Corrective qualification completed in 256.927 s: all 17 jobs passed, including +the new cross-package version regression in the Go race test run. +Package 0.8.38-2 SHA256: +9443c079d4396adc569445ccbe745152c164732b31474ac526cd2b5eb1423a94. +Owner release 851ee3935d7db0de2d6be048 SHA256: +348fa611c9b0a2ed361c144c4a6ec2798c45a0a4952f2bab7123f10f892ad4ba. +APT simulation upgrades only Node 0.8.38-1 to 0.8.38-2, without added or removed +packages. The release opened its local Ubuntu installer; OS sudo authorization +and live read-only acceptance are pending. No direct OS edits were made. + +After the corrective installer launch, the board stopped responding to SSH; +Core's last observed heartbeat was 12:51:14 local time. Bounded Tailscale status +inspection reported the local client Running/online and the target Mini +offline; its existing tailnet route remained on the Tailscale interface. Two +SSH checks timed out. These observations do not establish whether the install +finished, or why the board went offline. Owner was asked for the visible Mini +and installer state; no reboot, USB manipulation, route change or additional +installation attempt was initiated. Post-install identity and limits-read +acceptance remain pending until the board returns. + +Owner subsequently reports a black Mini screen. Fresh bounded checks still +show the Mini offline in Tailscale and SSH timing out. The owner was asked to +try a single Shift/mouse wake and report the power LED / monitor signal state, +without a reboot. Static audit of both immutable source snapshots confirms +identical preinst/postinst/prerm/postrm, installer and launcher scripts. The +normal upgrade path restarts Mission Core services; no suspend, shutdown, +reboot, display-manager stop or network stop was found in that path. VESC +preparation reloads udev rules and triggers change only on discovered VESC tty +devices; startup port recovery is not started by the installer. This audit is +not proof of causality or exclusion: the actual last completed installer step, +system journal and host resource state are unavailable while the Mini is +offline. No new package, OS mutation or hardware command was issued during +this incident investigation. + +Owner identified a loose cable and restored it. The Mini returned on a new +boot; Node 0.8.38-1 is fully configured, `dpkg --audit` is empty, and Node/VESC +services have zero restarts. Startup USB recovery again completed without any +port retry. Root filesystem has about 340.8 GB free. The prior boot journal ends +without an orderly shutdown entry in the inspected tail. The cable report and +recovery support power interruption; no software shutdown was commanded. + +The interrupted release's staged deb was truncated to 109051904 bytes instead +of 218843100. The original installer archive still matches its SHA256; scripts +and release manifest also match. The launcher's checksum guard rejected the +truncated staging, and no 0.8.38-2 installation had been completed. Existing +staging is preserved. The product launcher now writes into a temporary file, +fsyncs it before publication without overwrite, and fsyncs directories before +opening sudo. It continues to reject modified files and symlinks. Four focused +interruption/idempotency/integrity tests passed locally and on Ubuntu; they are +also added to future Linux build qualification. + +An artifact-owned temporary owner-release build repackaged the unchanged, +qualified 0.8.38-2 deb. The first wrapper lacked two installer inputs and failed +before producing a release; the complete second wrapper passed its four tests. +Wrapper SHA256 a4cbc35f1bf5af5fa62f60920c389fe54c0d5f84cbd574b02cb696d400f4df2d. +New owner release 3f418604a94057e97414d71a SHA256: +b4eb8ba129c4ba6c8ea1750be6a85aba5c2dbdcaa98abb92c56a47d22377e337. +APT simulation remains one Node upgrade with no additions/removals. Its local +Ubuntu installer was opened; owner sudo and live acceptance remain pending. +No installed OS file or controller configuration was manually repaired. + +Owner asks whether the tracks can be fitted and repeats that a contact was +torn from wiring labelled Hall, with side/contact unknown and no soldering or +replacement pins available. Archived canonical FOC receipts confirm LEFT +sensorless and RIGHT Hall calibration; independent and simultaneous unloaded +30-second tests and owner RC checks passed. The separate Hall comparison +remains incomplete, loaded startup is unaccepted, and the previous LEFT +four-state observation alone does not identify a physical broken pin. Owner was +advised to finish the Hall investigation while the drivetrain is unloaded; +there is no new motion authorization and no diagnostic motor run in this entry. + +The owner subsequently authorized necessary unloaded diagnostics and confirmed +tracks removed, rover raised, transmitter off and attendance. Asked about the +means of interrupting the noninterruptible FW 5.02 native Hall cycle, the owner +identified an Anderson battery connector as the only disconnect. Its exact +model and load-break rating are unknown; no instruction to unplug under load +was given. No new Hall or other motor procedure has started. The existing +0.8.38-2 installer still waits at local sudo; installed Node remains 0.8.38-1. + +The owner supplied three transmitter photos. Exterior matches the official +FlySky FS-i6S diagram, with Robcom Venom Drone marking; hardware/firmware +identity remains provisional until its About screen is read. The old receiver +photo identifies FS-iA6B. Official FlySky Mix/Models/failsafe documentation and +VESC 5.02 PPM source were reviewed. Existing archived PPM settings decode as +Duty Cycle on both controllers, with different response curves/ramps; no +configuration was changed. The two requested tank/arcade profiles and their +input/fallback requirements are recorded in 23_ROVER_CONTROL_PROFILES.md. +No native radio mixing capability or live profile switch is claimed accepted. + +Owner clarified the field-control requirement: an enabled, neutral transmitter +may accompany autonomous/remote driving; stick input must immediately take +authority without a UI mode switch and latch out all Core sources until an +explicit neutral handback. This is separate from selecting tank/arcade mapping. +Read-only source audit confirms the native decoded-PPM read and existing bounded +test latch/250 ms PPM-output leases. Neither full radio-channel capture nor a +qualified continuous driving arbiter is claimed. Firmware-side lease expiry +does not cover faulty software that keeps renewing it. The permanent authority +contract and maintenance-calibration exception are recorded in plan 23. No +network scan, radio/receiver change or motor command was performed in this audit. + +Corrective owner release 3f418604a94057e97414d71a completed at +2026-09-24T11:04:21.135514Z, duration 17.846 s. dpkg confirms Node 0.8.38-2 +fully installed; Node and VESC services are active with zero automatic restarts. +Core now admits exactly two verified VESC snapshots at plugin version 0.6.5, +both publishing board-settings capability. The 1x1 profile remains revision 2 +with the same UUID assignments; test_active and rc_latched are false. + +A bounded engineering probe through existing Core/Node SDK actions performed +six read-only vesc.input.read calls, three per controller, without motor, +lease or configuration writes. At 11:05:39–11:05:46Z the RIGHT decoded input +was approximately −0.058 to −0.060 and 1.470–1.471 ms; LEFT was +0.074 to +0.076 +and 1.537–1.538 ms. These are raw inputs near the archived neutral bands, not +proof of radio-link state or independent transmitter switch positions. + +The owner then corrected the switch hypothesis: motors remain controllable +with all four transmitter toggles down. The proposed SWA comparison was +cancelled; initial readings carry an operator-reported condition only and do +not establish causality. No new Hall/FOC procedure or driven test was started. +Private installation, fleet and RC receipts remain in native-probe evidence. + +Owner now requests stop-first RC takeover: first stick input cancels autonomous +and remote motion, subsequent input may drive manually. Clarification was sent +to distinguish another packet of a held stick from a deliberate second gesture +after neutral. Existing direct PWM and expiring test leases do not implement +stop-first; simply releasing the lease would pass the original deflection to +the motor. This limitation and the required command-revocation/neutral boundary +were recorded in plan 23. No live control change or driven test was performed. + +The owner explicitly confirmed the sequence: stop → neutral → manual control. +Plan 23 now records this as accepted, including both input channels, rejection +of delayed Core commands and no automatic autonomous resumption. The first +held deflection cannot become a drive command merely because another packet +arrives or a delay expires. Ordinary gestures once already in manual control +do not repeat the takeover procedure. + +A bounded source audit checked the cached FW 5.02 commit +3f670137e27e6e383fa79c50cc6b1fa85aab1554 against its Git tree blob hashes. +Safe Start is not rearmed by expiry of app-disable output. Persistent app +configuration writes, indefinite output disable and restarting applications +through CAN-mode configuration were rejected as takeover mechanisms. The +current native release sends zero current, not a verified braking or neutral +gate command. A healthy-Mini wait loop cannot guarantee the same gesture +semantics after loss of Mini/USB. Coordinated actuator-side support remains +necessary to qualify the full requirement; no firmware or working RC settings +were changed. The FS-i6S manual's assignable-switch semantics were also recorded; +actual switch assignments and transmitter firmware remain unverified. + +Official VESC documentation identifies stock LispBM support from FW 6.00 as +a candidate for controller-resident input arbitration, not an accepted solution. +It documents PPM value/age and PPM override; direct-command bypass, coordinated +multi-controller behavior and script-failure handling still need qualification. +The hardware marker alone is insufficient for firmware selection. The owner was +asked for the controller manufacturer/model if known. No update or script was +uploaded, and no motion was commanded. + +Owner requested software-only controller identification before considering +physical access. A bounded audit used eight existing read actions through +Core/Node/native Tool: backup, telemetry, PPM and CAN ping for each controller. +All completed. Read-only SSH collected Linux sysfs USB descriptors without +opening serial, resetting ports or changing the host. Both distinct VESC UUIDs +and FW 5.02 / 75_300_R2 were confirmed; USB descriptors and USB serial strings +are identical. Each backup decodes into 151 motor and 149 application parameters. +Core history contains both new backups, and their motor/app SHA-256 values +match the accepted 2026-09-23 21:05 UTC versions. Calibration was preserved. + +Both CAN queries returned no peers; physical wiring is not inferred from that +result. No movement, configuration write, restart or firmware operation occurred. +The manufacturer and commercial board model remain unconfirmed: Flipsky's own +75-series documentation explicitly describes multiple boards using 75_300_R2; +this does not identify these boards as Flipsky. Private receipts, decoded +passports, USB evidence, archive acceptance and hashes are saved under the +identity-audit-20260924 artifacts. Current-version diagnostics do not require +disassembly; exact update compatibility remains a separate evidence requirement. + + +## 2026-09-24 — Hall preflight and sensorless standstill, Node 0.8.39-1 + +Before any Hall cycle, read-only link.check stopped with not_idle: LEFT +reported -161 ERPM, zero wire duty and about 0.08 A. Repeated individual reads +reported -140 to -168 ERPM, zero input current/duty and 0.06–0.10 A motor +current. RIGHT reported zero ERPM. Owner explicitly observed the LEFT leading +sprocket fully stationary. No driven command or native procedure was sent. +Private preflight, idle-read and idle-observed receipts retain UTC/monotonic +identity and raw telemetry; their SHA256 values are respectively +229df6a4abbe55d03e0bbfcbc1331647e2bd6768e6d2b7b16ac9be4736f07734, +adab11366c597579259b53bdecc0b9e602a197b5933665cdcb4201b540a13738, +d39185797ddc1b3e99385e922161aabac1121df67c94922d099eae212cc6825a. + +Pinned FW 5.02 mcpwm_foc.c (3f670137e27e6e383fa79c50cc6b1fa85aab1554) +continues observer and PLL updates while undriven; get_rpm and tachometer use +that phase estimate. Changing tachometer is not independent movement evidence. +This explains why the old ±30 ERPM stationary gate cannot reliably admit an +attended sensorless Hall measurement. It does not prove the observer's error +magnitude or motor state without the operator's physical observation. + +The correction is scoped to Hall measurement. New requests must explicitly +confirm all motors physically stationary. For FOC sensorless mode only, that +observation replaces the speed gate while wire duty must be exactly zero; +finite speed is still required. Other idle electrical/fault/temperature bounds +remain, battery current must be within ±1 A, and fresh telemetry plus PPM +neutral are checked ten times before any lease/current write. Sensored Hall +preflight and every ordinary motor/FOC test retain the existing speed gate. +Raw preflight values and the observation flag are archived in the Hall receipt. +The Tool algorithm, current, duration and no-table-write contract are unchanged. + +Core and Node reuse the existing Hall confirmation control; new clients send +the observation field only to a board advertising the new capability. The +0.6.6 driver rejects old clients lacking the explicit observation. No live +runtime bypass or OS edit is introduced. Package qualification, installation, +observer resynchronization and actual Hall comparison are still pending. + + +Local acceptance: all 109 VESC tests passed, including seven Hall standstill +fault-injection cases. The active Core passed four architecture tests, +TypeScript, all 916 unit tests and production build. Its existing port-8000 +process serves the exact new index SHA256 without a server restart. In-app +browser verification shows the Hall observation text and a disabled measurement +button while unconfirmed, in normal and expanded presentation; no measurement +control was activated. Escape was exercised but did not exit the existing +expanded vehicle surface; this unchanged window behavior is not accepted by +that check and was not modified in the Hall fix. + +Immutable source b6097066b4068f72483c4b68, SHA256 +37896e9d6b7df1b6f0170aab073761aaa81de2ba05cd48ace9508c1bc1749c16, +was transferred and verified on the Mini. Its unprivileged, bounded build is +running; installed runtime remains 0.8.38-2 until owner installation. Exact FW +source blob 416eacbadb2696081d5e85e4342cd798f5d08906 was verified against the +pinned Git tree. Ops instructions endpoint again failed at HTTP transport; +no Ops write was attempted or claimed. + + +Ubuntu qualification completed in 255.491 s; every recorded job passed, +including VESC regressions, Node UI build and Go race tests. Node 0.8.39-1 deb +SHA256 e0ceb0116be62962944657723d30bf14498491c5dc34902be00845d716a87b26 +(218843958 bytes). Owner release f196781a2f4ff411ada25090 SHA256 +09eed256684a2c70b52318e33a6df02a01848feb644f2e50fac6c7129ede0f51. +APT simulation upgrades only mission-core-node 0.8.38-2 → 0.8.39-1 with no +added/removed packages. The artifact opened its local Ubuntu installer; owner +sudo entry and live acceptance are pending. Hall comparison has not started. + + +Owner entered sudo. Installation e96d63c6a3364b25bde5bb3a8813a12c completed +at 2026-09-24T12:10:15.346435Z in 17.851 s. dpkg confirms 0.8.39-1; +Node and VESC services are active/running with NRestarts=0. Fresh Core inventory +confirms exactly the two original UUIDs, plugin 0.6.6, the required Hall +standstill capability and no active/latched procedure. No port reset, firmware +flash or calibration write was performed. Observer resynchronization was +requested before the first actual comparative Hall measurement. + + +Both attended comparative measurements completed through Core → Node → native +VESC Tool, after fresh owner confirmation of stopped motors, removed tracks, +raised rover and transmitter off. LEFT operation began 12:12:16.619604Z and +finished 12:12:41.467723Z; its native cycle lasted 12.224 s. Result: +[255,173,255,120,255,21,255,68], states [1,3,5,7], firmware success false. +Owner observed actual slow backward movement followed by forward movement. +RIGHT began 12:13:12.520652Z and finished 12:13:36.369798Z; native cycle +12.225 s. Result [255,167,97,133,37,198,71,255], states [1,2,3,4,5,6], +firmware success true. Both report unchanged configuration, no configuration +write, confirmed release and no issues. Each receipt contains twenty idle +preflight observations and 119 cycle telemetry samples. LEFT/RIGHT private +receipt SHA256: 5f4972011019b53dc9803b47eeffd357de647ac161a2949b49473ecb702877c1, +1faa352ce8eed1483a46d9c92eb10b5305e3dcaf32ffa98c2833e1103720023f. + +Diagnostic conclusion: LEFT has a reproducible incomplete Hall signal during +observed movement; bit zero remains high in all returned states. RIGHT passes +the canonical six-state measurement. This is consistent with the owner's +damaged contact on the LEFT Hall circuit, but USB cannot distinguish exact +wire/contact, sensor or controller input. The LEFT remains sensorless and the +RIGHT remains Hall-controlled; the fault is localized, not repaired. Loaded +startup and field driving remain unqualified. + +Owner then requests plainly visible sustained forward and reverse rotation +instead of further small Hall movements. Hall comparison is complete; no +additional Hall/FOC cycle is needed. The next product increment will add signed +speed testing to the existing rotation card, retaining current limits and +requiring a separate physically stopped confirmation before each direction. +No automatic reversal of a coasting sensorless motor is authorized by this +implementation plan. Existing native adapter currently admits only 0..3000 +ERPM, so reverse requires a versioned adapter/package update, not a bypass. + + +## 2026-09-24 — attended bidirectional rotation, 0.8.40-1 (qualification) + +Owner requested visible sustained forward/reverse rotation after the completed +comparative Hall diagnosis. Extend the existing single/profile speed test with +a direction selector. Native VESC Tool `Commands::setRpm` receives signed ERPM; +no firmware, sensor mode, inversion setting or calibration rewrite. Bound remains +300–3000 ERPM magnitude, current ceiling 30 A, observed hold duration up to 30 s. +Use signed ramp and speed tolerance; wrong-direction motion never earns hold time. +Each operation starts independently from an explicitly observed physical stop. +No automatic reversal on coasting motors. UI clears the confirmation after each +operation and direction change; older driver capability disables reverse. + +Sensorless FW 5.02 idle PLL drift established in the prior Hall investigation +also affects normal bench preflight. Attended speed/profile/release requests now +require a strict standstill confirmation and ten fresh neutral/electrical samples +from every connected controller. Sensorless ERPM is recorded, not used as physical +standstill proof; finite values, zero PWM, low motor/input current, voltage, thermal, +fault, identity, CAN, receiver, cancellation and pending-restoration gates remain. +Hall-mode speed still blocks; legacy current pulse and FOC retain their old gates. + +Version ownership: Node 0.8.40-1, VESC plugin 0.6.7; native adapter delivered through +the versioned installer/preparation payload only. Bounded Ubuntu native build +383ac3eb5d0bdf9a3e3b3584 completed in 37.10 s with 13 checks, including upstream +positive/negative RPM serialization and denial of hardware in offline mode. +Upstream objects unchanged. Runtime SHA-256 +`dab6dc61fe4ff29f734a69e372e20ec66ffcc36d1513f4f89b2e4c29f311f45a`. +119 Python VESC regressions passed, including reverse 30 s hold, current-limit +restoration, per-direction configured speed bound, missing/invalid observation, +late PWM rejection, observed idle drift, RC preemption and complete-profile reverse. +Installation and physical rotation remain pending at this entry. + +Qualification and handoff: the immutable Node source artifact +`4a5e80a91a7a1526795a3f2c` (SHA-256 +`2fb53048d741c1d3da098163b9b74de688289c8f2b1f52e6197f579f474f06a7`) +passed the bounded Ubuntu qualification suite. Owner installer +`86a0dccb179cf082e6548d64`, SHA-256 +`a1360a296b11d65f90288a40c8b6c4fc8e7d67401ccd3ab74237df2b679caf8a`. +APT simulation upgrades only Node 0.8.39-1 → 0.8.40-1, adds/removes no packages. +Local Ubuntu installer was launched for owner sudo entry. No ad-hoc runtime +or OS patching. Transfer reused a disposable staging copy as rsync basis (previous +immutable source preserved); final source SHA verified before execution. + +Operator Core: 4 architecture tests, TypeScript, 916 unit tests and production +build pass. Only VescMotor.tsx and model.ts were promoted into the active checkout. +Canonical 8000 serves the matching new index +`c71c979185d48c90701d7569b947e1192c9f81be72bccab608517b1ec43c43c6`. +Browser verifies direction control, old-driver reverse disabled, initially +unchecked observation and legible 30 A/30 s fields. No motor command during UI QA. + +Physical acceptance: Node 0.8.40-1 installed successfully in 18.52 s, finished +2026-09-24T12:36:40.136111Z. Node and VESC services active, zero restarts; fresh +Core inventory verified both UUIDs with plugin 0.6.7 and signed-speed capability. +After fresh owner confirmation (tracks off, raised rig, TX off, observed physical +stop), complete 1x1 profile ran at +3000 ERPM, 30 A ceiling per motor, with +30.0447 s common hold. Owner saw both rotate evenly and confirmed full stop. +Then separately authorized -3000 ERPM yielded 30.0474 s common hold; owner saw +both rotate backwards at similar speed and stop. Both operations outcome duration, +release confirmed, limits restored, fault codes zero, no transport failures. +Forward steady current was approximately 2.7/3.0 A: 30 A is a ceiling, not a forced +current while holding speed. Original calibration/configuration remained in use. +Raw operation and installation receipts with hashes are retained privately in +native-probe/rotation-040-*; these attest unloaded rotation only. Left Hall hardware +fault remains localized and unrepaired; RC profiles and new takeover protocol are +separate outstanding work, not implied by this bench acceptance. + + +RC/failsafe follow-up began with read-only Core/Node operations and owner-confirmed +TX off / raised stationary rig. Both configuration backups saved; both inputs +within configured neutral, zero PWM/input current and fault 0. Different existing +PPM ramp/expo settings recorded; no configuration write. Details and remaining +acceptance gates: docs/node/24_RC_FAILSAFE_ACCEPTANCE.md. No new package needed +for initial reads. Direct Ops MCP instruction retrieval again failed at HTTP +transport; no Tasker write claimed or alternate card API used. + +2026-09-24, unattended development authorized by the owner for approximately +15 minutes: no additional hardware test or configuration write was performed. +The previously nonneutral TX-on capture was clarified by the owner as manual +stick movement, not spontaneous startup. Follow-up neutral evidence and the +pending TX About/Failsafe questions are recorded in 24_RC_FAILSAFE_ACCEPTANCE.md. + +Added an isolated executable prototype in packages/rover-control and the +Control Station developer-only rover-control-preview tool. Tank/Arcade mixing, +semantic-axis mapping, UUID fan-out (2/4/10 motors), strict desired-profile JSON, +and stop → neutral → manual authority transitions are tested without a hardware +adapter. RC takeover observes its configured full axis set even when Arcade +uses only one stick to drive. Missing axes do not become neutral. Existing +MotorTest authority, firmware, system services and package versions are intact. + +Validation: 21 final focused behavioural tests passed; 4 architecture checks, +Control Station typecheck and a 935-test full UI pass completed before the final +extra monitored-axis test. Preview typecheck and minified self-contained build +passed after the final change. Browser visual QA is not claimed: the Browser +use URL policy rejected navigation to the local HTML artifact; no alternate +browser/server workaround was attempted. Network is disabled in its CSP, and +source has no serial/Core transport. Private artifact manifest/logs/trace live +in outputs/rover-006-control-prototype. The running Core still returns two +verified online VESCs with test_active=false. No installer or password needed. + +This prototype does not solve independent receiver fallback or qualify physical +stopping. Current FW 5.02 does not provide the age/live-link evidence or the +independent stop-first enforcement required by the reference contract. Production +profile activation stays absent pending that integration. Model timing constants +are synthetic fixtures, not measured rover safety limits. Direct Ops MCP remains +unavailable at HTTP transport; local evidence is preserved without claiming an +Ops update. Rollback: remove the unreferenced prototype/tool artifacts only; +there is no installed board change to roll back. + +2026-09-24 RC failsafe bench acceptance: owner found Functions/Failsafe on the +touchscreen and reported 0% on all ten channels. An initial right-side attempt +returned the stick before removing the TX battery, so it was explicitly excluded +as loss-of-radio stopping evidence. The repeated right-side test held the stick +until battery extraction; owner confirmed immediate observed stop. Same procedure +on LEFT also physically stopped. Final TX restoration with both sticks neutral +caused no motion, confirmed by the owner and zero PWM in recorded telemetry. +Completed private captures b208d87f / cc289f6f / 6811a686, with full identifiers +and hashes in docs/node/24_RC_FAILSAFE_ACCEPTANCE.md. No runtime/firmware/settings +write, output lease, alive or Core motor command; only shipped input.read and +telemetry.read. This qualifies the observed unloaded RC loss/neutral restoration +scenario, not exact response latency, loaded braking, Mini-independent new +stop-first arbitration or repaired LEFT Hall hardware. Continuing read-only TX +Mix/channel inspection for the requested profile integration. + + +## 2026-09-25 — observation channel, Node 0.8.41-1 + +Versioned Node 0.8.41-1 / VESC integration 0.7.0 adds the separate paired mTLS +remote-control channel and native watchdog. Native source artifact +ad291aa57e2b828f14619673 and Node source artifact 4f5ded93cde5b3d271fbef5c +were built and qualified in bounded Mini staging. Node qualification peaked at +2,907,676,672 bytes under its 3 GiB ceiling. Native offline checks, 127 VESC tests, +Go race tests, DG packages/catalog/registry, Node UI and environment/USB/startup +qualification passed without driving hardware during the build. + +Package SHA-256 e0d4d43ed026b3f8e841492793942cfd1b7cb761da1da2c2e40951b9e120de04. +Owner installer a4f1163407e76521b6139ab6, SHA-256 +076576893e54b69377910d8e1bcf85596629e9d6644e0895af743be01ca2badf. +Its plan upgraded only mission-core-node 0.8.40-1 to 0.8.41-1; no other package +addition/removal. The owner-authorized local Ubuntu installation completed; +dpkg version and active Node/VESC services were read back over SSH. The package +owns every installed file and service change; no manual board runtime patch. +Rollback uses the preceding versioned owner-release artifact, not hand edits. + +Core 8000 receives fresh RIGHT samples through the new channel, supported=true, +state=observing, session_id=null, controlling=false. LEFT is not enumerated in +Linux; its profile UUID binding survives. USB descriptor errors -71 predate +installation; owner confirms reconnecting USB/power. No motor command or USB +reset was issued in this implementation session. Physical root cause and +both-controller channel acceptance remain open. Attended remote movement, +release/blur/timeout and RC stop-neutral-manual acceptance are still outstanding. +Stock FW 5.02 does not guarantee that protocol independently of a failed Mini. + +Full implementation, UI acceptance and limitations are recorded in +25_OBSERVATION_AND_REMOTE_CONTROL.md; private hashes, qualification and raw +read-only evidence are under outputs/rover-006-observation-control-20260925. + + +### Follow-up 0.8.41-2 — observed sensorless idle and session completion + +Owner restored both USB controllers by disconnecting/reconnecting the battery +at 11:35 MSK, not by restarting Mission Core. Twenty read-only samples contained +both assigned UUIDs. One freshly authorized API trial at 11:38:46 was rejected +before movement at reported sensorless duty=0.001; no positive demand or volatile +limit write was reached. Pinned FW computes that quantity from measured phase +voltages even undriven, so the previous exact-zero admission assumption was +incorrect. Follow-up permits one encoded quantum only in the explicitly +owner-observed sensorless case, while retaining current, fault, temperature, +voltage, RC neutral and physical-observation requirements. + +The same follow-up reports ordinary terminal input leases as stopped after +cleanup. Failed release/restoration still reports fault. Actual loop tests now +exercise expiry after sending speed through the session wrapper, plus a failed +controller during cleanup. All 130 VESC tests pass. + +First qualification stopped on a mismatched declared driver version; the Node +model registry was corrected to 0.7.1. A subsequent passing package was +superseded before installation to include normal-session completion. Final +source artifact b889d129c87de5b811c0ee6c, SHA-256 +74c48e186d8877c92d1501b7dbbd43943e476c4f2b8cf89a136b1d8aea227981, +passed the complete bounded Mini qualification. Package SHA-256 +fb1a484ddaad2e8ff3dc1ca99d7ba6f5fb5d1d78b9075e04643a727eba100f9e, +218,851,386 bytes. Owner installer f1a536e5d42ef73dabf1d7f0, SHA-256 +9b71a345928c198a68fad9af0f8a426ef0cf3ff8c79deb0d33729fbd88d5aa09. +APT simulation upgrades only Node 0.8.41-1 to 0.8.41-2, no additions/removals. +Owner entered the local Ubuntu authorization. Installer completed successfully +at 2026-09-25 09:08:23 UTC (24.9 seconds), all steps exit 0. Installed package +0.8.41-2 and VESC runtime 0.7.1 verified by read-only SSH; both services active. +After observation refresh both assigned UUIDs report fresh values (14–205 ms), +zero currents/duty/faults, no active control session. Evidence: postinstall +receipt and API samples in the private observation-control evidence directory. +Attended movement retry remains pending fresh owner observation. No firmware, +calibration or persistent electrical-limit change is part of this package. + +### Follow-up 0.8.41-3 — diagnose preparation lease cancellation + +Owner authorized one bounded forward trial after installing 0.8.41-2. The first +helper call at 12:18:51 MSK declined stale telemetry before arm. Read-only refresh +restored both fresh UUIDs; the armed trial at 12:19:28 ended stopped about five +seconds into preparation, with no forward demand sent. Browser/Core heartbeats +continued at approximately 100 ms. Neither Node nor VESC restarted. The cause +of the lease cancellation was not preserved by the earlier transport logging. + +The follow-up adds only a bounded private channel diagnostic flight recorder +to Node. VESC runtime remains 0.7.1; native Tool, deadlines, current limits and +output behavior are unchanged. Source artifact a93510d58156a2ec1ed8fa74, SHA-256 +ea46f9e4666523a02cf869565c65ab982763f053fa43987dd019cc97e059ee76. +Slow SCP was stopped before build execution; delta staging from the existing +source artifact produced an identical full SHA-256, verified before launch. +Qualification runs in the artifact-owned 3 GiB / 150% CPU temporary cgroup. +Installation and further physical acceptance remain pending. + +Qualification completed at 09:33:39 UTC in 263.8 seconds: Go race tests including +the bounded diagnostic history cases, Node UI, environment, installer and all +130 VESC tests passed. Package SHA-256 +bb7d23fe7ae134d1249b60e92aebbd5f09ef40a165ff12dec77f821950b1b8e3, +218,855,416 bytes. Installer c400214393c2c5c4c26e6489, SHA-256 +48cfe00d4d54cf3825177deafb097efb66cb8a9d2038657e680502e0ca271a8b. +APT simulation changes only mission-core-node 0.8.41-2 to 0.8.41-3, no other +package additions/removals. Before launch Core reports no active session and +stopped. The local Ubuntu installer was opened; OS authorization is pending. + +Node 0.8.41-3 installation completed successfully at 09:36:34 UTC in 18 seconds +after owner-local Ubuntu authorization. Package version and active Node/VESC +services verified. Both assigned UUIDs produce fresh readings (190/199 ms), +zero motor current and fault codes; no control session. Owner observation is +requested again before one bounded repeat; no motor output sent after the +12:19 preparation abort. + +### Follow-up 0.8.42-1 — separate commands from telemetry round trips + +The 12:38 and 12:46 MSK attended attempts ended during preparation without a +forward command. Node diagnostics localized short-lease consumption to serial +request/response timing. TCP_NODELAY reduced some delays but did not resolve +the admission failure. No new USB fault was established by these attempts. + +The new Node streams latest Core intent independently from telemetry and feeds +the local owner at 20 Hz. Commands carry their original Core monotonic expiry; +conservative clock bounds subtract network time rather than starting a new +400 ms lease on receipt. Reconnect must cross an acknowledged null command, +and interrupted IDs are retained even if they never reached the driver. +Native VESC runtime remains 0.7.1, its output watchdog remains 200 ms, and the +firmware, motor calibration and electrical limits are unchanged. + +First source 6a008b44ecdd7d4ba550795b passed bounded Linux qualification but was +superseded before installation to include the undelivered-session tombstone +regression. Final source 4721a12daa5599d3e6cd3e19, SHA-256 +5420a70de810a80234cb586695109c2e38f857dfe1721f103dac2c2ad1cccc4e, +466,985,414 bytes, is undergoing the same qualification. Both staging copies +were transferred as deltas and fully SHA-256 verified before execution. No +installed Mini files or system configuration were patched. + +Core transport.py, registry.py and rover_control.py were promoted after 58 +Fleet regressions passed against both development and active operator sources. +The existing canonical launchd service was restarted only with no active +session; 8000 and fresh telemetry for both assigned UUIDs recovered. Legacy +Node 0.8.41-3 remains installed until the final package passes qualification +and the versioned owner installer completes. New motion acceptance is pending. + +Final qualification completed: all 18 jobs exit 0, including Go race tests and +130 VESC tests. Package 0.8.42-1 is 218,865,950 bytes, SHA-256 +b091b9ced7310e6aacae12c6911170e3acbd4f80138e3fe65863a49a6e2a8bc0. +Installer f80c3eb98fef89e31e93b076 is 218,888,341 bytes, SHA-256 +2ce07d7b266a1ae31640bcdeec9bdd8c8c945099f4ef8368bb5ff502ede07b1a. +Its fresh APT simulation upgrades only mission-core-node 0.8.41-3 to 0.8.42-1, +with no new or removed packages. No active control session was present before +launching its local Ubuntu window. Owner OS authorization is pending; do not +confuse opening the installer with installation or movement acceptance. + +Owner authorization completed; 0.8.42-1 installed at 10:22:27 UTC in 18.1 s, +all steps exit 0. Node and VESC services are active. Ten-second read-only +verification contained both fresh UUIDs, zero currents/faults and no active +session. A fresh owner-observed trial at 10:25:53 UTC nevertheless ended in +preparation without forward demand. Stream/local-loop timing improved, but +one retained update crossed the prior command's deadline by roughly 20 ms. +The session remained retired as designed; no automatic motion retry. + +Candidate 0.8.42-2 removes periodic waiting for new commands on Core and Node, +without increasing the 400 ms expiry or native output watchdog. Core: 59 tests +passed. Node uses a coalescing signal, not a command queue, and retains stopped +session tombstones. Qualification/installation is pending; 0.8.42-1 remains +the installed predecessor. + +Final 0.8.42-2 source: 82ecb65d554eb431616494ee, SHA-256 +3b36ee72e923a44c392706b8fb8c159cc22360ec7e42f740efbd367d8481ff54. +Candidate cb7441a86c04cb2cdd91652c passed qualification but was superseded +before installation to reject malformed/non-integral command sequences before +comparing latest intent. This prevents invalid JSON types from disrupting the +Go receiver. The final candidate is undergoing the same bounded qualification. + +Final qualification passed all 18 jobs. Package 0.8.42-2: 218,867,020 bytes, +SHA-256 0be7052996013522f2240b44e0fca2284e6b357675f83fa8a6210ce61e1027b1. +Installer fd7d351f1882ed2131cd5057: 218,889,411 bytes, SHA-256 +74fdb94bc10cf8a54d82e62e58f1539f6a179c2f9b151f2dd021edde9580f311. +APT plan upgrades only mission-core-node 0.8.42-1 to 0.8.42-2, no additions +or removals. No active session before opening the local Ubuntu installer; +owner OS authorization is pending. No further motion has been attempted. + +Owner OS authorization completed: final 0.8.42-2 installed at 10:47:29 UTC +in 18.67 seconds, all installer steps exit 0; Node and VESC services active. +Forty read-only samples over ten seconds confirmed observing/no active session. +The final twenty contained both assigned controllers, at most 216 ms old, +with zero motor/input current, duty and fault. Fresh owner observation has +been requested before any new motion; the five previous failed preparation +attempts remain failures, not movement acceptance. + +Sixth attended Core API attempt, 10:52:51 UTC, stopped before forward demand: +"another VESC operation is running". Recorded command TTL remained 323 ms, +so this particular failure is different from the preceding lease expiry. +The remote observer shares operation_lock; _prepare previously attempted +nonblocking acquisition and treated any overlapping read as a fatal conflict. +The trace does not identify which operation held the lock; code and a +concurrent regression reproduce this admission race without hardware. + +Candidate Node 0.8.43-1 / VESC 0.7.2 waits up to 500 ms for exclusive access, +checks the existing input lease every 20 ms and after acquisition, and skips +new observer cycles while the control worker is alive. It does not queue a +future drive or extend the input lease. Tests cover completing an in-flight +read, Stop while waiting, expiry before acquisition, bounded rejection of a +long operation, and observer yielding. Canonical unittest discovery passes +135 tests. A first full pytest invocation incorrectly collected the imported +protocol helper test_packet as a fixture-based test; no product failure was +reported, and the suite was rerun with its canonical unittest runner. +Installation and a separately synchronized physical retry are pending. + +Final source c2d98db61de6722f2a77c4ed qualified: all 18 Linux jobs exit 0. +Source SHA-256 a0854257a11a97dba7f544203a0babde835d144d9ab897f46f28e4f3e6643461. +Node package 0.8.43-1: 218,867,200 bytes, SHA-256 +09fa9bba4595673d1b763cb49d6caee6d5f2519e08ed667e733a07867810ae98. +Installer 38c4764476007a22c2c594a3: 218,889,591 bytes, SHA-256 +cb195603fc5bc490bb2d64d3a7201b71b58479ea5af309963e13b931e05b9379. +The plan upgrades only mission-core-node from 0.8.42-2; no new or removed +packages. No active control session before launching the local installer. +Owner OS authorization is pending. Firmware and calibration remain unchanged; +no further motion has been attempted after the sixth failed preparation. + +Node 0.8.43-1 / VESC 0.7.2 installed at 11:06:32 UTC in 18.49 s, +all installer steps exit 0. Both services active; final 20/40 read-only +samples contained both assigned UUIDs, age <=219 ms, zero currents/faults, +observing/no control session. A fresh attended trial is requested separately. + +Seventh observed Core API attempt at 11:10:39 UTC reached preparing without +the ownership fault, then stopped before forward demand. Sequence 19 arrived +with ~313 ms remaining; sequence 20 followed ~315 ms later, consistent with +expiry at this boundary. The old trial sent a command, synchronously fetched +telemetry and only then scheduled its next input. Telemetry reads introduced +periodic delays up to ~319 ms in its sample cadence. This differs from the UI, +where the command heartbeat and telemetry poll are independent. + +The corrected attended_stream_test.py separates bounded telemetry polling +from 100 ms command renewal, preserves the same 400 ms lease and all existing +preflight/stop checks, and records request timing for every command. Synthetic +checks prove blocked reads do not hold the input path, failures abort and +reader threads terminate. This is a test-harness correction, not movement +acceptance or proof that all transport jitter is solved. A fresh observed +trial is requested; there is no automatic motion retry. + +Core-only timing logs were added to distinguish registry wait, archive and +save delay. All 59 Fleet tests pass; loopback HTTP test needed sandbox network +permission. The active Core received only this reviewed registry.py diff and +was restarted without an active session. Read-only samples: max local GET +179.8 ms, three of forty above 100 ms; retained registry waits 25.9–58.5 ms. +No archive/save delay above 25 ms was reported in the initial capture. Thus a +registry persistence bottleneck is not yet established by these measurements. + +Eighth observed trial at 11:22:27 UTC still stopped before forward demand. +Independent input recording showed local Core command POST outliers 103.4, +166.5, 216.1 and 127.4 ms (normally 2–10 ms). Sequence 17 reached Node with +312.7 ms remaining; sequence 19 followed after 335 ms. Separating trial +telemetry therefore did not by itself solve the delivery problem. + +A bounded read-only macOS sample of the operator Core found JSON encoding and +zlib work on its ASGI main thread. The periodically polled completed planning +report /api/v1/mission-planner/live-tests/active is 2,403,591 bytes and took +218.5 ms for one local GET. Its endpoint fetched the dict in a worker, but +FastAPI recursively encoded it and the middleware compressed it on the event +loop. This shared process also admits rover commands. + +planning_live_api.py now constructs the JSON response and optional gzip body +in the existing thread pool, preserving the full report contract and bypassing +second compression through Content-Encoding. No polling is disabled, evidence +is not removed, and Node, calibration, current limits and leases are unchanged. +13 focused tests passed against development and active Core: JSON/gzip execute +off-loop, exact content survives decompression, empty/failure contracts and +existing planning presentation/compression behavior remain valid. Canonical +8000 was restarted without active control. Sixty ordinary read-only rover +samples over 15 seconds then had max 86.1 ms, p95 64.5 ms and zero over 100 ms; +both assigned UUIDs fresh, currents/faults zero. This improves measured delay, +but does not yet establish motion or field acceptance. A fresh observed retry +is requested separately. Private process samples and device traces stay out +of normal Git. + + +Ninth attended Core API trial at 11:31:08 UTC passed preparation and completed +8 seconds of forward demand at up to 2000 ERPM, with a 30 A ceiling per motor. +The owner confirmed both motors physically rotated forward and subsequently +confirmed both stopped. Final state stopped, release_confirmed=true, zero +motor/input current and fault. Recorded peaks: left 2001 ERPM / 2.88 A motor, +right 2028 ERPM / 2.81 A motor; these are sampled peaks, not current ceilings. +During driving device ages stayed <=104 ms, all recorded fault codes zero. +Preparation retained old motor samples up to 10.1 s while exclusive setup ran; +those samples are not treated as live motion telemetry. Command POST max +81.28 ms, p95 10.05 ms across 201 requests. The normal stop command was accepted. + +This accepts the observed API forward/release path on Node 0.8.43-1 / VESC +0.7.2 and the corrected operator Core. It does not accept physical keyboard +input, Stop/blur, channel loss, RC takeover, loaded or field operation. Those +remain separate checks. No new calibration, firmware, USB reset or OS change +was performed for this trial. Private raw evidence and owner notes are hashed +in the experiment manifest; the previous eight preparation failures remain +recorded as failures. + + +At 11:38–11:39 UTC the owner physically held W in the 3D View after UI arming, +then released it. Owner reports both motors forward, immediate perceived stop +on release and approximately 0.5–1 s before initial motion. Exact key-event +latency was not instrumented and is not claimed resolved. Read-only capture: +393 samples, no request errors; driving observed for about 10 s (the requested +hold was approximately 8 s). Sampled peaks left 2004 ERPM / 3.51 A, right +2032 ERPM / 2.85 A; driving sample age <=113 ms, all faults zero. Release +returned to ready with motors stopped; the UI Stop action then reached stopped, +release_confirmed=true. Final UI explicitly says control disabled. The read-only +recorder exited and no motion input remained active. + +This accepts actual W forward/release, separately from the prior API trial. +Reverse/turns/Tank, Stop while moving/blur, channel-loss and RC takeover remain +unaccepted on the new UI path. Owner startup-delay observation is retained +for a separately instrumented check. No hardware limits or calibration changed. +MISSIONCOR-85 now records both successful trials, their limits and the previous +operator event-loop diagnosis while preserving all hardware/Hall history. + + +Observed S/A/D session, 11:45–11:47 UTC: the owner confirmed reverse on S +and opposite sides on A (left reverse, right forward); also reports D worked +before the agent disabled control. The telemetry records both opposite-side +patterns with neutral intervals. Final state stopped, release_confirmed=true. +The owner reports a repeatable approximately two-second start delay, with +immediate perceived release. This blocks completion of drive-response acceptance. + +Root cause in the remote output loop: it ramps the speed setpoint from zero +at 600 ERPM/s. Both saved configurations have s_pid_min_erpm=900. Pinned +upstream bldc mcpwm_foc.c (3f670137e27e6e383fa79c50cc6b1fa85aab1554) forces +zero duty and resets speed-PID state for targets below that threshold. The +result is 1.5 s of ineffective commands on each start, plus the retained +0.5 s undriven interval when changing direction. Recorded telemetry already +says driving while the rotor remains stopped, consistent with this mechanism. +This delay is downstream of command admission; the exact key-to-node timing +was not captured and no claim of zero network delay is made. + +Candidate Node 0.8.44-1 / VESC 0.7.3 starts the remote speed request at each +controller's own read-back minimum PID speed (rounded up for native integer +setRpm), then ramps at the existing rate above it. It does not change the +firmware threshold, motor configuration or current ceiling. Subthreshold +analogue requests release instead of being amplified above the request; +invalid/unreachable thresholds reject before output claim. Zero input still +releases immediately; expiry, RC takeover and the reversal dwell remain. +Synthetic tests cover distinct thresholds including fractional serialization, +first-cycle output, ramp above the threshold, turn signs, subthreshold input, +immediate release and invalid thresholds. Physical response after installation +requires a new observed trial; this candidate is not yet installed. + + +0.8.44-1 qualification completed: all 18 Ubuntu stages succeeded in 268.87 s, +including 140 VESC tests, Go race checks and Node UI. Source 1b1be6ef5913fd3740a11c69; +package SHA-256 46cae05efa621a2636251f69ab8071ff4e18db67f23203eab396a71f0ef0972b. +Owner installer bf270c06ae6d1e598e963756 launched in the local Ubuntu session. +APT simulation changes only mission-core-node 0.8.43-1 -> 0.8.44-1, with no +added or removed packages. Before launch Core showed stopped, release confirmed, +both currents/ERPM/faults zero. Local OS authorization is pending; launch is +not evidence of installation or an accepted new motor response. + + +Owner authorization completed: 0.8.44-1 installed at 12:01:17 UTC in 18.56 s, +all installer steps exit 0; Node and VESC services active. Twenty read-only +samples captured after installation, final sample both assigned controllers +fresh (53/63 ms), ERPM/current/fault zero and no active control. Fresh owner +observation requested for W start/release; improved physical response is not +yet accepted. + + +Post-0.8.44-1 owner keyboard series at 12:05–12:06 UTC included repeated +forward/reverse and both turn patterns. Owner reports delay approximately +halved, forward-to-reverse works, but one side sometimes starts sooner. +Read-only recording: 947 samples, no errors, all faults zero; 23 driving +segments. First side above 300 ERPM in the same sample or 0.25–0.51 s later; +both sides by 0–0.76 s. These are state-relative samples, not key-event timing. +The four-minute recorder ended at ready; a separately saved final snapshot +confirms stopped/release_confirmed, both ERPM and currents zero after UI Stop. +Sampled peaks left 2007 ERPM / 5.04 A, right 2025 ERPM / 3.32 A. + +Asymmetry diagnosis: after a turn, the remote code held only the reversing +motor for its 0.5 s neutral interval, while the other side immediately drove +the new command. Trace 12:05:39 (turn -> forward): right above 300 ERPM in the +first driving sample, left +0.763 s. The mirror transition at 12:05:33 had +left first, right +0.511 s. This is a software coordination defect, not evidence +that all smaller differences arise from the broken left Hall circuit. + +Candidate Node 0.8.45-1 / VESC 0.7.4 uses one reversal barrier for the entire +assigned drive group. If any side reverses, all outputs release until all +motors have been observed quiet and undriven for 0.5 s, then the current +latest targets start in the same output cycle. Already observed neutral time +counts; no extra dwell is added after a sufficiently long released pause. +Cancelled/replaced direction requests are not queued. The per-controller PID +threshold correction, speed ramp, immediate zero, current caps, expiry and RC +priority remain. Synthetic regressions cover turn->straight synchronization, +a slower coasting companion, counting an existing neutral pause and cancelling +a pending reversal. Installed software remains 0.8.44-1 pending qualification +and owner installation of this separate candidate. + + +0.8.45-1 / VESC 0.7.4 passed all 18 Ubuntu qualification stages in 267.11 s, +including 144 VESC tests. Source d31a8b586b9a600a2a8e61b3; package SHA-256 + af412c607fec9b34aba0af0e8e67614cd6f4d373fb641d7202341fea30be9ba1. +Installer f1a8a72c4a1a7efc4aeebedd launched in Ubuntu. Its APT plan upgrades +only mission-core-node 0.8.44-1 -> 0.8.45-1; no added/removed packages. +Before launch both controllers had zero ERPM/current/fault, control stopped, +release confirmed. OS authorization and new physical acceptance are pending. + + +0.8.45-1 installed at 12:23:15 UTC after owner OS authorization, 18.56 s, +all steps exit 0. Node and VESC services active. Twenty read-only samples; +final both assigned UUIDs fresh (115/124 ms), zero ERPM/current/fault and +no control session. Fresh owner observation requested for turn->forward +transitions; physical synchrony and remaining control/RC acceptance pending. + + +Observed 0.8.45-1 keyboard trial, 12:32–12:34 UTC: 545 read-only samples, +no read errors, fault codes zero, driving sample age <=105 ms. Twelve driving +segments; both sides above 300 ERPM in the same sample or within one 0.25 s +sample. Peaks left/right 2014/2043 ERPM and 4.35/3.24 A. Owner reports responsive +forward/reverse/turns. This is coarse telemetry, not exact key-to-output timing. + +CRITICAL physical acceptance failure: owner reports D continued after leaving +the browser and releasing the physical key; later clicks recovered it. The +trace contains prolonged D segments (22.82 and 20.56 s), but browser focus/key +source events were not recorded, so exact focus-loss latency is unknown. +Agent ended control through UI; stopped/release_confirmed=true and both motors +zero ERPM/current/fault. Remote-control acceptance remains blocked by this defect. + +The UI already subscribed to blur/pagehide/visibility events. Its 100 ms +command sender nevertheless renewed a remembered nonzero demand without a +focus or input-freshness check; a missed browser-host event could hold it +indefinitely. Fix uses a core-owned held-input binding, capture listeners, +50 ms focus polling, and a guard checked at every command heartbeat. A key +requires a fresh trusted press, then OS-repeat evidence: <=1000 ms initially, +<=300 ms after a repeat. This fallback bounds a lost keyup even if the host +also misses focus events. Focus loss/expiry clears all held states and disarms; +returning focus or delivering a late repeat cannot resume movement. Continuous +keyboard control therefore requires OS repeat within those bounds; this is +not a global-background keyboard implementation. Pointer up/cancel/capture-loss +and component disposal release held state. No onboard install or firmware/config +change belongs to this UI fix. Physical focus-loss re-test remains pending. + + +Owner follow-up after the first focus fix: movement now stops on focus loss, +but terminating the control session is explicitly rejected. New required +behavior is neutral hold with the current healthy control session preserved; +returning focus requires a new physical press, not another arm/preparation. +The implementation now separates input pause (clear held input, send zero, +keep session) from explicit Stop/pagehide/unmount/fault (end session). Guards +still run before every send; old demand is never restored on focus return. +The periodic neutral messages maintain the session only while communication +remains healthy. Actual background suspension/channel expiry is still a stop, +not permission to extend the motion watchdog. Continuous keyboard holds still +require OS repeat evidence within the bounded input lease. + +Preparation now hides key controls and renders the existing canonical warning +StatusBadge as Подготовка управления; readiness alone admits the green state +and key controls. Initial focus-fix physical evidence confirms stopping but +not the requested session-preserving behavior. Revised physical test pending. + + +Final revised UI qualification: 934 unit tests, architecture checks, TypeScript +and production build pass. Canonical Core serves the exact new index/assets; +no Node/OS/firmware change. Browser verified amber Подготовка управления with +keys absent until ready. Owner observed the revised trial and confirmed: +focus loss stops motors, returning allows a fresh press without another arm +or preparation. One active session persisted throughout all six short driving +segments. Explicit UI Stop after completion ended the session; final fresh +telemetry confirms stopped/release_confirmed=true, both ERPM/current/fault zero. +The private result includes UTC/monotonic traces, owner notes and SHA-256. +This accepts focus loss/resume on the observed host. Tank, explicit Stop while +moving, command-channel loss, RC takeover and loaded/field behavior remain +separate outstanding physical checks. No exact key-to-stop timing is claimed. + + +2026-09-25 13:21 UTC — operator startup UI regression fix only. +Node remains 0.8.45-1 / VESC plugin 0.7.4; no OS, firmware or motor-config +change. Fixed stale-read revocation of a newly acquired session and silent +Manage availability. One first-click neutral-only preparation completed; +explicit Stop confirmed release and both motors zero. 307 samples, no read +errors/faults/motion; 938 unit tests, typecheck, architecture and build pass. +See 25_OBSERVATION_AND_REMOTE_CONTROL.md and private entry-startup-result.json. diff --git a/docs/node/18_VESC_TOOL_NATIVE_BACKEND.md b/docs/node/18_VESC_TOOL_NATIVE_BACKEND.md new file mode 100644 index 0000000..0e6fea8 --- /dev/null +++ b/docs/node/18_VESC_TOOL_NATIVE_BACKEND.md @@ -0,0 +1,176 @@ +# VESC Tool as the onboard engine + +Owner decision, 2026-09-23: Mission Core supplies the local and remote product +interface; upstream VESC Tool supplies firmware compatibility, configuration +schemas/codecs and motor calibration. Do not continue a separate Python +implementation of Tool algorithms. Node 0.8.29-1's separate Hall/speed experiment +was built but withheld before installation. Installed hardware remains on +0.8.28-1. Calibration and sustained-rotation acceptance are still outstanding. + +## Upstream boundary + +Use the stable [Tool 7.00 source](https://github.com/vedderb/vesc_tool/tree/01d5f10901116c311e3fb84d5a1541f663d3ce20) +unchanged. This is a Qt application, not an existing HTTP service or a documented +standalone SDK. A small C++ process adapter is necessary; it calls the actual +`VescInterface`, `Commands`, `ConfigParams` and `Utility` implementations. It +must not replace them with translations of their algorithms. Keep upstream +license and corresponding source/build provenance with the combined payload. + +Mission Core owns device identity/position, exclusive access, operation and +configuration history, session authority, local/paired transport and UI composed +from Design Guideline components. Device parameter definitions, groups, labels, +units, limits and enum options come from native `ConfigParams`; they must not +be copied into a second permanent hand-maintained schema. + +Updates change a pinned upstream source plus its matching resources and rerun +compatibility/replay acceptance. Neither a Tool update nor connecting to a board +automatically authorizes firmware flashing or replacing controller settings. + +## Verified native execution + +`plugins/vesc/native/offline_main.cpp` links the existing unmodified Tool object +files, substituting only the application entry point. It has no admitted serial, +TCP, Bluetooth or powered-operation entry point and does not start an event loop. +The versioned `packaging/build_native_probe.py` / `native_probe.py` artifact +compiles under an unprivileged 3 GiB user scope; it neither installs dependencies +nor touches running services. Separate private Qt settings prevent inheriting an +operator's saved connection. + +The adapter replays archived identity through native firmware negotiation, +checks archive hash/command/length against the native firmware schema, passes +the original configuration packets to `Commands::processPacket`, and exports +the resulting native parameter groups and XML. Native serialization must +reproduce the original binary configuration exactly. Unsupported firmware, +corrupt hashes, wrong signatures and truncated payloads must fail closed. + +An offline `Commands::detectAllFoc` serialization probe also demonstrates the +real compatibility behavior: Tool automatically halves a 100 W example to +50 W on the wire for FW 5.02. No bytes are delivered to hardware. This correction +comes from `VescInterface::fwVersionReceived` and `Commands::detectAllFoc`; +implementing only the documented-looking command packet would miss it. + +Tool's own XML writer rounds floating point text (`QString::number` default +precision). XML is suitable for native import/export but is not a byte-exact +archive. Preserve the original binary snapshots alongside native XML. Native +`ConfigParams::checkDifference` supplies the comparison tolerance; do not call +XML conversion a lossless binary backup. + +This proves engine reuse and offline compatibility, not a shipped hardware +backend. Production dependency closure, installer integration, USB ownership +handoff, operation API and physical calibration remain separate acceptance work. + +## Canonical calibration for this 1×1 rover + +The [upstream motor wizard](https://vesc-project.com/node/180) distinguishes +motor setup from the [input wizard](https://vesc-project.com/node/181). +The current desktop implementation is +[`DetectAllFocDialog::runDetect`](https://github.com/vedderb/vesc_tool/blob/01d5f10901116c311e3fb84d5a1541f663d3ce20/widgets/detectallfocdialog.cpp), +calling the actual +[`Utility::detectAllFoc`](https://github.com/vedderb/vesc_tool/blob/01d5f10901116c311e3fb84d5a1541f663d3ce20/utility.cpp). + +1. Confirm each controller's own identity, take motor and application backups, + inspect faults and retain existing battery protections. The problematic motor + is LEFT; RIGHT works normally from RC. Do not copy right-side Hall calibration + to the left or use software-induced right-side stops as a hardware diagnosis. +2. Determine actual connection topology. Two motors, or a Mission Core 1×1 + layout, do not imply CAN master/slave. There are two USB connections and two + receiver inputs (CH3 presumed left, CH2 right). Previous native CAN discovery + returned no peers. Calibrate each directly connected device separately until + another topology is evidenced; do not enable CAN forwarding merely because + the rover has two motors. +3. Choose the appropriate native motor procedure. The full auto-FOC wizard + prepares parameters, temporarily adjusts battery cutoffs, detects R/L, flux + and sensors, writes resulting settings, restores cutoffs and checks direction. + It is not equivalent to invoking a Hall command or only starting a motor. + Its `maxPowerLoss` is motor heating allowance, not rated shaft power; a + remembered 500 W nameplate is not an instruction to pass 500 W here. +4. For diagnosis without changing battery settings, use upstream's individual + `measureRLBlocking`, `measureLinkageOpenloopBlocking` and + `measureHallFocBlocking` procedures. The necessary current/start parameters + and actual effects must be explicit. Use upstream calculation/application + functions when measurements are accepted; never silently transplant a new + Hall table or overwrite unmeasured settings. +5. Inspect the resulting sensor mode and measurement status. Firmware 5.02 + autodetection can report success with a sensorless fallback when Hall/encoder + detection fails. That is not proof that the broken Hall pin was repaired or + that loaded low-speed startup is acceptable. Firmware Hall measurement locks + ordinary motor controls during the cycle; do not promise an RC or USB stop + that the firmware cannot perform. +6. Read back and archive the applied result, then coordinate a visible direction + and startup test. Assign the physical position in the existing Mission Core + profile only from observation. Finish motor setup before changing receiver + endpoints, neutral, deadband or direction. The receiver remains connected. +7. Verify sustained rotation using native motor control with current limits and + a speed setpoint. Requested duration means measured rotation after settling; + startup, stalled motion and an early guard stop do not count as completed + time. A torque/current command alone cannot promise 30 seconds of rotation. + +The full auto wizard includes configuration writes beyond measurements. In +particular, blindly executing its battery stage from stale configuration metadata +is unsuitable here: saved battery metadata says 3S / 6 Ah while observed input is +about 50 V. Existing cutoffs are approximately 44.2 / 39 V. Retaining these +settings for motor diagnosis is distinct from validating their suitability. + +Battery brand/capacity are not prerequisites for motor identification. Chemistry +and series count are needed when recalculating voltage protection; pack/BMS +charge and discharge ratings are needed when changing battery current limits. +Do not block native engine preparation or motor-only diagnosis on unknown Ah. + +## Hardware evidence and uncertainty + +Owner photos show UNITE branding and model family BM1418HQF on one motor; the +other marking is worn. Owner recalls approximately 0.5 kW per motor, tentatively. +The [manufacturer catalog](https://m.unitemotorco.com/brushless-motor/) lists +350/500/650/750 W variants with several voltage options. This confirms the +family, not the exact rating of this unit. Do not select a direct-drive hub +profile based solely on the saved 46-pole / gear-ratio fields. + +Owner reports a nominal 48 V CATL-cell battery and a verbally ambiguous capacity +around 120 Ah. The photo shows 13 visible cell bodies, but labels and the complete +electrical topology are not visible. Chemistry, exact S/P count and BMS ratings +remain unconfirmed. Raw photos, controller identities and native replay outputs +stay in private evidence, outside normal Git/Ops. + +## Remaining implementation acceptance + +- Carry the native engine and its qualified runtime dependencies through the + existing versioned Node installer; no ad-hoc board package/library repair. +- Admit one hardware owner at a time. Existing Python serial descriptors must + not compete with VescInterface, and background polling must not interleave + another session's calibration commands. +- Expose explicit operation requests/results and native parameter metadata on + the private onboard boundary; reuse the existing Node and paired Core path. +- Keep backups, compatibility checks, timeouts, durable unknown-operation state, + readback and observed sensor mode in the receipt. No automatic retry of motion. +- Before each powered agent test obtain a fresh observing reply and announce + target/parameters. Existing authorization does not establish that the owner is + still watching after a build. +- Qualify native device reads before calibration, then verify left and right + startup/direction and actual sustained rotation separately. Do not mark the + rover calibrated from offline tests. + +## Native runtime candidate 0.4.0 + +The per-device `native/engine_main.cpp` now implements bounded JSON requests +on private inherited pipes. Native VescInterface owns and exclusively locks the +actual serial descriptor; the service never opens a competing descriptor. +Configuration reads verify upstream serialization against the original bytes. +The admitted native methods cover identity/telemetry/configuration/CAN/PPM reads, +short app-output leases, current release, bounded current and speed, volatile +current scales, native parameter/XML export and upstream blocking Hall detection. +No arbitrary packet, firmware flash or general command execution API is exposed. + +`runtime/native_link.py` owns subprocess lifetime and attachment checks. An +unmatched/lost response closes the stream; no powered command is retried. +Reconnection creates a fresh device session. Pending measurements and current +limit restoration remain durable across process failures. During Hall detection +only its status, telemetry/PPM reads and release/leases are allowed; none is +represented as cancelling firmware's non-interruptible measurement. + +The versioned runtime carries private Qt/offscreen dependencies and source/license +provenance. `native_check.py` verifies the installed files and runs the disconnected +engine as the service account before USB discovery. Qualification and actual +installation/measurement outcomes are recorded in the installation ledger. +Full auto-FOC, application of measured calibration, general parameter editing +and physical motor acceptance remain outstanding; do not equate this API with +complete VESC Tool UI parity. diff --git a/docs/node/19_VESC_OPERATOR_CALIBRATION.md b/docs/node/19_VESC_OPERATOR_CALIBRATION.md new file mode 100644 index 0000000..e156759 --- /dev/null +++ b/docs/node/19_VESC_OPERATOR_CALIBRATION.md @@ -0,0 +1,99 @@ +# Калибровка VESC через Mission Core + +Проверено на Node 0.8.35-1 / VESC plugin 0.6.3, VESC Tool 7.00 и прошивке +контроллеров 5.02. Это описание доступного процесса; журнал конкретных +испытаний находится в `17_VESC_INSTALLATION_LEDGER.md`. + +## Действия оператора + +Открыть «Аппараты», нужный аппарат, устройства его бортового компьютера, +нужный VESC и «Настройка VESC». В блоке «Калибровка мотора» проверить выбранный +контроллер, параметр допустимых потерь, подтвердить наблюдение и нажать +«Откалибровать мотор». Дождаться результата записи, проверки конфигурации +и снятия тока. Для второго контроллера открыть его карточку и выполнить +отдельную калибровку. Профиль 1×1 сам по себе не запускает групповую калибровку. + +Моторы должны свободно вращаться, пульт — быть выключен. В прошивке 5.02 +нативное измерение нельзя прервать обычной кнопкой остановки или пультом; +оператор должен иметь возможность отключить силовое питание. + +Перед процедурой сохраняются конфигурации подключённых контроллеров. +Мастер измеряет электрические параметры выбранного мотора, определяет +датчики, рассчитывает настройки FOC и записывает результат. Mission Core +проверяет прочитанную обратно конфигурацию и сохраняет версии до/после. +Настройки другого мотора, аккумулятора и приёмника защищены от незапрошенного +изменения. Полная процедура повторно не нужна перед обычным запуском мотора. + +## Что означает 50 Вт + +«Допустимые потери в моторе» — входной параметр штатного мастера VESC Tool. +Он задаёт расчётные резистивные потери на нагрев при предельном токе. По нему +и измеренному сопротивлению мастер выбирает токи измерения и рассчитывает +сохраняемый предел тока мотора. Это не напряжение аккумулятора, не полезная +механическая мощность и не паспортная мощность мотора. Увеличение значения +может увеличить ток и нагрев; вводить сюда номинальные 500 Вт автоматически +неправильно. Параметр не заменяет измерение температуры и тепловую проверку. + +В принятой калибровке двух моторов при 50 Вт мастер установил примерно +34,21 и 34,41 А. Это результат конкретных измерений, а не универсальный +допустимый ток всех моторов. Поправку совместимости с прошивкой 5.02 +выполняет сам VESC Tool. Она не воспроизводится отдельной формулой Mission Core. + +Источник: [объяснение автора VESC](https://www.vesc-project.com/node/1029), +[влияние параметра на токи измерения](https://vesc-project.com/node/1640), +`Commands::detectAllFoc` и `Utility::detectAllFoc` в закреплённом исходнике Tool. + +## Датчики Холла и отдельное измерение + +Датчики сообщают контроллеру положение ротора. При автоопределении FOC мастер +уже проверяет датчики и может выбрать работу без них. Успешная калибровка в +режиме без датчиков не доказывает исправность проводки Холлов. + +Кнопка «Измерить датчики Холла» выполняет отдельную диагностику выбранного +мотора: штатный цикл при 5 А с медленными смещениями получает таблицу +состояний. Она не применяется автоматически, рабочая конфигурация сохраняется. +Это проверка для поиска неисправности, а не обязательный второй этап каждой +калибровки. Неполная таблица требует различать проблемы датчиков/соединений +и недостаточное движение при измерении. Номер физического сломанного контакта +не определяется по таблице без проверки распиновки и проводки. + +Для подготовки к измерению в Node 0.8.39-1 / plugin 0.6.6 оператор отдельно +подтверждает неподвижность всех моторов. Бессенсорная прошивка может сообщать +ненулевые ERPM и изменение тахометра при физической остановке: оба значения +вычисляются из оценки положения ротора. Приложение сохраняет эти показания, +а перед измерением повторно проверяет нейтраль приёмника, отсутствие PWM, +малый ток и отсутствие ошибок. Это исключение действует только для +наблюдаемого измерения Холлов в бессенсорном режиме, не для управления +движением. Установка и реальные результаты новой версии фиксируются отдельно +в журнале испытаний. + +## Назначение и проверка вращения + +Назначение «левый/правый» связывает постоянный UUID VESC с местом мотора на +аппарате. Оно нужно для адресного и общего управления, но не влияет на +измеряемое сопротивление или параметр потерь. После смены USB-порта назначение +сохраняется. Общий список назначений находится в разделе «Настройки борта»; +это профиль аппарата, а не перечень моторов внутри одного VESC. + +«Проверка вращения» запускается отдельно от калибровки. Скорость задаётся +в ERPM, ток задаёт верхний предел, длительность считается после разгона +и удержания скорости. Выбор всех моторов профиля запускает совместную +проверку; для 1×1 это два мотора. Успешная проверка на вывешенном приводе +не заменяет проверку под нагрузкой или надёжности связи. + + +### Visible forward/reverse bench rotation + +After Hall measurement, use **Проверка вращения** for sustained visible motion. +Select one controller or the complete assigned profile, then **Направление +вращения → Прямое / Обратное**, speed magnitude, motor-current ceiling and hold +duration. Direction is relative to each VESC's existing settings, not a certified +vehicle heading. Current is an upper torque limit, not a speed setting. + +Observe all motors fully stopped, raised and free before confirming each start. +Wait for physical stop before changing direction. There is no automatic forward/ +reverse sequence. On admitted sensorless firmware, idle ERPM alone cannot prove +standstill; the preflight records that estimate alongside electrical checks. +Timing begins after speed settles; preparation/ramp/gaps are excluded. Compare +VESC observations with actual movement. This is an unloaded bench test, not +acceptance of loaded starts or the unresolved left Hall hardware fault. diff --git a/docs/node/20_VESC_POWER_LIMITS_PLAN.md b/docs/node/20_VESC_POWER_LIMITS_PLAN.md new file mode 100644 index 0000000..4068754 --- /dev/null +++ b/docs/node/20_VESC_POWER_LIMITS_PLAN.md @@ -0,0 +1,145 @@ +# VESC: план привода и ограничения мощности + +Актуализация 2026-09-24 после установки: Node 0.8.38-2 установлен, Core +принял оба VESC; владелец подтвердил появление устройств после перезапуска. +Ниже сохранён исходный аудит сбоя загрузки и состояние ранних сборок, а не +текущий статус установки. Последний журнал — `17_VESC_INSTALLATION_LEDGER.md`; +текущая очерёдность диагностики, RC-перехвата и профилей — +`23_ROVER_CONTROL_PROFILES.md`, раздел «Приёмка и порядок». + +Статус на 2026-09-24: исследование и план. Пользователь попросил разобраться +в штатном механизме VESC Tool; управление пределами пока не реализуется и +настройки контроллеров не меняются. + +## Принятый результат и незавершённая работа + +- Оба мотора откалиброваны штатным нативным VESC Tool; калибровка, история + конфигураций, назначение и одиночная/совместная проверка доступны в UI. +- Принят совместный тест примерно 30 секунд и хороший ход обоих моторов с + пульта по наблюдению владельца. Это проверка вывешенного привода. +- Левый работает без датчиков, правый с Холлами. Отдельная повторная + диагностика Холлов не завершена; повреждённый контакт не локализован. +- Надёжность USB не принята: после успешного теста повторялись ошибки чтения. +- Node 0.8.36-1 с исправлением проверки нейтрали PPM подготовлен и проверен, + но не установлен. Это исправление не объявляется решением USB-сбоев. + +## Отсутствие устройств после загрузки + +Сегодня Node 0.8.35-1 и VESC-служба активны, без автоматических перезапусков. +Linux не перечисляет VESC среди USB-устройств; ttyACM и serial/by-id отсутствуют. +Во время загрузки есть ошибки чтения USB-дескрипторов и адресации (-71) на +двух портах. Дескрипторы этих устройств не получены: приписывать им личность +VESC или конкретную причину ошибки пока нельзя. Изменение портов не должно +менять идентичность: назначения привязаны к UUID контроллеров. + +Владелец затем подтвердил подключённые USB-кабели и успешное управление обоими +моторами с пульта сейчас. Это подтверждает работу силового питания и моторного +управления, но не USB-канала. Первые ошибки USB зарегистрированы около 9,124 с +от старта, процесс VESC-службы запущен на 11,111 с, Node — на 13,430 с. Значит, +первый сбой перечисления возник до запуска нашего прикладного драйвера в этой +загрузке. Это не устанавливает, неисправен кабель, устройство, питание USB или +контроллер USB Mini. Никакого ручного сброса портов в аудите не выполнялось. + +Отдельный недостаток продукта подтверждён исходниками: drive-profile.json +сохраняется на борту, но Service.inventory публикует drive_profile только +внутри обнаруженных устройств. Node сохраняет отсутствующие устройства через +реестр initialized, который обновляется при prepare; автоматически обнаруженная +личность сама в него не добавляется. В текущем Core один VESC остаётся offline, +второго нет в inventory, хотя архивы обоих доступны. Это не потеря калибровки, +но модель отображения известных устройств и общего профиля недостаточна. + +Нужны независимая доступность профиля аппарата и сохранённый список назначенных +контроллеров со статусом «нет связи». Нельзя выдавать сохранённые сведения за +свежую телеметрию или разрешать команды без нового подтверждения UUID/сеанса. +Сохранность самого файла профиля в этом аудите напрямую не проверена: у SSH +пользователя нет права чтения. Факт сохранения установлен по реализации и +вчерашним квитанциям; текущие архивы обоих контроллеров прочитаны через Core. + +## Последние подтверждённые пределы + +Данные из архивов 2026-09-23 21:05 UTC, а не новое чтение недоступных VESC. + +| Параметр | Левый | Правый | +| --- | ---: | ---: | +| Максимальный ток мотора | 34,2135 А | 34,4078 А | +| Масштаб тока разгона | 100% | 100% | +| Предел тока батареи | 55 А | 55 А | +| Предел рекуперации в батарею | −55 А | −55 А | +| Отдельное ограничение мощности | выключено | выключено | + +Значение watt max 1500000 соответствует выключенному ограничению в профилях +Tool. Оно не является мощностью оборудования. Значение absolute current +160 А — отдельный порог защиты, а не паспортный рабочий ток. Настройки батареи +унаследованы и не подтверждают возможности BMS. Максимумы мотора около 34 А +получены мастером при допустимых потерях 50 Вт. Этот параметр калибровки не +является выходной мощностью. Временные 30 А и 2000 ERPM теста не являются +постоянным ограничением ручного управления; квитанции подтверждают восстановление +временных токовых масштабов после принятого теста. + +## Штатный механизм + +Базовые Motor Current Max, Battery Current Max, рекуперация и другие пределы +хранятся в конфигурации каждого VESC. Профиль Tool задаёт масштаб тока разгона +и торможения, скорость, duty и мощность. Процент тока не равен проценту ватт: +ток мотора в первую очередь задаёт момент, а батарейный ток относится к +потреблению от общей батареи. + +В закреплённом Tool ProfileDisplay вызывает Commands::setMcconfTemp и предлагает +«Use until reboot» и постоянное применение. FW 5.02 поддерживает сохранение, +пересылку по CAN и деление ватт между обнаруженными CAN-контроллерами. Поэтому +общий профиль возможен, но исполняют ограничения отдельные контроллеры. Их +применение влияет и на PPM-пульт; для этого не нужна повторная калибровка. +Временное применение не требует записи каждого движения ползунка во flash. + +В штатной пересылке подтверждение ведущего не является подтверждением каждого +ведомого: FW подавляет ack для пересланных команд. В интеграции нужны проверка +состава назначенных UUID и чтение результата у каждого участника. Делить бюджет +по случайному числу отвечающих устройств нельзя: пропавший контроллер может +снова появиться, и общий бюджет батареи будет превышен. Конкретную политику +частичного применения и восстановления следует определить до реализации. + +## Предлагаемая модель Mission Core + +Общий профиль привода размещается у аппарата. Он содержит уже существующую +схему 1×1/2×2 и назначения, подтверждённый бюджет общей батареи и режим работы. +Карточка каждого VESC хранит калибровку, паспортные основания пределов и его +индивидуальные ограничения. Общий режим применяет согласованные значения к +назначенным контроллерам через нативный Tool; подтверждённые ограничения +исполняются на VESC независимо от связи с Core. + +Запас 20% рассчитывается от подтверждённых допустимых характеристик при +реальном охлаждении и длительности нагрузки. Для каждой пары мотор–контроллер +нужен допустимый фазный ток; для общей батареи — суммарный ток разряда и +отдельный ток заряда/рекуперации. Пиковый ток нельзя считать непрерывным. +Маркер прошивки 75_300_R2 не доказывает производителя и реальные характеристики +платы, а приблизительные 500 Вт мотора не определяют допустимый фазный ток. +Поэтому численный новый потолок пока не назначен. Нужны точные модели или +подтверждённые характеристики от изготовителя и параметры BMS. + +## Очерёдность + +1. Установить состояние питания/подключений и восстановить USB-обнаружение, + затем проверить связь без вращения. Смена портов не должна требовать + повторного назначения, перезагрузка не должна скрывать сохранённый профиль. +2. Исправить доступ к общему профилю и отображение известных offline-устройств; + применить и проверить подготовленное исправление нейтрали пульта через + версионный установщик с согласованным прерыванием служб. +3. Сверить паспорта моторов, контроллеров и BMS; сформировать индивидуальные + пределы и общий бюджет с согласованным запасом. Затем реализовать профили + ограничений штатными средствами Tool, с резервированием и чтением результата. +4. Завершить отдельную диагностику Холлов, сохранив принятую калибровку. +5. Принять работу под нагрузкой, ограничения температуры/рекуперации и + остановку при потере связи; далее полноценное ручное удалённое управление, + приоритет пульта и автономный режим. Общий тест пока не означает готовность + всей системы управления к эксплуатации. + +## Первичные источники + +- [VESC: назначение пределов тока](https://vesc-project.com/node/180). +- [Tool: штатные профили и применение](https://github.com/vedderb/vesc_tool/blob/01d5f10901116c311e3fb84d5a1541f663d3ce20/mobile/ProfileDisplay.qml). +- [Tool: поля профиля](https://github.com/vedderb/vesc_tool/blob/01d5f10901116c311e3fb84d5a1541f663d3ce20/mobile/ProfileEditor.qml). +- [FW 5.02: COMM_SET_MCCONF_TEMP](https://github.com/vedderb/bldc/blob/5.02/commands.c). + +Ops MCP на момент обновления возвращает HTTP transport error; план и свежая +диагностика в Ops не опубликованы. Частные журналы и UUID находятся вне Git +в outputs/rover-006-vesc-context-20260923/native-probe/boot-20260924-*. diff --git a/docs/node/21_STARTUP_AND_USB_RECOVERY.md b/docs/node/21_STARTUP_AND_USB_RECOVERY.md new file mode 100644 index 0000000..2a67032 --- /dev/null +++ b/docs/node/21_STARTUP_AND_USB_RECOVERY.md @@ -0,0 +1,95 @@ +# Подготовка окружения, автозапуск и USB при загрузке + +Требование владельца от 24.09.2026: пользователь получает сборку Node, +открывает приложение и выполняет его настройку. Все необходимые изменения ОС +выполняет версионированный продукт. Ручные правки Linux не являются частью +установки, диагностики с исправлением или первого испытания. + +## Владение настройкой + +Существующая страница «Настройка окружения → Сконфигурировать» использует +профиль `ubuntu-24.04-amd64/3`. Добавлены два этапа в существующий список: + +- «Автозапуск приложения»: root-owned XDG entry открывает обычное окно Node + после входа в графическую сессию. Перед запуском оно до 180 секунд ожидает + HTTP-службу. Gtk.Application сохраняет одно окно на пользовательскую сессию. + Авторизация локального интерфейса остаётся обычной polkit-авторизацией; + автозапуск не выдаёт новые права и не настраивает автоматический вход в ОС. +- «Обнаружение устройств при загрузке»: устанавливает фиксированную политику, + включает отдельную службу на следующую загрузку и читает возможности текущих + USB-хабов. Подготовка окружения не перезапускает USB-порты в текущей сессии. + +Системная служба Node уже включалась установщиком и работает до входа в рабочий +стол. Открытие окна и работа борта — разные жизненные циклы. Постоянного +интерфейса управления портами нет; обновление устройств только обновляет список. + +Политика и XDG entry создаются из шаблонов пакета. Повторное выполнение +идемпотентно; чужие файлы/ссылки не перезаписываются. При удалении пакета +удаляются только неизменённые принадлежащие продукту файлы, служба отключается. +Пакет запрещает замену файлов во время переключения USB или незавершённого +обратного включения. При откате до версии раньше 0.8.37 prerm также отключает эту службу и удаляет +только совпадающие с шаблонами настройки, прежде чем dpkg удалит новые helper. +Физическая проверка downgrade ещё не выполнена. + +Подтверждаемый профиль пока Ubuntu 24.04 amd64. Новые дистрибутивы и архитектуры +должны получить собственные поддерживаемые профили и проверку dependency closure; +этот пакет не является доказательством работы на любом Linux. + +## Ограниченная процедура USB + +1. Служба запускается до Node и VESC, только если подготовка среды включила + политику. После udev-settle выдерживается возраст загрузки не менее 30 секунд: + ядро может ещё повторять обнаружение после завершения udev-settle. +2. Из журнала **текущей загрузки**, только transport=kernel, выбираются порты с + окончательным `unable to enumerate USB device` в первые 60 секунд. Более + позднее подключение/отключение отменяет устаревший кандидат. Ошибка чтения + дескриптора сама по себе не разрешает сброс. +3. На порту и его USB 2/3 companion не должно быть дочернего устройства, + состояния незавершённого обнаружения, отключения или зарегистрированного + overcurrent. Встроенные hardwired-порты исключены. Проверяются взаимные peer + ссылки, поколение/адрес хаба и нахождение атрибутов в sysfs. +4. Дескриптор каждого хаба должен подтвердить individual port power switching. + При ganged/no switching/нечитаемом дескрипторе порт пропускается. Поддержка + физического отключения VBUS всё равно зависит от железа; успешный sysfs write + не доказывает восстановление устройства. +5. До первого изменения сохраняется root-owned журнал обратного включения. + После повторной проверки свободных портов пара отключается на одну секунду, + включается в `finally`; до восьми секунд ожидается новое обнаружение. + ExecStopPost повторяет обратное включение при остановке процесса. Уже включённый + порт не переключается повторно. Ошибка восстановления сохраняет pending и + останавливает обработку других портов. +6. Не более одной попытки на физическую пару за загрузку, общий бюджет 90 секунд, + начало только в первые 180 секунд. Поздний запуск службы/перезапуск приложения + не сбрасывает USB. Повторный запуск сохраняет исходный результат. + +До чтения дескриптора тип проблемного устройства неизвестен: это ограниченное +восстановление ошибки Linux USB, а не угадывание VESC по пустому разъёму. +Конкурентное физическое подключение полностью не атомарно относительно sysfs; +проверки выполняются непосредственно перед записью. Процедура не меняет драйвер +хост-контроллера и не сбрасывает целый USB-контроллер/хаб. Она не отправляет +команды моторам. После обнаружения обычный драйвер сопоставляет VESC по firmware +UUID, а не по tty, разъёму или неуникальному USB serial. + +Результаты остаются в `/run/mission-core-usb-startup/`: inspection.json, +result.json, attempted, при незавершённом восстановлении pending.json. +Синтетические тесты используют временный sysfs; реальное переключение в них +не выполняется. + +## Приёмка + +- Локально: 36 тестов подготовки/автозапуска/USB, shell syntax и diff check прошли. +- Ubuntu qualification: 17 этапов прошли; пакет 0.8.37-1 и штатный установщик + сформированы, APT-план проверен. Пакет установлен штатным установщиком. + Хеши и результаты находятся в ledger. +- Подготовка через поставляемый UI: все девять этапов завершены, XDG entry и + USB-политика созданы, служба восстановления включена для следующей загрузки. + Сводная проверка нашла поддержку у USB-хабов; возможности именно корневых + портов ещё нельзя вывести из сводного статуса. Оба VESC доступны. +- Холодная загрузка с подключёнными VESC, сохранение UUID/назначений и отсутствие + вмешательства в камеры: ещё не приняты. Программный перезапуск службы не + заменяет этот тест. Без владельца перезагрузка борта не выполняется. + +Основания: Linux [USB sysfs ABI](https://github.com/torvalds/linux/blob/master/Documentation/ABI/testing/sysfs-bus-usb), +[port.c](https://github.com/torvalds/linux/blob/master/drivers/usb/core/port.c), +[USB error codes](https://docs.kernel.org/driver-api/usb/error-codes.html), +[uhubctl: switching and USB 2/3 peers](https://github.com/mvp/uhubctl). diff --git a/docs/node/22_BOARD_SETTINGS_SURFACE.md b/docs/node/22_BOARD_SETTINGS_SURFACE.md new file mode 100644 index 0000000..61f4789 --- /dev/null +++ b/docs/node/22_BOARD_SETTINGS_SURFACE.md @@ -0,0 +1,37 @@ +# Карточка аппарата: борт, настройки и устройства + +Согласовано владельцем 2026-09-24: существующую карточку аппарата разделить +на три независимо сворачиваемых блока; повторить композицию в Node. + +- «Бортовой компьютер»: идентичность, связь, характеристики и существующие действия. +- «Настройки борта»: общий профиль привода, назначения UUID и чтение ограничений VESC. +- «Устройства аппарата»: существующий инвентарь и переход к конкретному устройству. + +Используется канонический DG Inspector variant=panel. Новая навигация и новые +визуальные сущности не вводятся. Альтернатива — дополнительные окна настроек — +отклонена владельцем в пользу блоков на существующей карточке. + +Открытые секции сохраняются автоматически в JSON на стороне приложения: +в Core отдельно для каждого аппарата, в Node локально для его борта. Это +представление оператора, не конфигурация контроллера. Изменение одного блока +не перезаписывает состояние остальных. Пустой список означает «всё свёрнуто». +Инвентарь и выполняющиеся команды живут выше Inspector: сворачивание не +останавливает соединения и не скрывает ошибки сохранения. + +Общий профиль и назначения используют прежние проверенные команды VESC. +Калибровка, Холлы, тест вращения и версии конфигурации остаются в карточке +конкретного контроллера. Чтение ограничений идёт через нативный VESC Tool, +не меняет моторную конфигурацию и не запускает мотор. Значения являются +настройками контроллера, а не паспортными пределами оборудования. + +Изменение рабочих пределов мощности остаётся отдельным этапом по плану 20: +нужны подтверждённые пределы оборудования и политика согласованного применения. +Никаких искусственных «80% мощности» или новых токовых пределов этот этап +не записывает. Проверки: сохранение после навигации/перезагрузки, разделение +аппаратов, конкурентные изменения секций, ошибки JSON/связи и обе поверхности. + +Последующее требование владельца: добавить здесь два режима ручного управления +ровером. Исследование источника команд, пульта и независимого RC-пути находится +в [плане 23](23_ROVER_CONTROL_PROFILES.md). Этот режим не совпадает со схемой +1×1/2×2; переключатель не объявляется действующим до реализации и проверки +реального пути команд. diff --git a/docs/node/23_ROVER_CONTROL_PROFILES.md b/docs/node/23_ROVER_CONTROL_PROFILES.md new file mode 100644 index 0000000..ea86995 --- /dev/null +++ b/docs/node/23_ROVER_CONTROL_PROFILES.md @@ -0,0 +1,595 @@ +# Профили ручного управления ровером + +Актуальное решение владельца 25.09.2026: оставить работающее управление двумя +стиками; Tank/Arcade и управление одним стиком отложить до отдельного возврата +к задаче. Сейчас Mini получает CH2/CH3, но не горизонтальную ось выбранного +стика; новую проводку/адаптеры владелец исключил. Прототип не включать в +production и не показывать переключение RC-профиля как применённое. +Требование stop → neutral → manual сохранено незавершённым. + +Полный контрольный паспорт, конфигурации, история экспериментов и чекеры +опубликованы в [MISSIONCOR-85 — Гусеничный ровер Node 006](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-85). +Карточка прочитана обратно через прямой Ops MCP: все 35 структурированных +блоков совпали с подготовленным содержимым, включая 600 параметров VESC. + +Статус 2026-09-24: исследование и автономный программный прототип. Рабочие +настройки пульта, приёмника и VESC не изменены; новый режим движения на +оборудовании пока не реализован. + +## Требование владельца + +В существующих «Настройках борта» нужны два профиля: независимое управление +левым и правым бортом двумя рычагами и управление движением/поворотом одним +двухосевым рычагом. Тот же профиль должен быть доступен локально на Node и +через Core. Пульт должен сохранять возможность управления при отказе Mini. + +Профиль управления не заменяет схему привода 1×1/2×2 и назначения моторов. +Последние определяют физические исполнительные устройства; профиль определяет +смысл входных команд. Новые режимы не требуют повторной калибровки моторов. + +Уточнение владельца: при автономном движении или удалённом ручном управлении +пульт может оставаться включённым и готовым к немедленному перехвату. Движение +рычага за пределами проверенной нейтрали должно отбирать управление у всех +источников Mission Core без переключения режима в интерфейсе. После перехвата +нейтраль пульта не возобновляет прерванную задачу. Локальный оператор может +освободить застрявший ровер даже при недоступном операторском Core; отказ самого +Mini также не должен лишать его независимого RC-пути. Уведомления об аномалии +и обнаружение застревания пока описывают будущий сценарий, не реализованный код. + +Следующее уточнение владельца: отдельный интерфейс переключения источника +управления не нужен. Владелец наблюдает, что пульт работает только когда четыре +верхних переключателя подняты, и предлагает использовать это как сигнал +ручного перехвата. Наблюдение ещё не разделено на блокировку при включении и +поведение уже работающего передатчика. По руководству FS-i6S, раздел 4.1, +верхнее положение требуется при включении; раздел 2.2.3 описывает SwA–SwD как +назначаемые переключатели. Документ не подтверждает отдельный передаваемый +признак «все четыре подняты» или отключение радиолинка любым из них. + +Владелец затем исправил наблюдение: управление моторами сохраняется и со +всеми четырьмя тумблерами в нижнем положении. Гипотеза «любая нижняя позиция +выключает управление/радиосвязь» отозвана. Начальный пассивный замер был +помечен заявленным положением SWA, но его нельзя использовать как доказательство +влияния тумблера: синхронное сравнение состояний не завершено. Предложенное +переключение SWA для следующего замера отменено. Проверка положений при +включении остаётся вероятным объяснением, не подтверждённой настройкой пульта. + +Это требование к автоматическому выбору источника не отменяет ранее заказанную +настройку Tank/Arcade: раскладка органов управления и право выдавать команду +моторам — разные свойства. Перехват не должен требовать клика в Core. + +## Последнее уточнение: первый ввод останавливает, следующий управляет + +Владелец изменил непосредственную реакцию на RC: первый ввод с рычага должен +только прервать автономное/удалённое движение; последующий ввод может управлять +моторами. Отменяются задачи автономной езды и их вычислительные исполнители, +включая связанные с ней inference/планирование/обработку облаков. Запрет на +выходные команды должен вступать в силу раньше и независимо от завершения +таких задач. Нельзя ждать остановки тяжёлого вычисления, прежде чем запретить +ему движение; запоздавшие результаты и команды теряют допуск. + +Один удерживаемый рычаг создаёт непрерывную последовательность пакетов, поэтому +«следующий пакет» не равен второму осознанному действию. Подтверждённая владельцем +последовательность — первый выход из нейтрали: остановка; затем оба моторных +канала в устойчивой нейтрали; затем новое отклонение: ручное движение. +Ответ владельца 2026-09-24: «Да: остановка → нейтраль → управление». +Требование принято; изменение рабочего моторного runtime ещё не выполнено. + +Для этой трактовки нужны состояния прекращения команд, подтверждения остановки, +ожидания нейтрали и ручного управления. Нельзя пропускать первое удерживаемое +отклонение после фиксированной паузы или считать перезапуск процесса разрешением +движения. Проверяются свежесть входа, все назначенные стороны и отзыв старых +допусков. Длительность нейтрали и допустимое время остановки задаются после +выбора и проверки исполнительного механизма, не случайной константой. + +Текущая прямая PWM-проводка приёмник→VESC и истечение 250 мс аренды сами по себе +не реализуют это требование: отпустив аренду при удерживаемом RC, программа +передаст в мотор уже первое отклонение. Нельзя выдавать существующий test latch +за stop-first. Также удержание блокировки только на Mini не гарантирует эту +семантику при отказе Mini. Для независимой гарантии проверка перехода должна +жить у исполнителя либо в отдельном независимом тракте; stock FW 5.02 такой +квалифицированной функции в нынешней схеме не имеет. Это архитектурная граница, +не разрешение автоматически прошивать VESC или покупать новый контроллер. + +Остановка вычислительных задач не означает остановку служб приёма RC, +контроля привода и наблюдения его состояния. Нулевая команда тока не доказывает +физическую остановку: выбег/торможение и допустимая рекуперация требуют отдельной +проверки. Автоматический возврат к прерванной задаче после нейтрали запрещён. + +### Подтверждённая последовательность + +| Состояние | Событие | Требуемая реакция | +| --- | --- | --- | +| Движением управляет Mission Core | Первое допустимое отклонение любого назначенного RC-канала | Отозвать допуск всех остальных источников, очистить их очередь, начать согласованную остановку всех приводов и отменить задачи автономного движения. Первое отклонение не передавать как команду езды. | +| Остановка / ожидание нейтрали | Рычаг остаётся отклонённым, приходят новые пакеты | Сохранять запрет движения; количество пакетов и прошедшее время сами по себе его не снимают. | +| Остановка / ожидание нейтрали | Остановка подтверждена, все назначенные рычаги вернулись в подтверждённую нейтраль | Разрешить следующий осознанный RC-жест; Mission Core остаётся без допуска к движению. | +| Пульт готов к движению | Новое отклонение рычага | Передать ручную команду назначенным приводам. | +| Пульт управляет | Последующие отклонения и возвраты в нейтраль | Обычное ручное управление. Каждый новый жест не повторяет процедуру перехвата. | +| Любое состояние после перехвата | Пришла запоздавшая команда отменённой задачи / восстановилась связь Core | Отклонить команду. Восстановление связи не возобновляет автономное движение. | + +Это контракт поведения, не таблица состояний установленной реализации. +Условия свежести и нейтрали относятся ко всем назначенным каналам, независимо +от схемы 1×1/2×2 и числа моторов. Пропавший канал не считается нейтральным. +Ответ на USB-запрос с последним декодированным значением сам по себе не +доказывает свежий импульс приёмника: FW 5.02 не возвращает его возраст в +`COMM_GET_DECODED_PPM`. Нейтральный failsafe также не доказывает отпускание +стика оператором. Эти ограничения должны быть учтены до допуска автономии. + +### Проверка штатной FW 5.02 + +Аудит выполнен по сохранённому upstream commit +`3f670137e27e6e383fa79c50cc6b1fa85aab1554`; Git blob-хэши `app_ppm.c`, +`app.c`, `commands.c`, `datatypes.h` совпадают с сохранённым деревом Git. +Это проверка исходников upstream, не доказательство побайтового совпадения +прошивки производителя в имеющихся контроллерах. + +- `applications/app_ppm.c`: вход декодируется при отключённом выходе; + Safe Start использует счётчик нейтральных импульсов после конфигурации, + тайм-аута приёмника или ошибки. Ветка отключённого выхода не сбрасывает + этот счётчик. Завершение USB-аренды не создаёт новую проверку нейтрали. +- `applications/app.c::app_disable_output`: положительное время отключает + выход до истечения таймера; его callback просто разрешает выход. Значение + −1 отключает бессрочно, что не подходит для независимого RC при отказе Mini. +- `commands.c::COMM_SET_APPCONF`: перезапускает приложения и сохраняет + конфигурацию во flash. Это не команда ручного перехвата на каждый жест. +- `COMM_SET_CAN_MODE` может вызвать тот же перезапуск без сохранения, но + перезапуск PPM/UART и других приложений через настройку CAN не является + проверенным механизмом передачи управления. Такой обход не применяется. +- Наш native `release` отправляет `setCurrent(0)`: это снятие тяги, а не + подтверждённое торможение и не повторное включение Safe Start. + +Для исправного Mini возможен программный цикл удержания выхода до нейтрали. +Он не обеспечивает одинаковое поведение при потере Mini/USB: таймер в VESC +всё равно истечёт. Штатной проверенной функции для полного требования в +текущем тракте не найдено. Нужна поддержка перехвата на исполнительном уровне +либо другой независимый тракт. Простого изменения в одном VESC недостаточно: +отклонение одного канала должно согласованно остановить весь борт, а топология +межконтроллерной связи пока не подтверждена. + +Следующий этап реализации — выбрать и проверить такой механизм по имеющемуся +железу, включая отзыв прямых USB-команд, согласование всех приводов, остановку +и нейтраль при отказе Mini. Обновление/доработка прошивки требует отдельного +плана совместимости и восстановления. Пока проверяются эти условия, +не активировать автономное движение и не выдавать действующие стендовые +тесты за принятый постоянный арбитр. Прошивки и рабочая RC-конфигурация в этом +аудите не изменялись. + +Кандидат для следующей проверки без отдельного бортового контроллера — +штатная LispBM-поддержка современных VESC: upstream документирует для FW 6.00+ +`get-ppm`, `get-ppm-age`, `app-ppm-detach`, `app-ppm-override`, а также доступ +к PPM других VESC через настроенный CAN. Код исполняется в контроллере, +не на Mini. Это возможный исполнитель подтверждённой последовательности, +не готовая встроенная функция перехвата и не доказанная гарантия приоритета +над прямыми USB-командами. Нужны проверка совместимости платы, согласованный +обмен между приводами, исключение обхода арбитра, реакция на остановку скрипта +и квалификация поведения при потере каждого соединения. Возраст PPM отличает +отсутствие импульсов от их наличия, но не живой радиолинк от импульсов failsafe. +Текущая версия 5.02 этой документированной LispBM-возможностью не подтверждена. +Маркер 75_300_R2 недостаточен для выбора прошивки; у владельца запрошены +производитель и точная модель, если известны. Обновление не запускалось. +[Документация LispBM VESC](https://github.com/vedderb/bldc/blob/master/lispBM/README.md), +[описание поддержки в FW 6.00 автором VESC](https://vesc-project.com/node/3385). + +## Что подтверждено + +Приёмник на прежней фотографии — FlySky FS-iA6B. По сообщению владельца, +левый VESC подключён к CH3, правый к CH2. Принятое вращением назначение +контроллеров хранится по UUID, независимо от USB-порта. + +Новые фотографии пульта показывают маркировку Robcom Venom Drone. Корпус, +две кнопки питания, сенсорный экран, расположение переключателей, задних +кнопок и PS/2/USB совпадают со схемой FlySky FS-i6S. Это обоснованная +идентификация семейства по внешности. Владелец сообщает о втором внешне таком +же пульте без маркировки Robcom. Последующий осмотр About 2026-09-25 подтвердил +сообщаемые устройством Flysky FS-i6S, прошивку 2.00 от 04-Apr-2020 и Hardware +V_3.0; подробности видеоподтверждения приведены ниже. Это не аудит возможных +OEM-изменений электроники. + +По руководству семейства FS-i6S, разделы 2.2.3 и 6.8, SwA/SwB/SwC/SwD — +назначаемые переключатели: их можно связать с дополнительным каналом или +функцией передатчика. У каждого нет постоянного назначения «камера», +«ручной режим» или «аварийный стоп». На дополнительном канале передаётся +значение, соответствующее положению; смысл ему задаёт принимающая система. +Фактические назначения конкретного пульта ещё не прочитаны. Меню Aux. Channels +показывает назначения дополнительных каналов; функции самого передатчика +могут использовать переключатели отдельно (например Trainer Mode, раздел 7.3). +Текущее подключение CH2/CH3 к VESC не даёт Mini доступ ко всем этим каналам. + +В архиве конфигураций после принятого общего теста оба входа VESC настроены +как PPM Duty Cycle. Левый использует приложение PPM, правый — PPM and UART. +Настройки отклика различаются: разгон/сброс слева 0,4/0,2 с, справа 0,5/0,5 с; +параметр polynomial curve слева −1, справа −1,5; deadband у обоих 0,15. +Это сохранённые значения, не новое чтение после текущей загрузки и не +основание автоматически уравнивать параметры. Ровное вращение на общей +команде ERPM не означает одинаковую реакцию на одинаковое положение стиков. + +У обоих сохранён multi_esc=true. Наличие и топология физического CAN ещё +не подтверждены. Перед изменением схемы команд надо исключить взаимную +пересылку между левым и правым бортом; одну настройку нельзя считать схемой +проводки. Никакого CAN broadcast или изменения multi_esc сейчас не сделано. + +## Канонические механизмы + +В терминологии WPILib первый режим — Tank Drive, второй — Arcade Drive. +Arcade преобразует движение и поворот в согласованную пару команд левой и +правой стороны. Curvature Drive — отдельный вариант поведения поворота; +его нельзя незаметно подменять под тот же профиль. Стороны могут включать +несколько назначенных моторов. [Официальное описание WPILib](https://docs.wpilib.org/en/stable/docs/software/hardware-apis/motors/wpi-drive-classes.html). + +Микширование не должно трактовать ток как заданный радиус поворота: ток +связан с моментом, а скорость зависит от нагрузки. Нормализация, насыщение, +знаки, нейтраль, движение назад и разворот на месте требуют явной модели и +приёмки. Микшер и ограничения мощности — разные части системы. + +Штатное приложение PPM прошивки VESC 5.02 читает один импульсный вход. +multi_esc пересылает ту же команду другим контроллерам, а не вычисляет +дифференциальное управление из двух осей. +[Исходник FW 5.02](https://github.com/vedderb/bldc/blob/5.02/applications/app_ppm.c). + +В официальном руководстве FS-i6S есть Mix (master/slave, положительный и +отрицательный коэффициенты), сохранённые модели и просмотр каналов. Число +доступных независимых миксов, назначение осей и поведение их композиции в +имеющейся прошивке ещё не проверены. Наличие пункта Mix не доказывает +возможность получить два требуемых выхода на нынешних CH2/CH3. Меню About +показывает модель и версии. Failsafe=Off в руководстве означает удержание +последнего значения; выключенный передатчик нельзя приравнивать к нейтрали +без измерения выхода приёмника. [Руководство производителя](https://www.flysky-cn.com/s/FS-i6S-User-manual-20200628-al4y.pdf), разделы 6.9, 6.10, 7.2, 7.13. + +## Где может исполняться профиль + +1. В пульте. Сначала проверить штатное микширование на экране каналов без + команд моторам. Такой путь сохраняет независимость от Mini. Через два + имеющихся PWM-провода Mission Core не может читать или менять модель + передатчика: нельзя показывать локально сохранённый выбор как применённый. +2. На Node. Нужен полный вход с осями и явным выбором управления, например + через приёмник iBUS и совместимый интерфейс. Разъём iBUS есть у семейства + FS-iA6B, но соответствующего подключения к Mini сейчас не подтверждено. + Сначала проверить уровни, адаптер, формат и режим реального приёмника. + Текущих двух вертикальных осей недостаточно для правого двухосевого стика. +3. Во внешнем контроллере/микшере. Это технический вариант, а не принятое + решение: владелец хочет обойтись существующим бортовым компьютером. + +Выбор пути зависит от наблюдаемой аппаратуры. Реализацию универсального +переключателя нельзя завершить, скрыв эту зависимость. Не прошивать пульт или +VESC и не переподключать каналы ради проверки гипотезы без отдельного плана. + +## Наблюдение входа и приоритет пульта: существующая граница + +Текущий native backend уже читает через VESC Tool `COMM_GET_DECODED_PPM`: +декодированный уровень и длительность последнего импульса одного входа VESC. +Два USB-соединения дают два подключённых канала приёмника. Это не полный +радиообмен передатчика с приёмником, не все оси/переключатели и не подтверждение +радиолинка. Штатный PPM-код продолжает декодировать вход при временно отключённом +выходе приложения. Прямые команды тока/ERPM через USB уже применялись в тестах; +воспроизведение радиопакетов или подмена PWM-проводов для этого не нужны. + +По двум нейтральным значениям CH2/CH3 нельзя различить включённый передатчик +с отпущенными стиками и выключенный передатчик при нейтральном failsafe. +Положения SwA–SwD тоже не следует выводить из этих значений. Для перехвата по +переключателю нужен проверенный соответствующий канал, доступный на борту; +для перехвата по наличию радиолинка — подтверждённый признак валидности связи. +Подключение полного потока приёмника к Mini пока не подтверждено. Если сама +готовность включённого пульта означает ручной режим, автономия с включённым +готовым пультом блокируется; это отличается от предыдущего сценария перехвата +движением рычага. До выяснения реального сигнала не менять рабочую схему. + +В `motor_test.py` и `group_test.py` проверка входа выполняется до следующей +подачи команды. Активный канал записывает состояние `rc`, прерывает тест и +запрещает новый запуск до явного `vesc.control.release` после нейтрали. +`receiver.py` использует свежую конфигурацию deadband каждого VESC, а не +считает любой ненулевой шум командой. Это действующий код коротких стендовых +тестов, не принятый постоянный арбитр автономного движения. + +Тесты временно приостанавливают выход PPM отдельными продлеваемыми арендами +по 250 мс. Таймер исполняется в VESC: при прекращении продления PPM возвращается +без участия Mini. Это защита от исчезновения процесса/USB, а не гарантия +приоритета RC при ошибочной программе, продолжающей продлевать аренду. Также +250 мс не являются измеренной максимальной задержкой перехвата всего ровера. +Надёжный постоянный тракт требует проверки таймаутов, возврата RC, отсутствия +поздних USB-команд и поведения всех назначенных сторон. Гарантия при ошибочной +программе на живом Mini потребует независимого решения у исполнительного +уровня; наличия такой гарантии в stock FW 5.02 не установлено. + +Штатные FOC/Hall-процедуры FW 5.02 не прерываются обычной командой пульта. +Они остаются отдельным сервисным режимом вывешенного привода и не могут +запускаться в автономном движении под обещание постоянного RC-перехвата. + +## Контракт реализации в Mission Core + +- Один версионный профиль борта: режим, источник входа, проверенное назначение + осей, стороны/UUID, параметры отклика и ссылка на отдельные пределы привода. + Хранить желаемое и подтверждённое применённое состояние раздельно. +- Общий интерфейс в существующем блоке через компоненты Design Guideline; + калибровка конкретного двигателя остаётся в карточке VESC. +- Смена профиля только после нейтрали всех назначенных сторон. При частичной + потере связи запрещено объявлять общий профиль применённым. +- Перехват пультом фиксируется до явного возврата управления. Нулевое значение + PWM само по себе не определяет, выключен передатчик или стоит в нейтрали. +- На Node должен быть один владелец выхода: все команды автоматики, клавиатуры, + удалённого джойстика и другого управления проходят через него. Перехват RC + отзывает их допуск и отменяет очередь; опоздавшая команда старого допуска + не может вновь включить движение. Core отображает состояние, но не является + звеном, необходимым для локального перехвата. +- Потеря Core, Node, входного потока или одного VESC должна иметь проверенное + поведение. Существующая аренда отключения PPM для коротких тестов не является + приёмкой постоянного удалённого управления. Без Mini должен сохраняться + понятный оператору независимый путь RC, а не внезапная смена смысла стиков. +- Нативный VESC Tool остаётся владельцем протокола и конфигурации контроллеров; + калибровочные алгоритмы не копируются в новый модуль профилей. + +## Приёмка и порядок + +Node 0.8.38-2 установлен; Core принял оба VESC после исправления версии драйвера. + +1. Завершить диагностику существующего привода до установки гусениц: + подтвердить связь и сохранить свежие конфигурации; отдельно сравнить Холлы + левого и правого мотора без замены принятой калибровки. Перед процедурой + заново синхронизироваться с наблюдающим владельцем. Если сигнал отсутствует, + отделить неисправность проводки/датчика от недостаточности измерения. + Повторная калибровка не восстанавливает физический контакт. +2. После результата проверить оба направления, старт и остановку, затем + поведение пульта при потере связи на вывешенном приводе. При необходимости + уточнить нейтраль и failsafe через штатные средства. Дать отдельный вывод + о готовности к ограниченной нагрузочной проверке; существующий ровный + тест без нагрузки и исправный правый Hall не доказывают исправность левого. +3. Для нового управления прочитать About, меню Mix, карту каналов и failsafe + пульта без изменения рабочей модели. Проверить точную модель VESC и +межконтроллерную связь. Недостающая модель не блокирует диагностику текущей + версии, но блокирует обоснованный выбор новой прошивки. +4. Выбрать штатный исполнитель перехвата с независимостью от Mini, подготовить + версионную интеграцию и сначала проверить переходы без движения. LispBM + остаётся кандидатом; обновление не является обязательным следующим шагом + и не выполняется по одному имени 75_300_R2. Приёмка включает удержание + первого жеста, нейтраль всех входов, второй жест, запоздалые команды, + потерю Core/Mini/USB/связи между контроллерами и отсутствие самовозврата. +5. Реализовать Tank/Arcade и общий профиль ограничений в существующих + «Настройках борта», с индивидуальными пределами каждого привода. Выбрать + место микширования по реально доступным каналам. Новые численные максимумы + и запас 20% требуют характеристик моторов, VESC и общей батареи/BMS; + приблизительные 500 Вт и имя аппаратной прошивки их не подтверждают. + +Испытание на гусеницах зависит от результата пунктов 1–2 и допустимых рабочих +пределов, а не от завершения будущей автономии. Новый RC-перехват и Arcade +проверяются на вывешенном приводе до проверки под нагрузкой. + +Уточнение владельца: идентифицировать контроллеры программно; разборка ровера +ради чтения маркировки нежелательна и сейчас не требуется. В выполненном +аудите через установленный native Tool оба контроллера подтвердили уникальные +UUID, FW 5.02 / 75_300_R2, штатный тип VESC, test_firmware=0 и custom_configs=0. +С каждого считаны полные motor/app-конфигурации (151/149 параметров), вход PPM +и телеметрия. Оба штатных CAN ping дали пустой список: межконтроллерный обмен +не подтверждён, но отсутствие физических проводов из этого не следует. +USB-дескрипторы и USB-серийники одинаковы; идентичность по-прежнему задаёт +UUID VESC. Новые резервные копии есть в истории Core и совпадают с принятыми +архивами после калибровки. Движение и изменения настроек не выполнялись. + +Аппаратная сборка не определяет коммерческую модель: сам производитель +[Flipsky описывает разные платы серии 75 на основе 75_300_R2](https://flipsky.net/blogs/vesc-tool/tips-of-75-serise-esc). +Это подтверждение неоднозначности, не доказательство бренда имеющихся плат. +Ни новый образ прошивки, ни паспортные пределы не выбираются по одному этому +имени. Продолжить неразрушающую программную диагностику и использовать +существующую комплектацию/документацию изготовителя ровера для свойств, +которые текущий протокол не сообщает. + +Для выбранной реализации проверить нейтраль, прямое/обратное движение, +повороты и крайние диагонали, одинаковую ограниченную реакцию сторон, переход +между режимами в нейтрали, RC-перехват и отказ каждого канала связи. Сначала +без движения (преобразование входов), затем на вывешенном приводе; нагрузочные +испытания и настройка поворота на гусеницах — отдельный этап. Успешный тест +без нагрузки не подтверждает старт под нагрузкой с повреждённым Холлом. + + +## Comparative Hall result, 2026-09-24 12:13 UTC + +Node 0.8.39-1 / plugin 0.6.6 completed both separate canonical measurements. +LEFT again yields only [1,3,5,7] while the owner observes movement both ways; +RIGHT yields [1,2,3,4,5,6] and firmware success. Both configurations are unchanged +and current release is confirmed. Hall diagnostic localization is complete: +LEFT circuit incomplete, RIGHT six-state signal accepted. Exact broken physical +contact is not identified and no hardware repair is claimed. Sensorless LEFT +versus Hall RIGHT operation remains. The owner next requests visible sustained +rotation in both directions; this is a bench-test feature, separate from RC +Tank/Arcade profiles and the stop → neutral → manual authority contract. + +## Прототип во время отсутствия владельца + +По прямому запросу владельца подготовлены `packages/rover-control/src/profile.ts` +и `authority.ts`: расчёт Tank/Arcade, UUID-назначения произвольного числа моторов, +версионный JSON желаемого профиля и модель stop → neutral → manual. В production +runtime они не подключены. 21 направленный тест проверяет знак и пределы +смешивания, 2/4/10 моторов, первый/второй жест, непрерывную нейтраль, потерю +любого привода/приёмника, устаревшие данные, часы, команды и допуски после reboot. +Оси для перехвата объявляются отдельно от осей микшера: в макете даже второй +рычаг останавливает Core в Arcade, а пропавшая ось не считается нейтралью. + +Отдельный макет `apps/control-station/tools/rover-control-preview` использует +канонические контролы Design Guideline, показывает расчёт и сохраняет/выгружает +черновик. Сеть запрещена CSP; никакого обращения к роверу или новой продуктовой +вкладки нет. Пороговые времена в моделировании — синтетические, не приёмка +времени остановки Rover006. Алгоритмы калибровки VESC Tool не копировались. +Контракт и ограничения: [rover-control README](../../packages/rover-control/README.md). + +## Текущий пульт: приёмка потери сигнала завершена + +2026-09-24 владелец прочитал Failsafe: CH1…CH10 показывают 0%. После отдельной +проверки каждого мотора с удерживаемым рычагом и извлечением батарейки пульта +владелец подтвердил остановку обоих. Возврат питания/радиосвязи с рычагами +в центре не вызвал движения. Журналы, ограничения измерений и отличие от +непринятого первого опыта записаны в [протоколе 24](24_RC_FAILSAFE_ACCEPTANCE.md). +Рабочие конфигурации не менялись; это приёмка существующего прямого RC-пути, +не новой логики перехвата. Можно продолжать чтение Functions → Mix и карты +каналов. Подтверждение аппаратного исполнителя профилей в Core остаётся +обязательным до их активации: один переключатель в UI не меняет проводку. + +## Сохранённые настройки пульта: осмотр 2026-09-25 + +Владелец последовательно прочитал и затем явно подтвердил весь список: всего +четыре правила Mix, номера 1/3/4 выключены, только Mix 2 включён. Параметры +Mix 2: Master C3, Slave C4, Offset 0%, NEG −100%, POS −100%. Это перечень +правил внутри текущей модели, не четыре взаимоисключающих профиля ровера. +Настройки не меняли. Назначение C4 в конструкции пока не установлено; по +сообщённой проводке моторные входы подключены к CH2/CH3. Нельзя приписывать +этому миксу управление вторым мотором без проверки всей карты каналов. + +Владелец прислал видеозапись меню продолжительностью около 74 секунд. +Выполнен локальный визуальный разбор кадров; исходное видео не изменено, +аудиодорожка не транскрибировалась. Закрытый manifest с SHA-256 исходника, +методом разбора и кадрами хранится вне репозитория в +`outputs/rover-006-tx-menu-review-20260925/manifest.json` корня рабочего пространства. +Время ниже приблизительное, это не измерение задержки управления. + +| Экран | Наблюдение | +| --- | --- | +| Монитор каналов, 8–13 с | Полосы CH1…CH6, затем прокрутка. Отдельных движений осей с одновременным наблюдением каналов нет. | +| Reverse, 21–23 с | CH9 — Rev; остальные показанные каналы CH1…CH10 — Nor. | +| End points, 28 с | CH2: 100/110%; CH3: 110/100%, в порядке двух столбцов экрана. Это диапазон сигнала пульта, не проценты мощности или тока VESC. | +| Subtrim, 33–36 с | Видимые значения 0%. | +| Trims, 40–42 с | Off. | +| Rate/Exp., 45–47 с | Только показанный CH1 Normal: Rate 100, Exp. 0. Значения других каналов не проверены. | +| Rate/Exp. switch, 50–51 с | Assign SW: Null. | +| Throt curve, 56–57 с | График визуально прямой; численные значения всех точек не открывались. | +| Aux. channels, 60–62 с | Channel 5 назначен SwA. Назначения SwB/SwC/SwD ещё не прочитаны. | +| Failsafe, 66–67 с | CH1…CH10 показывают 0%, согласуется с предыдущим чтением и принятой проверкой потери связи. | + +SWA → CH5 подтверждает назначаемую функцию переключателя в текущей модели, +но не доступ Mini к этому каналу и не аварийную остановку. Монитор каналов +найден; повторно искать его или перебирать Mix не требуется. Следующее чтение +— системные Sticks Mode, Output Mode и About: установить раскладку, режим +выхода и версию устройства без изменения модели. Фактическое соответствие +осей выходам затем проверяется отдельно; этот ролик его не доказывает. +Никаких команд аппаратуре или изменений приложения при разборе видео нет. + +## Системные меню и идентификация пульта, 2026-09-25 + +Вторая запись владельца, около 77 секунд, содержит экран About на 72–74 с: +Flysky FS-i6S, версия 2.00, дата 04-Apr-2020, Hardware V_3.0. Идентификация +пульта теперь опирается на его собственный экран, а не только на форму корпуса. +Это не идентификация VESC и не повод обновлять прошивку пульта или моторов. + +Trainer Mode показан OFF, Switch Null; Student Mode показан OFF. Попытки +открыть Output Mode (около 22 с) и Sticks Mode (около 25 с) останавливаются +сообщением `Turn off RX!`. Значения режима выхода и раскладки рычагов не +открылись, поэтому нельзя объявлять Mode 2 либо конкретный PWM/iBUS режим +прочитанными. RX здесь означает приёмник; повторное нажатие OK при работающем +приёмнике не раскрывает заблокированные настройки. Для чтения нужен штатно +обесточенный приёмник при оставленном включённым передатчике, без изменения +значений или обхода блокировки. Никакого отключения во время разбора не было. + +Закрытое подтверждение с SHA-256 исходника и пятью кадрами: +`outputs/rover-006-tx-system-review-20260925/manifest.json` корня рабочего +пространства. Видеофайл неизменён, аудио не транскрибировалось; просмотр кадров +не является проверкой движения или записью конфигурации. Не запускать +Sticks Adjust, Factory Reset, RX Bind или Firmware Update ради чтения профиля. + +## Ограничение комплектации: без нового подключения приёмника, 2026-09-25 + +Владелец явно исключил подключение FS-iA6B к Mini дополнительными проводами, +адаптером или пайкой: таких средств нет, этот вариант сейчас неприемлем. +Прямой вход iBUS/PPM в Mini не включать в обязательный текущий план. Он не +нужен для уже доказанного управления VESC по USB: оба существующих тракта +сохраняются — пульт → приёмник → моторный вход VESC и Mini → USB → VESC. +Через VESC доступны два подключённых входных канала; полный поток остальных +осей и переключателей от этого не появляется. + +Наличие двух рабочих путей не означает приёмку их одновременных конкурирующих +команд. Нынешний код ограниченных тестов временно удерживает выход PPM, +продолжает читать вход и прекращает тест при RC-команде. Это не готовая +постоянная логика «первый жест — остановка, нейтраль, второй жест — ручное +управление» с гарантией при отказе Mini. Требование владельца сохраняется; +нельзя объявлять его выполненным либо обещать независимую гарантию только +потому, что USB-команды и прямой пульт по отдельности проверены. + +Продолжать аудит штатного микшера пульта и исполнительных возможностей VESC +в имеющейся комплектации. Реализуемость Arcade на существующих моторных +выходах, переключение его из Mission Core и независимый перехват — отдельные +вопросы. Чтение меню пульта не доказывает дистанционную запись его профиля. +Если точное требование недостижимо в этой комплектации, описать конкретное +ограничение владельцу, не подменяя задачу профилем только для команд Core. + +## Разблокированные меню после отключения батареи, 2026-09-25 + +Владелец прислал ещё две записи, около 66 и 32 секунд, с отключённой, по его +сообщению, батареей ровера. Системные страницы теперь открываются. Прочитаны: + +- Models: Model 1. +- Output Mode: выбран PWM; отдельный Serial: выбран i-BUS. Наличие выбранного + i-BUS не означает подключение этой линии к Mini; существующие VESC получают + отдельные каналы PWM. Проводка остаётся прежней. +- Sticks Mode: первоначально M2; на 37-й секунде первого ролика видно + переключение в M1, затем на 38–39-й — возврат в M2 до выхода со страницы. +- Базовые назначения M2 до миксов: правый горизонтальный CH1, правый + вертикальный CH2, левый вертикальный CH3, левый горизонтальный CH4. + Включённый Mix 2 добавляет зависимость итогового CH4 от CH3; нельзя называть + его выход независимым сырым значением левой горизонтальной оси. +- Throt Mode: Self centering. + +Это подтверждает, что для правого Arcade требуются две оси CH1/CH2, тогда как +нынешние моторные подключения CH2/CH3 дают два вертикальных канала. Прямые +команды Mini по USB остаются доступным независимым путём. Штатное микширование +нужно проверять по фактическим выходам CH2/CH3, включая подавление ненужной оси, +знаки, нейтраль, насыщение и сохранение рабочего Tank. Руководство описывает +парный Master/Slave, но не доказывает конкретный порядок каскадирования миксов +и кривых; схему нельзя объявлять рабочей только по формуле или числу слотов. + +### Новая проверка перед возвратом к движению + +На 48-й секунде первого ролика открыт Sticks Adjust. До конца записи нет +полного прохода всех осей/крутилок по пределам; второй ролик начинается уже +в обычном меню. Завершение процедуры между роликами не видно. По штатному +руководству §7.8 это калибровка аналоговых органов пульта, с сохранением через +выход после центрирования, а не обычный монитор каналов. Нельзя гарантировать +неизменность калибровки или объявлять её испорченной по этим кадрам. + +Перед повторным включением силового питания нужен обычный монитор CH1…CH6 +с проверкой нейтрали и отдельных полных ходов осей при выключенных приводах. +Это проверка пульта, не повторная FOC/Hall-калибровка VESC. Не использовать +Sticks Adjust для чтения показаний и не запускать автоматический sweep. + +В первом ролике также кратко открыт RX Bind при выключенном, по сообщению +владельца, приёмнике; результат привязки не проверялся. Во втором открыт +диалог Factory Reset: нажата правая кнопка и выполнен возврат в меню; нет +подтверждения выполненного сброса. Firmware Update просмотрен до страницы +Continue, затем закрыт; обновление на записи не запускалось. Не превращать +обход меню в утверждение, что все действия были только чтением. + +Закрытые оригинальные хэши, кадры и метод разбора: +`outputs/rover-006-tx-offline-review-20260925/manifest.json` корня рабочего +пространства. Оригиналы не изменены, аудио не транскрибировалось. Со стороны +ассистента операций с пультом, Node или VESC при разборе не выполнялось. + +## Проверка монитора каналов после Sticks Adjust, 2026-09-25 + +Следующая запись владельца, `IMG_2491.MOV`, около 41 секунды, показывает +обычный монитор CH1…CH6 и движения сначала левого, затем правого рычага. +Оба используемых моторных канала проходят в положительную и отрицательную +сторону: CH3 при вертикальном движении левого рычага, CH2 — правого. После +возврата рычагов значения визуально близки к центру, с небольшими остаточными +смещениями. Признаков застрявшего крайнего значения или отсутствующей половины +хода этих двух каналов в записи нет. По полоскам нельзя измерить точные +проценты, ширину PWM-импульса или подтвердить допустимую нейтраль на VESC. + +Горизонтальные движения изменяют CH4 слева и CH1 справа; часть правого +горизонтального прохода затемнена/перекрыта рукой. Зависимость CH4 от +вертикального CH3 имеет противоположный знак и соответствует ранее прочитанному +Mix 2. Неподвижное пятно на поверхности экрана возле CH4 не является показанием +канала. Это качественная проверка раскладки M2 и моторных выходов пульта, +не приёмка Arcade, нового перехвата, радиосвязи или failsafe после изменения +меню. Повторное обследование меню для установления этих назначений не требуется. + +Следующий шаг после подтверждённого владельцем возврата питания на вывешенном +ровере с рычагами в центре — прочитать фактические уровни обоих входов через +VESC и сравнить их с сохранённой мёртвой зоной, без команд вращения. Во время +разбора этого видео силовое питание не включалось средствами ассистента, +команды приводам не отправлялись, калибровка VESC не менялась. + +Закрытые хэш исходника, 11 кадров и метод разбора: +`outputs/rover-006-tx-axis-review-20260925/manifest.json` корня рабочего +пространства. Оригинал не изменён; аудио не транскрибировалось. + +Продолжение: владелец вернул питание, проверил движение от стиков, затем +подтвердил нейтраль и физическую остановку обоих моторов. Чтение через VESC +подтвердило уровни справа −0.06, слева +0.068…+0.07 внутри deadband ±0.15, +нулевые duty/ток батареи и отсутствие ошибок. Motor/application конфигурации +обоих контроллеров побайтно совпадают с сохранёнными 2026-09-24. Проверка +нейтрали после просмотра меню закрыта; подробности и границы результата — +в `24_RC_FAILSAFE_ACCEPTANCE.md`, раздел «Нейтраль после возврата питания». +Профиль одного стика и постоянный перехват этим чтением не приняты. diff --git a/docs/node/24_RC_FAILSAFE_ACCEPTANCE.md b/docs/node/24_RC_FAILSAFE_ACCEPTANCE.md new file mode 100644 index 0000000..8f67876 --- /dev/null +++ b/docs/node/24_RC_FAILSAFE_ACCEPTANCE.md @@ -0,0 +1,247 @@ +# Приёмка пульта и потери сигнала + +Состояние: оба моторных канала прошли наблюдаемый вывешенный тест остановки +при потере питания передатчика. Восстановление связи с рычагами в нейтрали +не вызвало движения. Точное время реакции и поведение под нагрузкой не измерены. +Node 0.8.40-1, VESC plugin 0.6.7, FW 5.02. +Калибровка и рабочие настройки не изменяются этим исследованием. + +Обновление 2026-09-25: после просмотра системных меню передатчика и захода +в Sticks Adjust повторно проверены монитор каналов, физическая остановка по +сообщению владельца и фактическая нейтраль на обоих VESC. Конфигурации VESC +побайтно совпадают с исходными от 2026-09-24. Это не повторный тест потери +радиосвязи после действий с меню пульта; его прежняя приёмка относится к +описанным ниже испытаниям 2026-09-24. + +## Начальное состояние, 2026-09-24 + +Владелец подтвердил: пульт выключен, оба мотора неподвижны, гусеницы сняты, +ровер вывешен. Свежая инвентаризация Core подтверждает два прежних UUID, +нет активного теста или RC-защёлки. Через штатные операции сохранены обе +конфигурации и прочитаны входы/телеметрия. Никаких команд движения, аренды +выхода, alive, записи конфигурации или прямого доступа к serial не выполнялось. + +Оба контроллера: вход PPM около +0.010…+0.012 при deadband 0.15, PWM 0, +ток батареи 0, fault 0. Правый показывает 0 ERPM. Левый при физическом +покое показывает -153…-165 ERPM: ранее установленный дрейф бессенсорной +оценки, не доказательство движения. + +Сохранённые настройки: duty-cycle PPM control; Safe Start включён; timeout +1000 мс, timeout brake current 0 A; pulse 1.0/1.5/2.0 мс; multi_esc включён. +Слева PPM, справа PPM+UART. Плавность слева 0.4 с набор / 0.2 с сброс, +справа 0.5 / 0.5 с. Экспонента -1.0 слева и -1.5 справа. Из этого нельзя +делать вывод о дефекте мотора или автоматически унифицировать настройки. + +## Граница измерения + +Декодированный PPM в FW 5.02 сообщает последнее значение и длину импульса, +но не возраст импульса и не состояние радиолинка. Нейтраль при выключенном +передатчике сама по себе не доказывает failsafe: передатчик мог быть выключен +после нейтрали, а приёмник мог удержать последнее значение. + +По исходникам pinned upstream 3f670137: при утрате импульсов PPM обработчик +проверяет их возраст и тайм-аут, снимая тягу при timeout brake current 0. +Это не активное торможение с заданным временем остановки. Если приёмник +продолжает выдавать ненулевое последнее значение, тайм-аут VESC не решает +потерю радио. Руководство FS-i6S 2020-06-28, раздел 6.10, описывает Off как +удержание последнего значения. Точная модель/настройка имеющегося передатчика +ещё требует проверки его экрана; внешний вид не достаточен. + +## Порядок продолжения + +1. Включение пульта с обоими рычагами в нейтрали; чтение входов и наблюдение + отсутствия самопроизвольного движения. +2. Чтение About, Failsafe для CH2/CH3 и карты каналов на пульте; без изменения + текущей модели. Если выявлено удержание последнего положения, сначала + подготовить и проверить нейтральный failsafe через штатные средства. +3. Под наблюдением владельца проверить отклонение/возврат каждого рычага, + соответствие стороне и исчезновение команды в нейтрали. +4. Отдельно согласовать выключение передатчика во время ограниченного + движения, прочитать вход и состояние обоих VESC, получить физическое + наблюдение остановки. Возвращать радиосвязь с рычагами в нейтрали. +5. Проверить восстановление связи и отсутствие самопроизвольного движения. + +Чтение через отдельные удалённые операции даёт около 4.8 с на полный цикл +двух входов и двух телеметрий в начальном замере. Такой журнал фиксирует +состояния, но не позволяет подтвердить миллисекундную задержку остановки. +Не выдавать USB-время ответа за время реакции радиоканала. При необходимости +точного времени добавить продуктовую бортовую запись, не обходить драйвер. + +Исходный приватный протокол rc-failsafe-d83b84fb311245e5b8a3fea31716416b.json, +SHA-256 8098fe14a754622cb027472fa4f48f96fa9ffcb0548b16af557ac90a56ea6fb1. +Два полных цикла чтения, оба успешны. Наблюдатель rc_failsafe_observe.py +разрешает только input.read, telemetry.read и config.backup. + +## Уточнение наблюдения после включения пульта + +Протокол rc-failsafe-34b93f7184024d87a8e66327f2f60649.json был изначально +помечен `tx-on-neutral-confirmed`, но во время чтения зарегистрированы +отклонения входов и вращение правого. Владелец уточнил: «Двигал рычаги; +сейчас оба стоят». Поэтому этот замер содержит ручное управление и **не** +является ни доказательством самопроизвольного запуска, ни чистой проверкой +включения в нейтрали. Исходная метка и сырой протокол сохранены неизменными. +SHA-256: 26dd21ffae833b4ac13aa1ceb004b97a3b58de8ea4ded9856ec616a335744d4b. + +Следующее чтение rc-failsafe-ea478fad45c047db919f892c23a34dc2.json подтвердило: +справа вход −0.064 / 1.468 мс, слева +0.074 / 1.537 мс; оба в текущей зоне +нейтрали ±0.15. На обоих PWM 0, ток батареи 0, fault 0. Справа ERPM 0, +слева −156 при подтверждённом физическом покое — известная бессенсорная +оценка. Это не подтверждает исправность левого Холла и не измеряет failsafe. +SHA-256: 6fe3cceeae8d1afc6116048df9079001a46a1f08a8813de4782ac7433d33dab8. + +Владелец отошёл на 15 минут и разрешил независимую разработку/прототипирование. +Моторные испытания приостановлены до его возвращения и новой синхронизации. +Вопрос о модели в About и текущем Failsafe CH2/CH3 остаётся без ответа; +повторно спрашивать или самостоятельно менять настройки по догадке не нужно. + +## Возвращение владельца + +Владелец сообщил: гусеница снята, пульт включён, он рядом и готов выполнять +действия. Запрошено оставить рычаги в нейтрали и прочитать Failsafe CH2/CH3. +До ответа выполнены только два цикла input.read/telemetry.read: справа вход +−0.064…−0.066, слева +0.072…+0.074; оба в текущей зоне нейтрали. PWM и ток +батареи 0, fault 0 на обоих; справа ERPM 0, слева −159…−151 (прежняя +бессенсорная оценка, не отдельное подтверждение физического покоя). +Протокол rc-failsafe-b05818b1cf8a426f8dccd5e6f80b19a5.json, +SHA-256 511257aafc9d2f000d65073438399b9f7fa52c86515f4a7e994fd28b610737bb. +Команд движения, alive, аренды выхода или записи конфигурации не было. + +## Экран Failsafe и первый ручной тест потери сигнала + +Владелец открыл сенсорное меню Functions после разблокировки экрана и затем +Failsafe. Сообщил: каналы CH1…CH10, везде 0%. По официальному руководству +семейства FS-i6S числовая позиция означает заданное положение при потере +радиосигнала, в отличие от Off/удержания последней команды. Отдельные +настройки не изменялись. Модель/версия из About ещё не прочитана. + +Для проверки выдано задание: на вывешенном приводе с демонтированной +гусеницей запустить правый мотор небольшим отклонением, выключить пульт до +возврата рычага, затем отпустить его; сообщить наблюдение остановки. Если +вращение продолжается — вернуть рычаги в нейтраль и восстановить пульт. +Программа при этом только читала входы и телеметрию, 13 циклов за примерно +60 секунд. Зафиксированы правый вход +0.254, 798 ERPM и PWM 0.051; затем +PWM 0, 72 ERPM, и в последнем цикле вход −0.064, PWM 0, ERPM 0. Fault 0 +на обоих VESC. Пары input/telemetry снимаются последовательно, не синхронно. + +Протокол rc-failsafe-fe6aea514466484aad007568c9f90cc0.json, +SHA-256 d1c471f855f80c1715578df0bfc0e69a8c517a7cc9c2cf1aeaa09ef61e37c9a9. +Физический результат и факт выключения при удерживаемом ненулевом рычаге +пока ожидаются от владельца. До этого переход нельзя объявлять принятым +failsafe; USB-наблюдение не отличает потерю радиосвязи от отпускания стика. +Никакого испытания левого канала или восстановления радиосвязи ещё не принято. + +Уточнение владельца к первому тесту: он **сначала отпустил рычаг**, затем +вынул батарейку пульта. Поэтому этот опыт не подтверждает остановку из-за +потери радиосвязи. После снятия питания передатчика отдельное чтение показало +правый вход +0.010 / 1.504 мс, левый +0.012 / 1.506 мс; PWM и ток батареи 0, +fault 0 на обоих, ERPM правого 0. Протокол +rc-failsafe-f99b5bb25bff471dbe017ed0b8f4632b.json, +SHA-256 4ade3d8a2061048c67b3e21a83304fd6a9cb832942189f6a08c29792a6984adc. +Это подтверждение нейтрального выхода при выключенном пульте после нейтрали, +а не проверка прекращения ненулевой команды. Запущена отдельная запись для +повтора с явным удержанием рычага до физического отключения передатчика. + +## Правый канал: остановка при потере радио подтверждена + +Повтор rc-failsafe-b208d87fa223496ca5fffebddf4ad9be.json, 25 полных циклов, +2026-09-24T13:39:31.281029Z…13:41:33.274243Z, +SHA-256 00e64109018c8b815b96b5db1e69fbb32ca7ab80bd8eff672f3ac86b69caffb1. +После восстановления пульта вход правого вышел из нейтрали, зарегистрировано +вращение. На цикле 11 вход +0.232 / 1.616 мс, 282 ERPM, PWM 0.022; +на цикле 12 вход +0.010 / 1.505 мс, ERPM 0, PWM 0. Левый вход также +вернулся к прежнему значению выключенного передатчика, PWM 0. Fault 0 везде. + +Владелец подтвердил: он вращал правым рычагом, вынул батарейку, и мотор +остановился непосредственно при её извлечении. Это исправленный повтор +предыдущего опыта с отпусканием рычага до отключения. Для правого канала +поведение прекращения ручной тяги при потере радиосвязи принято в рамках +этого вывешенного теста. Точная задержка в миллисекундах не измерена; +нагрузочный тормозной путь и будущий stop-first перехват из Core не проверены. + +Следующий запуск записи для левого был случайно прерван владельцем. Проверено: +нового протокола не создано, процессов rc_failsafe_observe.py не осталось. +Команд движения не было. После возобновления запущен отдельный read-only +протокол левого и выдана та же последовательность удержания рычага до +отключения. Его результат пока ожидается; приёмка левого не следует из правого. + +## Левый канал: физическая остановка подтверждена владельцем + +Протокол rc-failsafe-cc289f6fce514a21af66bf7c17117e59.json завершён, +24 полных цикла; SHA-256 +64164b2083a1b28172ebe1471a7f59df88c1d10b085db6e204f7c60f81608d11. +На цикле 8 левый вход +0.280 / 1.640 мс, ток мотора 2.39 A; на цикле 9 +вход +0.012 / 1.506 мс, ток 0.04 A. После отключения оба PWM нулевые, +fault 0. Сама скорость вращения левого не попала в редкие последовательные +USB-замеры; его отрицательный ERPM при PWM 0 нельзя трактовать как движение. + +На отдельный прямой вопрос «Левый мотор действительно крутился до извлечения +батарейки и остановился именно после него, пока рычаг оставался отклонённым?» +владелец ответил «Да, крутился и остановился после извлечения». На основании +этого физического наблюдения и записи возврата входа в нейтраль поведение +левого канала при потере радио принято для данного вывешенного теста. +Точное время остановки, нагрузка и исправность Холла этим не подтверждаются. +Далее запущена отдельная запись восстановления пульта в нейтрали обоих рычагов. + +## Восстановление связи и итог + +Протокол rc-failsafe-6811a6865139462cb233566fb2bead05.json завершён, +13 полных циклов; SHA-256 +c9d36bf24ca7ae43bb51bd7777c936e58ca44f3dd3d3b3b14126f6cf8717516f. +В ходе записи входы перешли от значений выключенного пульта около +0.01 +к его включённой нейтрали: справа −0.062…−0.064, слева +0.076. PWM 0, +ток батареи 0 и fault 0 на обоих во всех записанных циклах. Правый ERPM 0; +слева прежняя ненулевая бессенсорная оценка при снятой тяге. + +Владелец подтвердил: после возврата батарейки, включения и ожидания около +пяти секунд с рычагами по центру оба мотора остались полностью неподвижны. +Приёмка текущего RC-пути в объёме стендового сценария завершена: +ненулевая ручная команда → полное отключение передатчика → остановка отдельно +справа и слева; затем восстановление связи в нейтрали без самопроизвольного +движения. Источник физического результата — наблюдение владельца; журналы +фиксируют входы/телеметрию с последовательным USB-опросом, а не точную задержку. + +Конфигурации и калибровка не изменялись, команды движения от Core не выдавались. +Этот результат не принимает новый stop → neutral → manual перехват из +автономии, отказ Mini/USB, поведение восстановления с отклонённым рычагом, +нагрузочный тормозной путь или исправность повреждённой левой цепи Холла. +Следующий этап — чтение текущих Mix/карты каналов пульта для Tank/Arcade, +без изменения рабочего радиопрофиля по догадке. + +## Нейтраль после возврата питания, 2026-09-25 + +После видеопроверки монитора передатчика владелец вернул питание ровера и +сообщил, что моторы вращаются от стиков. Перед чтением отдельно подтвердил: +пульт включён, оба стика по центру, оба мотора полностью неподвижны. Через +канонический Core выполнены config.backup обоих VESC и два последовательных +цикла input.read / telemetry.read. Тестов вращения, аренды выхода, alive и +записи конфигураций не было. Оба прежних UUID в свежей инвентаризации доступны, +активных моторных тестов нет. + +| Измерение | Правый | Левый | +| --- | --- | --- | +| Уровень декодированного входа | −0.059999 | +0.068…+0.069999 | +| Импульс | 1.470 мс | 1.534…1.535 мс | +| Настроенная зона нейтрали | ±0.15 | ±0.15 | +| Duty / ток батареи / fault | 0 / 0 / 0 | 0 / 0 / 0 | +| ERPM | 0 | −162…−147 | + +Оба входа внутри мёртвой зоны. Ненулевая бессенсорная оценка ERPM слева при +нулевом выходе и подтверждённом физическом покое не является вращением. +Сырые показания тока мотора справа −0.55…−0.79 A, слева +0.09…+0.11 A; +не подменять их утверждением, что все датчики показывали математический ноль. +Проверка нейтрали завершена; изменение deadband или повторная калибровка VESC +по этим результатам не требуется. Полный цикл чтения занимает около 6 секунд +и не измеряет задержку перехвата. + +Прочитанные motor/application payload каждого контроллера побайтно равны +исходным из протокола `rc-failsafe-d83b84fb311245e5b8a3fea31716416b.json`. +Рабочая FOC-калибровка, режимы sensorless/Hall, направление, токовые пределы +и настройки PPM сохранены. Это сравнение конфигураций VESC, не всей модели +или внутренней калибровки передатчика. + +Приватный протокол `rc-failsafe-b79d96f465f94fcb881e48a536ea0cc7.json`, +SHA-256 `c71b9c4b805f9b7a0909e8a26355297a831224997f7cb0fd908ce08bf88960eb`. +Отдельный результат сравнения: +`rc-neutral-comparison-b79d96f465f94fcb881e48a536ea0cc7.json` в той же закрытой +папке `outputs/rover-006-vesc-context-20260923/native-probe`. Наблюдатель +завершился штатно; постоянный процесс опроса не оставлен. diff --git a/docs/node/25_OBSERVATION_AND_REMOTE_CONTROL.md b/docs/node/25_OBSERVATION_AND_REMOTE_CONTROL.md new file mode 100644 index 0000000..7d296db --- /dev/null +++ b/docs/node/25_OBSERVATION_AND_REMOTE_CONTROL.md @@ -0,0 +1,545 @@ +# Observation and remote control — implementation record + +Owner request: 2026-09-25. Extend the existing per-vehicle observation center. +The operator sees cameras, map, a vehicle model and per-controller telemetry, +then explicitly takes keyboard/pointer control. Return goes to the vehicle list. + +## Product surface decision + +Selected: two new layers in the admitted observation composition, with the model +below the map and telemetry alongside it. Rejected: a separate driving workspace, +which would separate the operator from cameras and duplicate vehicle navigation. +No primary navigation or product root changes. Layer visibility/order/splits stay +in the existing versioned per-vehicle layout. The header host owns the back action. + +States: offline, observing, preparing, ready, driving, receiver takeover, stopped, +fault. Showing a model, pressing a key while disarmed, or reconnecting never arms +motion. Stale telemetry is unavailable, not zero. No fabricated position/distance +or model motion is inferred from keyboard intent. + +Design Guideline: existing Button/IconButton/Window/Select/Switch/LoadingRegion, +SplitPane, GlassSurface and StatusBadge. Owner explicitly approved outlined +momentary key buttons; shared KeyButton is added to DG first. Arcade W/S+A/D; +tank Q/A left forward/reverse, E/D right forward/reverse. Space stops/disarms. + +## Sources + +NodeDC source: `NODEDC_ENGINE_INFRA/nodedc-source/src/viewer/playcanvas/`. +Copy the rendering implementation, DEFAULT_POSTFX and environment atlas with +source hashes; keep lighting/postprocessing/grid shader settings unchanged. +Vehicle export preserves immutable Blender originals. v021 is a two-scheme +kinematic study, not the full rover; full reconstruction is v020. Owner explicitly selected v020. The export contains all 1,426 renderable +objects, joined into four donor material groups without geometric decimation. + +## Control boundary + +Existing five-second inventory/operation heartbeat is unsuitable for held keys. +Implement a separate authenticated, ephemeral command channel on the already +paired mTLS transport. Core does not access USB. The Node relays to its single +VESC owner. Browser, relay and native output each have bounded leases; commands +are identity/session/sequence bound and never persist or resume after restart. +Motion command transport is distinct from configuration/calibration operations. +Per-wheel current is measured motor current; battery input current is separate. + +Stock FW 5.02 resumes direct PPM when its output-disable lease expires. A healthy +board can stop on RC intent and require neutral; a failed board cannot guarantee +the full first-gesture-stop protocol against held RC input. This limitation must +remain explicit in acceptance and cannot be fixed by UI promises. + +## Validation — 2026-09-25 + +Core lease tests: 13 passed. VESC driver: 127 tests passed, including eight +remote-control tests (expired/duplicate frames, terminal stop, invalid bounds, +RC first-gesture zero hold, reversal neutral interval, one-port failure and +unconfirmed release). Native Tool adapter compiled and passed offline archive +and output-denial checks on Mini; no hardware access during qualification. +Control Station: architecture checks, typecheck, 939 unit tests and production +build passed. The active operator checkout retains its unrelated simulation and +AI polygon changes. Canonical 8000 was restarted through its existing launchd +service, preserving configuration and operator data. + +Browser acceptance: back returns to the fleet list; full v020 visible; model +selection persists across reload; Tank changes the key pad to Q/E/A/D; Arcade +restores W/A/S/D; both layers appear in Available layers; hidden telemetry stays +hidden after leaving/re-entering, then was restored. Pane maximize/restore keeps +the scene and canvas sizes correctly. No arm or motion command sent. + +Export correction: initial exporter unintentionally included the original +Blender scenes; visual QA found the studio floor obscuring the rover. Export is +now limited to the active export scene and selected joined object, verified as +one scene, one mesh, four donor materials (54,960,576-byte GLB). Immutable v020 +source is unchanged. All donor lighting/postprocess defaults remain unchanged; +only asset URLs, responsive hosting and model framing adapt to Mission Core. + +Node 0.8.41-1 / VESC integration 0.7.0 qualification passed and the versioned +owner installer completed on Mini. dpkg confirms 0.8.41-1; Node/VESC services +are active. The paired fast channel supplies fresh RIGHT telemetry with no +control session. LEFT is absent from Linux USB enumeration, while its UUID +assignment remains intact; kernel descriptor errors -71 occurred at 11:18–11:19 +MSK, before the installer stopped the driver at 11:20:28. The owner confirms +USB/power was reconnected during the work. This does not establish the physical +cause; no USB reset or ad-hoc OS change was performed. The telemetry layer now +retains missing assigned motors, explicitly shows no connection, and never +substitutes another UUID or zero measurements. +Hardware motion, actual channel latency and physical stopping require a fresh +attended acceptance test. Offline tests do not qualify loaded driving or the +Mini-independent stop-first RC behavior described above. +Ship every Node runtime change in the versioned installer; no ad-hoc board edits. + + +### Owner power-cycle and first admission attempt + +At 11:35 MSK the owner disconnected/reconnected the battery. Both USB devices +then enumerated and the existing runtime recovered both assigned UUIDs without +an application restart or agent-issued port reset. Twenty read-only samples +(10 seconds) all contained both fresh devices, no active control session. + +After fresh owner confirmation (tracks off, raised stationary rig, TX off, +observing), one Core API trial was armed at 11:38:46 MSK. Initial preflight +rejected sensorless duty=0.001; no forward command, output claim or temporary +limit application was reached. This is not a keyboard or motion acceptance. + +Source investigation: pinned FW 5.02 mcpwm_foc.c, commit +3f670137e27e6e383fa79c50cc6b1fa85aab1554, undriven branch lines 2550–2693, +computes duty_now from measured phase voltages/back EMF even with no driven +output. commands.c encodes this field with scale 1000. The earlier strict +zero-duty assumption for observed sensorless standstill was therefore incorrect. +The new bounded tolerance is one wire quantum, abs(duty)<=0.001, only for that +already explicitly observed sensorless case. The other current, voltage, +temperature, fault, input-current and stable-neutral checks remain in force. +This is an admission bound, not proof of physical stopping or a motor rating. +New regression verifies both signs of one quantum, rejection of two quanta and +continued rejection of unobserved speed drift. All 128 VESC tests passed. +Node 0.8.41-2 / VESC integration 0.7.1 passed qualification and was installed +through the owner-authorized versioned installer at 12:08:23 MSK; no ad-hoc +runtime patch and no automatic repeat of movement. + +The same follow-up separates terminal input-lease completion from hardware +faults: normal session end reports stopped only after cleanup; unconfirmed +release or restoration warnings remain fault. Regression drives the actual +output loop through the session wrapper and verifies release of both outputs. +The preceding qualification completed, but its package was superseded before +installation to include this correction in one owner update. Final VESC suite: 130 tests passed. + +Post-install verification: both services active, installed runtime 0.7.1, both +assigned controller UUIDs fresh after observation refresh (14–205 ms), zero +currents/duty/fault codes and no control session. Fresh owner observation is +required for the next attended API trial; physical keyboard/RC acceptance remains pending. + +### Attended retry and channel diagnostics + +At 12:18:51 MSK, the helper rejected cached device samples before sending arm. +Read-only refresh restored both fresh UUIDs. The one armed trial at 12:19:28 +remained in preparing for about five seconds, then ended stopped before the +helper ever sent forward demand. The browser-to-Core zero-demand heartbeat +continued every approximately 100 ms. No service restart occurred. The current +evidence does not distinguish a Core transport failure from a Node scheduling +gap; it does not establish a new USB failure. + +Node 0.8.41-3 adds a bounded 32-frame in-memory channel diagnostic recorder, +flushed to the private service journal on session transitions, transport errors +or long gaps during a session. It records monotonic intervals, binding wait, +Core/driver elapsed times, sequence/remaining TTL and state. It excludes trust +material, endpoints, request bodies and raw HTTP error text. Admission, timeout, +lease and motor-output behavior are unchanged. Qualification/installation is +pending; no automatic physical retry. + +Node 0.8.41-3 installation completed successfully at 09:36:34 UTC in 18 seconds +after owner-local Ubuntu authorization. Package version and active Node/VESC +services verified. Both assigned UUIDs produce fresh readings (190/199 ms), +zero motor current and fault codes; no control session. Owner observation is +requested again before one bounded repeat; no motor output sent after the +12:19 preparation abort. + +### Recorded channel timing and operator TCP correction + +The attended 12:38:43 MSK retry again ended in preparation without forward +demand. The new journal localizes the failure to the Core/Node transport budget: +Core round trips commonly took 100–270 ms, driver calls 1–3 ms and initial +binding-lock waits zero. One response explicitly expired in transit; another +response body exceeded the 300 ms HTTP deadline. The first inferred consecutive +command arrival gap was already greater than its remaining lease. No service +restart occurred. This does not establish an electrical or USB fault. + +Read-only Tailscale checks confirmed DERP(hel) relay rather than a direct path. +Five Tailscale probes: 42–120 ms; five ICMP probes: 42.8–157.5 ms, zero loss. +No VPN, route, firewall or onboard OS settings were changed. Private network +inventory is retained only in the private evidence directory. + +The paired Core HTTP handler used the standard TCP Nagle default while writing +small response headers and JSON separately. Enabled its supported +disable_nagle_algorithm option (TCP_NODELAY) to remove an avoidable buffering +source; this does not change authentication, TTLs or output limits. All 52 +Fleet tests passed. Promoted the same narrow change to the active operator +checkout and restarted its existing launchd service only after verifying no +active motor session. Canonical 8000 and both fresh controller readings recovered. +Whether this is sufficient for the current relay path still requires attended +acceptance; no automatic motion retry. + +The 12:46:39 MSK attended retry disproved sufficiency: responses improved to +47–70 ms at times but still reached 166 ms, and preparation ended before any +forward command. Four armed remote-channel attempts have now failed in +preparation; none is a motion acceptance. Subsequent motor trials are paused +while the command delivery mechanism is corrected. + +### Node 0.8.42: independent command stream (qualification pending) + +The paired Core endpoint now offers an authenticated NDJSON response containing +the latest command every 50 ms. Telemetry remains a separate request/response +channel. Certificate, binding and endpoint revision are checked on every frame. +No command queue is introduced. Legacy Node clients retain their existing +exchange response; new clients consume commands only from the stream. + +Core attaches a random process clock epoch and an absolute monotonic expiry to +each command. Node estimates a conservative upper bound on Core clock offset +using request-send time and the timestamp taken afterward at Core. It never +assumes symmetric network latency or synchronized wall clocks. A 5 ms margin, +1000 ppm clock-rate allowance and 25 ms private driver-call reserve reduce the +remaining lease. The original 400 ms deadline is not extended on receipt or +repeated frames. Clock calibration expires after two seconds; loss of return +telemetry retires the Core session after one second. These are software timing +bounds, not hard-real-time or field-safety certification. + +A separate local 20 Hz loop feeds only the latest unexpired intent to the +single VESC owner. Stream silence cancels its network read after 350 ms; +disconnect, epoch change, binding change or failed local RPC requires an +acknowledged null command before accepting further frames. An interrupted +session remains retired in the existing native-driver lease and cannot resume +on reconnection. The C++ output watchdog (200 ms), PPM suppression lease +(250 ms), firmware, calibration and output limits are unchanged. + +Qualification covers asymmetric delay, measured relay jitter, original expiry, +replayed frames, stop-ack races, old clock epochs, stale calibration, silent +HTTP streams, multiple frames per response and binding revocation midstream. +Physical API motion, keyboard release/blur and RC takeover acceptance remain +pending and require fresh owner observation after installation. + +Node 0.8.42-1 installed successfully at 10:22:27 UTC. Forty read-only samples +over ten seconds showed observing/no active session; the last twenty contained +both assigned controllers with ages at most 217 ms, zero current and fault. +The freshly authorized 13:25:53 MSK API trial still ended during preparation, +without forward demand. Unlike the previous transport, the local driver loop +held 50–51 ms intervals and 1–3 ms responses; no stream disconnect was logged. +In the retained timeline sequence 26 had about 29 ms remaining at local time +218304 ms; sequence 28 reached the driver at 218355 ms. This is consistent +with an expired previous lease despite delivery of a subsequently fresh frame. +The driver correctly does not revive such a session. It is not evidence of a +new USB fault or accepted movement. + +Follow-up 0.8.42-2 removes periodic-tick waiting for new intent at both ends: +Core condition notification wakes the stream immediately on accepted input or +stop; Node uses a one-slot wake signal and always reads the latest intent. +The 50 ms periodic tick remains a fallback, not an input queue. Tests cover +updates before/during wait, immediate stop, coalescing and unchanged replay. +Original 400 ms expiry, output watchdog and current limits remain unchanged. +The private diagnostic history expands to 128 frames, and terminal telemetry +no longer triggers idle journal spam solely because it retains a session ID. +Core tests: 59 passed. This follow-up requires qualification and installation +before a separately synchronized physical retry. + +Owner OS authorization completed: final 0.8.42-2 installed at 10:47:29 UTC +in 18.67 seconds, all installer steps exit 0; Node and VESC services active. +Forty read-only samples over ten seconds confirmed observing/no active session. +The final twenty contained both assigned controllers, at most 216 ms old, +with zero motor/input current, duty and fault. Fresh owner observation has +been requested before any new motion; the five previous failed preparation +attempts remain failures, not movement acceptance. + +Sixth attended Core API attempt, 10:52:51 UTC, stopped before forward demand: +"another VESC operation is running". Recorded command TTL remained 323 ms, +so this particular failure is different from the preceding lease expiry. +The remote observer shares operation_lock; _prepare previously attempted +nonblocking acquisition and treated any overlapping read as a fatal conflict. +The trace does not identify which operation held the lock; code and a +concurrent regression reproduce this admission race without hardware. + +Candidate Node 0.8.43-1 / VESC 0.7.2 waits up to 500 ms for exclusive access, +checks the existing input lease every 20 ms and after acquisition, and skips +new observer cycles while the control worker is alive. It does not queue a +future drive or extend the input lease. Tests cover completing an in-flight +read, Stop while waiting, expiry before acquisition, bounded rejection of a +long operation, and observer yielding. Canonical unittest discovery passes +135 tests. A first full pytest invocation incorrectly collected the imported +protocol helper test_packet as a fixture-based test; no product failure was +reported, and the suite was rerun with its canonical unittest runner. +Installation and a separately synchronized physical retry are pending. + +Node 0.8.43-1 / VESC 0.7.2 installed at 11:06:32 UTC in 18.49 s, +all installer steps exit 0. Both services active; final 20/40 read-only +samples contained both assigned UUIDs, age <=219 ms, zero currents/faults, +observing/no control session. A fresh attended trial is requested separately. + +Seventh observed Core API attempt at 11:10:39 UTC reached preparing without +the ownership fault, then stopped before forward demand. Sequence 19 arrived +with ~313 ms remaining; sequence 20 followed ~315 ms later, consistent with +expiry at this boundary. The old trial sent a command, synchronously fetched +telemetry and only then scheduled its next input. Telemetry reads introduced +periodic delays up to ~319 ms in its sample cadence. This differs from the UI, +where the command heartbeat and telemetry poll are independent. + +The corrected attended_stream_test.py separates bounded telemetry polling +from 100 ms command renewal, preserves the same 400 ms lease and all existing +preflight/stop checks, and records request timing for every command. Synthetic +checks prove blocked reads do not hold the input path, failures abort and +reader threads terminate. This is a test-harness correction, not movement +acceptance or proof that all transport jitter is solved. A fresh observed +trial is requested; there is no automatic motion retry. + +Core-only timing logs were added to distinguish registry wait, archive and +save delay. All 59 Fleet tests pass; loopback HTTP test needed sandbox network +permission. The active Core received only this reviewed registry.py diff and +was restarted without an active session. Read-only samples: max local GET +179.8 ms, three of forty above 100 ms; retained registry waits 25.9–58.5 ms. +No archive/save delay above 25 ms was reported in the initial capture. Thus a +registry persistence bottleneck is not yet established by these measurements. + +Eighth observed trial at 11:22:27 UTC still stopped before forward demand. +Independent input recording showed local Core command POST outliers 103.4, +166.5, 216.1 and 127.4 ms (normally 2–10 ms). Sequence 17 reached Node with +312.7 ms remaining; sequence 19 followed after 335 ms. Separating trial +telemetry therefore did not by itself solve the delivery problem. + +A bounded read-only macOS sample of the operator Core found JSON encoding and +zlib work on its ASGI main thread. The periodically polled completed planning +report /api/v1/mission-planner/live-tests/active is 2,403,591 bytes and took +218.5 ms for one local GET. Its endpoint fetched the dict in a worker, but +FastAPI recursively encoded it and the middleware compressed it on the event +loop. This shared process also admits rover commands. + +planning_live_api.py now constructs the JSON response and optional gzip body +in the existing thread pool, preserving the full report contract and bypassing +second compression through Content-Encoding. No polling is disabled, evidence +is not removed, and Node, calibration, current limits and leases are unchanged. +13 focused tests passed against development and active Core: JSON/gzip execute +off-loop, exact content survives decompression, empty/failure contracts and +existing planning presentation/compression behavior remain valid. Canonical +8000 was restarted without active control. Sixty ordinary read-only rover +samples over 15 seconds then had max 86.1 ms, p95 64.5 ms and zero over 100 ms; +both assigned UUIDs fresh, currents/faults zero. This improves measured delay, +but does not yet establish motion or field acceptance. A fresh observed retry +is requested separately. Private process samples and device traces stay out +of normal Git. + + +Ninth attended Core API trial at 11:31:08 UTC passed preparation and completed +8 seconds of forward demand at up to 2000 ERPM, with a 30 A ceiling per motor. +The owner confirmed both motors physically rotated forward and subsequently +confirmed both stopped. Final state stopped, release_confirmed=true, zero +motor/input current and fault. Recorded peaks: left 2001 ERPM / 2.88 A motor, +right 2028 ERPM / 2.81 A motor; these are sampled peaks, not current ceilings. +During driving device ages stayed <=104 ms, all recorded fault codes zero. +Preparation retained old motor samples up to 10.1 s while exclusive setup ran; +those samples are not treated as live motion telemetry. Command POST max +81.28 ms, p95 10.05 ms across 201 requests. The normal stop command was accepted. + +This accepts the observed API forward/release path on Node 0.8.43-1 / VESC +0.7.2 and the corrected operator Core. It does not accept physical keyboard +input, Stop/blur, channel loss, RC takeover, loaded or field operation. Those +remain separate checks. No new calibration, firmware, USB reset or OS change +was performed for this trial. Private raw evidence and owner notes are hashed +in the experiment manifest; the previous eight preparation failures remain +recorded as failures. + + +At 11:38–11:39 UTC the owner physically held W in the 3D View after UI arming, +then released it. Owner reports both motors forward, immediate perceived stop +on release and approximately 0.5–1 s before initial motion. Exact key-event +latency was not instrumented and is not claimed resolved. Read-only capture: +393 samples, no request errors; driving observed for about 10 s (the requested +hold was approximately 8 s). Sampled peaks left 2004 ERPM / 3.51 A, right +2032 ERPM / 2.85 A; driving sample age <=113 ms, all faults zero. Release +returned to ready with motors stopped; the UI Stop action then reached stopped, +release_confirmed=true. Final UI explicitly says control disabled. The read-only +recorder exited and no motion input remained active. + +This accepts actual W forward/release, separately from the prior API trial. +Reverse/turns/Tank, Stop while moving/blur, channel-loss and RC takeover remain +unaccepted on the new UI path. Owner startup-delay observation is retained +for a separately instrumented check. No hardware limits or calibration changed. +MISSIONCOR-85 now records both successful trials, their limits and the previous +operator event-loop diagnosis while preserving all hardware/Hall history. + + +Observed S/A/D session, 11:45–11:47 UTC: the owner confirmed reverse on S +and opposite sides on A (left reverse, right forward); also reports D worked +before the agent disabled control. The telemetry records both opposite-side +patterns with neutral intervals. Final state stopped, release_confirmed=true. +The owner reports a repeatable approximately two-second start delay, with +immediate perceived release. This blocks completion of drive-response acceptance. + +Root cause in the remote output loop: it ramps the speed setpoint from zero +at 600 ERPM/s. Both saved configurations have s_pid_min_erpm=900. Pinned +upstream bldc mcpwm_foc.c (3f670137e27e6e383fa79c50cc6b1fa85aab1554) forces +zero duty and resets speed-PID state for targets below that threshold. The +result is 1.5 s of ineffective commands on each start, plus the retained +0.5 s undriven interval when changing direction. Recorded telemetry already +says driving while the rotor remains stopped, consistent with this mechanism. +This delay is downstream of command admission; the exact key-to-node timing +was not captured and no claim of zero network delay is made. + +Candidate Node 0.8.44-1 / VESC 0.7.3 starts the remote speed request at each +controller's own read-back minimum PID speed (rounded up for native integer +setRpm), then ramps at the existing rate above it. It does not change the +firmware threshold, motor configuration or current ceiling. Subthreshold +analogue requests release instead of being amplified above the request; +invalid/unreachable thresholds reject before output claim. Zero input still +releases immediately; expiry, RC takeover and the reversal dwell remain. +Synthetic tests cover distinct thresholds including fractional serialization, +first-cycle output, ramp above the threshold, turn signs, subthreshold input, +immediate release and invalid thresholds. Physical response after installation +requires a new observed trial; this candidate is not yet installed. + + +0.8.44-1 qualification completed: all 18 Ubuntu stages succeeded in 268.87 s, +including 140 VESC tests, Go race checks and Node UI. Source 1b1be6ef5913fd3740a11c69; +package SHA-256 46cae05efa621a2636251f69ab8071ff4e18db67f23203eab396a71f0ef0972b. +Owner installer bf270c06ae6d1e598e963756 launched in the local Ubuntu session. +APT simulation changes only mission-core-node 0.8.43-1 -> 0.8.44-1, with no +added or removed packages. Before launch Core showed stopped, release confirmed, +both currents/ERPM/faults zero. Local OS authorization is pending; launch is +not evidence of installation or an accepted new motor response. + + +Owner authorization completed: 0.8.44-1 installed at 12:01:17 UTC in 18.56 s, +all installer steps exit 0; Node and VESC services active. Twenty read-only +samples captured after installation, final sample both assigned controllers +fresh (53/63 ms), ERPM/current/fault zero and no active control. Fresh owner +observation requested for W start/release; improved physical response is not +yet accepted. + + +Post-0.8.44-1 owner keyboard series at 12:05–12:06 UTC included repeated +forward/reverse and both turn patterns. Owner reports delay approximately +halved, forward-to-reverse works, but one side sometimes starts sooner. +Read-only recording: 947 samples, no errors, all faults zero; 23 driving +segments. First side above 300 ERPM in the same sample or 0.25–0.51 s later; +both sides by 0–0.76 s. These are state-relative samples, not key-event timing. +The four-minute recorder ended at ready; a separately saved final snapshot +confirms stopped/release_confirmed, both ERPM and currents zero after UI Stop. +Sampled peaks left 2007 ERPM / 5.04 A, right 2025 ERPM / 3.32 A. + +Asymmetry diagnosis: after a turn, the remote code held only the reversing +motor for its 0.5 s neutral interval, while the other side immediately drove +the new command. Trace 12:05:39 (turn -> forward): right above 300 ERPM in the +first driving sample, left +0.763 s. The mirror transition at 12:05:33 had +left first, right +0.511 s. This is a software coordination defect, not evidence +that all smaller differences arise from the broken left Hall circuit. + +Candidate Node 0.8.45-1 / VESC 0.7.4 uses one reversal barrier for the entire +assigned drive group. If any side reverses, all outputs release until all +motors have been observed quiet and undriven for 0.5 s, then the current +latest targets start in the same output cycle. Already observed neutral time +counts; no extra dwell is added after a sufficiently long released pause. +Cancelled/replaced direction requests are not queued. The per-controller PID +threshold correction, speed ramp, immediate zero, current caps, expiry and RC +priority remain. Synthetic regressions cover turn->straight synchronization, +a slower coasting companion, counting an existing neutral pause and cancelling +a pending reversal. Installed software remains 0.8.44-1 pending qualification +and owner installation of this separate candidate. + + +0.8.45-1 / VESC 0.7.4 passed all 18 Ubuntu qualification stages in 267.11 s, +including 144 VESC tests. Source d31a8b586b9a600a2a8e61b3; package SHA-256 + af412c607fec9b34aba0af0e8e67614cd6f4d373fb641d7202341fea30be9ba1. +Installer f1a8a72c4a1a7efc4aeebedd launched in Ubuntu. Its APT plan upgrades +only mission-core-node 0.8.44-1 -> 0.8.45-1; no added/removed packages. +Before launch both controllers had zero ERPM/current/fault, control stopped, +release confirmed. OS authorization and new physical acceptance are pending. + + +0.8.45-1 installed at 12:23:15 UTC after owner OS authorization, 18.56 s, +all steps exit 0. Node and VESC services active. Twenty read-only samples; +final both assigned UUIDs fresh (115/124 ms), zero ERPM/current/fault and +no control session. Fresh owner observation requested for turn->forward +transitions; physical synchrony and remaining control/RC acceptance pending. + + +Observed 0.8.45-1 keyboard trial, 12:32–12:34 UTC: 545 read-only samples, +no read errors, fault codes zero, driving sample age <=105 ms. Twelve driving +segments; both sides above 300 ERPM in the same sample or within one 0.25 s +sample. Peaks left/right 2014/2043 ERPM and 4.35/3.24 A. Owner reports responsive +forward/reverse/turns. This is coarse telemetry, not exact key-to-output timing. + +CRITICAL physical acceptance failure: owner reports D continued after leaving +the browser and releasing the physical key; later clicks recovered it. The +trace contains prolonged D segments (22.82 and 20.56 s), but browser focus/key +source events were not recorded, so exact focus-loss latency is unknown. +Agent ended control through UI; stopped/release_confirmed=true and both motors +zero ERPM/current/fault. Remote-control acceptance remains blocked by this defect. + +The UI already subscribed to blur/pagehide/visibility events. Its 100 ms +command sender nevertheless renewed a remembered nonzero demand without a +focus or input-freshness check; a missed browser-host event could hold it +indefinitely. Fix uses a core-owned held-input binding, capture listeners, +50 ms focus polling, and a guard checked at every command heartbeat. A key +requires a fresh trusted press, then OS-repeat evidence: <=1000 ms initially, +<=300 ms after a repeat. This fallback bounds a lost keyup even if the host +also misses focus events. Focus loss/expiry clears all held states and disarms; +returning focus or delivering a late repeat cannot resume movement. Continuous +keyboard control therefore requires OS repeat within those bounds; this is +not a global-background keyboard implementation. Pointer up/cancel/capture-loss +and component disposal release held state. No onboard install or firmware/config +change belongs to this UI fix. Physical focus-loss re-test remains pending. + + +Owner follow-up after the first focus fix: movement now stops on focus loss, +but terminating the control session is explicitly rejected. New required +behavior is neutral hold with the current healthy control session preserved; +returning focus requires a new physical press, not another arm/preparation. +The implementation now separates input pause (clear held input, send zero, +keep session) from explicit Stop/pagehide/unmount/fault (end session). Guards +still run before every send; old demand is never restored on focus return. +The periodic neutral messages maintain the session only while communication +remains healthy. Actual background suspension/channel expiry is still a stop, +not permission to extend the motion watchdog. Continuous keyboard holds still +require OS repeat evidence within the bounded input lease. + +Preparation now hides key controls and renders the existing canonical warning +StatusBadge as Подготовка управления; readiness alone admits the green state +and key controls. Initial focus-fix physical evidence confirms stopping but +not the requested session-preserving behavior. Revised physical test pending. + + +Final revised UI qualification: 934 unit tests, architecture checks, TypeScript +and production build pass. Canonical Core serves the exact new index/assets; +no Node/OS/firmware change. Browser verified amber Подготовка управления with +keys absent until ready. Owner observed the revised trial and confirmed: +focus loss stops motors, returning allows a fresh press without another arm +or preparation. One active session persisted throughout all six short driving +segments. Explicit UI Stop after completion ended the session; final fresh +telemetry confirms stopped/release_confirmed=true, both ERPM/current/fault zero. +The private result includes UTC/monotonic traces, owner notes and SHA-256. +This accepts focus loss/resume on the observed host. Tank, explicit Stop while +moving, command-channel loss, RC takeover and loaded/field behavior remain +separate outstanding physical checks. No exact key-to-stop timing is claimed. + + +Startup-entry follow-up, 2026-09-25: owner reports silently disabled Manage +and intermittent first-arm failure on a fresh Core page. The outer button +previously depended on fresh/supported status without explaining the wait. +A reproduced hook race allowed a poll begun during POST /arm to return the +old controlling=false state after the arm acknowledgement and revoke the new +session. The error path had the same missing generation guard; repeated arm +calls before acknowledgement also escaped the session-only check. Three new +regressions failed before the fix; actual current-generation authority loss +already passed and must continue to end control. + +The acknowledgement now retires pre-acknowledgement reads; poll success and +failure require the current generation. An in-flight arm guard prevents +duplicate submission. Status reads may wait 1000 ms; command/arm 350 ms +deadlines and all board motion watchdogs remain unchanged. Manage always +opens settings, while actual arm waits for fresh supported idle authority. +The dialog remains open on failed arm. Canonical amber status distinguishes +synchronization, preparation, unavailable data and previous-session cleanup; +ready alone shows green and motion keys. Title is now exactly +«Центр наблюдения и управления». No board install/configuration change. + +Validation: 938 unit tests, architecture check, TypeScript and production +build passed; final copy/color adjustment rechecked with 22 focused tests +and production build. Fresh browser entry acquired control on its first click. +13:20:28–13:20:38 UTC preparation was visible, then ready; no motion input +was sent. Explicit UI Stop completed at 13:21:09 UTC, release confirmed. +307 read-only samples, no read errors, all ERPM and fault codes zero. +A subsequent page reload and settings reopen also passed. These are bounded +UI/lifecycle checks, not new acceptance of driving or RC takeover. Private +entry-startup-result.json contains UTC/monotonic evidence and SHA-256 hashes. diff --git a/docs/runbooks/ROVER_006_ENGINEERING_ACCESS.md b/docs/runbooks/ROVER_006_ENGINEERING_ACCESS.md new file mode 100644 index 0000000..52372b9 --- /dev/null +++ b/docs/runbooks/ROVER_006_ENGINEERING_ACCESS.md @@ -0,0 +1,75 @@ +# Rover 006: инженерный SSH и административные действия + +Проверено 23.09.2026 около 11:02 UTC. Источник: живой paired inventory Core, +Tailscale, сравнение SSH host key с ранее доверенной записью и успешный SSH. + +## Проверенный путь + +Текущий Ubuntu Mission Core Node и исторический Device Edge — разные записи +доступа. Для текущего борта подтверждён пользователь **`dcsudo`** и основной +персональный ключ оператора `~/.ssh/id_ed25519`. Приватный ключ не копируется. +Обычный вход работает с `BatchMode=yes`, без ввода пароля и без `sudo`. + +Сохранённый в операторском `~/.ssh/config` alias `nodedc-edge` относится к +прежней записи с пользователем `ndcsudo` и старым LAN-адресом. Он не является +источником адреса/пользователя нынешнего Rover 006. Не менять его вслепую: +другие задачи могут использовать историческую запись. + +На текущем операторском Mac создан и проверен отдельный приватный профиль: + +`/Users/dcconstructions/Downloads/mnt/NODEDC/outputs/rover-006-vesc-context-20260923/ssh-config` + +Он выбирает `rover-006`, актуальное MagicDNS-имя, `dcsudo`, персональный ключ, +`IdentitiesOnly=yes`, `BatchMode=yes`, `StrictHostKeyChecking=yes` и прежнюю +доверенную запись через `HostKeyAlias`. Команда проверки: + +```sh +ssh -F /Users/dcconstructions/Downloads/mnt/NODEDC/outputs/rover-006-vesc-context-20260923/ssh-config rover-006 'id -un; hostname' +``` + +Адреса, полный host-key fingerprint и USB-идентификаторы не включаются в +переносимую документацию. Приватный профиль не содержит пароля или содержимого +ключа. Его отсутствие на другом Mac не означает отказ борта. + +## Как восстанавливать контекст + +1. Прочитать MISSIONCOR-76 и последнее дополнение об инженерном доступе. +2. Проверить `GET http://127.0.0.1:8000/api/v1/fleet`: выбрать именно сопряжённый + Rover 006, проверить свежесть inventory, hostname, node identity и адреса. +3. Сопоставить эту машину с текущим Tailscale peer. Worker 006 и старый Device + Edge не являются бортом. Не сканировать подсеть. +4. Использовать проверенный профиль. При новом адресе сначала сравнить ключ с + известной доверенной записью. `ssh-keyscan` сам по себе не устанавливает + доверие; 23.09 ключ совпал побайтово с ранее сохранённым ключом Ubuntu Mini. +5. Если получен `Permission denied`, проверить **пользователя и выбранный ключ** + до обсуждения пароля/sudo. Не подбирать аккаунты, не сбрасывать ключи и не + выключать host-key checking. Если доказанного пути нет, использовать + существующий GUI Node «Система → SSH · доверенные устройства». + +Sandbox `Operation not permitted` и отказ запуска локального Tailscale CLI +не доказывают сетевой отказ. Повторить конкретное read-only действие с +разрешением инструмента, не менять маршруты и VPN на основании такой ошибки. + +## SSH не равен sudo + +Подтверждение владельцем пароля на экране Mini относится к административному +действию Ubuntu/установщика. Оно не требуется для обычного инженерного чтения. +Успешный SSH и членство в группе sudo не доказывают беспарольное повышение прав. + +Установка и изменения runtime выполняются штатным versioned installer/profile. +Если такой шаг требует системного подтверждения, сначала подготовить точный +артефакт и объяснить действие, затем использовать существующий системный диалог. +Не просить пароль в чате; не добавлять NOPASSWD, глобальный dialout/chmod или +новый канал обхода ради диагностики. На этапе первоначального аудита sudo не вызывался. Позднее 23.09 владелец +ввёл пароль локально в versioned установщике Node0.8.22-1; установка +подтверждена report.json и фактической версией пакета. + +Продуктовое управление устройствами проходит Core → mTLS → Node → plugin. +SSH остаётся инженерным инструментом, а не транспортом моторных команд. + +## Результат 23.09 + +Подтверждены Ubuntu 24.04.4 LTS, kernel 7.0.0-31-generic, Node 0.8.21-3, +K1 0.1.14, X4 0.1.3-9. Повторный вход через отдельный профиль вернул +правильного пользователя и hostname. SSH/sshd, учётные записи, доверие, +Tailscale, VPN и sudo policy не изменялись.