@nexgen-os/zaptec 0.0.0-stage → 0.5.0

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nexgen OS contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,99 @@
1
- # Temporary Holding Version
1
+ # `@nexgen-os/zaptec`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [Zaptec](https://zaptec.com) charging stations, read from their maker's
4
+ cloud on its public REST API (`https://api.zaptec.com`;
5
+ [documentation](https://api.zaptec.com/help/index.html)), with the account
6
+ of the charger's owner. What it reads lands on a charger of the
7
+ [`charging`](../../../modules/charging/README.md) module: its sessions and
8
+ the series of the device. MIT.
9
+
10
+ A station that speaks OCPP to a central system of the installation is read
11
+ by its log instead ([`@nexgen-os/ocpp`](../../formats/ocpp/README.md) and
12
+ `importStationLog()` of `charging`); this connector is for the stations that
13
+ report to Zaptec's cloud only, as most household stations do.
14
+
15
+ ## What it reads
16
+
17
+ ```ts
18
+ import { collectZaptecSessions, zaptec } from '@nexgen-os/zaptec';
19
+
20
+ const cloud = zaptec({ username, password }); // the secret of the connectors row
21
+ await cloud.chargers(); // the chargers the account reaches
22
+ await cloud.state(chargerId); // what one reported last
23
+ await collectZaptecSessions(db, cloud, { organisationId, deviceId, chargerId, from, to });
24
+ ```
25
+
26
+ | Call | Endpoint | Gives |
27
+ |---|---|---|
28
+ | `chargers()` | `GET /api/chargers`, every page | each charger: its id in the cloud (what the other calls take), its serial, name, installation, active, online |
29
+ | `state(chargerId)` | `GET /api/chargers/{id}/state` | the observations below, each at its own stamp, as series in the core's terms; the operation mode in words (`disconnected`, `connected_requesting`, `connected_charging`, `connected_finished`) |
30
+ | `sessions({ chargerId, from, to })` | `GET /api/sessions/archived`, every page of its cursor | the sessions that ended in the window, each as the record `charging.record()` takes and the readings of the energy it delivered |
31
+
32
+ | Observation | Series of the charger |
33
+ |---|---|
34
+ | `TotalChargePower` (513) | `consumption_power`, W, instant |
35
+ | `VoltagePhase1` to `3` (501–503) | `voltage`, V, instant, named `L1` to `L3` |
36
+ | `CurrentPhase1` to `3` (507–509) | `current`, A, instant, named `L1` to `L3` (the quantity of the `charging` module) |
37
+
38
+ A stamp the cloud gives without an offset is read as UTC, the time the
39
+ cloud dates in.
40
+
41
+ ## Sessions and their energy
42
+
43
+ `collectZaptecSessions(db, connector, request)` writes a window of sessions
44
+ on a charger described in `charging.devices` (`charger_not_described`
45
+ otherwise):
46
+
47
+ - each session through `charging.record()`, once per session id: source
48
+ `station` (the cloud is the station's central system), `source_ref` the
49
+ station's serial, `transaction_id` the session's id, its start, end and
50
+ energy, the name of the token the station read; in `metadata` the
51
+ station, the installation, a third party's transaction id, the firmware,
52
+ and whether it was recorded offline, on a trusted clock, signed (OCMF),
53
+ aborted or stopped by a card;
54
+ - the energy as one `consumption_energy` register of the device
55
+ (cumulative, kWh, `measured`, source `zaptec`): each session counts from
56
+ zero at its start, through the readings the cloud kept during it, to its
57
+ energy at its end. The core reads a register that falls back as a reset,
58
+ so `resample()` gives the energy of each hour or day across sessions. A
59
+ session without detailed readings puts its whole energy in the bucket it
60
+ started in.
61
+
62
+ A second collection of the same window changes nothing. What is left out is
63
+ named in `skipped`: a voided session, replaced by a corrected one
64
+ (`voided`); a session whose start or end is not a date
65
+ (`stamp_invalid`); the readings of a session recorded offline on a clock the
66
+ station did not trust, whose record is kept (`clock_unreliable`); a reading
67
+ below the one before it or outside the session (`value_invalid`).
68
+
69
+ ## Configuration
70
+
71
+ An organisation's `connectors` row names the source `zaptec` and the
72
+ account by `secret_ref` (the vault holds it; the caller resolves it and
73
+ passes `username` and `password`, the connector reads no environment), and
74
+ in `config` the charger ids it collects. The account is the owner's, or a
75
+ service partner's the owner granted access to its installation; the cloud
76
+ refuses a charger it does not own (`source_unauthorised`).
77
+
78
+ ## Its source
79
+
80
+ The package ships its `sources` row, [`source.json`](source.json)
81
+ (`zaptecSource`; write it with `registerSource()` of the core): kind `api`,
82
+ `auth = 'oauth2'` (the password grant of the cloud), worldwide, not
83
+ redistributable: the data is the charger owner's, read with their account.
84
+
85
+ ## What is not done yet
86
+
87
+ - The answers in `tests/fixtures` are built on the shapes of the published
88
+ OpenAPI description, not recorded: record them with a real account at the
89
+ first run and keep them beside these; the tests must pass unchanged.
90
+ - Commands (stop, resume, a current limit) wait for the device connector
91
+ contract of the core, through which a command a person validated is
92
+ carried.
93
+ - Left out on purpose: the user who authorised a session (a person's name
94
+ and e-mail), the signed payloads (kept by Zaptec), prices, the
95
+ installation's settings.
96
+
97
+ ## Licence
98
+
99
+ MIT.
@@ -0,0 +1,153 @@
1
+ import { type CollectedSeries, type Db, type SeriesPoint, type SourceRow } from '@nexgen-os/core';
2
+ /** The subset of `fetch` the connector uses, so a test or a proxy can stand in. */
3
+ export type HttpFetch = (url: string, init?: {
4
+ method?: string;
5
+ headers?: Record<string, string>;
6
+ body?: string;
7
+ }) => Promise<{
8
+ ok: boolean;
9
+ status: number;
10
+ json(): Promise<unknown>;
11
+ text(): Promise<string>;
12
+ }>;
13
+ export interface ZaptecOptions {
14
+ /** The account of the charger's owner (or of a service partner it granted), from the secret of the `connectors` row. */
15
+ username: string;
16
+ password: string;
17
+ /** `https://api.zaptec.com` by default. */
18
+ baseUrl?: string;
19
+ fetch?: HttpFetch;
20
+ /** The clock, in UTC milliseconds, by which the access token expires; `Date.now` by default. */
21
+ now?: () => number;
22
+ }
23
+ /** A charger as the cloud lists it. */
24
+ export interface ZaptecCharger {
25
+ /** The id the cloud knows the charger by: what `state()` and `sessions()` take. */
26
+ id: string;
27
+ /** The serial number of the station. */
28
+ device_id: string | null;
29
+ name: string | null;
30
+ installation_id: string | null;
31
+ installation_name: string | null;
32
+ active: boolean;
33
+ online: boolean | null;
34
+ }
35
+ /** The operation modes a charger reports (observation 710), in words. */
36
+ export declare const OPERATION_MODES: Record<number, string>;
37
+ /** The observations read into series: their id in the cloud's constants, the quantity, the unit and the name that tells phases apart. */
38
+ export declare const OBSERVATIONS: Record<number, {
39
+ quantity: string;
40
+ unit: string;
41
+ name: string | null;
42
+ }>;
43
+ /** What a charger reported last. */
44
+ export interface ZaptecState {
45
+ /** Its operation mode, a word of `OPERATION_MODES`, and when it was reported. */
46
+ operation_mode: {
47
+ mode: string;
48
+ at: string;
49
+ } | null;
50
+ /** One series per observation, with the one value it reported, at its own stamp. */
51
+ series: CollectedSeries[];
52
+ skipped: {
53
+ observation: number;
54
+ reason: string;
55
+ }[];
56
+ }
57
+ /** A session in the shape `charging.record()` takes. */
58
+ export interface ZaptecSessionRecord {
59
+ /** The session's id in the cloud. */
60
+ transaction_id: string;
61
+ started_at: string;
62
+ ended_at: string;
63
+ energy_kwh: number | null;
64
+ /** The name of the token the station read, as given: it may name a person. */
65
+ id_token?: string;
66
+ metadata: {
67
+ /** The serial number of the station that delivered it. */
68
+ device_id: string | null;
69
+ installation_id: string | null;
70
+ /** The transaction id of a third party that authorised it (OCPP), when there is one. */
71
+ external_id: string | null;
72
+ firmware: string | null;
73
+ /** Recorded while the station was offline; its stamps are its own clock's, trusted or not. */
74
+ offline: boolean;
75
+ reliable_clock: boolean;
76
+ /** Zaptec keeps a signed payload (OCMF) of the session. */
77
+ signed: boolean;
78
+ /** Unplugged before charging started. */
79
+ aborted: boolean;
80
+ stopped_by_rfid: boolean;
81
+ };
82
+ }
83
+ export interface ZaptecSession {
84
+ record: ZaptecSessionRecord;
85
+ /** The energy delivered, a register from zero at the start of the session, kWh; empty when its stamps cannot be trusted. */
86
+ energy: SeriesPoint[];
87
+ }
88
+ export interface ZaptecSessions {
89
+ sessions: ZaptecSession[];
90
+ /** Sessions or readings left out, with the name of the reason. */
91
+ skipped: {
92
+ session: string;
93
+ reason: string;
94
+ }[];
95
+ }
96
+ export interface ZaptecConnector {
97
+ readonly source_code: 'zaptec';
98
+ /** Every charger the account reaches, page after page. */
99
+ chargers(): Promise<ZaptecCharger[]>;
100
+ /** What a charger reported last. */
101
+ state(chargerId: string): Promise<ZaptecState>;
102
+ /** The sessions of a charger that ended from `from` (included) to `to` (excluded), ISO 8601. */
103
+ sessions(request: {
104
+ chargerId: string;
105
+ from: string;
106
+ to: string;
107
+ }): Promise<ZaptecSessions>;
108
+ }
109
+ /** A connector on the cloud API of Zaptec, with the account of the charger's owner. `source_code` is `zaptec`. */
110
+ export declare function zaptec(options: ZaptecOptions): ZaptecConnector;
111
+ /**
112
+ * A stamp of the cloud as ISO 8601 UTC. The cloud dates in UTC, and some of
113
+ * its answers leave the offset out: a stamp without one is read as UTC.
114
+ * Null when it is not a date.
115
+ */
116
+ export declare function instantOf(stamp: unknown): string | null;
117
+ /** An answer of `GET /api/chargers/{id}/state` in the core's terms: the observations of `OBSERVATIONS` as series, the operation mode in words. */
118
+ export declare function stateOfZaptec(observations: unknown): ZaptecState;
119
+ /**
120
+ * Sessions of `GET /api/sessions/archived` as records and energy readings.
121
+ * A voided session (replaced by a corrected one) is skipped
122
+ * (`voided`), and so is a session whose start or end is not a date
123
+ * (`stamp_invalid`). An offline session on a clock the station did not
124
+ * trust keeps its record, never its readings (`clock_unreliable`); a reading
125
+ * below the one before it is skipped (`value_invalid`).
126
+ */
127
+ export declare function sessionsOfZaptec(archived: unknown[]): ZaptecSessions;
128
+ export interface CollectedSessions {
129
+ /** The sessions recorded, by id in `charging.sessions`, in the order of the cloud. */
130
+ sessions: string[];
131
+ /** The energy series of the charger, and the readings it received. */
132
+ energy: {
133
+ seriesId: string;
134
+ inserted: number;
135
+ } | null;
136
+ skipped: ZaptecSessions['skipped'];
137
+ }
138
+ /**
139
+ * The sessions of a Zaptec charger that ended in a window, written on its
140
+ * device described in `charging.devices`: each session once by
141
+ * `charging.record()` (source `station`, `source_ref` the station's serial),
142
+ * the energy as one `consumption_energy` register of the device, `measured`,
143
+ * source `zaptec`. Refuses as `charging.record()` does (`charger_not_described`).
144
+ */
145
+ export declare function collectZaptecSessions(db: Db, connector: Pick<ZaptecConnector, 'sessions'>, request: {
146
+ organisationId: string;
147
+ deviceId: string;
148
+ chargerId: string;
149
+ from: string;
150
+ to: string;
151
+ }): Promise<CollectedSessions>;
152
+ /** The `sources` row this package ships (`source.json`): write it with `registerSource()`. */
153
+ export declare const zaptecSource: SourceRow;
package/dist/index.js ADDED
@@ -0,0 +1,300 @@
1
+ // Zaptec — https://zaptec.com, charging stations reported to their maker's
2
+ // cloud, read on its public REST API (https://api.zaptec.com/help/index.html)
3
+ // with the account of the charger's owner. Source `zaptec`, shipped with the
4
+ // package.
5
+ //
6
+ // Three reads, in the core's terms:
7
+ //
8
+ // - `chargers()`: the chargers the account reaches (`GET /api/chargers`),
9
+ // each with the id the cloud knows it by, which the organisation's
10
+ // `connectors` row or the device keeps;
11
+ // - `state(chargerId)`: what a charger reported last
12
+ // (`GET /api/chargers/{id}/state`), each value at its own stamp: the
13
+ // power it delivers (`consumption_power`, W), the voltage and the current
14
+ // of each phase (`voltage`, V; `current`, A, the quantity of the
15
+ // `charging` module), and its operation mode;
16
+ // - `sessions({ chargerId, from, to })`: the completed sessions that ended in
17
+ // the window (`GET /api/sessions/archived`, every page of its cursor),
18
+ // each as the record `charging.record()` takes and as the readings of the
19
+ // energy it delivered, a register counted from zero at the start of the
20
+ // session (`consumption_energy`, cumulative, kWh). The core reads a
21
+ // register that falls back as a reset, so the sessions of a charger make
22
+ // one series: `resample()` gives the energy of each hour or day.
23
+ //
24
+ // `collectZaptecSessions()` writes a window of sessions on a charger
25
+ // described in `charging.devices`: the sessions through `charging.record()`
26
+ // (source `station`, the charger's serial as `source_ref`), once per session
27
+ // id, and the energy through `storeSeries()`; a second collection of the
28
+ // same window changes nothing.
29
+ //
30
+ // Left out, on purpose: the user who authorised a session (a person's name
31
+ // and e-mail: the token name the station read is kept, as for OCPP), the
32
+ // signed payloads of a session (OCMF, kept by Zaptec; `signed` says there is
33
+ // one), the price of energy, the installation's settings. Commands (stop,
34
+ // resume, a current limit) wait for the device connector contract of the
35
+ // core, through which a person's validated command is carried.
36
+ //
37
+ // Nothing here reads the environment or the database: the account comes
38
+ // from the secret the organisation's `connectors` row names, resolved by the
39
+ // installation's vault.
40
+ import { readFileSync } from 'node:fs';
41
+ import { GestureError, storeSeries } from '@nexgen-os/core';
42
+ /** The operation modes a charger reports (observation 710), in words. */
43
+ export const OPERATION_MODES = {
44
+ 0: 'unknown',
45
+ 1: 'disconnected',
46
+ 2: 'connected_requesting',
47
+ 3: 'connected_charging',
48
+ 5: 'connected_finished',
49
+ };
50
+ /** The observations read into series: their id in the cloud's constants, the quantity, the unit and the name that tells phases apart. */
51
+ export const OBSERVATIONS = {
52
+ 513: { quantity: 'consumption_power', unit: 'W', name: null },
53
+ 501: { quantity: 'voltage', unit: 'V', name: 'L1' },
54
+ 502: { quantity: 'voltage', unit: 'V', name: 'L2' },
55
+ 503: { quantity: 'voltage', unit: 'V', name: 'L3' },
56
+ 507: { quantity: 'current', unit: 'A', name: 'L1' },
57
+ 508: { quantity: 'current', unit: 'A', name: 'L2' },
58
+ 509: { quantity: 'current', unit: 'A', name: 'L3' },
59
+ };
60
+ const OPERATION_MODE = 710;
61
+ const PAGE_SIZE = 100;
62
+ const SESSIONS_PAGE_SIZE = 200;
63
+ /** A connector on the cloud API of Zaptec, with the account of the charger's owner. `source_code` is `zaptec`. */
64
+ export function zaptec(options) {
65
+ if (!options.username || !options.password)
66
+ throw new GestureError('secret_not_found: zaptec needs the account of the charger\'s owner (the secret of its connectors row)');
67
+ const base = (options.baseUrl ?? 'https://api.zaptec.com').replace(/\/+$/, '');
68
+ const doFetch = options.fetch ?? globalThis.fetch;
69
+ const now = options.now ?? Date.now;
70
+ let token = null;
71
+ const send = async (path, init) => {
72
+ try {
73
+ return await doFetch(`${base}${path}`, init);
74
+ }
75
+ catch (error) {
76
+ throw new GestureError(`source_unavailable: zaptec does not answer on ${path}: ${error.message}`);
77
+ }
78
+ };
79
+ const refused = async (response, path) => {
80
+ const detail = (await response.text().catch(() => '')).slice(0, 300);
81
+ if (response.status === 400 && path === '/oauth/token')
82
+ throw new GestureError(`source_unauthorised: zaptec refuses the account: ${detail}`);
83
+ if (response.status === 401 || response.status === 403)
84
+ throw new GestureError(`source_unauthorised: zaptec ${response.status} on ${path}: ${detail}`);
85
+ throw new GestureError(`source_unavailable: zaptec ${response.status} on ${path}: ${detail}`);
86
+ };
87
+ const accessToken = async () => {
88
+ if (token && token.expires > now())
89
+ return token.value;
90
+ const body = new URLSearchParams({ grant_type: 'password', username: options.username, password: options.password }).toString();
91
+ const response = await send('/oauth/token', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' }, body });
92
+ if (!response.ok)
93
+ return refused(response, '/oauth/token');
94
+ const r = (await response.json());
95
+ if (typeof r.access_token !== 'string' || !r.access_token)
96
+ throw new GestureError('source_unauthorised: zaptec gave no access token');
97
+ // Renewed a minute before it expires.
98
+ const lifetime = typeof r.expires_in === 'number' ? r.expires_in : 3600;
99
+ token = { value: r.access_token, expires: now() + Math.max(lifetime - 60, 0) * 1000 };
100
+ return token.value;
101
+ };
102
+ const get = async (path, query = {}) => {
103
+ const params = new URLSearchParams();
104
+ for (const [k, v] of Object.entries(query))
105
+ if (v !== undefined)
106
+ params.set(k, String(v));
107
+ const url = params.toString() ? `${path}?${params}` : path;
108
+ const call = async () => send(url, { method: 'GET', headers: { Authorization: `Bearer ${await accessToken()}`, Accept: 'application/json' } });
109
+ let response = await call();
110
+ // A token revoked before its time: asked again once.
111
+ if (response.status === 401) {
112
+ token = null;
113
+ response = await call();
114
+ }
115
+ if (!response.ok)
116
+ return refused(response, path);
117
+ return response.json();
118
+ };
119
+ return {
120
+ source_code: 'zaptec',
121
+ async chargers() {
122
+ const out = [];
123
+ for (let page = 0;; page++) {
124
+ const r = (await get('/api/chargers', { PageSize: PAGE_SIZE, PageIndex: page }));
125
+ for (const c of r.data ?? [])
126
+ out.push(chargerOf(c));
127
+ if (!r.data?.length || page + 1 >= (r.pages ?? 1))
128
+ return out;
129
+ }
130
+ },
131
+ async state(chargerId) {
132
+ return stateOfZaptec(await get(`/api/chargers/${encodeURIComponent(chargerId)}/state`));
133
+ },
134
+ async sessions({ chargerId, from, to }) {
135
+ const all = { sessions: [], skipped: [] };
136
+ let cursor;
137
+ do {
138
+ const r = (await get('/api/sessions/archived', { chargerId, from, to, pageSize: SESSIONS_PAGE_SIZE, cursor }));
139
+ const page = sessionsOfZaptec(r.sessions ?? []);
140
+ all.sessions.push(...page.sessions);
141
+ all.skipped.push(...page.skipped);
142
+ cursor = r.hasMore && r.cursor ? r.cursor : undefined;
143
+ } while (cursor);
144
+ return all;
145
+ },
146
+ };
147
+ }
148
+ const text = (v) => (typeof v === 'string' && v !== '' ? v : null);
149
+ function chargerOf(c) {
150
+ return {
151
+ id: String(c.id),
152
+ device_id: text(c.deviceId),
153
+ name: text(c.name),
154
+ installation_id: text(c.installationId),
155
+ installation_name: text(c.installationName),
156
+ active: c.active !== false,
157
+ online: typeof c.isOnline === 'boolean' ? c.isOnline : null,
158
+ };
159
+ }
160
+ /**
161
+ * A stamp of the cloud as ISO 8601 UTC. The cloud dates in UTC, and some of
162
+ * its answers leave the offset out: a stamp without one is read as UTC.
163
+ * Null when it is not a date.
164
+ */
165
+ export function instantOf(stamp) {
166
+ if (typeof stamp !== 'string' || stamp === '')
167
+ return null;
168
+ const s = /(?:Z|[+-]\d{2}:?\d{2})$/i.test(stamp) ? stamp : `${stamp}Z`;
169
+ const ms = Date.parse(s);
170
+ return Number.isNaN(ms) ? null : new Date(ms).toISOString();
171
+ }
172
+ /** An answer of `GET /api/chargers/{id}/state` in the core's terms: the observations of `OBSERVATIONS` as series, the operation mode in words. */
173
+ export function stateOfZaptec(observations) {
174
+ const state = { operation_mode: null, series: [], skipped: [] };
175
+ for (const o of Array.isArray(observations) ? observations : []) {
176
+ const id = Number(o.stateId);
177
+ const known = OBSERVATIONS[id];
178
+ if (!known && id !== OPERATION_MODE)
179
+ continue;
180
+ const at = instantOf(o.timestamp);
181
+ if (at === null) {
182
+ state.skipped.push({ observation: id, reason: 'stamp_invalid' });
183
+ continue;
184
+ }
185
+ const value = Number(o.valueAsString);
186
+ if (o.valueAsString === null || o.valueAsString === undefined || o.valueAsString === '' || !Number.isFinite(value)) {
187
+ state.skipped.push({ observation: id, reason: 'value_invalid' });
188
+ continue;
189
+ }
190
+ if (id === OPERATION_MODE) {
191
+ state.operation_mode = { mode: OPERATION_MODES[value] ?? 'unknown', at };
192
+ continue;
193
+ }
194
+ state.series.push({ quantity_code: known.quantity, value_kind: 'instant', step: null, unit: known.unit, name: known.name, values: [{ at, value }] });
195
+ }
196
+ return state;
197
+ }
198
+ /**
199
+ * Sessions of `GET /api/sessions/archived` as records and energy readings.
200
+ * A voided session (replaced by a corrected one) is skipped
201
+ * (`voided`), and so is a session whose start or end is not a date
202
+ * (`stamp_invalid`). An offline session on a clock the station did not
203
+ * trust keeps its record, never its readings (`clock_unreliable`); a reading
204
+ * below the one before it is skipped (`value_invalid`).
205
+ */
206
+ export function sessionsOfZaptec(archived) {
207
+ const out = { sessions: [], skipped: [] };
208
+ for (const s of archived) {
209
+ const id = String(s.id ?? '');
210
+ if (s.voided === true) {
211
+ out.skipped.push({ session: id, reason: 'voided' });
212
+ continue;
213
+ }
214
+ const started = instantOf(s.startDateTime);
215
+ const ended = instantOf(s.endDateTime);
216
+ if (!id || started === null || ended === null) {
217
+ out.skipped.push({ session: id, reason: 'stamp_invalid' });
218
+ continue;
219
+ }
220
+ const energy = typeof s.energy === 'number' && Number.isFinite(s.energy) ? s.energy : null;
221
+ const record = {
222
+ transaction_id: id,
223
+ started_at: started,
224
+ ended_at: ended,
225
+ energy_kwh: energy,
226
+ metadata: {
227
+ device_id: text(s.deviceId),
228
+ installation_id: text(s.installationId),
229
+ external_id: text(s.externalId),
230
+ firmware: text(s.chargerFirmwareVersion),
231
+ offline: s.offline === true,
232
+ reliable_clock: s.reliableClock !== false,
233
+ signed: s.signed === true,
234
+ aborted: s.aborted === true,
235
+ stopped_by_rfid: s.stoppedByRfid === true,
236
+ },
237
+ };
238
+ const tokenName = text(s.tokenName);
239
+ if (tokenName)
240
+ record.id_token = tokenName;
241
+ if (record.metadata.offline && !record.metadata.reliable_clock) {
242
+ out.skipped.push({ session: id, reason: 'clock_unreliable' });
243
+ out.sessions.push({ record, energy: [] });
244
+ continue;
245
+ }
246
+ // The register starts from zero when the session starts, and ends on the
247
+ // energy of the session when the details stop before it.
248
+ const points = new Map([[started, 0]]);
249
+ const details = (Array.isArray(s.energyDetails) ? s.energyDetails : [])
250
+ .map((d) => ({ at: instantOf(d.timestamp), value: d.energy }))
251
+ .filter((d) => d.at !== null && typeof d.value === 'number' && Number.isFinite(d.value))
252
+ .sort((a, b) => a.at.localeCompare(b.at));
253
+ for (const d of details)
254
+ points.set(d.at, d.value);
255
+ if (energy !== null && !points.has(ended))
256
+ points.set(ended, energy);
257
+ let last = -Infinity;
258
+ const readings = [];
259
+ for (const [at, value] of [...points].sort(([a], [b]) => a.localeCompare(b))) {
260
+ if (at < started || at > ended || value < last) {
261
+ out.skipped.push({ session: id, reason: 'value_invalid' });
262
+ continue;
263
+ }
264
+ readings.push({ at, value });
265
+ last = value;
266
+ }
267
+ out.sessions.push({ record, energy: readings });
268
+ }
269
+ return out;
270
+ }
271
+ /**
272
+ * The sessions of a Zaptec charger that ended in a window, written on its
273
+ * device described in `charging.devices`: each session once by
274
+ * `charging.record()` (source `station`, `source_ref` the station's serial),
275
+ * the energy as one `consumption_energy` register of the device, `measured`,
276
+ * source `zaptec`. Refuses as `charging.record()` does (`charger_not_described`).
277
+ */
278
+ export async function collectZaptecSessions(db, connector, request) {
279
+ const read = await connector.sessions({ chargerId: request.chargerId, from: request.from, to: request.to });
280
+ const sessions = [];
281
+ for (const s of read.sessions) {
282
+ const r = await db.query('select charging.record($1, $2::jsonb, $3, $4) id', [
283
+ request.deviceId, JSON.stringify(s.record), 'station', s.record.metadata.device_id,
284
+ ]);
285
+ sessions.push(r.rows[0].id);
286
+ }
287
+ // A session that starts at the instant the one before it ended keeps the
288
+ // end of the earlier one: the core counts the next reading below it as a
289
+ // reset, the energy of the new session from zero.
290
+ const byInstant = new Map();
291
+ for (const p of read.sessions.flatMap((s) => s.energy))
292
+ byInstant.set(p.at, Math.max(byInstant.get(p.at) ?? -Infinity, p.value));
293
+ const values = [...byInstant].sort(([a], [b]) => a.localeCompare(b)).map(([at, value]) => ({ at, value }));
294
+ const energy = values.length
295
+ ? await storeSeries(db, { organisationId: request.organisationId, objectKind: 'device', objectId: request.deviceId, sourceCode: 'zaptec', kind: 'measured' }, { quantity_code: 'consumption_energy', value_kind: 'cumulative', step: null, unit: 'KiloW-HR', values })
296
+ : null;
297
+ return { sessions, energy, skipped: read.skipped };
298
+ }
299
+ /** The `sources` row this package ships (`source.json`): write it with `registerSource()`. */
300
+ export const zaptecSource = JSON.parse(readFileSync(new URL('../source.json', import.meta.url), 'utf8'));
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@nexgen-os/zaptec",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.5.0",
4
+ "description": "Zaptec charging stations read from their cloud as a Nexgen OS connector: the chargers of an account, their state, and their completed sessions with the energy delivered, as sessions and series of the charger.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/nexgen-os/nexgen-os.git",
9
+ "directory": "packages/connectors/zaptec"
10
+ },
11
+ "publishConfig": {
12
+ "access": "public"
13
+ },
14
+ "type": "module",
15
+ "engines": {
16
+ "node": ">=20"
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "source.json",
21
+ "README.md",
22
+ "LICENSE"
23
+ ],
24
+ "main": "./dist/index.js",
25
+ "types": "./dist/index.d.ts",
26
+ "exports": {
27
+ ".": {
28
+ "types": "./dist/index.d.ts",
29
+ "import": "./dist/index.js"
30
+ }
31
+ },
32
+ "scripts": {
33
+ "build": "tsc -p tsconfig.build.json"
34
+ },
35
+ "dependencies": {
36
+ "@nexgen-os/core": "^0.5.0"
37
+ }
38
+ }
package/source.json ADDED
@@ -0,0 +1,14 @@
1
+ {
2
+ "code": "zaptec",
3
+ "name": "Zaptec",
4
+ "description": "The cloud of Zaptec charging stations: the chargers an account owns, their state as they last reported it (power, voltage and current of each phase, operation mode) and their completed sessions with the energy each delivered. Read by @nexgen-os/zaptec with the account of the charger's owner.",
5
+ "kind": "api",
6
+ "base_url": "https://api.zaptec.com",
7
+ "docs_url": "https://api.zaptec.com/help/index.html",
8
+ "auth": "oauth2",
9
+ "license": "Zaptec's terms of use; the data is the charger owner's, read with their account",
10
+ "attribution": "Zaptec",
11
+ "retention_days": null,
12
+ "redistributable": false,
13
+ "published_by": "@nexgen-os/zaptec"
14
+ }