@vehicle-sil/gui-client 0.0.0-stage → 0.2.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.ja.md +839 -0
- package/README.md +836 -2
- package/dist/elements.js +872 -0
- package/dist/index.js +5354 -0
- package/package.json +39 -4
- package/timeline/vehicle-sil-timeline.d.ts +108 -0
- package/timeline/vehicle-sil-timeline.js +4391 -0
- package/timeline/vehicle-sil-timeline.mjs +4393 -0
- package/types/client.d.ts +148 -0
- package/types/connection.d.ts +155 -0
- package/types/elements/index.d.ts +25 -0
- package/types/elements/outside-parts.d.ts +20 -0
- package/types/elements/page-intent.d.ts +10 -0
- package/types/elements/part.d.ts +48 -0
- package/types/elements/reasons.d.ts +12 -0
- package/types/elements/run-parts.d.ts +21 -0
- package/types/elements/scenario-parts.d.ts +18 -0
- package/types/elements/variable-parts.d.ts +28 -0
- package/types/front-actions.d.ts +122 -0
- package/types/front-compose.d.ts +61 -0
- package/types/front-outside.d.ts +19 -0
- package/types/front-types.d.ts +353 -0
- package/types/front-variable.d.ts +28 -0
- package/types/front.d.ts +50 -0
- package/types/http.d.ts +71 -0
- package/types/index.d.ts +28 -0
- package/types/protocol/launcher.d.ts +578 -0
- package/types/protocol/read.d.ts +72 -0
- package/types/protocol/server.d.ts +758 -0
- package/types/protocol.d.ts +15 -0
- package/types/run.d.ts +74 -0
- package/types/session-state.d.ts +289 -0
- package/types/session.d.ts +130 -0
- package/types/time.d.ts +133 -0
- package/types/token.d.ts +35 -0
- package/types/urls.d.ts +8 -0
- package/types/values.d.ts +54 -0
- package/types/variable-binding.d.ts +181 -0
- package/types/variable-state.d.ts +134 -0
- package/types/variables.d.ts +382 -0
package/README.md
CHANGED
|
@@ -1,3 +1,837 @@
|
|
|
1
|
-
#
|
|
1
|
+
# gui/client
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[日本語](README.ja.md)
|
|
4
|
+
|
|
5
|
+
Reference for the client library of the GUI server (`vehicle-sil-gui`), written in TypeScript and published as `@vehicle-sil/gui-client`. It covers how to get and import the library, the public API, basic usage, reading and writing ECU variables, and the lifecycle.
|
|
6
|
+
|
|
7
|
+
The library handles the connection (token, reconnection), the session copy (a copy of the run state, built from the server's summary and events), run and time control, ECU variables (list, watching values, writes and their results), and the types and parsers of the server API. It depends on no other package, not even Angular or RxJS. The sample screens (`gui/web`) use only this library, through a thin Angular wrapper (`gui/web/src/app/core/session/`).
|
|
8
|
+
|
|
9
|
+
| To find | See |
|
|
10
|
+
| ------------------------------------------------------------------ | -------------------------------------------------------- |
|
|
11
|
+
| Where to get the library and how to import it | [Installing and importing](#installing-and-importing) |
|
|
12
|
+
| Which names are public | [Entry points](#entry-points), [Public API](#public-api) |
|
|
13
|
+
| The code to connect and start a run | [Basic usage](#basic-usage) |
|
|
14
|
+
| Reading and writing variable values | [ECU variables](#ecu-variables) |
|
|
15
|
+
| What a screen shows and which buttons work: `connect()` | [The front door (`connect()`)](#the-front-door-connect) |
|
|
16
|
+
| The elements to put in HTML, with no script | [Parts (custom elements)](#parts-custom-elements) |
|
|
17
|
+
| Building sliders and lamps (the values of `condition` and `block`) | [Build widgets (`bind`)](#build-widgets-bind) |
|
|
18
|
+
| What happens after `connect()` and `close()` | [Lifecycle](#lifecycle) |
|
|
19
|
+
| Developing the library | [Coding rules](#coding-rules), [Tests](#tests) |
|
|
20
|
+
|
|
21
|
+
## Installing and importing
|
|
22
|
+
|
|
23
|
+
The library is TypeScript source with no dependencies. Each release publishes it on the npm registry as `@vehicle-sil/gui-client` (the dist-tag `latest` is the newest release, `next` the newest pre-release) and attaches the same package to the release as `vehicle-sil-gui-client-<version>.tgz`. Install the version of your GUI server: the client refuses a server that speaks another version of the GUI protocol.
|
|
24
|
+
|
|
25
|
+
| Use | How to get it | Import |
|
|
26
|
+
| ----------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ |
|
|
27
|
+
| A page that the GUI server serves (`--web`) | Nothing to copy: the server serves the files (below) | `import { connect } from '/vsil/vehicle-sil-gui-client.mjs'` |
|
|
28
|
+
| Plain JavaScript, outside such a page | Put `vehicle-sil-gui-client.mjs`, the library bundled into one ESM file, next to your script | `import { connect } from './vehicle-sil-gui-client.mjs'` |
|
|
29
|
+
| TypeScript and any framework | Run `npm install @vehicle-sil/gui-client@<version>` in your project (or `npm install <the release's .tgz>`) | `import { connect } from '@vehicle-sil/gui-client'` |
|
|
30
|
+
| A TypeScript app in this repository (`gui/web`) | Point the entry point names to `src/` with `paths` in `tsconfig.json` | `import { createClient } from '@vehicle-sil/gui-client'` |
|
|
31
|
+
|
|
32
|
+
Where to find the 3 files:
|
|
33
|
+
|
|
34
|
+
| File | Prebuilt tools | Build in the repository (run in `gui/web`) |
|
|
35
|
+
| -------------------------------------- | ----------------------------------------------------- | ------------------------------------------------------------------------------------- |
|
|
36
|
+
| `vehicle-sil-gui-client.mjs` | `<tools>/client/vehicle-sil-gui-client.mjs` | `npm run build:client` creates `build/gui-client/vehicle-sil-gui-client.mjs` |
|
|
37
|
+
| `vehicle-sil-gui-elements.mjs` | `<tools>/client/vehicle-sil-gui-elements.mjs` | `npm run build:client` creates `build/gui-client/vehicle-sil-gui-elements.mjs` |
|
|
38
|
+
| `vehicle-sil-gui-client-<version>.tgz` | `<tools>/client/vehicle-sil-gui-client-<version>.tgz` | `npm run pack:client` creates `build/gui-client/vehicle-sil-gui-client-<version>.tgz` |
|
|
39
|
+
|
|
40
|
+
The releases page has the same `.tgz`. `build/` is the one at the top of the repository and is not tracked in Git.
|
|
41
|
+
|
|
42
|
+
The GUI server also serves the two `.mjs` files, without the token, as `/vsil/vehicle-sil-gui-client.mjs` and `/vsil/vehicle-sil-gui-elements.mjs` (in the repository, from `build/gui-client/`; it says what to run when they are not built). A screen without a build can load them from there and copy nothing.
|
|
43
|
+
|
|
44
|
+
- **Bundled file**: loads in the browser and in Node (22 or later). `scripts/verify-gui.py` runs an example that uses this file from Node against the replay launcher.
|
|
45
|
+
- **Package**: contains the bundled ESM, `.d.ts` files, `exports`, the README and the LICENSE (`pack.mjs` builds it). Its version is the same as the GUI server's. Its types use the browser types (`DOM` in `lib`). Its entry points are `.`, `./elements` and `./timeline` (`testing` and `internal` are not included).
|
|
46
|
+
|
|
47
|
+
## Entry points
|
|
48
|
+
|
|
49
|
+
| Entry point | Name | Contents |
|
|
50
|
+
| --------------------------------------------------------------------------------------------------------------- | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
51
|
+
| `src/index.ts` | `@vehicle-sil/gui-client` | The public API ("Public API" below). This entry point and `./elements` are kept compatible |
|
|
52
|
+
| `src/testing/index.ts` | `@vehicle-sil/gui-client/testing` | Test helpers (usable in tests of your own widgets) |
|
|
53
|
+
| `src/internal.ts` | `@vehicle-sil/gui-client/internal` | **No compatibility guarantee.** Internal classes and functions; do not use them in apps |
|
|
54
|
+
| `src/elements/index.ts` (in the package as `dist/elements.js`, which imports `dist/index.js`) | `@vehicle-sil/gui-client/elements` | The parts (custom elements `<vsil-status>` and 10 more), `pageIntent` and `setReasonText`: importing it defines them ("Parts (custom elements)" below). It needs a DOM; the main entry does not import it |
|
|
55
|
+
| `../timeline/vehicle-sil-timeline.js` (in the package as `timeline/vehicle-sil-timeline.mjs`, with `export {}`) | `@vehicle-sil/gui-client/timeline` | The element `<vehicle-sil-timeline>`, with its types: importing it defines the element ("Putting a timeline on your own screen" in [docs/gui.md](../../docs/gui.md#putting-a-timeline-on-your-own-screen)) |
|
|
56
|
+
|
|
57
|
+
- `testing` contains a fake WebSocket (`FakeWebSockets`), a fake HTTP (`FakeHttp`), loaders for `gui/protocol/examples/`, and `sessionViewFrom`, which builds a `SessionView` from a summary.
|
|
58
|
+
- `internal` contains the internal classes, the functions that apply a summary, and the parsers. They are public for tests only, and change or disappear without notice.
|
|
59
|
+
|
|
60
|
+
The public API is kept small, because adding to it keeps compatibility and removing from it breaks compatibility. If the public entry point lacks something you need, do not reach into `internal`; decide whether to add it to the public API.
|
|
61
|
+
|
|
62
|
+
## Public API
|
|
63
|
+
|
|
64
|
+
The names that `src/index.ts` exports, by group. Parentheses list the members of the object.
|
|
65
|
+
|
|
66
|
+
### Client
|
|
67
|
+
|
|
68
|
+
| Kind | Name |
|
|
69
|
+
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
70
|
+
| Function | `createClient(options)` |
|
|
71
|
+
| Type | `ClientOptions` (`baseUrl`, `token`, `origin`, `http`, `socket`, `answerTimeoutMs`, `onError`) |
|
|
72
|
+
| Type | `GuiClient` (`connection`, `session`, `run`, `time`, `variables`, `app`, `limits`, `connect()`, `close()`, `loadApp()`, `configs()`, `config(file)`, `check()`, `describe()`, `saveConfig()`, `connections()`, `fetchSession()`, `dashboard(file)`, `scenarios(file)`, `recording()`) |
|
|
73
|
+
| Constant | `DEFAULT_LIMITS` |
|
|
74
|
+
|
|
75
|
+
### Front door
|
|
76
|
+
|
|
77
|
+
| Kind | Name |
|
|
78
|
+
| -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
79
|
+
| Function | `connect(options?)`, `createFront(options)`, `watch(source, fn)`, `until(source, test, options?)` |
|
|
80
|
+
| Class | `ActionError` (`code`, `message`, `outcome`, `findings`) |
|
|
81
|
+
| Type | `ConnectOptions` (`base_url`, `token`, `origin`, `http`, `socket`, `answer_timeout_ms`, `on_error`), `Front` (`low`, `status`, `clock`, `controls`, `scenario`, `outside`, `run`, `time`, `variable()`, `scenarios()`, `connections()`, `check()`, `readConfig()`, `describeAgain()`, `saveConfig()`, `close()`), `FrontStatus`, `FrontResult`, `FrontClock`, `FrontControls`, `Control`, `Reason`, `FrontScenario`, `FrontRun`, `FrontTime`, `FrontVariable`, `VariableView`, `Intent`, `Outside`, `ConnectEntry`, `ConnectTarget`, `ConnectListError`, `Link`, `RunState`, `EndKind`, `Pacing`, `OperationName` |
|
|
82
|
+
|
|
83
|
+
### Token
|
|
84
|
+
|
|
85
|
+
| Kind | Name |
|
|
86
|
+
| -------- | ------------------- |
|
|
87
|
+
| Function | `takeToken(place)` |
|
|
88
|
+
| Type | `TokenPlace` |
|
|
89
|
+
| Constant | `TOKEN_STORAGE_KEY` |
|
|
90
|
+
|
|
91
|
+
In the browser, call `takeToken(window)`. It reads `#token=` from the URL, removes it from the URL and stores it in sessionStorage. If the URL has no token, it returns the one in sessionStorage; if neither has one, it returns `null`.
|
|
92
|
+
|
|
93
|
+
### Connection (read-only)
|
|
94
|
+
|
|
95
|
+
| Kind | Name |
|
|
96
|
+
| -------- | -------------------------------------------------------------------------------------------------- |
|
|
97
|
+
| Type | `ClientConnection` (`state`, `failures`, `lastClose`, `tryAgainReason`, `onBatch`, `onUnreadable`) |
|
|
98
|
+
| Type | `ConnectionState`, `CloseInfo` |
|
|
99
|
+
| Constant | `BATCH_MS`, `TRY_AGAIN_LATER` |
|
|
100
|
+
|
|
101
|
+
### Session copy
|
|
102
|
+
|
|
103
|
+
| Kind | Name |
|
|
104
|
+
| -------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
105
|
+
| Type | `ClientSession` (`session`, `ready`, `allowed`, `lastEventAt`, `notices`, `rejected`, `incompatible`, `onMessages`, `report`, `dismissNotice`) |
|
|
106
|
+
| Type | `Notice`, `SessionView`, `ParticipantView`, `LauncherView`, `LogLine`, `LogSource`, `TimeView`, `CommandView`, `RunOutcome`, `LauncherAnswer` |
|
|
107
|
+
| Function | `runOutcome`, `phaseIndex`, `isHolding`, `launcherAnswer` |
|
|
108
|
+
|
|
109
|
+
`ClientSession.allowed` is what the GUI server accepts now (`start`, `stop` and `force`, each with `ok`, a `reason` code and a `message`; the larger `rev` wins; `null` until the server says). `SessionView.launcherState` is the launcher's last `state` event (where the run stands and what it accepts; the larger `rev` wins; `null` until one arrives). `launcherAnswer(launcherState, name)` reads what it says of one operation (`write`, `pause`, ...): `reason` (`null` when the launcher accepts it) and `caution`. A launcher that has not said (no `state` yet, or no entry for the operation) does not accept it (`unsupported`). The front door's `controls` and `variables.bind` read the launcher with it.
|
|
110
|
+
|
|
111
|
+
### Run control
|
|
112
|
+
|
|
113
|
+
| Kind | Name |
|
|
114
|
+
| ---- | ------------------------------------------------------------------------------------------------ |
|
|
115
|
+
| Type | `ClientRun` (`starting`, `stopping`, `stopWhileStarting`, `error`, `start`, `stop`, `forceStop`) |
|
|
116
|
+
| Type | `StopAction` |
|
|
117
|
+
|
|
118
|
+
### Time
|
|
119
|
+
|
|
120
|
+
| Kind | Name |
|
|
121
|
+
| -------- | ---------------------------------------------------------------------------------------- |
|
|
122
|
+
| Type | `ClientTime` (`state`, `answerTimeoutMs`, `pause`, `resume`, `step`, `setSpeed`, `send`) |
|
|
123
|
+
| Type | `TimeState`, `TimeFailure`, `Lateness`, `SendResult`, `NotSentReason` |
|
|
124
|
+
| Constant | `ANSWER_TIMEOUT_MS` |
|
|
125
|
+
|
|
126
|
+
### ECU variable API
|
|
127
|
+
|
|
128
|
+
| Kind | Name |
|
|
129
|
+
| -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
130
|
+
| Type | `ClientVariables` (`state`, `operations`, `watchProblem`, `watch`, `write`, `bind`) |
|
|
131
|
+
| Type | `VariableWatch` (`values`, `value`, `history`, `close`) |
|
|
132
|
+
| Type | `VariablesState`, `VariablesStatus`, `VariablePeer`, `VariableInfo`, `VariableRef`, `VariableValue`, `WatchOptions`, `WatchValues`, `VariableReading`, `HistoryPoint` |
|
|
133
|
+
| Type | `WriteOptions`, `OperationView`, `OperationPeer`, `WatchProblem` |
|
|
134
|
+
| Class | `WriteError` |
|
|
135
|
+
| Constant | `WATCH_PERIOD_MS`, `WATCH_PERIODS_MS`, `WRITE_TIMEOUT_MS`, `HISTORY_MAX`, `HISTORY_TOTAL_MAX`, `OPERATIONS_KEPT` |
|
|
136
|
+
|
|
137
|
+
### Binding variables to widgets (`bind`)
|
|
138
|
+
|
|
139
|
+
| Kind | Name |
|
|
140
|
+
| -------- | ------------------------------------------------------------------------------------------------------------------------- |
|
|
141
|
+
| Method | `client.variables.bind(ref, options)` |
|
|
142
|
+
| Type | `BindOptions` (`periodMs`, `history`, `needsRange`, `needsValue`, `visible`) |
|
|
143
|
+
| Type | `VariableBinding` (`ref`, `state`, `history()`, `write(value)`, `reject(message)`, `setVisible(visible)`, `close()`) |
|
|
144
|
+
| Type | `BoundVariable` (`ref`, `info`, `reading`, `condition`, `block`, `launcherReason` (a `Reason`), `writeStatus`, `pending`) |
|
|
145
|
+
| Type | `ValueCondition`, `WriteBlock`, `WriteStatus`, `WriteValue` |
|
|
146
|
+
| Function | `isWriteError`, `hasRange` |
|
|
147
|
+
| Function | `valueCondition` (`ConditionInput`), `writeBlock` (`WriteBlockInput`) |
|
|
148
|
+
| Constant | `DROPPED_MESSAGE` |
|
|
149
|
+
|
|
150
|
+
`valueCondition`, `writeBlock` and `hasRange` are the pure functions that `bind` builds its state with.
|
|
151
|
+
|
|
152
|
+
### `Readable` (read-only value)
|
|
153
|
+
|
|
154
|
+
| Kind | Name |
|
|
155
|
+
| ---- | ---------------------------------------- |
|
|
156
|
+
| Type | `Readable<T>` (`get()`, `subscribe(fn)`) |
|
|
157
|
+
|
|
158
|
+
### APIs for substitution
|
|
159
|
+
|
|
160
|
+
| Kind | Name |
|
|
161
|
+
| -------- | ---------------------------------------------------------------------- |
|
|
162
|
+
| Type | `SocketFactory`, `SocketHandlers`, `SocketLike` |
|
|
163
|
+
| Type | `HttpTransport`, `HttpRequest`, `HttpOutcome`, `FetchTransportOptions` |
|
|
164
|
+
| Function | `webSocketFactory`, `fetchTransport` |
|
|
165
|
+
| Constant | `DEFAULT_TIMEOUT_MS` |
|
|
166
|
+
|
|
167
|
+
### Errors
|
|
168
|
+
|
|
169
|
+
| Kind | Name |
|
|
170
|
+
| -------- | ----------------------------------------------------------- |
|
|
171
|
+
| Class | `HttpError` (`status`, `statusText`, `problem`, `timedOut`) |
|
|
172
|
+
| Class | `ProtocolError` |
|
|
173
|
+
| Function | `errorMessage` |
|
|
174
|
+
|
|
175
|
+
### Server API types and parsing
|
|
176
|
+
|
|
177
|
+
Types for the shapes that `gui/protocol` defines, and the parsers to use when you read the server API yourself.
|
|
178
|
+
|
|
179
|
+
| Subject | Name |
|
|
180
|
+
| ---------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
181
|
+
| Types of the `gui/protocol` shapes | `SessionSummary`, `ServerMessage`, `LauncherEvent`, `CheckResult`, `RunResult`, `AppInfo` and others |
|
|
182
|
+
| Constants and functions | `PROTOCOL_VERSION`, `PHASES`, `severityRank` |
|
|
183
|
+
| Parsers | `readServerMessage`, `readAppInfo`, `readConfigList`, `readConfigText`, `readSavedConfig`, `readCheckResponse`, `readConnections`, `readSessionResponse`, `readTimeResponse`, `readWriteResponse`, `readVariablesSummary`, `readDashboardResponse`, `readScenarioList`, `readRecording` |
|
|
184
|
+
| Shapes of the variable API | `VariablesSummary`, `VariableSummary`, `ValuesMessage`, `OperationReport`, `WatchMessage`, `WriteAnswer` |
|
|
185
|
+
| Dashboard files (`dashboard(file)`) | `DashboardResponse`, `DashboardFile`, `DashboardFileSection`, `DashboardFileItem`, `DashboardFileError`, `DashboardPanelModule`, `DashboardVariable` |
|
|
186
|
+
| Scenarios (`--scenario`, `scenarios(file)`, `recording()`) | `ScenarioStep`, `ScenarioStepStatus`, `ScenarioStatus`, `CheckScenario`, `ScenarioResult`, `SummaryScenario`, `ScenarioList`, `ScenarioFile`, `Recording` |
|
|
187
|
+
| Request shapes | `CheckRequest`, `CheckTextRequest`, `DescribeRequest`, `SaveConfigRequest`, `RunRequest`, `ConnectionsRequest`, `Speed`, `StopRequest`, `TimeCommand` |
|
|
188
|
+
| List of configuration files | `ConfigList`, `ConfigFile`, `ConfigText`, `SavedConfig` |
|
|
189
|
+
| Error shape | `ServerProblem` |
|
|
190
|
+
| Findings | `Finding`, `Severity` |
|
|
191
|
+
| The launcher's keys and traffic | `FromLauncher`, `LauncherFields`, `RunTraffic`, `TrafficNetwork`, `TrafficParticipant`, `TrafficUnplaced`, `ParticipantRole`, `OutsideState` |
|
|
192
|
+
| `SessionView.scenario` of the session copy | `ScenarioView` |
|
|
193
|
+
|
|
194
|
+
## Basic usage
|
|
195
|
+
|
|
196
|
+
This is the lower door of the library, `createClient`, which the front door is built on (it is `client.low` there). A screen starts with `connect()` and the parts ("The front door (`connect()`)" and "Parts (custom elements)" below) and uses this door for what they do not cover: events, logs, findings, participants and `bind`.
|
|
197
|
+
|
|
198
|
+
```ts
|
|
199
|
+
import { createClient, takeToken } from '@vehicle-sil/gui-client';
|
|
200
|
+
|
|
201
|
+
// A screen opened from the URL the server printed (http://127.0.0.1:<port>/#token=<token>): take #token= from the URL and remove it.
|
|
202
|
+
// A Node tool takes baseUrl and the token out of that URL itself and passes them (examples/gui_client, in a clone of the repository).
|
|
203
|
+
const client = createClient({
|
|
204
|
+
baseUrl: new URL('/', location.href).href,
|
|
205
|
+
token: takeToken(window),
|
|
206
|
+
});
|
|
207
|
+
await client.loadApp(); // the server's information (the start-up file, the limits, whether variables are available)
|
|
208
|
+
client.connect();
|
|
209
|
+
const stop = client.session.session.subscribe((session) => {
|
|
210
|
+
if (session?.result) console.log(session.result.result);
|
|
211
|
+
});
|
|
212
|
+
await client.run.start({ file: 'simulation.yaml', disable: [] });
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
### Read state (`Readable`)
|
|
216
|
+
|
|
217
|
+
Every state is a `Readable` (a read-only value).
|
|
218
|
+
|
|
219
|
+
| Call | What it does |
|
|
220
|
+
| --------------------- | ------------------------------------------------------------------ |
|
|
221
|
+
| `get()` | Returns the current value |
|
|
222
|
+
| `subscribe(fn)` | Notifies `fn` of later changes (not called with the current value) |
|
|
223
|
+
| The returned function | Ends the subscription |
|
|
224
|
+
|
|
225
|
+
- Notifications are synchronous: they arrive inside the code that changed the value.
|
|
226
|
+
- A subscriber that unsubscribes during a notification still receives that notification.
|
|
227
|
+
- If a subscriber changes the same value, every subscriber receives the new value, and the old value does not arrive afterward.
|
|
228
|
+
- A framework wrapper takes the first value with `get()` and converts later values into its own state with `subscribe()` (an Angular signal is shown in "[A project with a framework](../../examples/gui_starter/README.md#a-project-with-a-framework)"; the package has no framework code).
|
|
229
|
+
- If a subscriber (a function passed to `subscribe`, `onBatch`, `onMessages` or `onUnreadable`) throws, the other subscribers are still notified and the library carries on (disconnecting when rejected, rebuilding and so on). The thrown value goes to `onError` (default `console.error`).
|
|
230
|
+
- `client.session.ready` tells whether the session copy is complete (connected, and `hello` and the replay have arrived). Other features (values, for example) have their own ready state.
|
|
231
|
+
|
|
232
|
+
### Rejections and timeouts
|
|
233
|
+
|
|
234
|
+
- If the token is rejected (for example, because the server was restarted), `client.session.rejected` becomes true (WebSocket), and HTTP requests are rejected with an `HttpError` of status 401.
|
|
235
|
+
- When an operation is rejected, its Promise rejects with an `HttpError`, and the same reason appears in the state (`client.run.error`, `failure` in `client.time.state`).
|
|
236
|
+
- A request waits for its response for up to `DEFAULT_TIMEOUT_MS`. After that it fails with an `HttpError` whose `timedOut` is true (status 0).
|
|
237
|
+
- Start (`run.start()`) and check (`check()`) wait up to twice the check limit (`limits.check_timeout_s`) plus `DEFAULT_TIMEOUT_MS`. The server runs checks one at a time, and both the wait in the queue and the check itself can take up to the check limit; a start also checks the configuration file again if it changed.
|
|
238
|
+
- A timeout is not a rejection: no response came. For a start, the server may have started the run; the session copy (WebSocket) shows whether it did, and `client.run.error` says so.
|
|
239
|
+
- Redirects are not followed.
|
|
240
|
+
|
|
241
|
+
### The launcher's keys (`raw`)
|
|
242
|
+
|
|
243
|
+
The check result, the run result, findings and launcher events come from the launcher, and the library passes on every key of them. The typed fields (for example `traffic` of the run result, `participants[].log`, and `role` of a check participant) follow the launcher's format versions (`vehicle_sil_check`, `vehicle_sil_run`, `vehicle_sil_events`), not the version of this library. Every object read from the launcher also has `raw`: the launcher's object as it arrived, with the keys the types do not name. `raw` is read-only and not enumerable (`JSON.stringify` and spreading leave it out). Its values are unchecked JSON: check their type, and show them as text, never as HTML.
|
|
244
|
+
|
|
245
|
+
```ts
|
|
246
|
+
const result = client.session.session.get()?.result; // RunResult | null
|
|
247
|
+
for (const network of result?.traffic?.networks ?? []) console.log(network.name, network.delivered);
|
|
248
|
+
const strict = result?.raw?.['strict']; // a key without a typed field: unknown
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
### Handling unreadable notifications
|
|
252
|
+
|
|
253
|
+
The library parses each part separately.
|
|
254
|
+
|
|
255
|
+
- If part of a summary or an event cannot be read, the library uses the readable parts and adds the names of the unreadable parts to `SessionView.unreadable`.
|
|
256
|
+
- Unknown notifications and events pass through without changing the state, and `onMessages` does not get them (`client.connection.onBatch` receives everything, before parsing: read an event that the library does not know there).
|
|
257
|
+
- A notification that is not valid JSON raises a notice, and the library receives everything again from `hello`.
|
|
258
|
+
|
|
259
|
+
### Use from Node, or replace the transport
|
|
260
|
+
|
|
261
|
+
- In Node, the library sends the server's own origin as `Origin` (`createClient` builds it from `baseUrl`).
|
|
262
|
+
- In the browser and in Web Workers, do not pass `origin`: the browser sets it (a Worker's WebSocket cannot set handshake headers).
|
|
263
|
+
- To replace the HTTP implementation, pass `http` (`HttpTransport`); to replace the WebSocket, pass `socket` (`SocketFactory`).
|
|
264
|
+
|
|
265
|
+
For the rules the library does not enforce for you (the fields of check and start requests, whether a variable is writable, whether a value is stale), see "Rules for building a screen" in [docs/gui.md](../../docs/gui.md#rules-for-building-a-screen).
|
|
266
|
+
|
|
267
|
+
## The front door (`connect()`)
|
|
268
|
+
|
|
269
|
+
`connect()` returns the front door of the library: what a screen shows (`status`, `clock`, `controls`, `scenario`), the operations as Promises (`run`, `time`) and one variable at a time (`variable()`). It is built on the client described above and changes nothing in it: `front.low` is the same `GuiClient` (events, logs, findings, participants), and `createClient` still works as before. Use the front door for what a screen needs to decide ("which state is this", "may this button be pressed now, and if not, why"); use `low` for the rest.
|
|
270
|
+
|
|
271
|
+
An app that must show its screens before the server answers, and while it cannot be reached (the standard screens), uses `createFront(options)` instead: it makes the front door without connecting, as `createClient` does, and the app calls `front.low.connect()` and `front.low.loadApp()` itself. Until `loadApp()` has answered, the front knows no start-up file, and the ranges in `controls` are the defaults (`DEFAULT_LIMITS`).
|
|
272
|
+
|
|
273
|
+
```ts
|
|
274
|
+
import { ActionError, connect, until, watch } from '@vehicle-sil/gui-client';
|
|
275
|
+
|
|
276
|
+
// A page that the GUI server served, opened from the URL it printed: no options. The first call connects; the next calls
|
|
277
|
+
// (another part of the page) get the same connection. In Node, or for a second connection, pass the server's URL and the token.
|
|
278
|
+
const client = await connect();
|
|
279
|
+
// const client = await connect({ base_url: 'http://127.0.0.1:8765/', token });
|
|
280
|
+
|
|
281
|
+
const stop = watch([client.status, client.controls], (status, controls) => {
|
|
282
|
+
startButton.disabled = !controls.start.ok;
|
|
283
|
+
startButton.title = controls.start.reason?.message ?? '';
|
|
284
|
+
banner.textContent = status.problem?.message ?? '';
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
try {
|
|
288
|
+
await client.time.pause(); // a step needs a paused run (or start it paused: `run.start({ start_paused: true })`)
|
|
289
|
+
await client.time.step(100); // resolves when time has arrived and the run is paused again
|
|
290
|
+
} catch (error) {
|
|
291
|
+
if (error instanceof ActionError) console.log(error.code, error.message, error.outcome);
|
|
292
|
+
}
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
| Name | What it is |
|
|
296
|
+
| ------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
297
|
+
| `status` | The one state to show: `link`, `run`, `file`, `result` and `problem` (below). Discrete values only |
|
|
298
|
+
| `clock` | `sim_ms` (the virtual time in ms; `null` before a run), `speed`, `actual_speed` (the speed over about the last second; `null` while paused and right after the start) and `pacing` (`not-paced`, `on-time` or `late`). It changes often, so it is apart from `status` |
|
|
299
|
+
| `controls` | Whether each operation can be used now: `start`, `stop`, `force_stop`, `pause`, `resume`, `step` (with `min_ms` and `max_ms`), `run_until`, `speed` (with `min`, `max` and `fastest`: whether `'max'` is accepted besides the numbers), and `save` |
|
|
300
|
+
| `scenario` | The scenario of the current (or last) run: `file`, `name`, `status`, `steps`, `timeline_url`; `null` for a run without one |
|
|
301
|
+
| `outside` | The networks that the run's `connect` connected to a real bus ("Connecting a network outside" below) |
|
|
302
|
+
| `connections({ network }, { file }?)`, `check(intent?, { file }?)` | Where a network can be connected, and the check of an intent without starting it ("Connecting a network outside" below) |
|
|
303
|
+
| `readConfig({ file }?)` | The text of a configuration file as it is saved, with its `stamp` ("Editing the text of a configuration file" below) |
|
|
304
|
+
| `check(intent?, { file, text }?)` | With `text`, the check of an unsaved text of the file (the same section) |
|
|
305
|
+
| `describeAgain({ file, variant }?)` | Describes the participants of the saved file again, and returns that check (the same section) |
|
|
306
|
+
| `saveConfig({ file, text, stamp })` | Saves a text as the file, with the `stamp` it was read with (`null`: a new file), and returns the new `stamp` (the same section) |
|
|
307
|
+
| `run` | `start(intent?, { file }?)`, `stop()` and `forceStop()` |
|
|
308
|
+
| `time` | `pause()`, `resume()`, `step(ms)`, `setSpeed(value)` and `runUntil(ms)` |
|
|
309
|
+
| `variable(ref)` | One variable, by `"ECU.variable"` (cut at the first dot) or `{ peer, name }` (for an ECU whose name has a dot) |
|
|
310
|
+
| `low`, `close()` | The `GuiClient` of the same connection; `close()` disconnects (a shared connection is made again by the next `connect()`) |
|
|
311
|
+
| `watch(source, fn)`, `until(source, test, options)` | `watch` calls `fn` now and on every change (several sources: `watch([a, b], (a, b) => ...)`) and returns the function that stops it. `until` resolves with the first value that satisfies `test`; it rejects with an `ActionError` (`timeout` or `aborted`, both `unknown`) |
|
|
312
|
+
|
|
313
|
+
Data fields use the wire's names (`force_stop`, `sim_ms`); functions use JavaScript's (`forceStop`, `runUntil`). Every state is a `Readable`; `get()` returns the same object while nothing changed, and `get` and `subscribe` work without `this` (they can be passed to `useSyncExternalStore` as they are).
|
|
314
|
+
|
|
315
|
+
### `status`
|
|
316
|
+
|
|
317
|
+
| Field | Values |
|
|
318
|
+
| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
319
|
+
| `link` | `connecting`, `online`, `offline`, `rejected` (the token was refused) or `incompatible` (another protocol version). `online` means the copy matches the server |
|
|
320
|
+
| `run` | `none`, `starting` (a start is on its way, from this page or another), `waiting` (the launcher waits for the participants to join), `running`, `paused`, `stopping`, `ended` (there is a result) or `crashed` (the launcher ended without one) |
|
|
321
|
+
| `file` | The configuration file of the run (the last one if none is running); the server's start-up file before the first run. `null` until the first answer from the server (the type is `string \| null`), and when there is no start-up file |
|
|
322
|
+
| `result` | While `run` is `ended` or `crashed`: `end` (`completed`, `stopped`, `interrupted`, `failed`, `setup_failed` or `crashed`; `null` when nothing was started: the check failed, or the file or the command line could not be used), `scenario`, `ok` and `message` (one English sentence). A stop by the operator is `ok`, except when it stopped a scenario before its end |
|
|
323
|
+
| `problem` | The one problem to tell the user now (`{ code, message }`), or `null` |
|
|
324
|
+
|
|
325
|
+
`problem` is chosen in this order: the connection first (the token refused, another protocol version, offline); otherwise the newest of the launcher's crash, the failure of the last operation and a failed run (`result.ok` is false). A crash and a failed run go when the next run begins. The failure of an operation goes at the next operation or when `status.run` changes. A stop by the operator is not a problem, except when it stopped a scenario before its end (`result.ok` is false then, and the message says that the scenario has no verdict). The failure of a variable write is in the variable's own `problem`, not here. The server's notices (`low.session.session` `problems`) and `notices` stay in `low`.
|
|
326
|
+
|
|
327
|
+
`result.end`, `result.ok` and `result.message` are the launcher's: it writes them into its result (`end`, `ok` and `message`; see "How a run ended" in [simulation-run.md](../../docs/simulation-run.md#how-a-run-ended-end-ok-message)), and the library passes them on. The library has no table of result names. Only `crashed` is the library's own (`ok` is false, with a sentence of its own), because a launcher that ended without a result wrote nothing.
|
|
328
|
+
|
|
329
|
+
### `controls`
|
|
330
|
+
|
|
331
|
+
Each entry is `{ ok, reason, caution }`: `reason` is `{ code, message }` when `ok` is false, `caution` is the same shape for an operation that is accepted with something to know first. The codes stay the same (a new code may be added; the meaning of one does not change); the sentence is English, written by the owner of the rule.
|
|
332
|
+
|
|
333
|
+
| Entry | Comes from |
|
|
334
|
+
| ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
335
|
+
| `start` | The GUI server's `allowed.start` (`starting`, `already-running`, `launcher-unusable`, `shutting-down`), with its sentence |
|
|
336
|
+
| `stop`, `force_stop` | The GUI server's `allowed.stop` and `allowed.force`. `stop` is `ok` for the last known run (or a start on its way), also offline, and while the server says the launcher still runs after its result. `force_stop` is `ok` only after a first stop (`not-stopping` before) |
|
|
337
|
+
| `pause`, `resume`, `step`, `speed`, `run_until` | The launcher's `state.allowed` (reason, sentence and `caution` as the launcher wrote them; the ranges of `step` and `speed`; `fastest` is false when `min` equals `max`, as the launcher promises). No run in the copy: `not-running`; the launcher has not said yet (no `state` yet at the start of a run, or no entry for the operation): `unsupported` |
|
|
338
|
+
| `pause`, `resume` (what would change nothing) | `pause` is not `ok` while the run is paused (`paused`), `resume` is not `ok` while it is not (`not-paused`): the launcher accepts both, but a button has nothing to do. While a step or a run_until is on its way (accepted, and not yet seen to arrive: virtual time at its `at_ms` and the launcher's `state` paused), neither is claimed |
|
|
339
|
+
| `save` | The GUI server's `allowed.save` (`save-disabled`: started with `--no-save`; `shutting-down`), with its `caution` (`command-changes-allowed`: started with `--allow-command-changes`, so it also saves edits that change the commands that run). Whether one edit is saved is the answer to `saveConfig()` |
|
|
340
|
+
| All of them | The connection: `rejected`, `incompatible`, `offline` or `connecting` turn them off (`stop` and `force_stop` stay as above); `busy` while the same operation of this page has not been answered |
|
|
341
|
+
|
|
342
|
+
### Operations
|
|
343
|
+
|
|
344
|
+
`run.start(intent, { file })` takes the intent: `vehicle_sil_run_request` (1, optional), `variant`, `params`, `scenario`, `disable`, `enable`, `manual`, `strict`, `speed`, `start_paused`, `connect` and `time_policy`, as the launcher's request file names them (`scenario` is a `path` that `scenarios()` gave, relative to the GUI server's root; the request file's own `scenario` is relative to the configuration file's directory, and the server rewrites the path, so do not compose it) (any other field is refused with `unknown-field`; a choice that is not made is a key that is left out, never `null`); `file` defaults to the server's start-up file (`scenarios({ file })` and `connections()` default to it too: give the same `file` to each when a run uses another file). Every operation is a Promise. It rejects with an `ActionError`: `code`, a sentence (`message`), `findings` (for `check-failed`) and `outcome`: `refused` (the owner said no; nothing happened) or `unknown` (it may have been done: look at `status` and `clock` before you send it again).
|
|
345
|
+
|
|
346
|
+
| Operation | Resolves when | Rejects with |
|
|
347
|
+
| ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
348
|
+
| `run.start` | The server took the request. Whether the run began is `status.run` (wait with `until(client.status, s => s.run !== 'starting')`, then read `run`) | The refusal (`check-failed` with the `findings`, `already-running`, ...). No answer in time: `no-answer` (`unknown`: it may have started) |
|
|
349
|
+
| `run.stop`, `run.forceStop` | The server took the request. Sent whatever the state of the connection (HTTP may reach the server when the WebSocket is down); asking again while one is on its way is the same request | The same |
|
|
350
|
+
| `time.pause`, `resume`, `setSpeed` | The launcher answered. `pause` while paused and `resume` while running send nothing and resolve, only when the connection is `online` and a run takes the operation | The launcher's `reason` and sentence (`refused`); no answer within 5 seconds: `no-answer` (`unknown`); the run ended before the answer: `not-running` (`unknown`) |
|
|
351
|
+
| `time.step`, `time.runUntil` | Time has arrived and the run is paused again, so `clock` can be read after `await`. `runUntil(t)` arrives at `t` (a `t` the paused run has already passed resolves at once and time does not move); `step(ms)` at the `at_ms` the launcher writes in the answer (older launcher: the time it was accepted plus the `ms` it rounded to, an estimate) | As above; and `interrupted` (`unknown`) when a resume or a pause of another sender (another page or stdin) comes before it arrives (a pause or resume of this page, or a stop, rejects it the same way but is not shown in `status.problem`). Another step sent meanwhile does not end it |
|
|
352
|
+
|
|
353
|
+
The client refuses before sending only what it owns: the connection (`rejected`, `incompatible`), the same operation still waiting for its answer (`busy`; this includes `start()`) and the shape of an argument (`invalid-argument`). Anything else is sent even if `controls` says no, and the owner's answer comes back (the copy may be old). The 5 seconds are the front door's own (they do not apply to the wait for arrival, which ends when the run ends or another command interrupts it).
|
|
354
|
+
|
|
355
|
+
A time command carries a request number (`id`) that the page chose, and the answer is the launcher's `command` event with the same `id`; an answer to another page's or stdin's command with the same name is not taken for it.
|
|
356
|
+
|
|
357
|
+
### Connecting a network outside
|
|
358
|
+
|
|
359
|
+
A `can` or `ethernet` network can be connected to a real bus through the launcher's bridge ("Connecting a network outside" in [gui/protocol/README.md](../protocol/README.md#connecting-a-network-outside-connect-time_policy-apiconnections)). The front door adds three things for it, with no rule of its own.
|
|
360
|
+
|
|
361
|
+
```ts
|
|
362
|
+
const entries = await client.connections({ network: 'ETH_EXT' }); // when the user opens the choice
|
|
363
|
+
const intent = { connect: { ETH_EXT: 'fake0' }, time_policy: 'free' as const };
|
|
364
|
+
const result = await client.check(intent); // the launcher's findings, before anything starts
|
|
365
|
+
await client.run.start(intent);
|
|
366
|
+
const stop = watch(client.outside, (rows) => console.log(rows.map((r) => r.condition)));
|
|
367
|
+
```
|
|
368
|
+
|
|
369
|
+
- **`connections({ network }, { file }?)`** asks `POST api/connections` and lays the answer out as one list, in its order: `{ backend, value, label, detail, usable, reason }` for each target, and `{ backend, error }` (the launcher's sentence) for a backend whose bridge could not list, or for an error of the file. Tell the two apart with `'error' in entry`. A list that lacks a backend (exit code 1) is not a failure. It starts that network's bridge on the computer of the GUI server (on Windows, Npcap may ask to raise the rights there), so call it when the user opens the choice, not when the page opens. The list is that computer's, not the browser's. It rejects with an `ActionError` (`check-busy`, `unknown-network`, ...).
|
|
370
|
+
- **`intent.connect`** maps a network to a `value` that the list gave with `usable: true`, as written there; `'none'` keeps it on SIL Kit only, the same as leaving it out. The server refuses a value that its last list of that network did not give (`target-not-listed`): list the network again. **`intent.time_policy`** is `realtime` (the launcher's default: a connected run keeps real time) or `free`.
|
|
371
|
+
- **`check(intent?, { file, signal }?)`** returns the launcher's check result of what `run.start(intent)` would start (`findings`; `time_lock` and `networks[].outside` are in `raw`), or rejects with an `ActionError`. Its failure is not put into `status.problem`. It sends one check at a time: the next is sent after the answer to the one before (the server runs checks one at a time and refuses with `check-busy` when too many wait). A check of the same intent and file as one that waits or is on its way shares it, so the parts and the screen of a page that check the same page intent make one check. A check that waits is not sent when `signal` has aborted for every caller of it; it rejects with the signal's reason. A check on its way is shared too, and its answer reads the file as it was when it was sent: pass `fresh: true` when the user asks to check again (it shares only a check that waits). After `close()`, a check that waits is not sent and rejects with `closed`.
|
|
372
|
+
- **`outside`** has one row for each network that the run's `connect` connected: `network`, `target`, `participant`, `link` (Ethernet) or `bus` (CAN), `condition` (`ok`, `interrupted`, `degraded`), `reasons` (codes, in the launcher's order), `nothing_received` (apart from `condition`), and `to_outside` and `from_outside` (`null` until an `outside` event has arrived on this page). It is empty while no run is going, and in a run that a `role: bridge` participant of the file connects: do not read from it whether the run is connected outside (`time_lock.because` of the check says what makes the run keep real time). How the run ended, `connect-failed` and `connect-lost` included, is in `status`.
|
|
373
|
+
|
|
374
|
+
### Editing the text of a configuration file
|
|
375
|
+
|
|
376
|
+
A screen that edits a configuration file reads it, checks the text before it is saved, saves it, and asks for the participants to be described again after an executable was built again ("The text of a configuration file" and "Saving a text" in [gui/protocol/README.md](../protocol/README.md#the-text-of-a-configuration-file-apiconfig-text-of-apicheck-apidescribe)). The client does not read YAML: the text is a string to it.
|
|
377
|
+
|
|
378
|
+
```ts
|
|
379
|
+
const { text } = await client.readConfig({ file: 'simulation.yaml' }); // the file as it is saved
|
|
380
|
+
const edited = text + '\n# edited on the screen\n'; // the screen's own edit
|
|
381
|
+
const result = await client.check({ variant: 'fast' }, { file: 'simulation.yaml', text: edited });
|
|
382
|
+
console.log(result.findings.map((f) => `${f.severity}: ${f.message}`));
|
|
383
|
+
const open = result.participants.filter((p) => p.status === 'not_described');
|
|
384
|
+
if (open.length > 0) {
|
|
385
|
+
console.log(`${open.length} participants need describeAgain before they are compared`);
|
|
386
|
+
await client.describeAgain({ file: 'simulation.yaml', variant: 'fast' }); // then check the text again
|
|
387
|
+
}
|
|
388
|
+
```
|
|
389
|
+
|
|
390
|
+
Saving sends the `stamp` that was read. When the file changed meanwhile, the server refuses with `config-changed`: read it again and make the edit on that text.
|
|
391
|
+
|
|
392
|
+
```ts
|
|
393
|
+
const read = await client.readConfig({ file: 'simulation.yaml' });
|
|
394
|
+
const edited = read.text.replace('kind: can', 'kind: can\n external: true'); // the screen's own edit
|
|
395
|
+
try {
|
|
396
|
+
const saved = await client.saveConfig({
|
|
397
|
+
file: 'simulation.yaml',
|
|
398
|
+
text: edited,
|
|
399
|
+
stamp: read.stamp,
|
|
400
|
+
});
|
|
401
|
+
console.log(`saved; the next save sends ${saved.stamp}`);
|
|
402
|
+
} catch (error) {
|
|
403
|
+
if (error instanceof ActionError && error.code === 'config-changed') {
|
|
404
|
+
// the file changed since it was read: read it again, edit that text, save again
|
|
405
|
+
} else if (error instanceof ActionError && error.code === 'commands-changed') {
|
|
406
|
+
console.log(error.message); // the edit changes the commands that run: the launcher's finding says what
|
|
407
|
+
} else {
|
|
408
|
+
throw error;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
```
|
|
412
|
+
|
|
413
|
+
- **`readConfig({ file }?)`** asks `GET api/config` and returns `{ file, text, stamp }`: the bytes as UTF-8 as they are, and the SHA-256 of those bytes (`stamp` is what `saveConfig` sends). `file` defaults to the start-up file (`no-file` if there is none). It rejects with an `ActionError` (`not-a-configuration`, `config-too-large`, `config-unreadable`, ...).
|
|
414
|
+
- **`check(intent?, { file, text }?)`** with `text` checks that text as the content of `file`, which must exist; no process starts. The intent takes only `variant`, `strict` and `vehicle_sil_run_request`; the types say so, and any other field rejects with `unknown-field` before anything is sent. The check waits its turn in the same line as the other checks, but it is never shared: a check of a text is not the check of the page, and the parts and `status` do not see its answer. A refusal (`text-too-large`, `check-busy`, `check-timeout`, ...) is the caller's, as for a check without `text`. A check can pass while a participant is `not_described`: that participant was not compared with its executable. Tell them apart in `result.participants[].status === 'not_described'` (in `raw.participants[].status` if you read the raw check).
|
|
415
|
+
- **`describeAgain({ file, variant }?)`** asks `POST api/describe`: it checks the saved file, saves the descriptions of its participants again, and returns that check. After it, the check of a text compares those participants; a participant that only the text has needs the file saved first. It waits in the same line. A describe of the same file and variant that waits or is on its way is shared (pressing again starts the executables once). Its answer is the caller's alone, and its failure is not put into `status.problem`.
|
|
416
|
+
- **`saveConfig({ file, text, stamp })`** asks `POST api/config` and resolves with `{ file, stamp }`, the stamp of the saved content (send it with the next save). `stamp` is the one `readConfig` gave, or `null` to make a new file. By default the server saves only an edit that keeps the commands that run, as the launcher's check of the text says (the networks, their mapping, `external`); `controls.save` tells whether the server saves at all, and its `caution` when it also saves edits that change the commands. The text is written as it is (a BOM and the line ends stay). It rejects with an `ActionError`: `save-disabled`, `commands-changed` (`findings` are the launcher's; also a new file to a server started without `--allow-command-changes`), `config-changed` (the file changed since it was read, or a new file is there already), `config-busy` (the file could not be replaced: another program has it open, say), `config-unreadable` (the launcher cannot read the text as a configuration; `findings`), `text-too-large`, `check-busy`, .... It waits in the server's line of the checks, not in this page's. Its failure is not put into `status.problem`. After a save, the next check of a text describes the saved file first (its executables start with `--describe`).
|
|
417
|
+
|
|
418
|
+
### One variable
|
|
419
|
+
|
|
420
|
+
```ts
|
|
421
|
+
const throttle = client.variable('Engine.engine.throttle');
|
|
422
|
+
const stop = throttle.subscribe((view) => {
|
|
423
|
+
slider.value = String(view.value ?? 0);
|
|
424
|
+
slider.disabled = !view.can_write;
|
|
425
|
+
slider.title = view.why?.message ?? view.note ?? '';
|
|
426
|
+
});
|
|
427
|
+
await throttle.write(40); // resolves when it was applied in an ECU step
|
|
428
|
+
stop(); // the last unsubscribe stops asking the server for values
|
|
429
|
+
```
|
|
430
|
+
|
|
431
|
+
The view has `value`, `text` (an enum shows the item's name), `unit`, `min`, `max`, `step`, `sim_ms`, `stale`, `note` (a sentence when the value is not a live one), `availability` (`unknown`, `active` or `inactive`: whether the ECU uses the variable now; information only, so `can_write`, `why` and `note` do not look at it, and a lost connection does not change it; `unknown` until the run's summary has the variable, then `active` with a GUI server that does not send it), `can_write` (the variable's own conditions and what the launcher accepts: `state.allowed.write`), `why` (a `{ code, message }` for what cannot be written: the variable's own reason first, then the launcher's), `writing`, `problem` (why the last write of this page did not go through), and the values of `client.low.variables.bind` (`condition`, `block`, `write_status`).
|
|
432
|
+
|
|
433
|
+
- The first subscription asks the server for the value, and the last unsubscribe stops it. There is no `close()`.
|
|
434
|
+
- `write(value)` needs no subscription (it sends that one write). It rejects with an `ActionError`; `no-answer` is `unknown`, and a write whose answer did not come is not sent again.
|
|
435
|
+
- The binding (`client.low.variables.bind`) holds back and merges writes while one is on its way (for sliders); `write()` of the front door sends each call.
|
|
436
|
+
|
|
437
|
+
## Parts (custom elements)
|
|
438
|
+
|
|
439
|
+
`@vehicle-sil/gui-client/elements` defines 11 custom elements that draw what `connect()` returns, so that a screen can be written as HTML without a script. They use native controls in the light DOM and have no styles of their own: your CSS styles them, and they work in plain HTML and in the templates of Angular, React, Vue and Svelte. Importing the module defines them (a name that is defined already is skipped).
|
|
440
|
+
|
|
441
|
+
| Element | What it shows or does | Attributes and properties |
|
|
442
|
+
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
443
|
+
| `<vsil-status>` | The connection, the run, the virtual time (marked when it falls behind real time) and the one problem | none |
|
|
444
|
+
| `<vsil-run-controls>` | Start (with the page's selection), Stop and, after a first stop, Stop without waiting | property `intent` (what the next run starts with); `label-start`, `label-stop`, `label-force-stop` (the button texts) |
|
|
445
|
+
| `<vsil-time-controls>` | Pause, Resume, Step, Run until and the speed | `speeds` (the speeds to choose from, separated by spaces; default `0.5 1 5 max`; a speed outside the range of `controls.speed` cannot be chosen, and `max` is not offered while `fastest` is false; the part does not say why, so a page that wants to say it reads the range from `client.controls`), `step-ms` (the size of a step in ms; default `10`); `label-pause`, `label-resume`, `label-step`, `label-run-until` (the button texts) |
|
|
446
|
+
| `<vsil-value>` | The value and its unit, and a sentence when it is not live. A bool shows as the `on` and `off` text | `variable`; `on`, `off` (the text for a bool's true and false); `no-unit` (leave the unit out) |
|
|
447
|
+
| `<vsil-slider>` | A number in the variable's range; it is written when the knob is released | `variable` |
|
|
448
|
+
| `<vsil-write>` | A button that writes one value (not usable when the variable already has it) | `variable`; `value` (what to write: JSON such as `false` or `3`, otherwise text); `label` (the button text) |
|
|
449
|
+
| `<vsil-scenario-select>` | The scenario of the next run, among those next to the run's configuration file (the first choice is none) | none |
|
|
450
|
+
| `<vsil-scenario-result>` | The status and the steps of the run's scenario | none |
|
|
451
|
+
| `<vsil-timeline>` | The timeline of the run's scenario, in the `<vehicle-sil-timeline>` that you put inside it | none; the attributes of that element are yours (see below) |
|
|
452
|
+
| `<vsil-connect>` | Where one network of the next run is connected: SIL Kit only first, then the targets of the list ("Connecting a network outside with the parts" below) | `network` (a `can` or `ethernet` network of the configuration file) |
|
|
453
|
+
| `<vsil-outside>` | One row for each network that the run connected, with its condition and counts | none |
|
|
454
|
+
|
|
455
|
+
A variable is written `ECU.variable` (cut at the first dot), as for `client.variable()`.
|
|
456
|
+
|
|
457
|
+
```html
|
|
458
|
+
<script type="module" src="/vsil/vehicle-sil-gui-elements.mjs"></script>
|
|
459
|
+
<vsil-status></vsil-status> <vsil-run-controls></vsil-run-controls>
|
|
460
|
+
<label>Throttle <vsil-slider variable="Engine.engine.throttle"></vsil-slider></label>
|
|
461
|
+
<vsil-write
|
|
462
|
+
variable="Engine.ecu.connected"
|
|
463
|
+
value="false"
|
|
464
|
+
label="Cut engine from the bus"
|
|
465
|
+
></vsil-write>
|
|
466
|
+
<p>
|
|
467
|
+
Engine lost:
|
|
468
|
+
<vsil-value variable="Dashboard.dashboard.engine_lost" on="LOST" off="ok"></vsil-value>
|
|
469
|
+
</p>
|
|
470
|
+
<vsil-time-controls speeds="0.5 1 5 max"></vsil-time-controls>
|
|
471
|
+
<label>Scenario of the next run <vsil-scenario-select></vsil-scenario-select></label>
|
|
472
|
+
<vsil-scenario-result></vsil-scenario-result>
|
|
473
|
+
<script src="/timeline/vehicle-sil-timeline.js"></script>
|
|
474
|
+
<vsil-timeline>
|
|
475
|
+
<vehicle-sil-timeline compact hide="help tables"></vehicle-sil-timeline>
|
|
476
|
+
</vsil-timeline>
|
|
477
|
+
```
|
|
478
|
+
|
|
479
|
+
`<vsil-timeline>` only ties the element to the run: it sets `src` (the run's `timeline_url`, from the server's root) and `hidden` (when the run has no timeline) of the `<vehicle-sil-timeline>` inside it, and nothing else of it. It adds a default element when you put none, and removes only that one. The part does not load the element's script: the page does (`<script src="/timeline/vehicle-sil-timeline.js">`, or `import '@vehicle-sil/gui-client/timeline'`); an element that is defined later works too. The element sends the token that the page keeps in the tab; for a part with another connection (`client`), give the element its `token` property. It sets `data-timeline` (`shown` or `none`) on itself. The attributes and events of the element are in "Putting a timeline on your own screen" in [docs/gui.md](../../docs/gui.md#putting-a-timeline-on-your-own-screen).
|
|
480
|
+
|
|
481
|
+
### What the parts promise
|
|
482
|
+
|
|
483
|
+
- **The page's connection.** A part calls `connect()` without options, so the page's own script and all the parts share one connection (one WebSocket), and a refusal of your own button shows in `<vsil-status>`. To give a part another connection, set its `client` property (a part that is in the document binds again).
|
|
484
|
+
- **One set of files.** Use the package, the copies of the single files, or the GUI server's `/vsil/` files, not a mix. The parts import the main entry by its file name; they do not carry a copy of it. In a project (the package) the parts and your script both import `@vehicle-sil/gui-client`. With copies, put `vehicle-sil-gui-elements.mjs` next to `vehicle-sil-gui-client.mjs` and import the client from that same file. With the server, load the parts from `/vsil/vehicle-sil-gui-elements.mjs` and the client from `/vsil/vehicle-sil-gui-client.mjs` (the parts' own import resolves to it). A second copy of the library, such as a copy of the client next to the page and the parts from `/vsil/`, makes a second connection.
|
|
485
|
+
- **Your markup and your CSS.** There is no shadow DOM. A part draws into one `<span class="vsil">` that it adds, and the children you put in the element stay. It sets `data-*` attributes for CSS: `data-link`, `data-run`, `data-pacing` (`<vsil-status>`), `data-stale`, `data-can-write`, `data-availability` and `data-on` (the variable parts; `data-availability` never disables a part; to dim an unused variable, write `[data-availability="inactive"] { opacity: .45; }`), `data-error` (every part that could not connect, the code of the error when it has one, else `error`; removed when it binds again), `data-status` (`<vsil-scenario-result>` and its steps), `data-network`, `data-chosen` and `data-reverted` (`<vsil-connect>`; its `data-error` is also the code of a list that failed), `data-network`, `data-condition` and `data-nothing-received` (each row of `<vsil-outside>`), and on each button of `<vsil-run-controls>` and `<vsil-time-controls>`, and on the speed select, `data-reason` and `data-caution` (the code, when there is one).
|
|
486
|
+
- **A button that cannot be used** is not `disabled`: it has `aria-disabled="true"` (so it keeps the focus), pressing it does nothing, and the reason is a sentence in an element that `aria-describedby` points to (the speed select is described the same way). A reason that only says there is nothing to do (`not-running`, `offline`) is in that element too, but the element is `hidden`: a screen reader reads it, and the page does not repeat it beside every button (`<vsil-status>` shows the state). The same goes for `<vsil-write>` when the variable already has the value ("already false"). A slider that cannot be written, or has no range, is `disabled`, and the reason is next to it.
|
|
487
|
+
- **Life.** A part subscribes when it enters the document and stops everything when it leaves. When it leaves while it waits for the connection, it draws nothing. When `variable` or another attribute changes, it binds again. `<vsil-connect>` takes its network out of `pageIntent.connect` when it leaves or its `network` or `file` changes, so that no run is connected by a choice that is not on the page (a part drawn again starts at SIL Kit only).
|
|
488
|
+
- **A part that could not connect** (no token, the server is not there) fails together with the other parts of the page, because they share one connection. The page shows the error sentence once: in `<vsil-status>`, or in the first part in document order when the page has no `<vsil-status>` (if that part leaves, another one shows it). Every such part gets `data-error`, so CSS and scripts see the failure; the mark goes when the part binds again and succeeds. A part that was given its own connection in `client`, or that fails while it draws (a missing `variable` attribute), shows its own sentence.
|
|
489
|
+
- **A failed action** (an `ActionError`) is not thrown at the page: `status.problem` shows it in `<vsil-status>`, and a failed write shows next to its variable.
|
|
490
|
+
- **No more than these 11.** Graphs, tables and the layout are the screen's work. For a graph of a variable over time, keep its history with `client.low.variables.bind(ref, { history: 600 })` and draw the points yourself ("[History](#history)" below).
|
|
491
|
+
|
|
492
|
+
### Words and the next run
|
|
493
|
+
|
|
494
|
+
The words are English. Attributes rename the buttons (`label-start` and the others in the table, and `label` of `<vsil-write>`). The sentences of reasons (a button that cannot be used, `caution`, the problem, why a variable cannot be written) come from the owner of the reason, in English; `setReasonText(fn)` replaces them: `fn(reason)` returns the sentence, or `null` or `undefined` to keep the English one, and `setReasonText(null)` removes it. Call it before the parts are in the page. The other words of the parts (`ready`, `writing…`, `(no scenario)`, `fastest`, `behind real time`, `Step (ms)`, `Until (ms)`, `Speed`, `-`, the default `on` and `off`, `SIL Kit only (not connected)`, the sentence of a choice taken back to SIL Kit only, and `link`, `bus`, `to outside`, `from outside` and `nothing received` of `<vsil-outside>`) cannot be changed.
|
|
495
|
+
|
|
496
|
+
The choosing parts and the start button are separate elements, so the module keeps what the page selected for the next run in `pageIntent` (`get()`, `subscribe(fn)` and `update(patch)`; a field set to `''` or `undefined` is removed). `<vsil-scenario-select>` writes `scenario`; `<vsil-run-controls>` starts with `{ ...pageIntent.get(), ...intent }`, so its `intent` property wins, and it starts the file that `status.file` names, the same file whose scenarios `<vsil-scenario-select>` lists (the server's start-up file when no run has been started). A screen that starts a run with its own code passes the intent to `client.run.start(intent)` itself; it writes the choices that the check sees into `pageIntent` too, so that `<vsil-connect>` checks what the screen will start.
|
|
497
|
+
|
|
498
|
+
Start the GUI server with a configuration file (`vehicle-sil-gui --web my-screen simulation.yaml`). Without one the server has no start-up file, and a screen made of parts alone cannot start a run: `<vsil-status>` shows the refusal (`no-file`). Only your own code can name the file then: `client.run.start(intent, { file })`.
|
|
499
|
+
|
|
500
|
+
```ts
|
|
501
|
+
import '@vehicle-sil/gui-client/elements'; // defines the parts
|
|
502
|
+
import { pageIntent, setReasonText } from '@vehicle-sil/gui-client/elements';
|
|
503
|
+
|
|
504
|
+
setReasonText((reason) => (reason.code === 'running' ? 'A run is going.' : null));
|
|
505
|
+
pageIntent.update({ variant: 'winter' }); // what the next start uses, with the scenario that was chosen
|
|
506
|
+
const controls = document.querySelector('vsil-run-controls'); // typed: the parts are in HTMLElementTagNameMap
|
|
507
|
+
if (controls) controls.intent = { speed: 'max' };
|
|
508
|
+
```
|
|
509
|
+
|
|
510
|
+
The parts need a DOM, so Node does not load them (the main entry does not import them).
|
|
511
|
+
|
|
512
|
+
### Connecting a network outside with the parts
|
|
513
|
+
|
|
514
|
+
`<vsil-connect network="ETH_EXT">` is a plain `<select>`. Its first choice is `none` (SIL Kit only). It asks for the list (`connections()`) only when the user opens it: a press, or a key other than Tab, Shift, Escape and the modifiers alone (passing it by with Tab asks for nothing, and neither does opening the page). It asks again each time, with `aria-busy` while it waits. The targets come in the list's order, under the name of their backend (`<optgroup>`). A target that cannot be used is a `disabled` option whose text is its label, its detail and the launcher's reason; a backend that has no list is a line in the element that describes the select (`aria-describedby`). The choice goes into `pageIntent.connect` (`none` takes the network out). A choice that the page put into `pageIntent` itself is shown as written. The part lists and checks the configuration file that its `file` attribute names (default: the start-up file, as `run.start`): a page that starts another file sets `file` to it.
|
|
515
|
+
|
|
516
|
+
While the network has a choice, the part checks the page intent (`check()`) about 200 ms after it last changed, whichever part or script changed it; the parts and the screen of a page that check the same intent share one check (`check()` shares it). It shows, as the launcher wrote them, the findings `connect-*` and `outside-*` of its network, the `connect-*` findings of the other networks of `connect` after their name (`CAN1: ...`; a finding about two networks names one of them), and the `outside-*` findings of the run when the check says that this network makes the run keep real time (`time_lock.because`). Each line has `data-code` and `data-severity`. These lines are a guide before the start: what the run does is decided when it starts, by the GUI server and the launcher. A refusal is shown as the server wrote it. After `target-not-listed`, a part that the user has opened lists the network again, once, and checks again if the choice is still listed. When a new list does not offer the choice, or offers it as one that cannot be used, the choice goes back to `none`: a line in the description says which value and why (`'<value>' is not in the list of this computer: back to SIL Kit only`, or `'<value>' cannot be used (<reason>): back to SIL Kit only`), and `data-reverted` holds the value until the user chooses again. The part does not keep a choice from one page load to the next, and it has no choice of `time_policy`: the page sets it with `pageIntent.update({ time_policy: 'free' })`.
|
|
517
|
+
|
|
518
|
+
`<vsil-outside>` draws the rows of `client.outside` in words (not only in colour; the counts are not a live region, since they change every second), and nothing when there are none.
|
|
519
|
+
|
|
520
|
+
## ECU variables
|
|
521
|
+
|
|
522
|
+
```ts
|
|
523
|
+
const watch = client.variables.watch([{ peer: 'Engine', name: 'engine.speed' }], {
|
|
524
|
+
periodMs: 100,
|
|
525
|
+
history: 600,
|
|
526
|
+
});
|
|
527
|
+
watch.values.subscribe((values) => console.log(values['Engine']?.['engine.speed']));
|
|
528
|
+
try {
|
|
529
|
+
const operation = await client.variables.write({ Engine: { 'engine.throttle': 50 } });
|
|
530
|
+
console.log(operation.peers['Engine'].appliedAtMs);
|
|
531
|
+
} catch (error) {
|
|
532
|
+
if (error instanceof WriteError) console.log(error.kind, error.message);
|
|
533
|
+
}
|
|
534
|
+
watch.close();
|
|
535
|
+
```
|
|
536
|
+
|
|
537
|
+
### List and state (`client.variables.state`)
|
|
538
|
+
|
|
539
|
+
| `status` | Meaning |
|
|
540
|
+
| ------------ | ---------------------------------------- |
|
|
541
|
+
| `unknown` | Not known yet |
|
|
542
|
+
| `off` | This run has no variables |
|
|
543
|
+
| `connecting` | Connecting |
|
|
544
|
+
| `ready` | Variables can be read and written |
|
|
545
|
+
| `failed` | Could not connect, or was refused |
|
|
546
|
+
| `ended` | The run ended (values are the last ones) |
|
|
547
|
+
|
|
548
|
+
- For `off`, `connecting` and `failed`, `reason` gives the reason, as text from the server (not localized).
|
|
549
|
+
- Before you start a run, `variables` in `client.app` (`available`, `reason`) tells whether variables are available.
|
|
550
|
+
- The variable definitions are `peers[].variables[]` (`type`, `role`, `writable`, `unit`, `min`, `max`, `step`, `description`, `enum`).
|
|
551
|
+
|
|
552
|
+
### Read values (`watch`)
|
|
553
|
+
|
|
554
|
+
`watch` receives the last values of the given variables (`'all'` for every variable). Always call `close()` when you are done.
|
|
555
|
+
|
|
556
|
+
**Values**: in `values` (a `Readable`), `values[peer]?.[name]` is a `VariableReading` (`value`, `sampleMs`, `simMs`, `paused`). Each value carries the time it belongs to.
|
|
557
|
+
|
|
558
|
+
| `paused` | What the value is |
|
|
559
|
+
| -------- | --------------------------------------------------------------------------------------------------------- |
|
|
560
|
+
| True | The value at the paused time `simMs` (it includes the values of every step that started before that time) |
|
|
561
|
+
| False | The last value while the simulation runs |
|
|
562
|
+
|
|
563
|
+
**Subscriptions**:
|
|
564
|
+
|
|
565
|
+
- However many watches look at a variable, the server has one subscription per variable. A variable joins the subscription with the shortest period requested (periods are rounded to one of 20, 50, 100, 200, 500 ms …).
|
|
566
|
+
- `close()` also ends the server subscription if no other watch looks at the variable.
|
|
567
|
+
- After a reconnection, the library subscribes again automatically.
|
|
568
|
+
- A watch continues across runs; the values and history of the previous run are discarded.
|
|
569
|
+
- Values are kept only for variables that someone is watching.
|
|
570
|
+
|
|
571
|
+
**History** (when you ask for `history`):
|
|
572
|
+
|
|
573
|
+
- For each variable, the library keeps up to that many points (`sampleMs`, `value`) in a ring buffer. The limit per variable is `HISTORY_MAX`; the oldest points are dropped first.
|
|
574
|
+
- Memory is allocated as points arrive, not when you ask.
|
|
575
|
+
- The history of all variables together holds up to `HISTORY_TOTAL_MAX` points (about 34 MB). Once that is reached, no history grows further: each keeps its current size and drops its oldest points (`history(ref)` returns fewer points than you asked for).
|
|
576
|
+
- Values of the same step are one point. If a changed value arrives for the same step, it replaces that point.
|
|
577
|
+
- When the run changes, the history starts empty.
|
|
578
|
+
- `watch.history(ref)` returns a new array on every call.
|
|
579
|
+
- Notifications arrive in batches about every 100 ms (`BATCH_MS`), so `values` notifies at that rate, but the history also holds the values in between.
|
|
580
|
+
|
|
581
|
+
**When a limit is near**:
|
|
582
|
+
|
|
583
|
+
- If you list many long names and one subscription message would exceed the server's limit (256 KiB), the library switches the subscription for that period to "all" (and uses only the watched variables from what arrives).
|
|
584
|
+
- If the server rejects a watch (a server with different limits), the problem appears in `client.variables.watchProblem`.
|
|
585
|
+
|
|
586
|
+
### Write values (`write`)
|
|
587
|
+
|
|
588
|
+
`write(writes, options)` sends the writes to the run that was current when you called it (`session` in `client.variables.state`, sent as `session` in the body).
|
|
589
|
+
|
|
590
|
+
- The server rejects the writes if that run is no longer running (`session-changed`). A write sent while one run ends and the next starts is therefore never written to the next run.
|
|
591
|
+
- If the run is not known yet, the library does not send and rejects with `refused` (`not-running`).
|
|
592
|
+
- The server checks type and range, then passes the writes to the launcher.
|
|
593
|
+
- The Promise resolves with the operation (`OperationView`) once the writes are applied (`applied`); otherwise it rejects with a `WriteError`.
|
|
594
|
+
- The library never resends a write automatically.
|
|
595
|
+
|
|
596
|
+
The `kind` of a `WriteError`:
|
|
597
|
+
|
|
598
|
+
| `kind` | Meaning | Safe to resend? |
|
|
599
|
+
| ----------- | ------------------------------------------------------------------- | -------------------------------------------------- |
|
|
600
|
+
| `refused` | The server did not accept the write (it did not reach the launcher) | Yes, after you fix it |
|
|
601
|
+
| `failed` | Accepted, but not applied | Yes, after you fix the reason (it was not applied) |
|
|
602
|
+
| `no-answer` | **Unknown whether it was applied** | **Do not resend as is** (see below) |
|
|
603
|
+
| `closed` | `close()` was called before the result | Same as above |
|
|
604
|
+
|
|
605
|
+
- The `code` of `refused` is `unknown-variable`, `not-writable`, `invalid-field`, `not-running`, `session-changed`, `variables-not-ready`, `write-busy` or similar.
|
|
606
|
+
- The `operation` of `failed` holds the state and reason for each participant (`late`, `rejected`, `invalid` and others).
|
|
607
|
+
- `no-answer` happens in any of these cases:
|
|
608
|
+
- No result came within `timeoutMs` (`operation` holds the last known state).
|
|
609
|
+
- There was no HTTP response.
|
|
610
|
+
- The server failed midway (500).
|
|
611
|
+
- The server gave up waiting for the Control Server's response (`code` is `write-timeout`) or was disconnected midway (`write-failed`).
|
|
612
|
+
- The run changed before the response.
|
|
613
|
+
- The operation completed during a reconnection and the result was lost ("Reconnection" below).
|
|
614
|
+
- The server could not keep track of all open operations and stopped following this one.
|
|
615
|
+
|
|
616
|
+
**Avoid writing twice**: after `no-answer`, check before you resend.
|
|
617
|
+
|
|
618
|
+
- If `error.operation` is set, follow the operation with that number in `client.variables.operations`. If it is `queued`, it is applied once the simulation reaches that step (the wait was only too short).
|
|
619
|
+
- If there is no number, look in `operations` for a new operation that looks like your write, and look at the variable's value (watch).
|
|
620
|
+
- Resend only once you know that the write was not applied.
|
|
621
|
+
- This matters most for writes that add to a value (writing twice gives a different result). Writing the same value twice gives the same result.
|
|
622
|
+
|
|
623
|
+
**Reconnection**: if the connection drops while you wait for a result, the summary after reconnecting (`hello`, `fetchSession()`) tells how it went on. The summary holds every open operation the server keeps, and every operation whose number is `operations_from_seq` or higher (of those the server receives: the operations of a scenario's own writes never come).
|
|
624
|
+
|
|
625
|
+
| Your operation | What the library does |
|
|
626
|
+
| ------------------------------------------------------------------ | --------------------------------------------------------------------------- |
|
|
627
|
+
| In the list | Uses its state (if still open, keeps waiting) |
|
|
628
|
+
| Not in the list, number below `operations_from_seq` | Treats it as completed while disconnected with its result lost: `no-answer` |
|
|
629
|
+
| Not in the list, and the server could not keep all open operations | Sets the old operations to `no-answer` |
|
|
630
|
+
|
|
631
|
+
- A write that has not been applied yet (for example, a write while paused) never becomes `no-answer` however many operations follow it.
|
|
632
|
+
- "The server could not keep all open operations" means more than 256 open operations (`operations_open_omitted` in the summary). The server no longer follows them, so the library reports `no-answer`, and the error message says why.
|
|
633
|
+
|
|
634
|
+
**Options and related state**:
|
|
635
|
+
|
|
636
|
+
- `onAccepted` (a function that receives `{session, seq}`) is called once, when the server has received the write and returned the operation number. This is before the result. It is not called when the write is rejected or no response comes.
|
|
637
|
+
- Use `onAccepted` to show "accepted, waiting to be applied", and to know when you may send the next write. Writes through `bind` use it: a next value that comes before the server has received the previous write is kept instead of sent, and only the last value is sent once the server has it.
|
|
638
|
+
- `timeoutMs` (default `WRITE_TIMEOUT_MS`) counts from the HTTP response. `Infinity` sets no time limit (the write waits until the run changes or `close()` is called). Values above 2^31-1 ms (about 24.8 days) are capped there. Non-numbers and values of 0 or less mean the default.
|
|
639
|
+
- A write is applied in the step at the given virtual time (`atMs`; if omitted, the next step), so it does not complete while the simulation is paused. To write while paused, wait for `queued` in `client.variables.operations` before you advance (`examples/gui_client/variables.mjs`, in a clone of the repository).
|
|
640
|
+
- `client.variables.operations` lists recent operations, including writes from other clients, but not a scenario's own writes.
|
|
641
|
+
|
|
642
|
+
### Write before the first step
|
|
643
|
+
|
|
644
|
+
A run started paused (`start_paused`) waits before the first step if the launcher can read and write variables. Meanwhile `isHolding(session)` is true (`holding` in the launcher's `state`, `launcherState` of the session copy), and you can resume and step (written values are applied in the step at time 0).
|
|
645
|
+
|
|
646
|
+
## Build widgets (`bind`)
|
|
647
|
+
|
|
648
|
+
For a widget that shows and writes one variable, such as a slider, a switch or a lamp, use `client.variables.bind(ref, options)` instead of combining `watch` and `write` yourself. It puts the value condition, whether the variable can be written and why not, and the write status into one `Readable` (`state`).
|
|
649
|
+
|
|
650
|
+
```ts
|
|
651
|
+
const throttle = client.variables.bind(
|
|
652
|
+
{ peer: 'Engine', name: 'engine.throttle' },
|
|
653
|
+
{ needsRange: true, needsValue: true },
|
|
654
|
+
);
|
|
655
|
+
throttle.state.subscribe(({ info, reading, pending, block, writeStatus, condition }) => {
|
|
656
|
+
slider.disabled = block !== null; // block: why it cannot be written now; null if it can
|
|
657
|
+
slider.value = String(pending ?? reading?.value ?? info?.min ?? 0); // pending: the value sent and waiting for its result
|
|
658
|
+
status.textContent = isWriteError(writeStatus) ? writeStatus.message : writeStatus.kind;
|
|
659
|
+
stale.hidden = condition.kind === 'live';
|
|
660
|
+
});
|
|
661
|
+
slider.onchange = () => throttle.write(Number(slider.value));
|
|
662
|
+
// when you are done
|
|
663
|
+
throttle.close();
|
|
664
|
+
```
|
|
665
|
+
|
|
666
|
+
Always call `close()` when you are done (it cleans up the watch and the subscriptions).
|
|
667
|
+
|
|
668
|
+
### Fields of `state` (`BoundVariable`)
|
|
669
|
+
|
|
670
|
+
| Field | Contents |
|
|
671
|
+
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
|
|
672
|
+
| `info` | The variable definition (`undefined` if the current run does not have the variable) |
|
|
673
|
+
| `reading` | The last value (`VariableReading`; `undefined` if there is none yet or while `visible` is false) |
|
|
674
|
+
| `condition` | The value condition ("Value condition (`condition`)" below) |
|
|
675
|
+
| `block` | Why the variable cannot be written now ("Why a write is blocked (`block`)" below) |
|
|
676
|
+
| `launcherReason` | When `block` is `launcher`: the launcher's reason (`code` and an English `message`, as `launcherAnswer` reads it); `null` otherwise |
|
|
677
|
+
| `writeStatus` | The status of the last write ("Write status (`writeStatus`, `pending`)" below) |
|
|
678
|
+
| `pending` | The value sent and still waiting for its result (`null` if none) |
|
|
679
|
+
|
|
680
|
+
- `subscribe` is called only on changes (get the first state with `state.get()`).
|
|
681
|
+
- `get()` always builds the state from the current values. So if you call `get()` during a notification of another `Readable` (such as `client.variables.state`), it may notify this `state`'s subscribers of a new state right there.
|
|
682
|
+
|
|
683
|
+
### Value condition (`condition`)
|
|
684
|
+
|
|
685
|
+
Switch on `condition.kind`.
|
|
686
|
+
|
|
687
|
+
| `kind` | Meaning |
|
|
688
|
+
| ------------- | -------------------------------------------------------------------------------------------- |
|
|
689
|
+
| `unavailable` | The variable feature is not available (`status` holds the state of `client.variables.state`) |
|
|
690
|
+
| `missing` | The current run does not have the variable |
|
|
691
|
+
| `waiting` | The current run has the variable, but no value has arrived yet |
|
|
692
|
+
| `live` | The last value while the simulation runs |
|
|
693
|
+
| `paused` | The value at the paused time |
|
|
694
|
+
| `stale` | A value that may be stale (the reason is in `why`) |
|
|
695
|
+
| `ended` | The last value read in a run that ended |
|
|
696
|
+
|
|
697
|
+
The `status` of `unavailable` is one of: not running, this run has no variables, connecting, cannot connect. The values of `why` for `stale`:
|
|
698
|
+
|
|
699
|
+
| `why` | Meaning |
|
|
700
|
+
| -------------- | -------------------------------------------------------- |
|
|
701
|
+
| `connection` | The connection between the client and the server dropped |
|
|
702
|
+
| `reconnecting` | The server is reconnecting to the launcher |
|
|
703
|
+
| `peer` | The ECU is disconnected |
|
|
704
|
+
| `reading` | Reading values keeps failing |
|
|
705
|
+
|
|
706
|
+
### Why a write is blocked (`block`)
|
|
707
|
+
|
|
708
|
+
`null` if the variable can be written. If several reasons apply, `block` is the one highest in the table.
|
|
709
|
+
|
|
710
|
+
The facts of the variable and the run come first, then the launcher's answer (`launcher`), then the client's prediction (`parameter`), then what the widget needs. Only `launcher` comes from the launcher; the other values are the client's own. The client has no rule of its own about what the launcher accepts: when the launcher takes a write during a scenario, `bind` lets it through. It reads the launcher's answer with `launcherAnswer(launcherState, 'write')`, as `controls` of the front door read theirs.
|
|
711
|
+
|
|
712
|
+
| `block` | Meaning |
|
|
713
|
+
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
714
|
+
| `read-only` | A read-only variable (`role` is `output`) |
|
|
715
|
+
| `disconnected` | The connection between the client and the server is down |
|
|
716
|
+
| `ended` | The run ended |
|
|
717
|
+
| `not-ready` | The variable feature is not available (not running, connecting, cannot connect) |
|
|
718
|
+
| `missing` | The current run does not have the variable |
|
|
719
|
+
| `peer-disconnected` | The ECU is not connected to the Control Server |
|
|
720
|
+
| `launcher` | The launcher does not take a write now (`allowed.write` of its `state`; `launcherReason` has its code and sentence, for example `scenario-running` while a scenario plays), or has not said yet that it does: until a `state` with `allowed.write` arrives, `unsupported` |
|
|
721
|
+
| `parameter` | A `parameter` can be written only before the first step of a run started paused (`isHolding(session)`: `holding` in the launcher's `state`). The client's prediction of the ECU's rule: the launcher does not say it for each variable |
|
|
722
|
+
| `no-range` | `needsRange` is set, but the variable has no range (`min` and `max`) |
|
|
723
|
+
| `no-value` | `needsValue` is set, and there is no value yet (neither read nor sent) |
|
|
724
|
+
|
|
725
|
+
### Write status (`writeStatus`, `pending`)
|
|
726
|
+
|
|
727
|
+
`writeStatus` is the status of the last write.
|
|
728
|
+
|
|
729
|
+
| `writeStatus` | Meaning |
|
|
730
|
+
| ------------------------------------------ | -------------------------------------------------------------- |
|
|
731
|
+
| `idle` | Empty (no last write) |
|
|
732
|
+
| `sending` | Sent |
|
|
733
|
+
| `queued` | The server received it (`seq` is the operation number) |
|
|
734
|
+
| `applied` | Applied (`atMs`) |
|
|
735
|
+
| `invalid` | The text passed to `reject(message)` (not sent) |
|
|
736
|
+
| `dropped` | A kept value was not sent ("How `write(value)` behaves" below) |
|
|
737
|
+
| `refused`, `failed`, `no-answer`, `closed` | The `kind` of a `WriteError` (has `message` and `code`) |
|
|
738
|
+
|
|
739
|
+
- `isWriteError(writeStatus)` picks out the statuses that have a `message` (the ones that did not succeed).
|
|
740
|
+
- `message` is not localized. To show it in the screen's language, build the text from `kind`.
|
|
741
|
+
- If `pending` is set, show it instead of the read value (so a switch you clicked does not appear to flip back while it waits for the result).
|
|
742
|
+
|
|
743
|
+
### How `write(value)` behaves
|
|
744
|
+
|
|
745
|
+
- If the variable cannot be written (`block`), it does nothing.
|
|
746
|
+
- It returns no Promise; the result appears in `writeStatus`.
|
|
747
|
+
- It waits for the operation's result with no time limit (a write while paused stays `queued` until the simulation advances).
|
|
748
|
+
- While the server has not yet received the previous write (`sending`), it keeps only the last of the next values instead of sending them, and sends it once the previous write is received (so a dragged slider or repeated keys do not pile up writes).
|
|
749
|
+
- Before it sends a kept value, it checks again that the run is the same and the variable is still writable; if not, it does not send and sets `dropped`.
|
|
750
|
+
- If the previous write is rejected before it is received, the kept value is not sent either.
|
|
751
|
+
- A write that got no result (`no-answer`) is never resent automatically.
|
|
752
|
+
- `reject(message)` reports an error that the widget found before sending (not a number, out of range) as `invalid`. It does not touch the write in flight, the kept value or `pending`.
|
|
753
|
+
|
|
754
|
+
### One state per variable
|
|
755
|
+
|
|
756
|
+
- However many places `bind` the same variable, they all see the same `writeStatus` and `pending`, and writes do not overlap.
|
|
757
|
+
- The state survives closing a `bind` and creating it again.
|
|
758
|
+
- The state belongs to the run: when the run changes, it starts empty (`idle`, `null`) and shows no results of writes from the previous run.
|
|
759
|
+
|
|
760
|
+
### Watch only while visible
|
|
761
|
+
|
|
762
|
+
`bind` receives values from the moment you create it (as with `watch`, the server has one subscription per variable). On a screen with many widgets, create it with `{ visible: false }`, call `setVisible(true)` when it becomes visible (IntersectionObserver or similar) and `setVisible(false)` when it is hidden. While `visible` is false:
|
|
763
|
+
|
|
764
|
+
| Field | While `visible` is false |
|
|
765
|
+
| ------------------------ | --------------------------------------------------------------------------------------------------- |
|
|
766
|
+
| `reading` | `undefined` |
|
|
767
|
+
| `condition` | `waiting` |
|
|
768
|
+
| `writeStatus`, `pending` | Reported as usual |
|
|
769
|
+
| `block` | Reported as usual (a `bind` with `needsValue` reports `no-value` unless there is a `pending` value) |
|
|
770
|
+
|
|
771
|
+
### History
|
|
772
|
+
|
|
773
|
+
If you create it with `{ history: 600 }`, `history()` returns the points, oldest first. `state` notifies every time a point is added; read the history again there.
|
|
774
|
+
|
|
775
|
+
### What is not checked, and after `close()`
|
|
776
|
+
|
|
777
|
+
- `write(value)` sends without checking the value's type and range. The server rejects a value that does not fit, and `writeStatus` becomes `refused`. To check first and show a message, check in the widget and call `reject(message)`.
|
|
778
|
+
- After `close()`, `write`, `reject` and `setVisible` do nothing.
|
|
779
|
+
- `close()` does not cancel writes already sent or the kept value. The kept value is sent once the previous write is received (the state belongs to the variable, so the next `bind` of the same variable sees it).
|
|
780
|
+
|
|
781
|
+
## Lifecycle
|
|
782
|
+
|
|
783
|
+
| Call | What it does |
|
|
784
|
+
| --------------------------------------------------- | ----------------------------------------------------------------------------- |
|
|
785
|
+
| `createClient()` | Only creates the client; does not connect |
|
|
786
|
+
| `connect()` | Connects over WebSocket (does nothing without a token) |
|
|
787
|
+
| `connect()` while connected | Does nothing (also while waiting to reconnect) |
|
|
788
|
+
| `close()` | Disconnects and does not reconnect (what it cleans up is below) |
|
|
789
|
+
| `connect()` after `close()` | Connects again and subscribes the remaining watches again |
|
|
790
|
+
| HTTP requests after `close()` | Work (`loadApp()`, `run.start()` and others can be sent without a connection) |
|
|
791
|
+
| `connect()` after a rejection or a version mismatch | Does nothing (`session.rejected` and `session.incompatible` do not reset) |
|
|
792
|
+
|
|
793
|
+
- `close()` stops pending timers, stops waiting for responses to time commands, and rejects writes waiting for results with a `WriteError` (`closed`). Notifications in a batch being collected are discarded. Variable watches remain.
|
|
794
|
+
- After `close()` and `connect()`, the session copy is still there, and the library receives again from where its copy ends.
|
|
795
|
+
- To connect with another token or version, create a new client.
|
|
796
|
+
|
|
797
|
+
## Coding rules
|
|
798
|
+
|
|
799
|
+
- Import nothing outside this library's own files (`eslint.config.js` blocks it; it also blocks dynamic `import()` except in the test helpers; `rootDir` in `tsconfig.json` blocks anything outside `src/`).
|
|
800
|
+
- Do not use anything that exists only in the browser (`window`, `document`, `localStorage` and so on). Take what you need through the options (`ClientOptions`).
|
|
801
|
+
- Human-readable text (such as `TimeFailure.message`) is in English. Turning it into the screen's language is the wrapper's job (built from machine-readable fields such as `kind`).
|
|
802
|
+
- When you add to the public API, add it to `src/index.ts` and to the "Public API" tables above, and update [Build your own screen for the browser GUI](../../docs/howto/gui-screen.md) to match.
|
|
803
|
+
|
|
804
|
+
## Tests
|
|
805
|
+
|
|
806
|
+
The tools (TypeScript, ESLint, Prettier, Vitest, esbuild) are the ones in `node_modules` of `gui/web`. Run these in `gui/web` (`scripts/verify-web.py` runs them too):
|
|
807
|
+
|
|
808
|
+
| Command | What it does |
|
|
809
|
+
| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
810
|
+
| `npm run test:client` | Type check (`tsc -p ../client`) and unit tests (Vitest; the library runs on Node, without Angular; the parts in `src/elements` run in a headless Chromium) |
|
|
811
|
+
| `npm run build:client` | Bundles into one ESM file, and the parts into a second one that imports it (esbuild, the copy that comes with the Angular build tools) |
|
|
812
|
+
| `npm run lint` | `gui/web`, and this directory with its `eslint.config.js` |
|
|
813
|
+
| `npm run format:check` | Formatting of `gui/web` and this directory (`gui/.prettierrc`) |
|
|
814
|
+
|
|
815
|
+
The tests of the parts need Playwright's Chromium (`npx playwright install --only-shell chromium` in `gui/web`; `scripts/doctor.py` says whether it starts). They run headless; to watch them, run `npx vitest --config ../client/vitest.config.mjs --project browser --browser.headless=false` in `gui/web`.
|
|
816
|
+
|
|
817
|
+
The unit tests feed the examples in `gui/protocol/examples/` instead of building server notifications by hand (`testing/protocol-examples.ts`).
|
|
818
|
+
|
|
819
|
+
## See also
|
|
820
|
+
|
|
821
|
+
| To find | Document |
|
|
822
|
+
| ---------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
|
|
823
|
+
| Which way to add your own code to the GUI: a custom panel, your own screen or a tool | "Build your own screen" in [docs/gui.md](../../docs/gui.md#build-your-own-screen) |
|
|
824
|
+
| How to build your own screen and have the GUI server serve it | [Build your own screen for the browser GUI](../../docs/howto/gui-screen.md) |
|
|
825
|
+
| The server API (HTTP and WebSocket shapes, versioning and compatibility rules, authentication) | [gui/protocol](../protocol/README.md) |
|
|
826
|
+
| The rules the library does not enforce for you | "Rules for building a screen" in [docs/gui.md](../../docs/gui.md#rules-for-building-a-screen) |
|
|
827
|
+
| Files to start your own screen from | The screen template [examples/gui_starter](../../examples/gui_starter/) |
|
|
828
|
+
| An example that uses the library from Node, without a screen | [examples/gui_client](../../examples/gui_client/) |
|
|
829
|
+
|
|
830
|
+
`examples/gui_client` exists only in the repository (the prebuilt tools archive contains `gui_starter/` and `client/`).
|
|
831
|
+
|
|
832
|
+
| File | What it does |
|
|
833
|
+
| ---------------------- | ---------------------------------------------------------- |
|
|
834
|
+
| `run.mjs` | Calls the server API without the library |
|
|
835
|
+
| `run-with-library.mjs` | Uses the bundled library file from plain JavaScript (Node) |
|
|
836
|
+
| `front.mjs` | Uses the front door (`connect()`, `status`) from Node |
|
|
837
|
+
| `variables.mjs` | Also uses the library, to read and write ECU variables |
|