@nexgen-os/mqtt 0.0.0-stage → 0.5.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.md +83 -2
- package/dist/index.d.ts +133 -0
- package/dist/index.js +223 -0
- package/package.json +36 -4
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,84 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `@nexgen-os/mqtt`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The readings of **P1 dongles**, received from an MQTT broker, as the series
|
|
4
|
+
of the meters they read. A dongle on the P1 port of a smart meter publishes
|
|
5
|
+
what the meter says every second or every few seconds: the JSON message of
|
|
6
|
+
the open P1M5 firmware, or the DSMR telegram as the meter wrote it. This
|
|
7
|
+
package places each message on the meter (or the device) its dongle is
|
|
8
|
+
known by, dates it by the meter's clock in the time zone of that object's
|
|
9
|
+
participant, keeps one reading a minute, and writes the kept readings in
|
|
10
|
+
batches through `store()`, the one write path of the core. MIT.
|
|
11
|
+
|
|
12
|
+
The broker is a protocol, never a library this package ships
|
|
13
|
+
([0014](../../../docs/decisions/0014-integrations-dashboards-warehouses-streams.md)):
|
|
14
|
+
any client that subscribes and emits `message` events fits, MQTT.js as it
|
|
15
|
+
is. The readings themselves are read by [`@nexgen-os/dsmr`](../../formats/dsmr/README.md)
|
|
16
|
+
and turned into series by `meterSeriesOfDsmr()` of `@nexgen-os/core`, the
|
|
17
|
+
same mapping a file of telegrams goes through.
|
|
18
|
+
|
|
19
|
+
## Use
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
import mqtt from 'mqtt';
|
|
23
|
+
import { listen, p1Stream, registerP1PortSource } from '@nexgen-os/mqtt';
|
|
24
|
+
|
|
25
|
+
await registerP1PortSource(db); // the `p1_port` source, once
|
|
26
|
+
const client = mqtt.connect(process.env.BROKER_URL!, { username, password }); // the secret from the vault
|
|
27
|
+
const stream = p1Stream(db, { scheme: 'p1_dongle', organisationId });
|
|
28
|
+
const listening = listen(client, stream, {
|
|
29
|
+
topics: ['p1/+/data/readings'],
|
|
30
|
+
onReceived: (r) => { if (r.status === 'refused') console.warn(r.identifier, r.problems); },
|
|
31
|
+
});
|
|
32
|
+
// …
|
|
33
|
+
await listening.stop(); // writes what is left
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
The installation records each dongle once, as an identifier of the meter it
|
|
37
|
+
reads, in a scheme of its own (the scheme is data, the package names none):
|
|
38
|
+
|
|
39
|
+
```sql
|
|
40
|
+
insert into identifier_schemes (code, name, pattern) values ('p1_dongle', 'A P1 dongle', '^[A-Z0-9]+$');
|
|
41
|
+
select add_identifier('meter', '<meter id>', 'p1_dongle', 'P1000001');
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## What a message becomes
|
|
45
|
+
|
|
46
|
+
1. **Its dongle.** `dongleIdentifier()` reads the `dongle_id` of a P1M5
|
|
47
|
+
message, otherwise the meter's equipment identifier (`0-0:96.1.1`) of a
|
|
48
|
+
telegram; `identifierOf` replaces it (a segment of the topic, say).
|
|
49
|
+
2. **Its object.** The identifier, valid now, in the stream's `scheme` (and
|
|
50
|
+
`organisationId` when given), read under the connection's rights: a
|
|
51
|
+
meter or a device. Found or not, a dongle is remembered for
|
|
52
|
+
`rememberSeconds` (300) before it is looked up again.
|
|
53
|
+
3. **Its time.** The reading is dated by the meter's clock in the time zone
|
|
54
|
+
of the object's participant, never by the time it was received.
|
|
55
|
+
4. **Thinned.** One reading per object every `keepEverySeconds` of meter
|
|
56
|
+
time (60; 0 keeps them all): the registers are cumulative, so the
|
|
57
|
+
quarter hours `resample()` gives lose nothing, and the power and voltage
|
|
58
|
+
are kept once a minute.
|
|
59
|
+
5. **Written.** `flush()` (every `flushEverySeconds`, 60, under `listen()`)
|
|
60
|
+
writes each object's batch as its series of kind `measured` under the
|
|
61
|
+
source `p1_port`: the energy registers as cumulative `offtake_energy` /
|
|
62
|
+
`injection_energy` series by tariff, the power and the voltage as
|
|
63
|
+
instants by phase.
|
|
64
|
+
|
|
65
|
+
| What came | What it gives |
|
|
66
|
+
|---|---|
|
|
67
|
+
| a message whose dongle no identifier names | refused, `identifier_unknown` |
|
|
68
|
+
| an identifier in several organisations the connection reads | refused, `identifier_ambiguous`; give `organisationId` |
|
|
69
|
+
| an identifier on another object than a meter or a device | refused, `object_not_measured` |
|
|
70
|
+
| a participant without a time zone | refused, `time_zone_required` |
|
|
71
|
+
| a message naming no dongle, or not a message | refused, `identifier_missing`, `telegram_unreadable` |
|
|
72
|
+
| a reading without the meter's time | refused, `time_missing` |
|
|
73
|
+
| a telegram whose checksum does not match | left out at the flush, in `skipped` |
|
|
74
|
+
| a batch the core refuses (another value kind on the series) | the flush's `error`, its readings dropped |
|
|
75
|
+
|
|
76
|
+
A refusal never stops the stream: the next message is read.
|
|
77
|
+
|
|
78
|
+
## Not yet
|
|
79
|
+
|
|
80
|
+
- The meters of the bus (gas, water, heat on channels 1 to 4): their volume
|
|
81
|
+
is in the telegram, and `meterSeriesOfDsmr(readings, { channel })` gives
|
|
82
|
+
it; the stream writes the electricity meter only.
|
|
83
|
+
- The one message shape of the stream door, the envelope of the
|
|
84
|
+
connectors' series, received from any broker.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@nexgen-os/mqtt`: the readings of P1 dongles, received from an MQTT
|
|
3
|
+
* broker, as the series of the meters they read.
|
|
4
|
+
*
|
|
5
|
+
* A dongle on the P1 port of a smart meter publishes what the meter says,
|
|
6
|
+
* every second or every few seconds, to a broker: the JSON message of the
|
|
7
|
+
* open P1M5 firmware, or the DSMR telegram as the meter wrote it. A stream
|
|
8
|
+
* of this package takes each message as it comes (`receive()`), finds the
|
|
9
|
+
* object it belongs to by the dongle's identifier in the core's
|
|
10
|
+
* `identifiers` (a scheme the installation names), reads it with
|
|
11
|
+
* `@nexgen-os/dsmr` in the time zone of that object's participant, keeps one
|
|
12
|
+
* reading per object every `keepEverySeconds`, and writes what it kept in
|
|
13
|
+
* batches (`flush()`) through `meterSeriesOfDsmr()` and `storeSeries()`, the
|
|
14
|
+
* one write path of the core. `listen()` ties a stream to any MQTT client
|
|
15
|
+
* that subscribes and emits `message` events (MQTT.js, or another): the
|
|
16
|
+
* broker is a protocol, never a library this package ships
|
|
17
|
+
* ([0014](../../../docs/decisions/0014-integrations-dashboards-warehouses-streams.md)).
|
|
18
|
+
*
|
|
19
|
+
* A message that cannot be placed is refused by name, never guessed:
|
|
20
|
+
* `identifier_missing`, `identifier_unknown`, `identifier_ambiguous`,
|
|
21
|
+
* `object_not_measured`, `time_zone_required`. A stream is never stopped by
|
|
22
|
+
* one bad message.
|
|
23
|
+
*/
|
|
24
|
+
import { type Db, type SourceRow } from '@nexgen-os/core';
|
|
25
|
+
import { type DsmrOptions, type DsmrProblem, type DsmrReading } from '@nexgen-os/dsmr';
|
|
26
|
+
/** The source of what a P1 port says, as this package ships it. */
|
|
27
|
+
export declare const P1_PORT_SOURCE: SourceRow;
|
|
28
|
+
/** Writes the `sources` row of the P1 port, once. */
|
|
29
|
+
export declare function registerP1PortSource(db: Db): Promise<void>;
|
|
30
|
+
/**
|
|
31
|
+
* Reads one message of a dongle: a P1M5 JSON message (text starting with
|
|
32
|
+
* `{`, or a parsed object), or a DSMR telegram (text starting with `/`).
|
|
33
|
+
*/
|
|
34
|
+
export declare function readP1Message(payload: string | Uint8Array | Record<string, unknown>, options?: DsmrOptions): DsmrReading;
|
|
35
|
+
/**
|
|
36
|
+
* The identifier a reading names its dongle by: the `dongle_id` of a P1M5
|
|
37
|
+
* message, otherwise the meter's equipment identifier (`0-0:96.1.1`).
|
|
38
|
+
*/
|
|
39
|
+
export declare function dongleIdentifier(_topic: string, reading: DsmrReading): string | null;
|
|
40
|
+
/** Whether a topic matches an MQTT topic filter, with its `+` and `#` wildcards. */
|
|
41
|
+
export declare function topicMatches(filter: string, topic: string): boolean;
|
|
42
|
+
export interface P1StreamOptions {
|
|
43
|
+
/** The identifier scheme the installation records its dongles under (`identifier_schemes`), on a meter or a device. */
|
|
44
|
+
scheme: string;
|
|
45
|
+
/** Only the identifiers of this organisation; any the connection may read otherwise. */
|
|
46
|
+
organisationId?: string;
|
|
47
|
+
/** The source the series are written under; `p1_port` by default. */
|
|
48
|
+
sourceCode?: string;
|
|
49
|
+
/** Keeps one reading per object every that many seconds of meter time; 60 by default, 0 keeps them all. */
|
|
50
|
+
keepEverySeconds?: number;
|
|
51
|
+
/** How long a dongle found, or not found, stays known before it is looked up again; 300 seconds by default. */
|
|
52
|
+
rememberSeconds?: number;
|
|
53
|
+
/** The identifier of a message's dongle; `dongleIdentifier()` by default. */
|
|
54
|
+
identifierOf?: (topic: string, reading: DsmrReading) => string | null;
|
|
55
|
+
/** The clock, for the memory of dongles; `Date.now` by default. */
|
|
56
|
+
now?: () => number;
|
|
57
|
+
}
|
|
58
|
+
/** The object a dongle's readings land on. */
|
|
59
|
+
export interface P1Target {
|
|
60
|
+
organisationId: string;
|
|
61
|
+
objectKind: 'meter' | 'device';
|
|
62
|
+
objectId: string;
|
|
63
|
+
timeZone: string;
|
|
64
|
+
}
|
|
65
|
+
/** What became of one message. */
|
|
66
|
+
export type P1Received = {
|
|
67
|
+
status: 'queued';
|
|
68
|
+
identifier: string;
|
|
69
|
+
target: P1Target;
|
|
70
|
+
at: string;
|
|
71
|
+
problems: DsmrProblem[];
|
|
72
|
+
} | {
|
|
73
|
+
status: 'thinned';
|
|
74
|
+
identifier: string;
|
|
75
|
+
target: P1Target;
|
|
76
|
+
at: string;
|
|
77
|
+
} | {
|
|
78
|
+
status: 'refused';
|
|
79
|
+
identifier: string | null;
|
|
80
|
+
problems: DsmrProblem[];
|
|
81
|
+
};
|
|
82
|
+
/** What one flush wrote, object by object. */
|
|
83
|
+
export interface P1Flushed {
|
|
84
|
+
objectKind: 'meter' | 'device';
|
|
85
|
+
objectId: string;
|
|
86
|
+
readings: number;
|
|
87
|
+
/** Readings left out whole (undated, checksum), by their index in the batch. */
|
|
88
|
+
skipped: {
|
|
89
|
+
index: number;
|
|
90
|
+
problems: DsmrProblem[];
|
|
91
|
+
}[];
|
|
92
|
+
series: {
|
|
93
|
+
quantity_code: string;
|
|
94
|
+
name: string | null;
|
|
95
|
+
seriesId: string;
|
|
96
|
+
inserted: number;
|
|
97
|
+
}[];
|
|
98
|
+
/** The refusal of the core when the batch could not be written; its readings are dropped. */
|
|
99
|
+
error?: string;
|
|
100
|
+
}
|
|
101
|
+
/** A stream of P1 messages: receive them as they come, write them in batches. */
|
|
102
|
+
export interface P1Stream {
|
|
103
|
+
receive(topic: string, payload: string | Uint8Array | Record<string, unknown>): Promise<P1Received>;
|
|
104
|
+
flush(): Promise<P1Flushed[]>;
|
|
105
|
+
/** Readings waiting for the next flush. */
|
|
106
|
+
readonly pending: number;
|
|
107
|
+
}
|
|
108
|
+
/** A stream that writes the readings of dongles on the objects their identifiers name. */
|
|
109
|
+
export declare function p1Stream(db: Db, options: P1StreamOptions): P1Stream;
|
|
110
|
+
/** What `listen()` needs of an MQTT client: MQTT.js fits as it is. */
|
|
111
|
+
export interface MqttClient {
|
|
112
|
+
subscribe(topic: string | string[], ...rest: unknown[]): unknown;
|
|
113
|
+
on(event: 'message', listener: (topic: string, payload: Uint8Array) => void): unknown;
|
|
114
|
+
removeListener(event: 'message', listener: (topic: string, payload: Uint8Array) => void): unknown;
|
|
115
|
+
}
|
|
116
|
+
export interface ListenOptions {
|
|
117
|
+
/** The topic filters to subscribe to (`p1/+/data/readings`); a message on another topic of the client is ignored. */
|
|
118
|
+
topics: string[];
|
|
119
|
+
/** Writes the readings kept every that many seconds; 60 by default. */
|
|
120
|
+
flushEverySeconds?: number;
|
|
121
|
+
onReceived?: (received: P1Received, topic: string) => void;
|
|
122
|
+
onFlushed?: (flushed: P1Flushed[]) => void;
|
|
123
|
+
/** A failure of the database or of a callback; the stream goes on. */
|
|
124
|
+
onError?: (error: unknown) => void;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Subscribes a client to the topics and feeds the stream with their
|
|
128
|
+
* messages, one at a time, in the order they came; flushes on a timer.
|
|
129
|
+
* `stop()` stops listening and writes what is left.
|
|
130
|
+
*/
|
|
131
|
+
export declare function listen(client: MqttClient, stream: P1Stream, options: ListenOptions): {
|
|
132
|
+
stop(): Promise<P1Flushed[]>;
|
|
133
|
+
};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@nexgen-os/mqtt`: the readings of P1 dongles, received from an MQTT
|
|
3
|
+
* broker, as the series of the meters they read.
|
|
4
|
+
*
|
|
5
|
+
* A dongle on the P1 port of a smart meter publishes what the meter says,
|
|
6
|
+
* every second or every few seconds, to a broker: the JSON message of the
|
|
7
|
+
* open P1M5 firmware, or the DSMR telegram as the meter wrote it. A stream
|
|
8
|
+
* of this package takes each message as it comes (`receive()`), finds the
|
|
9
|
+
* object it belongs to by the dongle's identifier in the core's
|
|
10
|
+
* `identifiers` (a scheme the installation names), reads it with
|
|
11
|
+
* `@nexgen-os/dsmr` in the time zone of that object's participant, keeps one
|
|
12
|
+
* reading per object every `keepEverySeconds`, and writes what it kept in
|
|
13
|
+
* batches (`flush()`) through `meterSeriesOfDsmr()` and `storeSeries()`, the
|
|
14
|
+
* one write path of the core. `listen()` ties a stream to any MQTT client
|
|
15
|
+
* that subscribes and emits `message` events (MQTT.js, or another): the
|
|
16
|
+
* broker is a protocol, never a library this package ships
|
|
17
|
+
* ([0014](../../../docs/decisions/0014-integrations-dashboards-warehouses-streams.md)).
|
|
18
|
+
*
|
|
19
|
+
* A message that cannot be placed is refused by name, never guessed:
|
|
20
|
+
* `identifier_missing`, `identifier_unknown`, `identifier_ambiguous`,
|
|
21
|
+
* `object_not_measured`, `time_zone_required`. A stream is never stopped by
|
|
22
|
+
* one bad message.
|
|
23
|
+
*/
|
|
24
|
+
import { meterSeriesOfDsmr, registerSource, storeSeries, } from '@nexgen-os/core';
|
|
25
|
+
import { readP1m5, readTelegram } from '@nexgen-os/dsmr';
|
|
26
|
+
/** The source of what a P1 port says, as this package ships it. */
|
|
27
|
+
export const P1_PORT_SOURCE = {
|
|
28
|
+
code: 'p1_port',
|
|
29
|
+
name: 'The P1 port of a smart meter',
|
|
30
|
+
description: 'What a smart meter says on its P1 port (DSMR, e-MUCS): energy registers, power and voltage, dated by the meter clock; read by a dongle on the port and received from an MQTT broker.',
|
|
31
|
+
kind: 'device',
|
|
32
|
+
auth: 'none',
|
|
33
|
+
license: null,
|
|
34
|
+
redistributable: false,
|
|
35
|
+
published_by: '@nexgen-os/mqtt',
|
|
36
|
+
};
|
|
37
|
+
/** Writes the `sources` row of the P1 port, once. */
|
|
38
|
+
export async function registerP1PortSource(db) {
|
|
39
|
+
await registerSource(db, P1_PORT_SOURCE);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Reads one message of a dongle: a P1M5 JSON message (text starting with
|
|
43
|
+
* `{`, or a parsed object), or a DSMR telegram (text starting with `/`).
|
|
44
|
+
*/
|
|
45
|
+
export function readP1Message(payload, options = {}) {
|
|
46
|
+
if (typeof payload === 'object' && !(payload instanceof Uint8Array))
|
|
47
|
+
return readP1m5(payload, options);
|
|
48
|
+
const text = typeof payload === 'string' ? payload : new TextDecoder('utf-8').decode(payload);
|
|
49
|
+
return text.trimStart().startsWith('/') ? readTelegram(text, options) : readP1m5(text, options);
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* The identifier a reading names its dongle by: the `dongle_id` of a P1M5
|
|
53
|
+
* message, otherwise the meter's equipment identifier (`0-0:96.1.1`).
|
|
54
|
+
*/
|
|
55
|
+
export function dongleIdentifier(_topic, reading) {
|
|
56
|
+
const id = reading.fields['dongle_id'];
|
|
57
|
+
if (typeof id === 'string' && id.trim() !== '')
|
|
58
|
+
return id.trim();
|
|
59
|
+
return reading.equipment_id;
|
|
60
|
+
}
|
|
61
|
+
/** Whether a topic matches an MQTT topic filter, with its `+` and `#` wildcards. */
|
|
62
|
+
export function topicMatches(filter, topic) {
|
|
63
|
+
const f = filter.split('/');
|
|
64
|
+
const t = topic.split('/');
|
|
65
|
+
for (let i = 0; i < f.length; i++) {
|
|
66
|
+
// `#` is last and matches its parent level too: `a/#` matches `a`.
|
|
67
|
+
if (f[i] === '#')
|
|
68
|
+
return true;
|
|
69
|
+
if (i >= t.length)
|
|
70
|
+
return false;
|
|
71
|
+
if (f[i] !== '+' && f[i] !== t[i])
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
return f.length === t.length;
|
|
75
|
+
}
|
|
76
|
+
const problem = (code, detail) => ({ code, detail });
|
|
77
|
+
/** A stream that writes the readings of dongles on the objects their identifiers name. */
|
|
78
|
+
export function p1Stream(db, options) {
|
|
79
|
+
const sourceCode = options.sourceCode ?? P1_PORT_SOURCE.code;
|
|
80
|
+
const keepMs = (options.keepEverySeconds ?? 60) * 1000;
|
|
81
|
+
const rememberMs = (options.rememberSeconds ?? 300) * 1000;
|
|
82
|
+
const identifierOf = options.identifierOf ?? dongleIdentifier;
|
|
83
|
+
const now = options.now ?? Date.now;
|
|
84
|
+
const known = new Map();
|
|
85
|
+
const lastKept = new Map();
|
|
86
|
+
let batches = new Map();
|
|
87
|
+
let pending = 0;
|
|
88
|
+
async function find(identifier) {
|
|
89
|
+
const remembered = known.get(identifier);
|
|
90
|
+
if (remembered && remembered.until > now())
|
|
91
|
+
return remembered;
|
|
92
|
+
const { rows } = await db.query(`select i.organisation_id::text, i.object_kind, i.object_id::text, p.time_zone
|
|
93
|
+
from identifiers i
|
|
94
|
+
left join participants p on p.id = participant_of(i.object_kind, i.object_id)
|
|
95
|
+
where i.scheme = $1 and i.value = $2
|
|
96
|
+
and (i.valid_from is null or i.valid_from <= now())
|
|
97
|
+
and (i.valid_to is null or i.valid_to > now())
|
|
98
|
+
and ($3::uuid is null or i.organisation_id = $3::uuid)`, [options.scheme, identifier, options.organisationId ?? null]);
|
|
99
|
+
let found = { until: now() + rememberMs, target: null, problem: null };
|
|
100
|
+
const row = rows[0];
|
|
101
|
+
if (!row) {
|
|
102
|
+
found.problem = problem('identifier_unknown', `no meter or device is known by ${options.scheme} ${identifier}`);
|
|
103
|
+
}
|
|
104
|
+
else if (rows.length > 1) {
|
|
105
|
+
found.problem = problem('identifier_ambiguous', `${options.scheme} ${identifier} names an object in ${rows.length} organisations; give organisationId`);
|
|
106
|
+
}
|
|
107
|
+
else if (row.object_kind !== 'meter' && row.object_kind !== 'device') {
|
|
108
|
+
found.problem = problem('object_not_measured', `${options.scheme} ${identifier} names a ${row.object_kind}, not a meter or a device`);
|
|
109
|
+
}
|
|
110
|
+
else if (!row.time_zone) {
|
|
111
|
+
found.problem = problem('time_zone_required', `the participant of ${row.object_kind} ${row.object_id} has no time zone: the meter's clock cannot be dated`);
|
|
112
|
+
}
|
|
113
|
+
else {
|
|
114
|
+
found = { ...found, target: { organisationId: row.organisation_id, objectKind: row.object_kind, objectId: row.object_id, timeZone: row.time_zone } };
|
|
115
|
+
}
|
|
116
|
+
known.set(identifier, found);
|
|
117
|
+
return found;
|
|
118
|
+
}
|
|
119
|
+
return {
|
|
120
|
+
get pending() {
|
|
121
|
+
return pending;
|
|
122
|
+
},
|
|
123
|
+
async receive(topic, payload) {
|
|
124
|
+
// The identifier does not depend on the clock: read once to find the
|
|
125
|
+
// dongle, then again in its participant's zone.
|
|
126
|
+
const first = readP1Message(payload);
|
|
127
|
+
const identifier = identifierOf(topic, first);
|
|
128
|
+
if (!identifier) {
|
|
129
|
+
const unreadable = first.problems.filter((p) => p.code === 'telegram_unreadable');
|
|
130
|
+
return {
|
|
131
|
+
status: 'refused', identifier: null,
|
|
132
|
+
problems: unreadable.length > 0 ? unreadable : [problem('identifier_missing', `the message on ${topic} names no dongle`)],
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
const { target, problem: refusal } = await find(identifier);
|
|
136
|
+
if (!target)
|
|
137
|
+
return { status: 'refused', identifier, problems: [refusal] };
|
|
138
|
+
const reading = readP1Message(payload, { timeZone: target.timeZone });
|
|
139
|
+
if (reading.at === null)
|
|
140
|
+
return { status: 'refused', identifier, problems: reading.problems };
|
|
141
|
+
const key = `${target.objectKind} ${target.objectId}`;
|
|
142
|
+
const at = Date.parse(reading.at);
|
|
143
|
+
const last = lastKept.get(key);
|
|
144
|
+
if (last !== undefined && keepMs > 0 && at >= last && at - last < keepMs) {
|
|
145
|
+
return { status: 'thinned', identifier, target, at: reading.at };
|
|
146
|
+
}
|
|
147
|
+
if (last === undefined || at > last)
|
|
148
|
+
lastKept.set(key, at);
|
|
149
|
+
let batch = batches.get(key);
|
|
150
|
+
if (!batch) {
|
|
151
|
+
batch = { target, readings: [] };
|
|
152
|
+
batches.set(key, batch);
|
|
153
|
+
}
|
|
154
|
+
batch.readings.push(reading);
|
|
155
|
+
pending += 1;
|
|
156
|
+
return { status: 'queued', identifier, target, at: reading.at, problems: reading.problems };
|
|
157
|
+
},
|
|
158
|
+
async flush() {
|
|
159
|
+
const taken = batches;
|
|
160
|
+
batches = new Map();
|
|
161
|
+
pending = 0;
|
|
162
|
+
const out = [];
|
|
163
|
+
for (const { target, readings } of taken.values()) {
|
|
164
|
+
const { series, skipped } = meterSeriesOfDsmr(readings);
|
|
165
|
+
const done = { objectKind: target.objectKind, objectId: target.objectId, readings: readings.length, skipped, series: [] };
|
|
166
|
+
try {
|
|
167
|
+
for (const s of series) {
|
|
168
|
+
const stored = await storeSeries(db, {
|
|
169
|
+
organisationId: target.organisationId, objectKind: target.objectKind, objectId: target.objectId, sourceCode, kind: 'measured',
|
|
170
|
+
}, s);
|
|
171
|
+
done.series.push({ quantity_code: s.quantity_code, name: s.name ?? null, seriesId: stored.seriesId, inserted: stored.inserted });
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
catch (error) {
|
|
175
|
+
done.error = error instanceof Error ? error.message : String(error);
|
|
176
|
+
}
|
|
177
|
+
out.push(done);
|
|
178
|
+
}
|
|
179
|
+
return out;
|
|
180
|
+
},
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Subscribes a client to the topics and feeds the stream with their
|
|
185
|
+
* messages, one at a time, in the order they came; flushes on a timer.
|
|
186
|
+
* `stop()` stops listening and writes what is left.
|
|
187
|
+
*/
|
|
188
|
+
export function listen(client, stream, options) {
|
|
189
|
+
// One connection, one thing at a time: every message and every flush
|
|
190
|
+
// waits for the one before it.
|
|
191
|
+
let chain = Promise.resolve();
|
|
192
|
+
const onError = options.onError ?? (() => { });
|
|
193
|
+
const enqueue = (work) => {
|
|
194
|
+
const next = chain.then(work);
|
|
195
|
+
chain = next.catch(onError);
|
|
196
|
+
return next;
|
|
197
|
+
};
|
|
198
|
+
const flush = () => enqueue(async () => {
|
|
199
|
+
const flushed = await stream.flush();
|
|
200
|
+
if (flushed.length > 0)
|
|
201
|
+
options.onFlushed?.(flushed);
|
|
202
|
+
return flushed;
|
|
203
|
+
});
|
|
204
|
+
const listener = (topic, payload) => {
|
|
205
|
+
if (!options.topics.some((f) => topicMatches(f, topic)))
|
|
206
|
+
return;
|
|
207
|
+
void enqueue(async () => {
|
|
208
|
+
const received = await stream.receive(topic, payload);
|
|
209
|
+
options.onReceived?.(received, topic);
|
|
210
|
+
}).catch(() => { });
|
|
211
|
+
};
|
|
212
|
+
client.on('message', listener);
|
|
213
|
+
client.subscribe(options.topics);
|
|
214
|
+
const timer = setInterval(() => void flush().catch(() => { }), (options.flushEverySeconds ?? 60) * 1000);
|
|
215
|
+
timer.unref?.();
|
|
216
|
+
return {
|
|
217
|
+
async stop() {
|
|
218
|
+
clearInterval(timer);
|
|
219
|
+
client.removeListener('message', listener);
|
|
220
|
+
return flush();
|
|
221
|
+
},
|
|
222
|
+
};
|
|
223
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,38 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nexgen-os/mqtt",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.5.1",
|
|
4
|
+
"description": "The readings of P1 dongles received from an MQTT broker as the series of the meters they read: a P1M5 message or a DSMR telegram, the meter found by the dongle's identifier, dated in its participant's time zone, thinned and written by store() in batches. Any MQTT client fits; no broker library is shipped.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/nexgen-os/nexgen-os.git",
|
|
9
|
+
"directory": "packages/connectors/mqtt"
|
|
10
|
+
},
|
|
11
|
+
"publishConfig": {
|
|
12
|
+
"access": "public"
|
|
13
|
+
},
|
|
14
|
+
"type": "module",
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=20"
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"dist",
|
|
20
|
+
"README.md",
|
|
21
|
+
"LICENSE"
|
|
22
|
+
],
|
|
23
|
+
"main": "./dist/index.js",
|
|
24
|
+
"types": "./dist/index.d.ts",
|
|
25
|
+
"exports": {
|
|
26
|
+
".": {
|
|
27
|
+
"types": "./dist/index.d.ts",
|
|
28
|
+
"import": "./dist/index.js"
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"scripts": {
|
|
32
|
+
"build": "tsc -p tsconfig.build.json"
|
|
33
|
+
},
|
|
34
|
+
"dependencies": {
|
|
35
|
+
"@nexgen-os/core": "^0.5.0",
|
|
36
|
+
"@nexgen-os/dsmr": "^0.5.0"
|
|
37
|
+
}
|
|
38
|
+
}
|