diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ea0d76b..f388388 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -165,7 +165,7 @@ jobs: uses: ./.github/actions/linux-deps timeout-minutes: 30 with: - extra: webkit2gtk-driver xvfb socat + extra: webkit2gtk-driver xvfb socat xdotool - run: cargo install tauri-driver --locked --version 2.1.0 # tauri-driver drives Edge WebView2 through msedgedriver, whose version must match the # WebView2 on the runner (https://v2.tauri.app/develop/tests/webdriver/ci/). diff --git a/CHANGELOG.md b/CHANGELOG.md index 27d99df..f66a545 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,22 @@ Notable changes to ModbusTool, newest first. Each section is also the text of it [GitHub release](https://github.com/chetto1983/ModbusTool/releases): the Release workflow publishes the section whose heading matches the pushed `vX.Y.Z` tag. The full history is in git. +## v3.5.0 — 2026-11-06 + +Import a device's register map as a dashboard, and record a dashboard's values to file. + +### Added + +- Register maps: a CSV with the name, table, address and type of each register (and optionally + byte order, units, decimals and scaling) becomes a dashboard with a table panel that reads them + all. A table exports the same format. A file with one invalid row is refused whole, with its + line. Addresses are protocol addresses from 0; the 40001 notation is refused with the reason. +- Recording: Record writes the dashboard's values, scaled, to a CSV file a day in + `Documents/ModbusTool/recordings` (or `~/ModbusTool/recordings` where there is no Documents + folder): a local time column, then one column per variable with its units. A row is written for + each reading, so the recording goes on while the window is hidden; without readings no rows are + written, and the gap shows in the time column. + ## v3.4.0 — 2026-11-06 A colour for every dashboard variable, from the theme or picked freely, and the end-to-end tests diff --git a/README.md b/README.md index fcb515a..09417f4 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,26 @@ Project page: . master is connected; neighbouring registers are read in one request. - Scaling as SCADA tags do it (raw range to engineering range, both ways), and a colour per variable from the theme or a colour picker. +- **Register maps:** import a device's register table from CSV as a dashboard with a table panel, + and export it back (format below). +- **Recording:** write a dashboard's values to a CSV file a day, one column per variable, in + `Documents/ModbusTool/recordings` (or `~/ModbusTool/recordings` where there is no Documents + folder). At 1 s with 200 variables that is about 90 MB a day. + +**Register map format.** A CSV with a header row; columns are found by name, in any order: + +| Column | Required | Values | +|---|---|---| +| `name` | yes | Shown in the table and the recording | +| `table` | yes | `coils`, `discrete inputs`, `holding registers`, `input registers` (or `coil`, `discrete`, `holding`, `input`) | +| `address` | yes | Protocol address from 0 (not the 40001 notation) | +| `type` | for registers | `UInt16` … `Float64`, `Hex`, `Binary`, `ASCII` | +| `byte_order` | no | `ABCD` (default), `CDAB`, `BADC`, `DCBA` | +| `units`, `decimals` | no | Text after the value; 0 to 10 decimals (default 1) | +| `raw_min`, `raw_max`, `eng_min`, `eng_max`, `clamp` | no | Scaling: all four limits or none | + +A file with one invalid row is refused whole, with its line. Exporting a table writes a complete +example. **Both** - Data types: UInt16, Int16, Hex, Binary, UInt32, Int32, Float32, UInt64, Int64, Float64, ASCII, diff --git a/docs/superpowers/plans/2026-11-06-register-maps-logging.md b/docs/superpowers/plans/2026-11-06-register-maps-logging.md new file mode 100644 index 0000000..05078dc --- /dev/null +++ b/docs/superpowers/plans/2026-11-06-register-maps-logging.md @@ -0,0 +1,50 @@ +# Piano — mappe registri e registrazione su file + +**Goal:** importare la mappa registri di un dispositivo in una dashboard (pannello tabella) e +registrarne le variabili su CSV giornalieri. + +**Architecture:** +- `src/lib/dashboards.ts`: nuovo pannello `table` (righe: variabile, unità, decimali). +- `src/lib/registerMap.ts`: lettura e scrittura del CSV della mappa (funzioni pure). +- `src/lib/recording.ts`: intestazione, righe, nomi dei file, cadenza (funzioni pure). +- `src/lib/recorder.svelte.ts`: stato della registrazione e scrittura in append con plugin-fs, + avanzata dalle letture. +- Componenti: `TableView` (corpo del pannello), voci in `DashboardView` (Importa mappa, + Registra/Ferma), esportazione dal menu del pannello tabella. + +**Tech Stack:** Svelte 5, `@tauri-apps/plugin-fs` 2.7.1, `@tauri-apps/plugin-dialog` 2.8.4, +fast-check, webdriverio + xdotool (dialoghi GTK nell'E2E). + +**Spec:** `docs/superpowers/specs/2026-11-06-register-maps-logging-design.md` + +**Global Constraints:** file ≤600 LOC; token Aura; testi in `messages/` (en, it); gate di +`CLAUDE.md`; coverage ≥85%; READ, THEN PROBE, THEN IMPLEMENT. + +**Review Focus:** una mappa non valida non entra a metà; nessuna scrittura fuori dalla cartella +scelta; le righe non dipendono da timer; i progetti esistenti si aprono ancora. + +**Decisions taken while writing this plan:** +- Unità e decimali stanno nella riga del pannello tabella, non in `Variable`: aggiungerli a + `Variable` cambierebbe tutti i pannelli e il formato del progetto per un solo uso. +- Il pannello tabella entra nel progetto come gli altri: nessun cambio di versione del file. +- La cadenza delle righe e il cambio di giorno sono funzioni pure con il tempo passato da fuori: + i test non aspettano la mezzanotte. + +## Task + +- [x] **T1 Pannello tabella (modello):** tipo, `newPanel`, validazione e lettura dei progetti, test. +- [x] **T2 CSV della mappa:** `parseRegisterMap` (errori con riga e campo), `registerMapCsv`; + test d'esempio e di proprietà (andata e ritorno). +- [x] **T3 Mappa nell'app:** `TableView`, editor delle righe, Importa mappa (unit id, nuova + dashboard), Esporta dal pannello; i18n; E2E su Linux: import col dialogo GTK, valori scalati letti + da pymodbus, export uguale all'originale. + T1–T3 in un solo commit: il pannello tabella senza interfaccia non si prova nell'E2E. + Misurato durante T3: i tasti inviati prima che il dialogo GTK sia pronto si perdono; l'E2E + ripete la risposta finché il dialogo non si chiude. +- [x] **T4 Registrazione (logica):** intestazione, righe, nomi, cadenza e giorno; registratore con + fs simulato; test. +- [x] **T5 Registrazione nell'app:** Registra/Ferma nella cartella fissa (spec L4, cambiata dopo la misura), indicatore, errori; + E2E su Linux e Windows: righe nel file confrontate con pymodbus; misure: finestra minimizzata, mappa di 200 + righe (un minuto, non un'ora: spec, Misure). + T4–T5 in un solo commit: la logica senza interfaccia non si prova nell'E2E. +- [x] **T6 Documenti:** README, CHANGELOG, file di verifica. diff --git a/docs/superpowers/specs/2026-11-06-register-maps-logging-design.md b/docs/superpowers/specs/2026-11-06-register-maps-logging-design.md new file mode 100644 index 0000000..9e6b17c --- /dev/null +++ b/docs/superpowers/specs/2026-11-06-register-maps-logging-design.md @@ -0,0 +1,86 @@ +# Mappe registri e registrazione su file + +Data: 2026-11-06. Stato: decisioni dell'utente (sotto), misure preliminari fatte, da implementare. + +## Perché + +- **Mappa:** oggi ogni registro di un dispositivo si configura a mano. Il manuale di un inverter o + di un PLC fornisce già la tabella dei registri (indirizzo, nome, tipo, unità, scala): importarla + toglie il lavoro più lungo del commissioning. +- **Registrazione:** lo storico del trend dura 10 minuti e solo in memoria. Una prova notturna o un + guasto intermittente richiedono valori su file, per ore. + +## Decisioni dell'utente (2026-11-06) + +1. Una mappa importata diventa una **dashboard**: una variabile per riga, mostrate da un pannello + tabella. Non crea poll del master, che hanno un solo tipo per blocco e nessuna scalatura. +2. Si registrano le **variabili di una dashboard**, in unità ingegneristiche (scalate). +3. CSV **largo**: una riga per lettura, una colonna per variabile. +4. **Un file nuovo al giorno.** + +## Decisioni + +### Mappa (R) + +| # | Decisione | Fonte | +|---|---|---| +| R1 | Formato CSV con riga di intestazione; colonne riconosciute per nome, in qualsiasi ordine, maiuscole indifferenti: `name`, `table`, `address`, `type`, `byte_order`, `units`, `raw_min`, `raw_max`, `eng_min`, `eng_max`, `decimals`. Obbligatorie `name`, `table`, `address`, e `type` per i registri (i bit non hanno tipo: per coil e discrete input il tipo si ignora); le quattro colonne di scala vanno insieme o nessuna, con `clamp` facoltativa (`true`/`false`, `yes`/`no`, `1`/`0`); `decimals` 0…10, predefinito 1 | Un formato da una tabella di manuale si scrive a mano o con un foglio di calcolo | +| R2 | `table`: `coils`, `discrete inputs`, `holding registers`, `input registers` (anche `coil`, `discrete`, `holding`, `input`). `address`: indirizzo di protocollo 0…65535, non la notazione 40001 | I manuali usano entrambe le notazioni: indovinarla sbaglierebbe di 1 senza che nessuno se ne accorga. Lo dice il messaggio d'errore e il README | +| R3 | `type` come nei menu dell'app (`UInt16` … `Float64`, `Hex`, `Binary`, `ASCII`); `byte_order` `ABCD`/`CDAB`/`BADC`/`DCBA`, predefinito `ABCD` | Nomi Modbus in inglese (spec i18n) | +| R4 | Un file con una sola riga non valida viene rifiutato tutto, con il numero di riga e il campo: una mappa importata a metà sembra completa e non lo è | — | +| R5 | L'import chiede l'unit id (un dispositivo, un unit id) e crea una dashboard col nome del file e un **pannello tabella** con tutte le righe | Decisione 1 | +| R6 | Pannello tabella: per riga nome, valore scalato con i decimali della riga, unità; valore vuoto se la lettura è vecchia o in errore. Le letture usano il raggruppamento esistente (D21) | Riuso di `dashboardReads` | +| R7 | Il pannello tabella si esporta nello stesso CSV: andata e ritorno restituiscono la stessa mappa | Il formato si documenta da sé con un esempio prodotto dall'app | +| R8 | Il CSV si legge con il parser già nel progetto (`src/lib/csv.ts`) | Inventario: nessuna libreria nuova | + +### Registrazione (L) + +| # | Decisione | Fonte | +|---|---|---| +| L1 | Si registrano le variabili distinte della dashboard aperta (stessa identità di `variableKey`), con il valore scalato; una cella vuota se la lettura è vecchia o in errore | Decisione 2 | +| L2 | Intestazione `time` e poi una colonna per variabile, `nome [unità]`. Il nome è quello della variabile; senza, il titolo del pannello che mostra solo lei (valore, lampada, comandi), come l'utente la chiama sullo schermo; altrimenti etichetta o indirizzo. Il tempo è locale, `AAAA-MM-GG hh:mm:ss.mmm`, che Excel e LibreOffice leggono come data | Decisione 3 | +| L3 | Una riga al più ogni mezzo periodo della dashboard, scritta all'arrivo di una lettura (nessun timer): le letture in leggero anticipo non saltano una riga e i blocchi di uno stesso ciclo ne fanno una sola. Senza letture valide, per esempio a master scollegato, non nascono righe e il buco si vede nella colonna del tempo | Misura sotto: con la finestra nascosta le righe continuano | +| L4 | ~~L'utente sceglie una cartella~~ (2026-11-06, decisione dell'utente dopo la misura sotto: il dialogo cartella di GTK non si pilota nell'E2E). Cartella **fissa**: `Documenti/ModbusTool/recordings`, oppure `~/ModbusTool/recordings` dove il sistema non definisce Documenti. I file si chiamano `_AAAA-MM-GG.csv` e cambiano a mezzanotte locale. Se il file del giorno esiste già con la stessa intestazione si continua a scriverlo; con un'intestazione diversa si apre `_AAAA-MM-GG_2.csv` (e così via) | Decisione 4. dirs 7.0.0 (`document_dir`): su Linux Documenti esiste solo se `~/.config/user-dirs.dirs` lo definisce, cosa che WSL2, container e runner CI spesso non hanno | +| L5 | Pulsante Registra/Ferma nella barra della dashboard, con indicatore, righe scritte e percorso completo del file (selezionabile). Un errore di scrittura, o la cartella che non si crea, ferma la registrazione e lo dice | — | +| L6 | Permessi: `fs:allow-mkdir` e lo scope solo su `$DOCUMENT/ModbusTool/recordings` e `$HOME/ModbusTool/recordings`, non su tutta la cartella Documenti. Nessun pulsante "Apri cartella": `tauri-plugin-opener` 2.7.2 aggiungeva 457 righe a `Cargo.lock` (lo stack D-Bus `zbus` su Linux) per un solo pulsante | Misura 2026-11-06 | + +## Inventario (versioni installate) + +- `src/lib/csv.ts`: parser e scrittura CSV con virgolette, già usati per import/export dello slave e + per il traffico. +- `Variable` (`src/lib/dashboards.ts`) ha tabella, indirizzo, tipo, byte order, scalatura e colore: + manca solo il testo dell'unità e i decimali, che stanno nella riga del pannello tabella. +- `@tauri-apps/plugin-fs` 2.7.1: `writeTextFile(path, data, { append: true })`; permessi + `fs:allow-read-text-file` e `fs:allow-write-text-file` già concessi. +- `tauri-plugin-dialog` 2.8.4 (`src/commands.rs`): `save()` concede lo scope **solo sul file** + scelto (`allow_file`); `open({ directory: true })` concede la cartella (`allow_directory`). + +## Misure preliminari (2026-11-06, Linux, Xvfb, WebKitGTK 2.52.6) + +- **Dialoghi nativi nell'E2E:** il dialogo GTK "Open" aperto dall'app si pilota con `xdotool` + (`windowfocus`, Ctrl+L, percorso, Invio): l'app ha aperto il progetto scelto. `windowactivate` + non funziona senza window manager. Su Windows i dialoghi nativi non si pilotano: lì quei + controlli si dichiarano non eseguiti, come quelli seriali. + +## Misure durante l'implementazione (2026-11-06, stesso ambiente) + +- **Dialogo apri e salva:** i tasti inviati prima che il dialogo sia pronto si perdono; l'E2E + ripete la risposta finché il dialogo non si chiude. Il dialogo di salvataggio ("Save File") + prende il percorso nel campo del nome (Ctrl+A). +- **Dialogo cartella ("Select Folder"):** non si chiude né con il percorso e Invio (entra nella + cartella), né con un secondo Invio, né con Alt+S (rfd 0.17.2 usa `GtkFileChooserNative` senza + etichetta propria). Dopo tre tentativi la scelta è passata all'utente: cartella fissa (L4). +- **Cartella fissa e permessi:** con una HOME senza `user-dirs.dirs` l'app crea + `~/ModbusTool/recordings` e ci scrive (E2E, 91/91). +- **Finestra nascosta e carico:** mappa di 200 registri (100 input e 100 holding), periodo 1 s, + build debug. Finestra visibile 5 s: 5 righe; poi nascosta (`xdotool windowunmap`) 60 s: altre 60 + righe, tutte con 200 valori. File: circa 1 KB a riga, cioè circa 90 MB al giorno a questo ritmo. + CPU dell'app nel minuto nascosto: 0,7% di un core. + +## Cosa NON è dimostrato + +- Nessuna misura su Windows dei dialoghi nativi (lì l'import della mappa non è nell'E2E) né della + registrazione con la finestra nascosta; la registrazione stessa è nell'E2E anche su Windows. +- "Nascosta" è la finestra tolta dallo schermo sotto Xvfb, non la riduzione a icona di un desktop + vero; il carico è misurato per un minuto, non per ore. +- La notazione 40001 non è supportata (R2): una mappa scritta così va convertita. diff --git a/docs/superpowers/verification/2026-11-06-register-maps-logging.md b/docs/superpowers/verification/2026-11-06-register-maps-logging.md new file mode 100644 index 0000000..7cf3b2e --- /dev/null +++ b/docs/superpowers/verification/2026-11-06-register-maps-logging.md @@ -0,0 +1,52 @@ +# Verifica: mappe registri e registrazione su file + +Data: 2026-11-06. Spec: `docs/superpowers/specs/2026-11-06-register-maps-logging-design.md`. +Piano: `docs/superpowers/plans/2026-11-06-register-maps-logging.md`. + +## Cosa è stato misurato + +**E2E contro pymodbus** (`node e2e/run.mjs`, build debug, Linux, Xvfb, WebKitGTK 2.52.6, HOME vuota +senza `user-dirs.dirs`, `LANG=C.UTF-8`): **91/91**. I controlli nuovi: + +- **Mappa importata:** + - una mappa con intestazioni scritte come in un manuale (maiuscole, `Byte order` con lo spazio), + importata dal dialogo GTK "Open File" guidato con xdotool; + - il pannello tabella mostra, letti da pymodbus: input 4 = `1,004 °C`; input 6 scalato + 1000…1010 → 0…100 = `60.0 %`; input 2–3 UInt32 ABCD = `65,668,075 m³`; discrete input 1 = `0`. +- **Mappa esportata:** dal dialogo GTK "Save File", il file è identico, carattere per carattere, al + formato atteso (colonne dell'app, default scritti per esteso, `°C` e `m³` intatti). +- **Registrazione:** + - la dashboard dell'E2E, periodo 200 ms, registrata finché il contatore supera 5 righe; + - nel file, la colonna `Pressure [bar]` vale 333 (il registro 2 di pymodbus) in ogni riga, e le + righe distano almeno mezzo periodo; + - la cartella è `~/ModbusTool/recordings`, il ripiego senza Documenti: lo scope dei permessi + funziona. + +**Misure a parte** (stesso ambiente, sonda con webdriverio): + +- Dialogo cartella GTK: non pilotabile (tre tentativi, spec "Misure"); da qui la cartella fissa, + scelta dall'utente. +- Finestra nascosta (`xdotool windowunmap`), mappa di 200 registri a 1 s: 60 righe in 60 s, tutte + con 200 valori; circa 1 KB a riga; CPU dell'app 0,7% di un core. + +**Test unitari** (vitest, 146 test, coverage righe 99,78%): + +- CSV della mappa: esempio da un inverter, ogni cella rifiutata con riga e colonna, andata e ritorno + di proprietà con fast-check. +- Azioni: import, file non valido, annullo, export, export fallito, dimensione della tabella. +- Registrazione: colonne e nomi, intestazione, ora locale, nomi dei file, cadenza; registratore con + fs simulato: cambio di giorno, file del giorno esistente o con altre colonne, ripiego sulla home, + errori di scrittura e di cartella. + +**Gate:** svelte-check, oxlint, prettier, knip, jscpd, check:i18n, file-size, build. + +## Cosa NON dimostra + +- **Windows:** l'import e l'export della mappa non sono nell'E2E, perché i dialoghi nativi non si + pilotano; la registrazione sì, ma la prima prova su Windows è la CI di questo commit. +- La finestra "nascosta" è tolta dallo schermo sotto Xvfb, non ridotta a icona su un desktop vero + né su WebView2; il carico è misurato per un minuto, non per ore né per giorni. +- Nessuna prova con un dispositivo reale né con mappe di manuali reali: le mappe sono costruite + sui valori noti di pymodbus. +- `cargo mutants` non si applica: nessun codice Rust nuovo. Stryker non è stato eseguito sui file + nuovi. diff --git a/e2e/dashboard.mjs b/e2e/dashboard.mjs index 14f68fa..0e1278d 100644 --- a/e2e/dashboard.mjs +++ b/e2e/dashboard.mjs @@ -2,6 +2,7 @@ // their own variables from the reference server, and command panels write to it. // Reference holding register n = 111 * (n + 1), even coils ON (reference_servers.py). +import { readFileSync, rmSync } from "node:fs"; import { setTimeout as sleep } from "node:timers/promises"; import { button, @@ -307,6 +308,38 @@ export async function dashboardScenario(browser, target) { }, "reset"); }); + await check("Dashboard: a recording writes a row per period with the values read", async () => { + await click(browser, button("", "Record")); + const status = browser.$("//span[contains(@class,'recording')]"); + await eventually( + async () => { + const rows = Number((await status.getProperty("textContent")).match(/(\d+) rows/)?.[1] ?? 0); + if (rows < 5) throw new Error(`${rows} rows`); + }, + "rows", + 10_000, + ); + const file = await status.getAttribute("title"); + await click(browser, button("", "Stop recording")); + const [header, ...lines] = readFileSync(file, "utf8").trim().split("\n"); + rmSync(file); + const columns = header.split(","); + expectEqual(columns[0], "time", "first column"); + const pressure = columns.indexOf("Pressure [bar]"); + if (pressure < 0) throw new Error(`no pressure column in ${header}`); + const rows = lines.map((line) => line.split(",")); + expectEqual( + rows.map((r) => r[pressure]), + rows.map(() => "333"), + "pressure", + ); + // At most one row per half period (200 ms), times as spreadsheets read them. + const times = rows.map((r) => Date.parse(r[0].replace(" ", "T"))); + for (let i = 1; i < times.length; i++) { + if (!(times[i] - times[i - 1] >= 100)) throw new Error(`rows ${times[i] - times[i - 1]} ms apart: ${lines}`); + } + }); + await check("Dashboard: reads stop when the master disconnects", async () => { await click(browser, "//nav//button[.//span[normalize-space()='Master']]"); await click(browser, button(panel("Connection"), "Disconnect")); diff --git a/e2e/helpers.mjs b/e2e/helpers.mjs index af1475f..ba69d28 100644 --- a/e2e/helpers.mjs +++ b/e2e/helpers.mjs @@ -15,6 +15,12 @@ export const python = process.platform === "win32" ? "python" : "python3"; * the run says so, rather than counting them as passed. */ export const serial = process.platform !== "win32"; +/** + * Native file dialogs are answered on Linux by typing into the GTK chooser with xdotool. WebDriver + * cannot reach them, and Windows has no such tool here: there those checks are not run, and the + * run says so. + */ +export const nativeDialogs = process.platform === "linux"; /** Failure screenshots and the run's files; E2E_OUT names a folder CI uploads when a run fails. */ export const tmp = process.env.E2E_OUT ? (mkdirSync(process.env.E2E_OUT, { recursive: true }), process.env.E2E_OUT) @@ -134,3 +140,45 @@ export async function editCell(browser, index, value) { await input.addValue(String(value)); await browser.keys("Enter"); } + +/** The id of the visible window titled `title`; throws while there is none. */ +function windowTitled(title) { + return execFileSync("xdotool", ["search", "--onlyvisible", "--name", `^${title}$`], { encoding: "utf8" }) + .trim() + .split("\n") + .pop(); +} + +/** + * Answers the GTK file dialog titled `title` ("Open File", "Save File") with `path`. Xvfb has no + * window manager, so the dialog is focused, not activated. Keys typed before the dialog is ready + * are lost (measured), so the answer is typed again until the dialog has closed. The location + * takes the path after Ctrl+L in the open dialog, in the selected name field in the save dialog. + */ +export async function answerFileDialog(title, path) { + await eventually( + async () => { + const id = windowTitled(title); + execFileSync("xdotool", ["windowfocus", "--sync", id]); + execFileSync("xdotool", ["key", title.startsWith("Save") ? "ctrl+a" : "ctrl+l"]); + execFileSync("xdotool", ["key", "ctrl+a"]); + execFileSync("xdotool", ["type", "--delay", "20", path]); + execFileSync("xdotool", ["key", "Return"]); + await eventually( + () => { + let open = true; + try { + windowTitled(title); + } catch { + open = false; + } + if (open) throw new Error(`"${title}" still open`); + }, + `"${title}" closed`, + 2000, + ); + }, + `"${title}" answered`, + 20_000, + ); +} diff --git a/e2e/registerMap.mjs b/e2e/registerMap.mjs new file mode 100644 index 0000000..f0e055d --- /dev/null +++ b/e2e/registerMap.mjs @@ -0,0 +1,85 @@ +// Register maps against pymodbus (docs/superpowers/specs/2026-11-06-register-maps-logging-design.md): +// a map imported through the native file dialog becomes a dashboard table that reads the reference, +// and the table exports the same map. Reference input register n = 1000 + n, discrete inputs off +// (reference_servers.py); no scenario writes them. + +import { readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { + answerFileDialog, + button, + check, + click, + dialog, + eventually, + expectEqual, + labelled, + setField, + tmp, +} from "./helpers.mjs"; + +// As a manual prints it: headers in its own words and case, mixed types, a scaled value, a bit. +const MAP = `Name,Table,Address,Type,Byte order,Units,Decimals,Raw min,Raw max,Eng min,Eng max +Inlet temperature,input registers,4,UInt16,,°C,0,,,, +Level,input registers,6,UInt16,,%,1,1000,1010,0,100 +Totaliser,input registers,2,UInt32,ABCD,m³,0,,,, +Alarm,discrete inputs,1,,,,0,,,, +`; + +// What the table exports: the app's own column names, every default written out. +const EXPORTED = `name,table,address,type,byte_order,units,decimals,raw_min,raw_max,eng_min,eng_max,clamp +Inlet temperature,input registers,4,UInt16,ABCD,°C,0,,,,, +Level,input registers,6,UInt16,ABCD,%,1,1000,1010,0,100,false +Totaliser,input registers,2,UInt32,ABCD,m³,0,,,,, +Alarm,discrete inputs,1,,,,0,,,,, +`; + +const rows = (browser) => + browser + .$$("//article//table//tbody/tr") + .map(async (tr) => (await tr.$$("td").map((td) => td.getProperty("textContent"))).map((t) => t.trim())); + +/** Runs with the master connected to the reference; leaves no dashboard behind. */ +export async function registerMapScenario(browser) { + console.log("Register map"); + const source = join(tmp, "drive.csv"); + const exported = join(tmp, "drive-exported.csv"); + writeFileSync(source, MAP); + await click(browser, "//nav//button[.//span[normalize-space()='Dashboard']]"); + + await check("Register map: an imported map reads every register, scaled, with its units", async () => { + await click(browser, button("", "Import register map")); + await setField(browser, dialog, "Device unit id", 1); + await click(browser, button(dialog, "Choose file")); + await answerFileDialog("Open File", source); + await eventually( + async () => + expectEqual( + await rows(browser), + [ + ["Inlet temperature", "1,004", "°C"], + ["Level", "60.0", "%"], + // Registers 2 and 3, high word first: 1002 * 65536 + 1003. + ["Totaliser", "65,668,075", "m³"], + ["Alarm", "0", ""], + ], + "table", + ), + "table", + ); + }); + + await check("Register map: a table exports the map it was imported from", async () => { + await click(browser, button("", "Edit")); + await click(browser, labelled("Edit drive")); + await click(browser, button(dialog, "Export register map")); + await answerFileDialog("Save File", exported); + await eventually(() => expectEqual(readFileSync(exported, "utf8"), EXPORTED, "exported map"), "export"); + await click(browser, button(dialog, "Cancel")); + await click(browser, button("", "Done")); + }); + + await click(browser, labelled("Delete dashboard")); + await click(browser, button(dialog, "Yes")); + await click(browser, "//nav//button[.//span[normalize-space()='Master']]"); +} diff --git a/e2e/run.mjs b/e2e/run.mjs index 42a44d3..6fe8daa 100644 --- a/e2e/run.mjs +++ b/e2e/run.mjs @@ -5,7 +5,8 @@ // npx tauri build --debug --no-bundle && node e2e/run.mjs [screenshot-dir] // // Needs: tauri-driver, the platform's WebDriver, python with pymodbus[serial]; on Linux also socat -// (the serial checks) and an X display. Windows runs every check but the serial ones. +// (the serial checks), xdotool (the native file dialogs) and an X display. Windows runs every check +// but the serial ones and those through a native file dialog. import { remote } from "webdriverio"; import { spawn } from "node:child_process"; @@ -23,6 +24,7 @@ import { expectEqual, gridValues, labelled, + nativeDialogs, panel, python, reference, @@ -35,6 +37,7 @@ import { track, } from "./helpers.mjs"; import { dashboardScenario } from "./dashboard.mjs"; +import { registerMapScenario } from "./registerMap.mjs"; import { typesMaster, typesSlave } from "./types.mjs"; const APP = process.platform === "win32" ? "modbus-tool.exe" : "modbus-tool"; @@ -193,6 +196,7 @@ async function masterScenario(browser, ports, serialRef) { await editPoll(browser, { Function: "FC03 · Holding registers" }); await typesMaster(browser, `127.0.0.1:${ports.tcp}`, 40); await dashboardScenario(browser, `127.0.0.1:${ports.tcp}`); + if (nativeDialogs) await registerMapScenario(browser); await editPoll(browser, { Function: "FC04 · Input registers", Address: 0, @@ -367,6 +371,7 @@ async function main() { } else { console.log("Not run on this platform (no socat): ASCII serial master, RTU serial slave\n"); } + if (!nativeDialogs) console.log("Not run on this platform (no xdotool): register map import and export\n"); background(python, [ join(root, "e2e/reference_servers.py"), ports.tcp, diff --git a/knip.json b/knip.json index 51fecf5..0e9e7d6 100644 --- a/knip.json +++ b/knip.json @@ -2,5 +2,6 @@ "$schema": "https://unpkg.com/knip@6/schema.json", "entry": ["site/site.js"], "ignoreExportsUsedInFile": true, - "ignoreDependencies": ["@inlang/plugin-message-format", "@inlang/plugin-m-function-matcher"] + "ignoreDependencies": ["@inlang/plugin-message-format", "@inlang/plugin-m-function-matcher"], + "ignoreBinaries": ["xdotool"] } diff --git a/messages/en.json b/messages/en.json index 96af790..595a4ff 100644 --- a/messages/en.json +++ b/messages/en.json @@ -53,6 +53,7 @@ "dashboard_delete_confirm": "Delete the dashboard {name} and its panels?", "panel_trend": "Trend", "panel_value": "Value", + "panel_table": "Table", "panel_bars": "Bars", "panel_lamp": "Lamp", "panel_button": "Button", @@ -249,5 +250,25 @@ "traffic_description": "Description", "traffic_bytes": "Bytes", "traffic_empty": "Frames sent and received by the master and the slave appear here.", - "traffic_exported": "Exported {count} frames" + "traffic_exported": "Exported {count} frames", + "map_import": "Import register map", + "map_import_help": "A CSV with the columns name, table, address and type, and optionally byte_order, units, decimals, raw_min, raw_max, eng_min, eng_max and clamp. Addresses are protocol addresses from 0. The map becomes a new dashboard with a table.", + "map_unit": "Device unit id", + "map_choose_file": "Choose file", + "map_export": "Export register map", + "map_file_type": "Register map", + "map_imported": "Imported {count} registers from {file}", + "map_exported": "Exported {count} registers to {file}", + "table_name": "Name", + "record_start": "Record", + "record_help": "Writes this dashboard's values to a CSV file a day, in Documents/ModbusTool/recordings", + "record_stop": "Stop recording", + "record_status": "Recording {dashboard}, {rows} rows: {file}", + "record_failed": "Recording stopped: {error}", + "table_value": "Value", + "table_units": "Unit", + "map_empty": "The register map has no rows", + "map_missing_columns": "The register map needs the columns: {columns}", + "map_invalid_cell": "Register map, line {line}: invalid {column} \"{value}\"", + "map_invalid_address": "Register map, line {line}: address \"{value}\" is not 0 to 65535 (the protocol address, not the 40001 notation)" } diff --git a/messages/it.json b/messages/it.json index 05ea6d5..b3daaa2 100644 --- a/messages/it.json +++ b/messages/it.json @@ -53,6 +53,7 @@ "dashboard_delete_confirm": "Eliminare la dashboard {name} e i suoi pannelli?", "panel_trend": "Trend", "panel_value": "Valore", + "panel_table": "Tabella", "panel_bars": "Barre", "panel_lamp": "Lampada", "panel_button": "Pulsante", @@ -249,5 +250,25 @@ "traffic_description": "Descrizione", "traffic_bytes": "Byte", "traffic_empty": "Qui compaiono i frame inviati e ricevuti dal master e dallo slave.", - "traffic_exported": "Esportati {count} frame" + "traffic_exported": "Esportati {count} frame", + "map_import": "Importa mappa registri", + "map_import_help": "Un CSV con le colonne name, table, address e type, e facoltative byte_order, units, decimals, raw_min, raw_max, eng_min, eng_max e clamp. Gli indirizzi sono quelli di protocollo, da 0. La mappa diventa una nuova dashboard con una tabella.", + "map_unit": "Unit id del dispositivo", + "map_choose_file": "Scegli file", + "map_export": "Esporta mappa registri", + "map_file_type": "Mappa registri", + "map_imported": "Importati {count} registri da {file}", + "map_exported": "Esportati {count} registri in {file}", + "table_name": "Nome", + "record_start": "Registra", + "record_help": "Scrive i valori di questa dashboard in un file CSV al giorno, in Documenti/ModbusTool/recordings", + "record_stop": "Ferma registrazione", + "record_status": "Registrazione di {dashboard}, {rows} righe: {file}", + "record_failed": "Registrazione fermata: {error}", + "table_value": "Valore", + "table_units": "Unità", + "map_empty": "La mappa registri non ha righe", + "map_missing_columns": "Alla mappa registri mancano le colonne: {columns}", + "map_invalid_cell": "Mappa registri, riga {line}: {column} non valido \"{value}\"", + "map_invalid_address": "Mappa registri, riga {line}: indirizzo \"{value}\" non compreso tra 0 e 65535 (l'indirizzo di protocollo, non la notazione 40001)" } diff --git a/package-lock.json b/package-lock.json index 9208eaa..2e938b5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "modbus-tool", - "version": "3.4.0", + "version": "3.5.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "modbus-tool", - "version": "3.4.0", + "version": "3.5.0", "license": "MIT", "dependencies": { "@tauri-apps/api": "^2.12.4", diff --git a/package.json b/package.json index a0179c6..8011d1e 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "modbus-tool", "private": true, - "version": "3.4.0", + "version": "3.5.0", "license": "MIT", "type": "module", "scripts": { diff --git a/site/index.html b/site/index.html index ad9d008..fe7b48f 100644 --- a/site/index.html +++ b/site/index.html @@ -102,6 +102,20 @@

Scaling like SCADA tags

units and written raw.

+
+

Register maps

+

+ Import a device's register table from CSV: names, types, units and scaling become a dashboard table that + reads them all. Export it back for the next device. +

+
+
+

Recording to file

+

+ Record a dashboard to CSV, one file a day and one column per value, ready for a spreadsheet. It keeps + recording with the window in the background. +

+