Compare commits
2
Commits
b1a5d47859
...
60d7c825fc
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
60d7c825fc | ||
|
|
712c6bf7ad |
No files matched your search
@@ -5,3 +5,4 @@ data
|
||||
.ruby-lsp
|
||||
.env
|
||||
node_modules
|
||||
can-recorder/target
|
||||
@@ -68,3 +68,6 @@
|
||||
/REVISION
|
||||
|
||||
node_modules/
|
||||
|
||||
# can-recorder's cargo build
|
||||
/can-recorder/target/
|
||||
+10
@@ -1,3 +1,11 @@
|
||||
# can-recorder (can-recorder/, Rust): the CAN bus into MF4 files, started
|
||||
# and stopped by lib/maptool/can_recorder.rb. Built in its own stage, only
|
||||
# the binary goes into the image (trixie as well: the same glibc).
|
||||
FROM rust:1.100-slim-trixie AS can-recorder
|
||||
WORKDIR /src
|
||||
COPY can-recorder/ ./
|
||||
RUN cargo build --release --locked
|
||||
|
||||
# trixie, not bookworm: Planetiler needs Java 21+ (UnsupportedClassVersionError
|
||||
# otherwise) and bookworm's own default-jre-headless is only Java 17 —
|
||||
# bookworm-backports doesn't carry a newer one either, only trixie's does.
|
||||
@@ -51,6 +59,8 @@ ARG PLANETILER_VERSION=0.11.1
|
||||
RUN curl -fsSL "https://github.com/onthegomap/planetiler/releases/download/v${PLANETILER_VERSION}/planetiler.jar" \
|
||||
-o /usr/local/lib/planetiler.jar
|
||||
|
||||
COPY --from=can-recorder /src/target/release/can-recorder /usr/local/bin/can-recorder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY Gemfile Gemfile.lock ./
|
||||
|
||||
@@ -218,6 +218,12 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho
|
||||
esphome-canopen), `data/can.json` in docs/deployment.adoc
|
||||
** [x] `/can.html` diagnostics: interfaces, nodes (heartbeat, last EMCY, what they send),
|
||||
decoded signals, every COB-ID (role, count, rate, last data)
|
||||
** [x] The bus recorded on the server into ASAM MDF4 (`/trace.html`, `can-recorder/` in Rust,
|
||||
`lib/maptool/can_recorder.rb`): every interface, a finished `.mf4` every 5 min in
|
||||
`data/can_rec/` (a power cut loses at most the last segment), the CANedge `CAN_DataFrame`
|
||||
layout — asammdf decodes it with a DBC (checked against candump: every frame, < 0.002 ms)
|
||||
*** [ ] Checked with CSS Electronics' converters (mdf2csv) too, and in CANalyzer if at hand
|
||||
*** [ ] Old recordings cleaned up (data/can_rec grows ~85 MB an hour at 1000 frames/s)
|
||||
** [ ] Nodes describing themselves — no hand-written signals for our own nodes:
|
||||
*** [x] esphome-canopen nodes over SDO: on a node's first heartbeat read its TPDOs
|
||||
(`0x1800+n`:1 COB-ID, `0x1A00+n` mapping), each mapped entity's type (`0x2001`:N) and
|
||||
@@ -230,6 +236,9 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho
|
||||
*** [ ] EDS (CiA 306) read from a node (`0x1021`) or a file, the same decoder from it — once the
|
||||
ESPHome side generates EDS (proposal for mrk in home-gitops `docs/canopen-nodes.adoc`); the
|
||||
car bridge's frames described the same way
|
||||
**** [x] Meanwhile one EDS for all of them: esphome-canopen's generic one (from can2mqtt) in
|
||||
`public/can/esphome.eds`, names the SDO objects in `/trace.html` (plus the entity objects);
|
||||
a node's own EDS (`0x1021`) to take its place per node
|
||||
*** [ ] 0x1008/0x1018 identity for any CANopen device in `/can.html`
|
||||
** [x] A node that stops its heartbeat (3 missed) is flagged: one journal line when it goes
|
||||
silent and when it's back (`can: node 2 silent, last heartbeat …`), red in `/can.html`
|
||||
|
||||
@@ -13,6 +13,7 @@ require_relative "lib/maptool/routing"
|
||||
require_relative "lib/maptool/mqtt_client"
|
||||
require_relative "lib/maptool/can"
|
||||
require_relative "lib/maptool/can_discovery"
|
||||
require_relative "lib/maptool/can_recorder"
|
||||
require_relative "lib/maptool/gnss_sim"
|
||||
require_relative "lib/maptool/trip"
|
||||
require_relative "lib/maptool/trip_log"
|
||||
@@ -463,6 +464,9 @@ module Maptool
|
||||
warn "can: #{CAN_CONFIG_PATH}: #{e.message} — CAN off"
|
||||
[nil, nil]
|
||||
end
|
||||
# The bus recorded on the server into MF4 files (/trace.html, can-recorder/).
|
||||
CAN_RECORDER = Can::Recorder.new(File.join(DATA_DIR, "can_rec"), CAN_CONFIG ? CAN_CONFIG.fetch("interfaces", []) : [])
|
||||
at_exit { CAN_RECORDER.stop }
|
||||
# Simulated driving (lib/maptool/gnss_sim.rb) in place of the GNSS node.
|
||||
GNSS_SIM = GnssSim.new(VALHALLA_URL)
|
||||
|
||||
@@ -540,6 +544,11 @@ module Maptool
|
||||
erb :can, layout: false
|
||||
end
|
||||
|
||||
# Every CAN frame as it came, decoded (polls GET /api/can?since=).
|
||||
get "/trace.html" do
|
||||
erb :trace, layout: false
|
||||
end
|
||||
|
||||
# A share to the installed app normally never reaches the server: the
|
||||
# service worker (public/sw.js) takes the POST, parks the files and
|
||||
# opens the app. Only lands here if no worker is running yet — back to
|
||||
@@ -1397,6 +1406,38 @@ module Maptool
|
||||
json snapshot.merge(available: !CAN_CONFIG.nil?, simulated: GNSS_SIM.running?)
|
||||
end
|
||||
|
||||
# Recording the bus into MF4 files on the server: GET whether it runs and
|
||||
# the files (newest first), POST starts it, DELETE stops it (the segment
|
||||
# being recorded is written); a file by GET /api/can/recordings/<name>.
|
||||
get "/api/can/recording" do
|
||||
require_login!
|
||||
json available: !CAN_CONFIG.nil?, running: CAN_RECORDER.running?, started_at: CAN_RECORDER.started_at,
|
||||
error: CAN_RECORDER.error, files: CAN_RECORDER.files
|
||||
end
|
||||
|
||||
post "/api/can/recording" do
|
||||
require_login!
|
||||
halt 409, json(error: "CAN is off: no data/can.json on this server") unless CAN_CONFIG
|
||||
begin
|
||||
CAN_RECORDER.start
|
||||
rescue SystemCallError => e
|
||||
halt 500, json(error: CAN_RECORDER.error || e.message)
|
||||
end
|
||||
json running: CAN_RECORDER.running?
|
||||
end
|
||||
|
||||
delete "/api/can/recording" do
|
||||
require_login!
|
||||
CAN_RECORDER.stop
|
||||
json running: CAN_RECORDER.running?, error: CAN_RECORDER.error
|
||||
end
|
||||
|
||||
get "/api/can/recordings/:name" do
|
||||
require_login!
|
||||
path = CAN_RECORDER.path(params[:name]) or halt 404
|
||||
send_file path, disposition: "attachment", type: "application/octet-stream"
|
||||
end
|
||||
|
||||
# The GNSS simulation: POST {"start": [lon, lat]} drives randomly from
|
||||
# there, POST {} from a random place in the offline countries, DELETE
|
||||
# stops it, GET says whether it's on (and why it stopped).
|
||||
|
||||
Generated
+457
@@ -0,0 +1,457 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "byteorder"
|
||||
version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "34fb07aac3b9f547c7af8dc897dfe73c10847b6c71130c364bdd7891d979c816"
|
||||
|
||||
[[package]]
|
||||
name = "can-recorder"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"embedded-can",
|
||||
"signal-hook",
|
||||
"socketcan",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||
|
||||
[[package]]
|
||||
name = "cfg_aliases"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
|
||||
|
||||
[[package]]
|
||||
name = "darling"
|
||||
version = "0.20.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee"
|
||||
dependencies = [
|
||||
"darling_core",
|
||||
"darling_macro",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling_core"
|
||||
version = "0.20.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e"
|
||||
dependencies = [
|
||||
"fnv",
|
||||
"ident_case",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"strsim",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling_macro"
|
||||
version = "0.20.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead"
|
||||
dependencies = [
|
||||
"darling_core",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "derive_builder"
|
||||
version = "0.20.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947"
|
||||
dependencies = [
|
||||
"derive_builder_macro",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "derive_builder_core"
|
||||
version = "0.20.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8"
|
||||
dependencies = [
|
||||
"darling",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "derive_builder_macro"
|
||||
version = "0.20.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c"
|
||||
dependencies = [
|
||||
"derive_builder_core",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.19.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
|
||||
|
||||
[[package]]
|
||||
name = "embedded-can"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e9d2e857f87ac832df68fa498d18ddc679175cf3d2e4aa893988e5601baf9438"
|
||||
dependencies = [
|
||||
"nb",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "errno"
|
||||
version = "0.3.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fnv"
|
||||
version = "1.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
|
||||
|
||||
[[package]]
|
||||
name = "getset"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6cf442baaabe4213ce7d1239afc26c039180b6456da2cededa316ae2c8a77a77"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hex"
|
||||
version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
|
||||
|
||||
[[package]]
|
||||
name = "ident_case"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.191"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
|
||||
|
||||
[[package]]
|
||||
name = "lock_api"
|
||||
version = "0.4.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
|
||||
dependencies = [
|
||||
"scopeguard",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.35"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
|
||||
|
||||
[[package]]
|
||||
name = "memoffset"
|
||||
version = "0.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nb"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8d5439c4ad607c3c23abf66de8c8bf57ba8adcd1f129e699851a6e43935d339d"
|
||||
|
||||
[[package]]
|
||||
name = "neli"
|
||||
version = "0.7.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6b152f4f18819e638ea350a740b16de75099302b5ec3a58f4f8766ef2fcf695d"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"byteorder",
|
||||
"derive_builder",
|
||||
"getset",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
"log",
|
||||
"neli-proc-macros",
|
||||
"parking_lot",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "neli-proc-macros"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "05d8d08c6e98f20a62417478ebf7be8e1425ec9acecc6f63e22da633f6b71609"
|
||||
dependencies = [
|
||||
"either",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"serde",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nix"
|
||||
version = "0.31.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2bc81ce8148d3b4f3274da811f11cdd824ae661ee4ef732cdb229825cf5be7f7"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"cfg-if",
|
||||
"cfg_aliases",
|
||||
"libc",
|
||||
"memoffset",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parking_lot"
|
||||
version = "0.12.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
|
||||
dependencies = [
|
||||
"lock_api",
|
||||
"parking_lot_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parking_lot_core"
|
||||
version = "0.9.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"redox_syscall",
|
||||
"smallvec",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "redox_syscall"
|
||||
version = "0.5.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "scopeguard"
|
||||
version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "signal-hook"
|
||||
version = "0.4.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "49f7447afd772ca79ad17ae0a3972a6b0df0cb4b80990fd82707593e9e012a74"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"signal-hook-registry",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "signal-hook-registry"
|
||||
version = "1.4.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
|
||||
dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "smallvec"
|
||||
version = "1.16.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59"
|
||||
|
||||
[[package]]
|
||||
name = "socket2"
|
||||
version = "0.6.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "socketcan"
|
||||
version = "4.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "472e000403167b1e2f65cfcf8ff235fe94b911f9bd9bdbc1f48047b8a1cf49aa"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"embedded-can",
|
||||
"hex",
|
||||
"libc",
|
||||
"log",
|
||||
"nb",
|
||||
"neli",
|
||||
"nix",
|
||||
"smallvec",
|
||||
"socket2",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "strsim"
|
||||
version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.119"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "2.0.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
|
||||
dependencies = [
|
||||
"thiserror-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror-impl"
|
||||
version = "2.0.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.61.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
@@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "can-recorder"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
embedded-can = "0.4"
|
||||
signal-hook = "0.4.6"
|
||||
socketcan = "4.0.0"
|
||||
@@ -0,0 +1,150 @@
|
||||
//! can-recorder: SocketCAN frames into ASAM MDF4 files (CAN bus logging, the
|
||||
//! CANedge layout: asammdf with a DBC, CSS Electronics' tools, CANalyzer).
|
||||
//!
|
||||
//! can-recorder [--segment SECONDS] OUT_DIR IFACE...
|
||||
//!
|
||||
//! One file per segment, `OUT_DIR/<UTC start>.mf4`, every interface in it
|
||||
//! (CAN_DataFrame.BusChannel 1, 2… in the order given), written whole when
|
||||
//! the segment ends (default 300 s) or on SIGTERM/SIGINT: a crash or a power
|
||||
//! cut loses at most the segment being recorded, every file there is a
|
||||
//! finished one (written as .part, then renamed). The frames' time: the
|
||||
//! kernel's receive timestamp.
|
||||
//!
|
||||
//! ponytail: a segment is held in memory until written (24 B a frame: 300 s
|
||||
//! of a full 500 kbit/s bus ≈ 30 MB); shorter segments if that's a lot.
|
||||
|
||||
mod mf4;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use embedded_can::{Frame, Id};
|
||||
use socketcan::{CanFrame, CanSocket, Socket, SocketOptions};
|
||||
|
||||
struct Segment {
|
||||
records: mf4::Records,
|
||||
start: SystemTime,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let mut segment = Duration::from_secs(300);
|
||||
if args.first().map(String::as_str) == Some("--segment") && args.len() > 1 {
|
||||
segment = Duration::from_secs(args[1].parse().expect("--segment: seconds"));
|
||||
args.drain(..2);
|
||||
}
|
||||
if args.len() < 2 || args.len() > 256 {
|
||||
eprintln!("usage: can-recorder [--segment SECONDS] OUT_DIR IFACE...");
|
||||
std::process::exit(2);
|
||||
}
|
||||
let out = PathBuf::from(&args[0]);
|
||||
std::fs::create_dir_all(&out).expect("OUT_DIR");
|
||||
let ifaces = args[1..].to_vec();
|
||||
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
for signal in [signal_hook::consts::SIGTERM, signal_hook::consts::SIGINT] {
|
||||
signal_hook::flag::register(signal, Arc::clone(&stop)).expect("signal handler");
|
||||
}
|
||||
|
||||
let (tx, rx) = mpsc::sync_channel::<(u8, SystemTime, CanFrame)>(100_000);
|
||||
for (i, iface) in ifaces.iter().cloned().enumerate() {
|
||||
let tx = tx.clone();
|
||||
std::thread::spawn(move || read(i as u8 + 1, &iface, tx));
|
||||
}
|
||||
drop(tx);
|
||||
|
||||
let mut current: Option<Segment> = None;
|
||||
while !stop.load(Ordering::Relaxed) {
|
||||
let next = rx.recv_timeout(Duration::from_millis(500));
|
||||
// a quiet bus still gets its segment closed on time
|
||||
let now = match &next {
|
||||
Ok((_, at, _)) => *at,
|
||||
Err(_) => SystemTime::now(),
|
||||
};
|
||||
if current.as_ref().is_some_and(|s| now.duration_since(s.start).unwrap_or_default() >= segment) {
|
||||
write(&out, &ifaces, current.take().unwrap());
|
||||
}
|
||||
match next {
|
||||
Ok((bus, at, CanFrame::Data(frame))) => {
|
||||
let s = current.get_or_insert_with(|| Segment { records: mf4::Records::default(), start: at });
|
||||
let t = at.duration_since(s.start).unwrap_or_default().as_secs_f64();
|
||||
let (id, extended) = match frame.id() {
|
||||
Id::Standard(id) => (u32::from(id.as_raw()), false),
|
||||
Id::Extended(id) => (id.as_raw(), true),
|
||||
};
|
||||
s.records.push(t, bus, id, extended, frame.data());
|
||||
}
|
||||
Ok(_) | Err(mpsc::RecvTimeoutError::Timeout) => {} // remote and error frames: not logged
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
}
|
||||
}
|
||||
if let Some(s) = current {
|
||||
write(&out, &ifaces, s);
|
||||
}
|
||||
}
|
||||
|
||||
/// An interface's frames into the channel; reopened every 5 s while it's
|
||||
/// missing or down.
|
||||
fn read(bus: u8, iface: &str, tx: mpsc::SyncSender<(u8, SystemTime, CanFrame)>) {
|
||||
loop {
|
||||
match CanSocket::open(iface).and_then(|socket| socket.set_recv_timestamp(true).map(|()| socket)) {
|
||||
Ok(socket) => loop {
|
||||
match socket.read_frame_with_timestamp() {
|
||||
Ok((frame, at)) => {
|
||||
if tx.send((bus, at, frame)).is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("can-recorder: {iface}: {e}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
},
|
||||
Err(e) => eprintln!("can-recorder: {iface}: {e}"),
|
||||
}
|
||||
std::thread::sleep(Duration::from_secs(5));
|
||||
}
|
||||
}
|
||||
|
||||
fn write(out: &Path, ifaces: &[String], s: Segment) {
|
||||
if s.records.count == 0 {
|
||||
return;
|
||||
}
|
||||
let since_epoch = s.start.duration_since(UNIX_EPOCH).unwrap_or_default();
|
||||
let bytes = mf4::file(&s.records, since_epoch.as_nanos() as u64, ifaces);
|
||||
let path = out.join(format!("{}.mf4", utc_stamp(since_epoch.as_secs())));
|
||||
let part = path.with_extension("mf4.part");
|
||||
match std::fs::write(&part, &bytes).and_then(|()| std::fs::rename(&part, &path)) {
|
||||
Ok(()) => eprintln!("can-recorder: {} frames → {}", s.records.count, path.display()),
|
||||
Err(e) => eprintln!("can-recorder: {}: {e}", path.display()),
|
||||
}
|
||||
}
|
||||
|
||||
/// YYYYMMDD-HHMMSS (UTC) of a unix time — Howard Hinnant's civil_from_days.
|
||||
fn utc_stamp(secs: u64) -> String {
|
||||
let (days, rem) = ((secs / 86_400) as i64, secs % 86_400);
|
||||
let z = days + 719_468;
|
||||
let era = z.div_euclid(146_097);
|
||||
let doe = z - era * 146_097;
|
||||
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let d = doy - (153 * mp + 2) / 5 + 1;
|
||||
let m = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||
let y = yoe + era * 400 + i64::from(m <= 2);
|
||||
format!("{y:04}{m:02}{d:02}-{:02}{:02}{:02}", rem / 3600, rem / 60 % 60, rem % 60)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn utc_stamp() {
|
||||
assert_eq!(super::utc_stamp(0), "19700101-000000");
|
||||
assert_eq!(super::utc_stamp(1_709_164_800 + 3_723), "20240229-010203");
|
||||
assert_eq!(super::utc_stamp(4_102_444_799), "20991231-235959");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
//! A minimal ASAM MDF 4.10 writer for CAN bus logging: one data group, one
|
||||
//! channel group of `CAN_DataFrame` records the way the ASAM bus logging
|
||||
//! spec and CANedge lay them out (asammdf's extract_bus_logging and DBC
|
||||
//! decoding, CSS Electronics' converters, CANalyzer read it).
|
||||
//!
|
||||
//! A record (24 bytes):
|
||||
//! 0..8 Timestamp (f64, s since the header's start time)
|
||||
//! 8 CAN_DataFrame.BusChannel (u8, 1 = the first interface)
|
||||
//! 9..13 CAN_DataFrame.ID (29 bits)
|
||||
//! 13 CAN_DataFrame.IDE (bit 0: an extended ID)
|
||||
//! 14 CAN_DataFrame.DLC (4 bits)
|
||||
//! 15 CAN_DataFrame.DataLength (u8)
|
||||
//! 16..24 CAN_DataFrame.DataBytes (8 bytes)
|
||||
|
||||
pub const RECORD: usize = 24;
|
||||
|
||||
const UNSIGNED: u8 = 0;
|
||||
const FLOAT: u8 = 4;
|
||||
const BYTES: u8 = 10;
|
||||
const BUS_EVENT: u32 = 1 << 10; // cn_flags
|
||||
const CG_BUS_EVENT: u16 = 1 << 1;
|
||||
const CG_PLAIN_BUS_EVENT: u16 = 1 << 2;
|
||||
|
||||
/// The frames of a segment, as records.
|
||||
#[derive(Default)]
|
||||
pub struct Records {
|
||||
data: Vec<u8>,
|
||||
pub count: u64,
|
||||
}
|
||||
|
||||
impl Records {
|
||||
pub fn push(&mut self, t: f64, bus: u8, id: u32, extended: bool, data: &[u8]) {
|
||||
let len = data.len().min(8);
|
||||
self.data.extend_from_slice(&t.to_le_bytes());
|
||||
self.data.push(bus);
|
||||
self.data.extend_from_slice(&(id & 0x1FFF_FFFF).to_le_bytes());
|
||||
self.data.push(extended as u8);
|
||||
self.data.push(len as u8); // classic CAN: DLC = length
|
||||
self.data.push(len as u8);
|
||||
let mut bytes = [0u8; 8];
|
||||
bytes[..len].copy_from_slice(&data[..len]);
|
||||
self.data.extend_from_slice(&bytes);
|
||||
self.count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// The blocks, each 8-byte aligned; links patched in once their target is written.
|
||||
struct File(Vec<u8>);
|
||||
|
||||
impl File {
|
||||
fn block(&mut self, id: &[u8; 4], links: usize, data: &[u8]) -> u64 {
|
||||
let at = self.0.len() as u64;
|
||||
let len = 24 + 8 * links + data.len();
|
||||
self.0.extend_from_slice(b"##");
|
||||
self.0.extend_from_slice(&id[2..]);
|
||||
self.0.extend_from_slice(&[0; 4]);
|
||||
self.0.extend_from_slice(&(len as u64).to_le_bytes());
|
||||
self.0.extend_from_slice(&(links as u64).to_le_bytes());
|
||||
self.0.resize(self.0.len() + 8 * links, 0);
|
||||
self.0.extend_from_slice(data);
|
||||
self.0.resize(self.0.len().next_multiple_of(8), 0);
|
||||
at
|
||||
}
|
||||
|
||||
fn link(&mut self, block: u64, n: usize, target: u64) {
|
||||
let at = block as usize + 24 + 8 * n;
|
||||
self.0[at..at + 8].copy_from_slice(&target.to_le_bytes());
|
||||
}
|
||||
|
||||
fn text(&mut self, id: &[u8; 4], s: &str) -> u64 {
|
||||
let mut data = s.as_bytes().to_vec();
|
||||
data.push(0);
|
||||
self.block(id, 0, &data)
|
||||
}
|
||||
|
||||
/// A CN block: name, type, where in the record; its unit if any.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn channel(&mut self, name: &str, cn_type: u8, sync: u8, data_type: u8, byte: u32, bit: u8, bits: u32, flags: u32, unit: Option<&str>) -> u64 {
|
||||
let mut d = vec![cn_type, sync, data_type, bit];
|
||||
d.extend_from_slice(&byte.to_le_bytes());
|
||||
d.extend_from_slice(&bits.to_le_bytes());
|
||||
d.extend_from_slice(&flags.to_le_bytes());
|
||||
d.extend_from_slice(&0u32.to_le_bytes()); // invalidation bit
|
||||
d.extend_from_slice(&[0, 0, 0, 0]); // precision, reserved, attachment count
|
||||
d.resize(d.len() + 6 * 8, 0); // value range and limits: none
|
||||
let cn = self.block(b"##CN", 8, &d);
|
||||
let tx = self.text(b"##TX", name);
|
||||
self.link(cn, 2, tx);
|
||||
if let Some(unit) = unit {
|
||||
let tx = self.text(b"##TX", unit);
|
||||
self.link(cn, 6, tx);
|
||||
}
|
||||
cn
|
||||
}
|
||||
}
|
||||
|
||||
/// The whole file: `start_ns` since 1970 (UTC), `buses` the interfaces in BusChannel order.
|
||||
pub fn file(records: &Records, start_ns: u64, buses: &[String]) -> Vec<u8> {
|
||||
let mut f = File(Vec::with_capacity(records.data.len() + 4096));
|
||||
// ID block: no block header, 64 bytes
|
||||
f.0.extend_from_slice(b"MDF 4.10 canrec ");
|
||||
f.0.extend_from_slice(&[0; 4]);
|
||||
f.0.extend_from_slice(&410u16.to_le_bytes());
|
||||
f.0.resize(64, 0);
|
||||
|
||||
let mut time = start_ns.to_le_bytes().to_vec();
|
||||
time.extend_from_slice(&[0, 0, 0, 0, 0, 0, 0, 0]); // tz, dst (UTC), time flags, class, flags, reserved
|
||||
let mut hd_data = time.clone();
|
||||
hd_data.resize(32, 0); // start angle, distance
|
||||
let hd = f.block(b"##HD", 6, &hd_data);
|
||||
|
||||
let fh = f.block(b"##FH", 2, &time);
|
||||
f.link(hd, 1, fh);
|
||||
let comment = format!(
|
||||
"<FHcomment><TX>recorded</TX><tool_id>can-recorder</tool_id><tool_vendor>maptool</tool_vendor><tool_version>{}</tool_version></FHcomment>",
|
||||
env!("CARGO_PKG_VERSION")
|
||||
);
|
||||
let md = f.text(b"##MD", &comment);
|
||||
f.link(fh, 1, md);
|
||||
|
||||
let dg = f.block(b"##DG", 4, &[0; 8]); // record id size 0: one channel group
|
||||
f.link(hd, 0, dg);
|
||||
|
||||
let mut cg_data = Vec::new();
|
||||
cg_data.extend_from_slice(&0u64.to_le_bytes()); // record id
|
||||
cg_data.extend_from_slice(&records.count.to_le_bytes());
|
||||
cg_data.extend_from_slice(&(CG_BUS_EVENT | CG_PLAIN_BUS_EVENT).to_le_bytes());
|
||||
cg_data.extend_from_slice(&(b'.' as u16).to_le_bytes()); // path separator
|
||||
cg_data.extend_from_slice(&[0; 4]);
|
||||
cg_data.extend_from_slice(&(RECORD as u32).to_le_bytes());
|
||||
cg_data.extend_from_slice(&0u32.to_le_bytes()); // invalidation bytes
|
||||
let cg = f.block(b"##CG", 6, &cg_data);
|
||||
f.link(dg, 1, cg);
|
||||
let acq = f.text(b"##TX", "CAN");
|
||||
f.link(cg, 2, acq);
|
||||
let si = f.block(b"##SI", 3, &[2, 2, 0, 0, 0, 0, 0, 0]); // type bus, bus type CAN
|
||||
let si_name = f.text(b"##TX", &buses.join(", "));
|
||||
f.link(si, 0, si_name);
|
||||
f.link(si, 1, si_name);
|
||||
f.link(cg, 3, si);
|
||||
|
||||
let time = f.channel("Timestamp", 2, 1, FLOAT, 0, 0, 64, 0, Some("s"));
|
||||
f.link(cg, 1, time);
|
||||
let frame = f.channel("CAN_DataFrame", 0, 0, BYTES, 8, 0, 16 * 8, BUS_EVENT, None);
|
||||
f.link(time, 0, frame);
|
||||
let parts = [
|
||||
("CAN_DataFrame.BusChannel", UNSIGNED, 8, 0, 8),
|
||||
("CAN_DataFrame.ID", UNSIGNED, 9, 0, 29),
|
||||
("CAN_DataFrame.IDE", UNSIGNED, 13, 0, 1),
|
||||
("CAN_DataFrame.DLC", UNSIGNED, 14, 0, 4),
|
||||
("CAN_DataFrame.DataLength", UNSIGNED, 15, 0, 8),
|
||||
("CAN_DataFrame.DataBytes", BYTES, 16, 0, 64),
|
||||
];
|
||||
let mut prev: Option<u64> = None;
|
||||
for (name, data_type, byte, bit, bits) in parts {
|
||||
let cn = f.channel(name, 0, 0, data_type, byte, bit, bits, BUS_EVENT, None);
|
||||
match prev {
|
||||
Some(p) => f.link(p, 0, cn),
|
||||
None => f.link(frame, 1, cn), // the frame's composition: its first part
|
||||
}
|
||||
prev = Some(cn);
|
||||
}
|
||||
|
||||
let dt = f.block(b"##DT", 0, &records.data);
|
||||
f.link(dg, 2, dt);
|
||||
f.0
|
||||
}
|
||||
@@ -165,6 +165,13 @@ Offline routing runs https://github.com/valhalla/valhalla[Valhalla]
|
||||
(`ghcr.io/valhalla/valhalla`, version pinned in `docker-compose.yaml`),
|
||||
over the same Geofabrik extracts (ODbL). See `docs/routing-design.adoc`.
|
||||
|
||||
`public/can/esphome.eds`, the CANopen object dictionary of
|
||||
https://github.com/mrk-its/esphome-canopen[esphome-canopen] nodes (the
|
||||
CAN trace names SDO objects by it), is copied from
|
||||
https://github.com/mrk-its/can2mqtt[can2mqtt]
|
||||
(`src/can2mqtt/eds/esphome.eds`, commit `815ad0f`, MIT or Apache-2.0,
|
||||
© mrk-its). Updated by hand.
|
||||
|
||||
Not a frontend asset like the above, but also baked into this app's own
|
||||
Docker image (not a separate container the way kiwix-serve is —
|
||||
see `docs/deployment.adoc`/`docs/development.adoc`): three CLI tools
|
||||
|
||||
+3
-3
@@ -137,7 +137,7 @@ module Maptool
|
||||
# every frame id seen (count, rate, last data) and the decoded signals.
|
||||
class Store
|
||||
MAX_FRAME_IDS = 2048 # ponytail: stops counting new ids past this, enough for a bus
|
||||
LOG_SIZE = 1000 # the last frames as they came, for /can.html's trace
|
||||
LOG_SIZE = 5000 # the last frames as they came, for /trace.html (a few seconds of a busy bus)
|
||||
|
||||
# Signals starting with this aren't taken from the bus (the GNSS
|
||||
# simulation's, put by #put, stand in for the node's meanwhile).
|
||||
@@ -213,11 +213,11 @@ module Maptool
|
||||
end
|
||||
end
|
||||
|
||||
# log: the frames after seq `since` (none without it).
|
||||
# log: the frames after seq `since` (none without it); log_seq: the last one's.
|
||||
def snapshot(since: nil)
|
||||
@mutex.synchronize do
|
||||
snap = { interfaces: @interfaces.dup, nodes: @nodes.dup, signals: @signals.dup, frames: @frames.values.map(&:dup) }
|
||||
since ? snap.merge(log: @log.select { |f| f[:seq] > since }) : snap
|
||||
since ? snap.merge(log: @log.select { |f| f[:seq] > since }, log_seq: @seq) : snap
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
require "fileutils"
|
||||
|
||||
module Maptool
|
||||
module Can
|
||||
# Recording the bus on the server: can-recorder (can-recorder/, Rust)
|
||||
# writes every interface's frames into ASAM MDF4 files, one per segment
|
||||
# (`<dir>/<UTC start>.mf4`, asammdf with a DBC, CSS Electronics' tools);
|
||||
# this starts it, stops it (SIGTERM: the segment being recorded is
|
||||
# written) and lists what it wrote.
|
||||
class Recorder
|
||||
NAME = /\A\d{8}-\d{6}\.mf4\z/
|
||||
STOP_WAIT = 10 # s for the last segment to be written
|
||||
|
||||
attr_reader :dir, :error, :started_at
|
||||
|
||||
def initialize(dir, interfaces, binary: ENV.fetch("CAN_RECORDER", "can-recorder"), segment: 300)
|
||||
@dir = dir
|
||||
@interfaces = interfaces
|
||||
@binary = binary
|
||||
@segment = segment
|
||||
@mutex = Mutex.new
|
||||
end
|
||||
|
||||
def running?
|
||||
@waiter&.alive? || false
|
||||
end
|
||||
|
||||
def start
|
||||
@mutex.synchronize do
|
||||
return if running?
|
||||
|
||||
FileUtils.mkdir_p(@dir)
|
||||
pid = Process.spawn(@binary, "--segment", @segment.to_s, @dir, *@interfaces)
|
||||
@waiter = Process.detach(pid)
|
||||
@pid = pid
|
||||
@started_at = Time.now.to_f
|
||||
@error = nil
|
||||
rescue SystemCallError => e
|
||||
@error = "#{@binary}: #{e.message}"
|
||||
raise
|
||||
end
|
||||
end
|
||||
|
||||
def stop
|
||||
@mutex.synchronize do
|
||||
return unless running?
|
||||
|
||||
Process.kill("TERM", @pid)
|
||||
@waiter.join(STOP_WAIT) or Process.kill("KILL", @pid)
|
||||
status = @waiter.value
|
||||
@error = "#{@binary} exited with #{status.exitstatus}" unless status.success?
|
||||
@started_at = nil
|
||||
end
|
||||
end
|
||||
|
||||
# The newest first.
|
||||
def files
|
||||
return [] unless Dir.exist?(@dir)
|
||||
|
||||
Dir.children(@dir).grep(NAME).sort.reverse.map do |name|
|
||||
stat = File.stat(File.join(@dir, name))
|
||||
{ name: name, size: stat.size, at: stat.mtime.to_f }
|
||||
end
|
||||
end
|
||||
|
||||
def path(name)
|
||||
path = File.join(@dir, name)
|
||||
path if NAME.match?(name) && File.file?(path)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,169 @@
|
||||
[DeviceInfo]
|
||||
VendorName=ESPHome
|
||||
VendorNumber=1
|
||||
BaudRate_10=0
|
||||
BaudRate_20=0
|
||||
BaudRate_50=0
|
||||
BaudRate_125=1
|
||||
BaudRate_250=1
|
||||
BaudRate_500=1
|
||||
BaudRate_800=0
|
||||
BaudRate_1000=1
|
||||
SimpleBootUpMaster=0
|
||||
SimpleBootUpSlave=1
|
||||
Granularity=8
|
||||
DynamicChannelsSupported=0
|
||||
CompactPDO=0
|
||||
GroupMessaging=0
|
||||
|
||||
NrOfRXPDO=0
|
||||
NrOfTXPDO=4
|
||||
LSS_Supported=0
|
||||
|
||||
[1008]
|
||||
ParameterName=DeviceName
|
||||
ObjectType=7
|
||||
DataType=9
|
||||
AccessType=R
|
||||
|
||||
[1009]
|
||||
ParameterName=HardwareVersion
|
||||
ObjectType=7
|
||||
DataType=9
|
||||
AccessType=R
|
||||
|
||||
[100a]
|
||||
ParameterName=SoftwareVersion
|
||||
ObjectType=7
|
||||
DataType=9
|
||||
AccessType=R
|
||||
|
||||
[1010]
|
||||
ParameterName=ParamStore
|
||||
ObjectType=9
|
||||
|
||||
[1010sub0]
|
||||
ParameterName=Number of ParamStore Entries
|
||||
ObjectType=7
|
||||
DataType=5
|
||||
AccessType=R
|
||||
|
||||
[1010sub1]
|
||||
ParameterName=Store All
|
||||
ObjectType=7
|
||||
DataType=7
|
||||
AccessType=RW
|
||||
|
||||
[1010sub2]
|
||||
ParameterName=Store Comm
|
||||
ObjectType=7
|
||||
DataType=7
|
||||
AccessType=RW
|
||||
|
||||
[1011]
|
||||
ParameterName=ParamReset
|
||||
ObjectType=9
|
||||
|
||||
[1011sub0]
|
||||
ParameterName=Number of ParamStore Entries
|
||||
ObjectType=7
|
||||
DataType=5
|
||||
AccessType=R
|
||||
|
||||
[1011sub1]
|
||||
ParameterName=Reset All Params
|
||||
ObjectType=7
|
||||
DataType=7
|
||||
AccessType=RW
|
||||
|
||||
[1011sub2]
|
||||
ParameterName=Reset Comm Params
|
||||
ObjectType=7
|
||||
DataType=7
|
||||
AccessType=RW
|
||||
|
||||
|
||||
|
||||
[1017]
|
||||
ParameterName=ProducerHeartbeatTime
|
||||
ObjectType=7
|
||||
DataType=6
|
||||
AccessType=RW
|
||||
|
||||
[1018]
|
||||
ParameterName=Identity
|
||||
ObjectType=9
|
||||
|
||||
[1018sub0]
|
||||
ParameterName=Number of Entries
|
||||
ObjectType=7
|
||||
DataType=5
|
||||
AccessType=R
|
||||
|
||||
[1018sub1]
|
||||
ParameterName=VendorId
|
||||
ObjectType=7
|
||||
DataType=7
|
||||
AccessType=R
|
||||
|
||||
[1018sub2]
|
||||
ParameterName=ProductCode
|
||||
ObjectType=7
|
||||
DataType=7
|
||||
AccessType=R
|
||||
|
||||
[1018sub3]
|
||||
ParameterName=RevisionNumber
|
||||
ObjectType=7
|
||||
DataType=7
|
||||
AccessType=R
|
||||
|
||||
[1018sub4]
|
||||
ParameterName=SerialNumber
|
||||
ObjectType=7
|
||||
DataType=7
|
||||
AccessType=R
|
||||
|
||||
[3000]
|
||||
ParameterName=Firmware
|
||||
ObjectType=9
|
||||
|
||||
[3000sub0]
|
||||
ParameterName=Firmware Max Index
|
||||
ObjectType=7
|
||||
DataType=5
|
||||
AccessType=R
|
||||
DefaultValue=0
|
||||
|
||||
[3000sub1]
|
||||
ParameterName=Firmware Command
|
||||
ObjectType=7
|
||||
DataType=7
|
||||
AccessType=RW
|
||||
DefaultValue=0
|
||||
|
||||
[3000sub2]
|
||||
ParameterName=Firmware Size
|
||||
ObjectType=7
|
||||
DataType=7
|
||||
AccessType=RW
|
||||
DefaultValue=0
|
||||
|
||||
[3000sub3]
|
||||
ParameterName=Firmware MD5
|
||||
ObjectType=7
|
||||
DataType=0xf
|
||||
AccessType=W
|
||||
|
||||
[3000sub4]
|
||||
ParameterName=Firmware Data
|
||||
ObjectType=7
|
||||
DataType=0xf
|
||||
AccessType=W
|
||||
|
||||
[3000sub5]
|
||||
ParameterName=Firmware Flags
|
||||
ObjectType=7
|
||||
DataType=7
|
||||
AccessType=R
|
||||
|
||||
@@ -172,6 +172,22 @@ class AppTest < Minitest::Test
|
||||
refute_includes request.get("/", **logged_in_env).body, "data-sync-client"
|
||||
end
|
||||
|
||||
def test_can_recordings_are_listed_and_served_by_name_only
|
||||
assert_equal 401, request.get("/api/can/recording").status
|
||||
dir = File.join(Maptool::App::DATA_DIR, "can_rec")
|
||||
FileUtils.mkdir_p(dir)
|
||||
File.write(File.join(dir, "20261202-181105.mf4"), "MDF")
|
||||
File.write(File.join(dir, "20261202-181105.mf4.part"), "")
|
||||
body = json_body(request.get("/api/can/recording", **logged_in_env))
|
||||
assert_equal [false, false, ["20261202-181105.mf4"]], [body["available"], body["running"], body["files"].map { |f| f["name"] }]
|
||||
assert_equal 409, request.post("/api/can/recording", **logged_in_env).status
|
||||
assert_equal "MDF", request.get("/api/can/recordings/20261202-181105.mf4", **logged_in_env).body
|
||||
assert_equal 404, request.get("/api/can/recordings/20261202-181105.mf4.part", **logged_in_env).status
|
||||
assert_equal 404, request.get("/api/can/recordings/..%2Fcan.json", **logged_in_env).status
|
||||
ensure
|
||||
FileUtils.rm_rf(dir)
|
||||
end
|
||||
|
||||
def test_can_requires_login_and_is_off_without_a_config
|
||||
assert_equal 401, request.get("/api/can").status
|
||||
assert_equal({ "interfaces" => {}, "nodes" => {}, "signals" => {}, "frames" => [], "available" => false, "simulated" => false }, json_body(request.get("/api/can", **logged_in_env)))
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
require_relative "test_helper"
|
||||
require "maptool/can"
|
||||
require "maptool/can_recorder"
|
||||
require "timeout"
|
||||
|
||||
class CanTest < Minitest::Test
|
||||
@@ -67,6 +68,7 @@ class CanTest < Minitest::Test
|
||||
assert_equal [:tpdo1, 1, 2, 0.5], tpdo.values_at(:role, :node, :count, :interval)
|
||||
assert_equal({ code: 0x8130, register: 0x11, at: 3.0 }, snapshot[:nodes][5][:emcy])
|
||||
assert_equal [3, 4], store.snapshot(since: 2)[:log].map { |f| f[:seq] }
|
||||
assert_equal [[], 4], store.snapshot(since: 99).values_at(:log, :log_seq)
|
||||
assert_equal "3081" "11", store.snapshot(since: 3)[:log].first[:data]
|
||||
end
|
||||
|
||||
@@ -100,4 +102,21 @@ class CanTest < Minitest::Test
|
||||
reader&.kill
|
||||
sender&.close
|
||||
end
|
||||
|
||||
def test_the_recorder_runs_its_binary_until_stopped
|
||||
Dir.mktmpdir do |dir|
|
||||
binary = File.join(dir, "fake-recorder")
|
||||
File.write(binary, "#!/bin/sh\necho \"$@\" > \"$3/args\"\ntrap 'exit 0' TERM\nwhile :; do sleep 0.1; done\n")
|
||||
File.chmod(0o755, binary)
|
||||
recorder = Maptool::Can::Recorder.new(File.join(dir, "rec"), %w[can0 vcan0], binary: binary, segment: 60)
|
||||
recorder.start
|
||||
assert recorder.running?
|
||||
sleep 0.05 until File.exist?(File.join(dir, "rec", "args"))
|
||||
recorder.stop
|
||||
refute recorder.running?
|
||||
assert_nil recorder.error
|
||||
assert_equal "--segment 60 #{dir}/rec can0 vcan0\n", File.read(File.join(dir, "rec", "args"))
|
||||
assert_raises(Errno::ENOENT) { Maptool::Can::Recorder.new(dir, [], binary: "/nonexistent").start }
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,4 +1,4 @@
|
||||
<%# The debug pages' switcher, on top of each (status, CAN, GNSS simulation). %>
|
||||
<%# The debug pages' switcher, on top of each (status, CAN, CAN trace, GNSS simulation). %>
|
||||
<style>
|
||||
.debug-nav { display: flex; flex-wrap: wrap; gap: 4px; margin: -16px -16px 12px; padding: 6px 12px; border-bottom: 1px solid color-mix(in srgb, CanvasText 15%, transparent); font-size: 0.9rem; }
|
||||
.debug-nav a { padding: 6px 12px; border-radius: 6px; color: inherit; text-decoration: none; }
|
||||
@@ -7,7 +7,7 @@
|
||||
.debug-nav .map { margin-left: auto; }
|
||||
</style>
|
||||
<nav class="debug-nav">
|
||||
<% [["/status.html", "Server status"], ["/can.html", "CAN analyzer"], ["/sim.html", "GNSS simulation"]].each do |href, label| %>
|
||||
<% [["/status.html", "Server status"], ["/can.html", "CAN analyzer"], ["/trace.html", "CAN trace"], ["/sim.html", "GNSS simulation"]].each do |href, label| %>
|
||||
<a href="<%= href %>"<%= ' aria-current="page"' if request.path == href %>><%= label %></a>
|
||||
<% end %>
|
||||
<a class="map" href="/" target="maptool">The map ↗</a>
|
||||
|
||||
+2
-120
@@ -32,15 +32,6 @@
|
||||
/* a byte that just changed, fading out over CHANGED_FOR */
|
||||
/* a fixed width: the column doesn't jump when a node goes "silent" */
|
||||
#nodes th:nth-child(2), #nodes td:nth-child(2) { width: 9em; min-width: 9em; }
|
||||
/* the trace: bytes colored by what they are (SDO: command, index, subindex, payload) */
|
||||
#trace-box { max-height: 70vh; overflow: auto; }
|
||||
#trace td { padding-top: 3px; padding-bottom: 3px; }
|
||||
#trace thead th { position: sticky; top: 0; background: Canvas; }
|
||||
.b-cmd { color: #e53935; } .b-idx { color: #1e88e5; } .b-sub { color: #64b5f6; } .b-pay { color: #00a37a; } .b-pad { color: color-mix(in srgb, CanvasText 30%, transparent); }
|
||||
.bits-cs { color: #a020f0; } .bits-x { color: color-mix(in srgb, CanvasText 30%, transparent); } .bits-n { color: #5a3fc0; font-weight: 600; } .bits-es { color: #9b8fd0; }
|
||||
.legend { color: var(--muted); font-size: 0.8rem; font-weight: 400; text-transform: none; letter-spacing: 0; }
|
||||
.legend span { margin-right: 8px; }
|
||||
button { padding: 6px 10px; font-size: 0.9rem; }
|
||||
.chg { background: color-mix(in srgb, #ffb300 calc(var(--fresh) * 70%), transparent); border-radius: 3px; }
|
||||
</style>
|
||||
</head>
|
||||
@@ -66,11 +57,6 @@
|
||||
<div class="scroll"><table id="frames"><thead><tr><th>Interface</th><th>COB-ID</th><th>Role</th><th>Node</th><th class="num">Count</th><th class="num">Rate</th><th>Data</th><th>Last</th></tr></thead><tbody></tbody></table></div>
|
||||
</div></div>
|
||||
|
||||
<h2>Trace <button id="pause" type="button">Pause</button> <button id="clear" type="button">Clear</button>
|
||||
<span class="legend"><span class="b-cmd">command</span><span class="b-idx">OD index</span><span class="b-sub">subindex</span><span class="b-pay">payload</span><span class="b-pad">unused</span>
|
||||
· byte 0: <span class="bits-cs">ccs/scs</span> <span class="bits-x">t</span> <span class="bits-n">n</span> <span class="bits-es">e s</span> · the frame filter applies</span></h2>
|
||||
<div id="trace-box" class="scroll"><table id="trace"><thead><tr><th class="num">#</th><th class="num">Time</th><th class="num">Δ ms</th><th>Interface</th><th>ID</th><th>Data</th><th>From</th><th>Byte 0</th><th>Meaning</th></tr></thead><tbody></tbody></table></div>
|
||||
|
||||
<script>
|
||||
// Polls GET /api/can (lib/maptool/can.rb's Store) once a second.
|
||||
const STALE_AFTER = 10; // s without a frame: greyed out
|
||||
@@ -140,117 +126,15 @@
|
||||
filter ? "No frame matches." : "No frame yet.", 8);
|
||||
}
|
||||
|
||||
// The trace: every frame as it came (the server keeps the last 1000),
|
||||
// each decoded by its CANopen role.
|
||||
const TRACE_MAX = 1000;
|
||||
let trace = [], logSince = 0, paused = false, t0 = null;
|
||||
|
||||
function canopenRole(id, ext) { // lib/maptool/can.rb's Can.canopen_role
|
||||
if (ext) return [null, null];
|
||||
const node = id & 0x7f, fn = id >> 7;
|
||||
if (fn === 0) return id ? [null, null] : ["nmt", null];
|
||||
if (fn === 1) return node ? ["emcy", node] : ["sync", null];
|
||||
if (fn === 2) return ["time", null];
|
||||
if (fn >= 3 && fn <= 10) return [`${fn % 2 ? "tpdo" : "rpdo"}${Math.floor((fn - 1) / 2)}`, node];
|
||||
return [{ 0xb: "sdo_tx", 0xc: "sdo_rx", 0xe: "heartbeat" }[fn] || null, node];
|
||||
}
|
||||
const le = (b) => b.reduceRight((v, x) => v * 256 + x, 0);
|
||||
const NMT = { 0x01: "start", 0x02: "stop", 0x80: "enter pre-operational", 0x81: "reset node", 0x82: "reset communication" };
|
||||
const HB = { 0x00: "boot-up", 0x04: "stopped", 0x05: "operational", 0x7f: "pre-operational" };
|
||||
const ABORT = { 0x05040000: "timeout", 0x05040001: "bad command", 0x06010000: "unsupported access", 0x06010001: "write-only", 0x06010002: "read-only",
|
||||
0x06020000: "no such object", 0x06070010: "length mismatch", 0x06090011: "no such subindex", 0x06090030: "value out of range",
|
||||
0x08000000: "general error", 0x08000020: "can't store", 0x08000022: "device state" };
|
||||
const SDO_CLIENT = ["download segment", "download init request", "upload init request", "upload segment request", "abort", "block upload", "block download"];
|
||||
const SDO_SERVER = ["upload segment", "download segment response", "upload init response", "download init response", "abort", "block download", "block upload"];
|
||||
|
||||
// → { cls: a class per byte, from, bits (byte 0, SDO), note }
|
||||
function decode(f) {
|
||||
const b = (f.data.match(/../g) || []).map((x) => parseInt(x, 16));
|
||||
const [role, node] = canopenRole(f.id, f.extended);
|
||||
const cls = b.map(() => "b-pay");
|
||||
const pad = (from) => { for (let i = from; i < b.length; i++) cls[i] = "b-pad"; };
|
||||
const value = (from, to) => { const v = le(b.slice(from, to)); return `${hex(v, 2 * (to - from))} = ${v}`; };
|
||||
let from = node != null ? `node ${node}` : "", bits = "", note = role || (f.extended ? "extended" : "");
|
||||
if (role === "nmt") {
|
||||
from = "master"; cls[0] = "b-cmd";
|
||||
note = `NMT ${NMT[b[0]] || hex(b[0] ?? 0, 2)} → ${b[1] ? `node ${b[1]}` : "all nodes"}`;
|
||||
} else if (role === "heartbeat") {
|
||||
note = `heartbeat: ${HB[b[0] & 0x7f] || "unknown"}`;
|
||||
} else if (role === "emcy" && b.length >= 3) {
|
||||
cls[0] = cls[1] = "b-cmd"; cls[2] = "b-idx";
|
||||
const code = b[0] | (b[1] << 8);
|
||||
note = code ? `EMCY ${hex(code, 4)}, error register ${hex(b[2], 2)}` : "EMCY: errors reset";
|
||||
} else if (role === "sync") {
|
||||
from = "master"; note = b.length ? `SYNC, counter ${b[0]}` : "SYNC";
|
||||
} else if (role?.startsWith("rpdo")) {
|
||||
from = `master → ${node}`; note = role.toUpperCase();
|
||||
} else if (role?.startsWith("tpdo")) {
|
||||
note = role.toUpperCase();
|
||||
} else if (role === "sdo_rx" || role === "sdo_tx") {
|
||||
const client = role === "sdo_rx", cs = b[0] >> 5;
|
||||
from = client ? `client → ${node}` : `server ${node}`;
|
||||
cls.fill("b-pad"); cls[0] = "b-cmd";
|
||||
const bin = b[0].toString(2).padStart(8, "0");
|
||||
const segment = cs === 0; // a data segment, either way
|
||||
const withIndex = client ? [1, 2, 4].includes(cs) : [2, 3, 4].includes(cs);
|
||||
bits = segment
|
||||
? `<span class="bits-cs">${bin.slice(0, 3)}</span><span class="bits-x">${bin[3]}</span><span class="bits-n">${bin.slice(4, 7)}</span><span class="bits-es">${bin[7]}</span>`
|
||||
: `<span class="bits-cs">${bin.slice(0, 3)}</span><span class="bits-x">${bin[3]}</span><span class="bits-n">${bin.slice(4, 6)}</span><span class="bits-es">${bin.slice(6)}</span>`;
|
||||
note = (client ? SDO_CLIENT : SDO_SERVER)[cs] || `command ${cs}`;
|
||||
if (withIndex && b.length >= 4) {
|
||||
cls[1] = cls[2] = "b-idx"; cls[3] = "b-sub";
|
||||
note += ` ${hex(b[1] | (b[2] << 8), 4).slice(2)}:${b[3].toString(16).toUpperCase().padStart(2, "0")}`;
|
||||
}
|
||||
if (cs === 4 && b.length === 8) {
|
||||
for (let i = 4; i < 8; i++) cls[i] = "b-pay";
|
||||
const code = le(b.slice(4)); note += ` ${hex(code, 8)}${ABORT[code] ? ` (${ABORT[code]})` : ""}`;
|
||||
} else if ((client && cs === 1) || (!client && cs === 2)) { // init with data or size
|
||||
const n = (b[0] >> 2) & 3, e = (b[0] >> 1) & 1, s = b[0] & 1;
|
||||
if (e) { const end = s ? 8 - n : 8; for (let i = 4; i < end; i++) cls[i] = "b-pay"; note += `, expedited ${end - 4} B: ${value(4, end)}`; }
|
||||
else if (s) { for (let i = 4; i < 8; i++) cls[i] = "b-pay"; note += `, segmented, ${le(b.slice(4, 8))} B`; }
|
||||
} else if (segment) {
|
||||
const n = (b[0] >> 1) & 7, end = 8 - n;
|
||||
for (let i = 1; i < end; i++) cls[i] = "b-pay";
|
||||
note += `, toggle ${(b[0] >> 4) & 1}, ${end - 1} B${b[0] & 1 ? ", last" : ""}`;
|
||||
}
|
||||
}
|
||||
return { b, cls, from, bits, note };
|
||||
}
|
||||
|
||||
function renderTrace() {
|
||||
const box = document.getElementById("trace-box");
|
||||
const atBottom = box.scrollHeight - box.scrollTop - box.clientHeight < 24;
|
||||
const filter = document.getElementById("filter").value.trim().toLowerCase();
|
||||
let prev = null;
|
||||
const rows = [];
|
||||
for (const f of trace) {
|
||||
const d = f.decoded ||= decode(f);
|
||||
const cob = f.extended ? hex(f.id, 8) : hex(f.id, 3);
|
||||
const dt = prev ? ((f.at - prev.at) * 1000).toFixed(1) : "";
|
||||
prev = f;
|
||||
if (filter && ![f.interface, cob, d.from, d.note].join(" ").toLowerCase().includes(filter)) continue;
|
||||
const data = d.b.map((x, i) => `<span class="${d.cls[i]}">${x.toString(16).toUpperCase().padStart(2, "0")}</span>`).join(" ");
|
||||
rows.push(`<tr><td class="num">${f.seq}</td><td class="num">${(f.at - t0).toFixed(4)}</td><td class="num">${dt}</td><td>${esc(f.interface)}</td><td><code>${cob}</code></td><td><code>${data}</code></td><td>${esc(d.from)}</td><td><code>${d.bits}</code></td><td>${esc(d.note)}</td></tr>`);
|
||||
}
|
||||
fill("trace", rows, trace.length ? "No frame matches." : "No frame yet.", 9);
|
||||
if (atBottom) box.scrollTop = box.scrollHeight;
|
||||
}
|
||||
|
||||
async function poll() {
|
||||
const status = document.getElementById("status");
|
||||
try {
|
||||
const response = await fetch(paused ? "/api/can" : `/api/can?since=${logSince}`, { cache: "no-store" });
|
||||
const response = await fetch("/api/can", { cache: "no-store" });
|
||||
if (response.status === 401) { status.textContent = "Not logged in — log in on the map first."; return; }
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
const date = Date.parse(response.headers.get("Date"));
|
||||
if (date) clockOffset = Math.abs(date / 1000 - Date.now() / 1000) > 2 ? date / 1000 - Date.now() / 1000 : 0;
|
||||
render(last = await response.json());
|
||||
if (last.log?.length) {
|
||||
logSince = last.log.at(-1).seq;
|
||||
t0 ??= last.log[0].at;
|
||||
trace = trace.concat(last.log).slice(-TRACE_MAX);
|
||||
renderTrace();
|
||||
}
|
||||
const silent = Object.keys(last.nodes).filter((id) => last.nodes[id].silent);
|
||||
status.className = silent.length ? "bad" : "";
|
||||
status.textContent = (silent.length ? `⚠ node ${silent.join(", ")} silent · ` : "") + `updated ${new Date().toLocaleTimeString()}`;
|
||||
@@ -260,9 +144,7 @@
|
||||
setTimeout(poll, 1000);
|
||||
}
|
||||
}
|
||||
document.getElementById("filter").addEventListener("input", () => { if (last) render(last); renderTrace(); });
|
||||
document.getElementById("pause").addEventListener("click", (e) => { paused = !paused; e.target.textContent = paused ? "Resume" : "Pause"; });
|
||||
document.getElementById("clear").addEventListener("click", () => { trace = []; t0 = null; renderTrace(); });
|
||||
document.getElementById("filter").addEventListener("input", () => last && render(last));
|
||||
poll();
|
||||
</script>
|
||||
</body>
|
||||
|
||||
+341
@@ -0,0 +1,341 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<title>CAN trace</title>
|
||||
<link rel="icon" href="/icons/icon.svg" type="image/svg+xml">
|
||||
<style>
|
||||
:root { color-scheme: light dark; --muted: GrayText; --line: color-mix(in srgb, CanvasText 15%, transparent); --bad: #c62828; }
|
||||
body { margin: 0; padding: 16px; background: Canvas; color: CanvasText; font: 15px/1.4 -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
|
||||
header { display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: baseline; margin-bottom: 8px; }
|
||||
h1 { font-size: 1.2rem; margin: 0; }
|
||||
#status { color: var(--muted); font-size: 0.85rem; } #status.bad { color: var(--bad); }
|
||||
.bar { display: flex; flex-wrap: wrap; gap: 6px 12px; align-items: center; margin-bottom: 8px; font-size: 0.9rem; }
|
||||
.bar label { display: inline-flex; gap: 4px; align-items: center; white-space: nowrap; }
|
||||
input[type=search] { padding: 6px 8px; font-size: 0.9rem; width: 260px; max-width: 100%; box-sizing: border-box; }
|
||||
select, button { padding: 6px 10px; font-size: 0.9rem; }
|
||||
.types { display: flex; flex-wrap: wrap; gap: 4px; }
|
||||
.types label { padding: 3px 8px; border: 1px solid var(--line); border-radius: 12px; cursor: pointer; }
|
||||
.types input { margin: 0; }
|
||||
#box { max-height: calc(100vh - 220px); overflow: auto; }
|
||||
table { border-collapse: collapse; font-size: 0.85rem; }
|
||||
th, td { padding: 3px 12px 3px 0; text-align: left; border-bottom: 1px solid var(--line); white-space: nowrap; }
|
||||
thead th { position: sticky; top: 0; background: Canvas; color: var(--muted); font-weight: 500; cursor: pointer; user-select: none; }
|
||||
thead th[data-dir]::after { content: " ▲"; } thead th[data-dir="-1"]::after { content: " ▼"; }
|
||||
.num { font-variant-numeric: tabular-nums; text-align: right; }
|
||||
code { font: 0.85rem ui-monospace, SFMono-Regular, Menlo, monospace; }
|
||||
.empty { color: var(--muted); }
|
||||
.legend { color: var(--muted); font-size: 0.8rem; } .legend span { margin-right: 8px; }
|
||||
/* bytes colored by what they are (SDO: command, index, subindex, payload) */
|
||||
.b-cmd { color: #e53935; } .b-idx { color: #1e88e5; } .b-sub { color: #64b5f6; } .b-pay { color: #00a37a; } .b-pad { color: color-mix(in srgb, CanvasText 30%, transparent); }
|
||||
.bits-cs { color: #a020f0; } .bits-x { color: color-mix(in srgb, CanvasText 30%, transparent); } .bits-n { color: #5a3fc0; font-weight: 600; } .bits-es { color: #9b8fd0; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<%= erb :_debug_nav, layout: false %>
|
||||
<header>
|
||||
<h1>CAN trace</h1>
|
||||
<span id="status"></span>
|
||||
<span id="count" class="legend"></span>
|
||||
</header>
|
||||
<div class="bar">
|
||||
<input id="text" type="search" placeholder="Filter: ID, data, from, meaning… (a, b = either)">
|
||||
<label>Interface <select id="iface"><option value="">all</option></select></label>
|
||||
<label>Node <select id="node"><option value="">all</option></select></label>
|
||||
<label title="Hide frames with the same data as the last one of their ID"><input id="changes" type="checkbox"> only changes</label>
|
||||
<button id="record" type="button">● Start</button> <button id="clear" type="button">Clear</button>
|
||||
<button id="export-log" type="button" title="candump log: can-utils (canplayer, log2asc), SavvyCAN, python-can, Wireshark">Export .log</button>
|
||||
<button id="export-csv" type="button" title="The frames shown (filter, order), decoded">Export CSV</button>
|
||||
</div>
|
||||
<div class="bar types" id="types"></div>
|
||||
<details id="server" class="bar">
|
||||
<summary>Recording on the server (MF4) <span id="server-state" class="legend"></span></summary>
|
||||
<p><button id="server-toggle" type="button">● Record on the server</button>
|
||||
<span class="legend">every interface, a .mf4 file each 5 min — asammdf with a DBC, CSS Electronics' tools; goes on with this page closed</span></p>
|
||||
<table id="server-files"><tbody></tbody></table>
|
||||
</details>
|
||||
<div class="legend" style="margin-bottom: 6px"><span class="b-cmd">command</span><span class="b-idx">OD index</span><span class="b-sub">subindex</span><span class="b-pay">payload</span><span class="b-pad">unused</span>
|
||||
· byte 0: <span class="bits-cs">ccs/scs</span> <span class="bits-x">t</span> <span class="bits-n">n</span> <span class="bits-es">e s</span> · SDO objects named by <a href="/can/esphome.eds" download>esphome.eds</a> · click a column to sort</div>
|
||||
<div id="box"><table id="trace"><thead><tr>
|
||||
<th class="num" data-key="seq" data-dir="-1">#</th><th class="num" data-key="seq">Time</th><th class="num" data-key="dt">Δ ms</th><th class="num" data-key="dtId" title="Since the last frame of the same ID">Δ ID ms</th>
|
||||
<th data-key="interface">Interface</th><th data-key="id">ID</th><th data-key="data">Data</th><th data-key="from">From</th><th>Byte 0</th><th data-key="note">Meaning</th>
|
||||
</tr></thead><tbody></tbody></table></div>
|
||||
|
||||
<script>
|
||||
// Every CAN frame as it came: GET /api/can?since=<seq> once a second
|
||||
// (lib/maptool/can.rb's Store keeps the last 1000), each decoded by its
|
||||
// CANopen role; filtered and sorted here. Records only between Start
|
||||
// and Stop (no polling meanwhile).
|
||||
const TRACE_MAX = 20000; // recorded at most: then it stops (export or clear)
|
||||
const RENDER_MAX = 1000; // rows in the table (the filter and sort see all)
|
||||
const POLL_MS = 500; // the server keeps 5000 frames: past ~10000 frames/s some get lost (counted)
|
||||
const TYPES = ["NMT", "SYNC", "EMCY", "TIME", "TPDO", "RPDO", "SDO", "Heartbeat", "Other"];
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const esc = (s) => String(s ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
|
||||
const hex = (n, width) => "0x" + n.toString(16).toUpperCase().padStart(width, "0");
|
||||
let trace = [], logSince = 0, recording = false, lost = 0, t0 = null, sortKey = "seq", sortDir = -1; // the newest on top
|
||||
const lastOf = new Map(); // "iface:id" → the previous frame of that ID
|
||||
const off = new Set(); // frame types hidden
|
||||
|
||||
function canopenRole(id, ext) { // lib/maptool/can.rb's Can.canopen_role
|
||||
if (ext) return [null, null];
|
||||
const node = id & 0x7f, fn = id >> 7;
|
||||
if (fn === 0) return id ? [null, null] : ["nmt", null];
|
||||
if (fn === 1) return node ? ["emcy", node] : ["sync", null];
|
||||
if (fn === 2) return ["time", null];
|
||||
if (fn >= 3 && fn <= 10) return [`${fn % 2 ? "tpdo" : "rpdo"}${Math.floor((fn - 1) / 2)}`, node];
|
||||
return [{ 0xb: "sdo_tx", 0xc: "sdo_rx", 0xe: "heartbeat" }[fn] || null, node];
|
||||
}
|
||||
const le = (b) => b.reduceRight((v, x) => v * 256 + x, 0);
|
||||
const NMT = { 0x01: "start", 0x02: "stop", 0x80: "enter pre-operational", 0x81: "reset node", 0x82: "reset communication" };
|
||||
const HB = { 0x00: "boot-up", 0x04: "stopped", 0x05: "operational", 0x7f: "pre-operational" };
|
||||
const ABORT = { 0x05040000: "timeout", 0x05040001: "bad command", 0x06010000: "unsupported access", 0x06010001: "write-only", 0x06010002: "read-only",
|
||||
0x06020000: "no such object", 0x06070010: "length mismatch", 0x06090011: "no such subindex", 0x06090030: "value out of range",
|
||||
0x08000000: "general error", 0x08000020: "can't store", 0x08000022: "device state" };
|
||||
const SDO_CLIENT = ["download segment", "download init request", "upload init request", "upload segment request", "abort", "block upload", "block download"];
|
||||
// Object names: esphome-canopen's EDS (public/can/esphome.eds, loaded
|
||||
// below) and its entity objects (lib/maptool/can_discovery.rb).
|
||||
// ponytail: one EDS for every node; per node when they carry their own (0x1021)
|
||||
const OD = {};
|
||||
const META = { 1: "name", 3: "unit", 7: "min", 8: "max" };
|
||||
function objectName(index, sub) {
|
||||
const key = index.toString(16).padStart(4, "0");
|
||||
const parent = OD[key], name = OD[`${key}sub${sub}`];
|
||||
if (parent || name) return name && parent && !name.startsWith(parent) ? `${parent}: ${name}` : name || parent;
|
||||
if (index === 0x3002 && sub === 1) return "TPDO layout hash";
|
||||
if (index === 0x2001) return `entity ${sub} type`;
|
||||
const n = (index - 0x2000) >> 4;
|
||||
if (index >= 0x2010 && index <= 0x2ff0 && !(index & 0xf)) return `entity ${n} ${META[sub] || `metadata ${sub}`}`;
|
||||
if (index >= 0x2011 && index <= 0x2ff1 && (index & 0xf) === 1) return `entity ${n} value`;
|
||||
return "";
|
||||
}
|
||||
fetch("/can/esphome.eds").then((r) => (r.ok ? r.text() : "")).then((text) => {
|
||||
let section = null;
|
||||
for (const line of text.split(/\r?\n/)) {
|
||||
const head = line.match(/^\[([0-9a-f]{4}(?:sub[0-9a-f]+)?)\]/i);
|
||||
if (head) section = head[1].toLowerCase().replace(/sub([0-9a-f]+)/, (_, n) => `sub${parseInt(n, 16)}`);
|
||||
else if (/^\[/.test(line)) section = null;
|
||||
else if (section && line.startsWith("ParameterName=")) OD[section] = line.slice(14).trim();
|
||||
}
|
||||
});
|
||||
const SDO_SERVER = ["upload segment", "download segment response", "upload init response", "download init response", "abort", "block download", "block upload"];
|
||||
|
||||
// → { cls: a class per byte, from, bits (byte 0, SDO), note }
|
||||
function decode(f) {
|
||||
const b = (f.data.match(/../g) || []).map((x) => parseInt(x, 16));
|
||||
const [role, node] = canopenRole(f.id, f.extended);
|
||||
const cls = b.map(() => "b-pay");
|
||||
const pad = (from) => { for (let i = from; i < b.length; i++) cls[i] = "b-pad"; };
|
||||
const value = (from, to) => { const v = le(b.slice(from, to)); return `${hex(v, 2 * (to - from))} = ${v}`; };
|
||||
let from = node != null ? `node ${node}` : "", bits = "", note = role || (f.extended ? "extended" : "");
|
||||
if (role === "nmt") {
|
||||
from = "master"; cls[0] = "b-cmd";
|
||||
note = `NMT ${NMT[b[0]] || hex(b[0] ?? 0, 2)} → ${b[1] ? `node ${b[1]}` : "all nodes"}`;
|
||||
} else if (role === "heartbeat") {
|
||||
note = `heartbeat: ${HB[b[0] & 0x7f] || "unknown"}`;
|
||||
} else if (role === "emcy" && b.length >= 3) {
|
||||
cls[0] = cls[1] = "b-cmd"; cls[2] = "b-idx";
|
||||
const code = b[0] | (b[1] << 8);
|
||||
note = code ? `EMCY ${hex(code, 4)}, error register ${hex(b[2], 2)}` : "EMCY: errors reset";
|
||||
} else if (role === "sync") {
|
||||
from = "master"; note = b.length ? `SYNC, counter ${b[0]}` : "SYNC";
|
||||
} else if (role?.startsWith("rpdo")) {
|
||||
from = `master → ${node}`; note = role.toUpperCase();
|
||||
} else if (role?.startsWith("tpdo")) {
|
||||
note = role.toUpperCase();
|
||||
} else if (role === "sdo_rx" || role === "sdo_tx") {
|
||||
const client = role === "sdo_rx", cs = b[0] >> 5;
|
||||
from = client ? `client → ${node}` : `server ${node}`;
|
||||
cls.fill("b-pad"); cls[0] = "b-cmd";
|
||||
const bin = b[0].toString(2).padStart(8, "0");
|
||||
const segment = cs === 0; // a data segment, either way
|
||||
const withIndex = client ? [1, 2, 4].includes(cs) : [2, 3, 4].includes(cs);
|
||||
bits = segment
|
||||
? `<span class="bits-cs">${bin.slice(0, 3)}</span><span class="bits-x">${bin[3]}</span><span class="bits-n">${bin.slice(4, 7)}</span><span class="bits-es">${bin[7]}</span>`
|
||||
: `<span class="bits-cs">${bin.slice(0, 3)}</span><span class="bits-x">${bin[3]}</span><span class="bits-n">${bin.slice(4, 6)}</span><span class="bits-es">${bin.slice(6)}</span>`;
|
||||
note = (client ? SDO_CLIENT : SDO_SERVER)[cs] || `command ${cs}`;
|
||||
if (withIndex && b.length >= 4) {
|
||||
cls[1] = cls[2] = "b-idx"; cls[3] = "b-sub";
|
||||
const index = b[1] | (b[2] << 8), name = objectName(index, b[3]);
|
||||
note += ` ${hex(index, 4).slice(2)}:${b[3].toString(16).toUpperCase().padStart(2, "0")}${name ? ` (${name})` : ""}`;
|
||||
}
|
||||
if (cs === 4 && b.length === 8) {
|
||||
for (let i = 4; i < 8; i++) cls[i] = "b-pay";
|
||||
const code = le(b.slice(4)); note += ` ${hex(code, 8)}${ABORT[code] ? ` (${ABORT[code]})` : ""}`;
|
||||
} else if ((client && cs === 1) || (!client && cs === 2)) { // init with data or size
|
||||
const n = (b[0] >> 2) & 3, e = (b[0] >> 1) & 1, s = b[0] & 1;
|
||||
if (e) { const end = s ? 8 - n : 8; for (let i = 4; i < end; i++) cls[i] = "b-pay"; note += `, expedited ${end - 4} B: ${value(4, end)}`; }
|
||||
else if (s) { for (let i = 4; i < 8; i++) cls[i] = "b-pay"; note += `, segmented, ${le(b.slice(4, 8))} B`; }
|
||||
} else if (segment) {
|
||||
const n = (b[0] >> 1) & 7, end = 8 - n;
|
||||
for (let i = 1; i < end; i++) cls[i] = "b-pay";
|
||||
note += `, toggle ${(b[0] >> 4) & 1}, ${end - 1} B${b[0] & 1 ? ", last" : ""}`;
|
||||
}
|
||||
}
|
||||
return { b, cls, from, bits, note };
|
||||
}
|
||||
|
||||
|
||||
const typeOf = (role) => !role ? "Other" : role.startsWith("sdo") ? "SDO" : role === "heartbeat" ? "Heartbeat" : role.replace(/\d$/, "").toUpperCase();
|
||||
|
||||
// A frame from the server, its decoding and what it's sorted and filtered by.
|
||||
function add(f, prev) {
|
||||
const [role, node] = canopenRole(f.id, f.extended);
|
||||
const key = `${f.interface}:${f.id}`, before = lastOf.get(key);
|
||||
Object.assign(f, decode(f), {
|
||||
type: typeOf(role), node, cob: f.extended ? hex(f.id, 8) : hex(f.id, 3),
|
||||
dt: prev ? (f.at - prev.at) * 1000 : null, dtId: before ? (f.at - before.at) * 1000 : null, same: before?.data === f.data,
|
||||
});
|
||||
lastOf.set(key, f);
|
||||
if (!$("iface").querySelector(`option[value="${CSS.escape(f.interface)}"]`)) $("iface").add(new Option(f.interface, f.interface));
|
||||
if (node != null && !$("node").querySelector(`option[value="${node}"]`)) {
|
||||
const options = [...$("node").options].slice(1).concat(new Option(`${node} (${hex(node, 2)})`, node));
|
||||
options.sort((a, b) => a.value - b.value).forEach((o) => $("node").add(o));
|
||||
}
|
||||
}
|
||||
|
||||
let lastRows = []; // filtered and sorted, for the CSV
|
||||
function render() {
|
||||
const terms = $("text").value.toLowerCase().split(",").map((t) => t.trim()).filter(Boolean);
|
||||
const iface = $("iface").value, node = $("node").value, changes = $("changes").checked;
|
||||
const rows = trace.filter((f) =>
|
||||
!off.has(f.type) && (!iface || f.interface === iface) && (!node || String(f.node) === node) && (!changes || !f.same) &&
|
||||
(!terms.length || terms.some((t) => [f.cob, f.data, f.from, f.note, f.type].join(" ").toLowerCase().includes(t))));
|
||||
if (sortKey === "seq") {
|
||||
if (sortDir === -1) rows.reverse();
|
||||
} else {
|
||||
rows.sort((a, b) => {
|
||||
const x = a[sortKey], y = b[sortKey];
|
||||
const c = x == null ? 1 : y == null ? -1 : typeof x === "number" ? x - y : String(x).localeCompare(String(y));
|
||||
return c * sortDir || a.seq - b.seq;
|
||||
});
|
||||
}
|
||||
const ms = (v) => (v == null ? "" : v.toFixed(1));
|
||||
const shown = rows.length <= RENDER_MAX ? rows : sortKey === "seq" && sortDir === 1 ? rows.slice(-RENDER_MAX) : rows.slice(0, RENDER_MAX);
|
||||
$("trace").tBodies[0].innerHTML = shown.length ? shown.map((f) => {
|
||||
const data = f.b.map((x, i) => `<span class="${f.cls[i]}">${x.toString(16).toUpperCase().padStart(2, "0")}</span>`).join(" ");
|
||||
return `<tr><td class="num">${f.seq}</td><td class="num">${(f.at - t0).toFixed(4)}</td><td class="num">${ms(f.dt)}</td><td class="num">${ms(f.dtId)}</td><td>${esc(f.interface)}</td><td><code>${f.cob}</code>${f.extended ? " ext" : ""}</td><td><code>${data}</code></td><td>${esc(f.from)}</td><td><code>${f.bits}</code></td><td>${esc(f.note)}</td></tr>`;
|
||||
}).join("") : `<tr><td class="empty" colspan="10">${trace.length ? "No frame matches." : "No frame yet."}</td></tr>`;
|
||||
$("count").textContent = !trace.length ? "" : (rows.length > shown.length ? `showing ${shown.length} of ${rows.length} matching, ` : `${rows.length} matching of `) +
|
||||
`${trace.length} recorded${lost ? ` · ${lost} lost (bus faster than the polling)` : ""}`;
|
||||
lastRows = rows;
|
||||
}
|
||||
|
||||
async function fetchLog(since) {
|
||||
const response = await fetch(`/api/can?since=${since}`, { cache: "no-store" });
|
||||
if (response.status === 401) throw new Error("not logged in — log in on the map first");
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
const data = await response.json();
|
||||
if (!data.available) throw new Error("CAN is off: no data/can.json on this server");
|
||||
return data;
|
||||
}
|
||||
|
||||
async function poll() {
|
||||
if (!recording) return;
|
||||
const status = $("status");
|
||||
try {
|
||||
const data = await fetchLog(logSince);
|
||||
if (data.log_seq < logSince) logSince = 0; // the server restarted: its frames from the start
|
||||
if (data.log.length && logSince && data.log[0].seq > logSince + 1) lost += data.log[0].seq - logSince - 1;
|
||||
status.className = "";
|
||||
status.textContent = `● recording · ${new Date().toLocaleTimeString()}`;
|
||||
if (data.log.length) {
|
||||
t0 ??= data.log[0].at;
|
||||
for (const f of data.log.slice(0, TRACE_MAX - trace.length)) { add(f, trace.at(-1)); trace.push(f); }
|
||||
logSince = data.log.at(-1).seq;
|
||||
if (trace.length >= TRACE_MAX) { stop(); status.textContent = `stopped: ${TRACE_MAX} frames recorded — export or clear`; }
|
||||
render();
|
||||
}
|
||||
} catch (e) {
|
||||
status.className = "bad";
|
||||
status.textContent = `can't record: ${e.message}`;
|
||||
} finally {
|
||||
if (recording) setTimeout(poll, POLL_MS);
|
||||
}
|
||||
}
|
||||
|
||||
// From now on: the server's frames after its latest.
|
||||
async function start() {
|
||||
try {
|
||||
logSince = (await fetchLog(Number.MAX_SAFE_INTEGER)).log_seq;
|
||||
} catch (e) {
|
||||
$("status").className = "bad";
|
||||
$("status").textContent = `can't record: ${e.message}`;
|
||||
return;
|
||||
}
|
||||
recording = true;
|
||||
$("record").textContent = "■ Stop";
|
||||
poll();
|
||||
}
|
||||
function stop() {
|
||||
recording = false;
|
||||
$("record").textContent = "● Start";
|
||||
$("status").textContent = "stopped";
|
||||
}
|
||||
|
||||
function download(name, text, type) {
|
||||
const a = document.createElement("a");
|
||||
a.href = URL.createObjectURL(new Blob([text], { type }));
|
||||
a.download = name;
|
||||
a.click();
|
||||
setTimeout(() => URL.revokeObjectURL(a.href), 1000);
|
||||
}
|
||||
const fileName = (ext) => `can-trace-${new Date(trace[0].at * 1000).toISOString().slice(0, 19).replace(/[-:]/g, "").replace("T", "-")}.${ext}`;
|
||||
const csvField = (v) => (/[",\n]/.test(String(v ?? "")) ? `"${String(v).replace(/"/g, '""')}"` : String(v ?? ""));
|
||||
|
||||
// The server's recorder (GET/POST/DELETE /api/can/recording), every 5 s.
|
||||
let server = null;
|
||||
const size = (b) => (b > 1e6 ? `${(b / 1e6).toFixed(1)} MB` : `${Math.ceil(b / 1e3)} kB`);
|
||||
async function pollServer() {
|
||||
try {
|
||||
const response = await fetch("/api/can/recording", { cache: "no-store" });
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
server = await response.json();
|
||||
$("server-state").textContent = !server.available ? "· CAN is off on this server" : server.running
|
||||
? `· ● recording since ${new Date(server.started_at * 1000).toLocaleTimeString()}` : server.error ? `· ${server.error}` : "· stopped";
|
||||
$("server-toggle").textContent = server.running ? "■ Stop recording on the server" : "● Record on the server";
|
||||
$("server-toggle").disabled = !server.available;
|
||||
$("server-files").tBodies[0].innerHTML = server.files.length ? server.files.map((f) =>
|
||||
`<tr><td><a href="/api/can/recordings/${encodeURIComponent(f.name)}" download>${esc(f.name)}</a></td><td class="num">${size(f.size)}</td><td>${new Date(f.at * 1000).toLocaleString()}</td></tr>`).join("")
|
||||
: `<tr><td class="empty">No recording yet.</td></tr>`;
|
||||
} catch (e) {
|
||||
$("server-state").textContent = `· can't reach the server: ${e.message}`;
|
||||
}
|
||||
}
|
||||
$("server-toggle").addEventListener("click", async () => {
|
||||
$("server-toggle").disabled = true;
|
||||
const response = await fetch("/api/can/recording", { method: server?.running ? "DELETE" : "POST" });
|
||||
if (!response.ok) $("server-state").textContent = `· ${(await response.json().catch(() => ({}))).error || `HTTP ${response.status}`}`;
|
||||
else await pollServer();
|
||||
$("server-toggle").disabled = false;
|
||||
});
|
||||
pollServer();
|
||||
setInterval(pollServer, 5000);
|
||||
|
||||
$("record").addEventListener("click", () => (recording ? stop() : start()));
|
||||
// candump -l's format: every recorded frame, in order
|
||||
$("export-log").addEventListener("click", () => trace.length && download(fileName("log"),
|
||||
trace.map((f) => `(${f.at.toFixed(6)}) ${f.interface} ${f.extended ? f.id.toString(16).toUpperCase().padStart(8, "0") : f.id.toString(16).toUpperCase().padStart(3, "0")}#${f.data.toUpperCase()}\n`).join(""), "text/plain"));
|
||||
$("export-csv").addEventListener("click", () => trace.length && download(fileName("csv"),
|
||||
[["seq", "time_s", "unix_time", "dt_ms", "dt_id_ms", "interface", "id", "extended", "dlc", "data", "type", "node", "from", "meaning"].join(",")].concat(lastRows.map((f) =>
|
||||
[f.seq, (f.at - t0).toFixed(6), f.at.toFixed(6), f.dt?.toFixed(3), f.dtId?.toFixed(3), f.interface, f.cob, f.extended, f.b.length, f.b.map((x) => x.toString(16).toUpperCase().padStart(2, "0")).join(" "), f.type, f.node, f.from, f.note].map(csvField).join(","))).join("\n") + "\n", "text/csv"));
|
||||
$("types").innerHTML = TYPES.map((t) => `<label><input type="checkbox" value="${t}" checked> ${t}</label>`).join("");
|
||||
$("types").addEventListener("change", (e) => { e.target.checked ? off.delete(e.target.value) : off.add(e.target.value); render(); });
|
||||
for (const id of ["text", "iface", "node", "changes"]) $(id).addEventListener("input", render);
|
||||
$("trace").tHead.addEventListener("click", (e) => {
|
||||
const th = e.target.closest("th[data-key]");
|
||||
if (!th) return;
|
||||
sortDir = th.dataset.key === sortKey && th.hasAttribute("data-dir") ? -sortDir : 1;
|
||||
sortKey = th.dataset.key;
|
||||
for (const h of $("trace").tHead.querySelectorAll("th")) h.removeAttribute("data-dir");
|
||||
th.dataset.dir = sortDir;
|
||||
render();
|
||||
});
|
||||
$("clear").addEventListener("click", () => { trace = []; t0 = null; lost = 0; lastOf.clear(); render(); });
|
||||
render();
|
||||
$("status").textContent = "stopped — Start records the frames from then on";
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in new issue
Block a user