@nexgen-os/core 0.4.1 → 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/README.md CHANGED
@@ -7,7 +7,7 @@ it speaks to.
7
7
  |---|---|
8
8
  | `src/db.ts` | `Db`, the one thing a package needs from a database driver: a query with positional parameters that answers with rows |
9
9
  | `src/address.ts` | the standard shape of a place (`Address`, `Place`, precision, source), the `Geocoder` interface, `placeFields()`, `addressLines()` and `geocoderFor()`, the chain: the country's register, the open fallback, a commercial service |
10
- | `src/series.ts` | the series API, each function one call of the SQL function of the same name: `store()`, `seriesEnsure()`, `resample()`, `window()`, `latest()`, `fill()`, `coverage()`, `forecastAt()`, `exportRows()`, `convertUnit()` |
10
+ | `src/series.ts` | the series API, each function one call of the SQL function of the same name: `store()`, `seriesEnsure()`, `resample()`, `aggregate()`, `window()`, `latest()`, `fill()`, `coverage()`, `forecastAt()`, `exportRows()`, `convertUnit()` |
11
11
  | `src/connectors/` | the interfaces of the clients of external APIs (`WeatherProvider`, `MeterDataProvider`, `PlacesProvider`) and `storeSeries()` (`interfaces.ts`); the runner of the JSON contract of the program connectors (`runner.ts`) and the request and result types of the `pv_yield`, `settlement` and `energy_sharing` kinds |
12
12
  | `src/geometry.ts` | WKT, the normal of a face, azimuth and tilt |
13
13
  | `src/sql.ts` | `SqlClient` and `connect()`, the one way the installer, the command line and the MCP server reach Postgres (node-postgres, an optional peer, loaded lazily) |
@@ -16,7 +16,7 @@ it speaks to.
16
16
  | `src/gestures.ts` | the gestures the command line and the MCP server share, one code path for both: the reads of the six objects, series, parameters, indicators, estimates, settlements and actions; the writes through the schema's function for each gesture; the keys; and `compute()`, which runs a module's computation handed in as `Computations` |
17
17
  | `src/geocoders.ts` | the geocoder chain of a surface, from the connectors the person named (`NEXGEN_GEOCODERS`), keyed by the countries and regions their `sources` rows serve |
18
18
  | `src/version.ts` | `compareVersions()` and `nexgenSchemaFloor()`, which refuses a database older than a surface (`schema_too_old`) |
19
- | `src/files/` | the importers and exporters of the format libraries the core's objects need: `exportGeoJson` (the participants, their devices and, when the `building` module is installed, their ground, buildings and surfaces), `importWeatherFile`, `exportWeatherYear`, `exportSeriesParquet`; each writes the plain shapes of a library through the gestures of the schema (`install_device`, `set_attribute`, `add_identifier`, `locate_participant`, `series_ensure`, `store`) and reads them back. The importers of buildings — CityJSON, IFC, a Home Assistant home — are the `building` module's ([`modules/building/src`](../../modules/building/src/index.ts)) |
19
+ | `src/files/` | the importers and exporters of the format libraries the core's objects need: `exportGeoJson` (the participants, their devices and, when the `building` module is installed, their ground, buildings and surfaces; the document it writes is described by [`schema/geojson-export.1.json`](schema/geojson-export.1.json)), `importGeoJsonParticipants` (the participants of a collection, at their place), `importWeatherFile`, `exportWeatherYear`, `exportSeriesParquet`, `importEvccCatalogue` (the products evcc's templates drive, into the catalogue `products`, with the templates a device of each model can be driven through), `importProject` (a project described as data, from whatever another system holds, found again on every replay), `importProjectSheet` (the projects of a sheet a spreadsheet saved, through `importProject`), `importPvsolStudy` (a PV\*SOL study: its participant and inverters through `importProject`, its PV system and arrays through `describePvSystem`); each writes the plain shapes of a library through the gestures of the schema (`install_device`, `set_attribute`, `add_identifier`, `locate_participant`, `series_ensure`, `store`) and reads them back. The importers of buildings — CityJSON, IFC, a Home Assistant home — are the `building` module's ([`modules/building/src`](../../modules/building/src/index.ts)) |
20
20
 
21
21
  The geocoders are connectors (`@nexgen-os/nominatim`, `photon`, `ban`,
22
22
  `geopunt`, `urbis`, `icar`) and import this package and nothing else of
@@ -0,0 +1,125 @@
1
+ import type { Db } from '../db.js';
2
+ import { type CollectedSeries } from './interfaces.js';
3
+ /** A device as the platform that reaches it knows it: its identifier in the scheme the connector reads. */
4
+ export interface DeviceOfSource {
5
+ identifier: string;
6
+ scheme: string;
7
+ /** `device_types.code`: a charger, a heat pump, an inverter… */
8
+ device_type: string;
9
+ }
10
+ /** What a reading of a device is given beside the device and the period. */
11
+ export interface DeviceReadingOptions {
12
+ /** The step asked, an ISO 8601 duration (`PT15M`); the platform's own when absent. */
13
+ step?: string;
14
+ /** The quantities asked, by `quantities.code`; every one the platform has when absent. */
15
+ quantities?: string[];
16
+ }
17
+ /**
18
+ * Series of a device from the platform that reaches it, from `from` to `to`
19
+ * (`YYYY-MM-DD`, `to` excluded): what it measured, each value dated at the
20
+ * start of its interval. `collectDeviceReadings()` calls it and stores what
21
+ * it returns on the device.
22
+ */
23
+ export interface DeviceReadingsProvider {
24
+ readonly source_code: string;
25
+ /** The identifier scheme the platform names its devices by (`identifier_schemes.code`). */
26
+ readonly scheme: string;
27
+ readings(device: DeviceOfSource, from: string, to: string, options?: DeviceReadingOptions): Promise<CollectedSeries[]>;
28
+ }
29
+ /** A command of the `actions` module as a carrier receives it: what is asked of which device, when. */
30
+ export interface DeviceCommand {
31
+ /** The action, to report on. */
32
+ id: string;
33
+ device: DeviceOfSource;
34
+ /** The series the value is asked on: its quantity, its kind (`setpoint` or `command`) and its name. */
35
+ quantity_code: string;
36
+ series_kind: 'setpoint' | 'command';
37
+ series_name: string | null;
38
+ /** The value asked, in `unit`, the unit of its quantity. */
39
+ value: number;
40
+ unit: string;
41
+ /** The instant it is asked for, ISO 8601 in UTC. */
42
+ due_at: string;
43
+ }
44
+ /** What the device answered: the instant it acknowledged the command, or why it did not. */
45
+ export type CommandAnswer = {
46
+ acknowledged_at: string;
47
+ } | {
48
+ failure: string;
49
+ };
50
+ /**
51
+ * Carries out a command on a device and says what the device answered. It
52
+ * sends, it does not decide: the command was validated by a person before it
53
+ * reaches a carrier.
54
+ */
55
+ export interface CommandCarrier {
56
+ readonly source_code: string;
57
+ /** The identifier scheme the platform names its devices by (`identifier_schemes.code`). */
58
+ readonly scheme: string;
59
+ carry(command: DeviceCommand): Promise<CommandAnswer>;
60
+ }
61
+ /** Records what a device answered to a command; `actions.report()` by default. */
62
+ export type CommandReport = (db: Db, actionId: string, at: string, failure: string | null) => Promise<void>;
63
+ /**
64
+ * The device as a platform knows it: its type and its identifier in the
65
+ * scheme, of the connector's organisation. Refuses `device_not_found`,
66
+ * `device_in_other_organisation`, `identifier_missing`.
67
+ */
68
+ export declare function deviceOfSource(db: Db, deviceId: string, scheme: string, organisationId: string): Promise<DeviceOfSource>;
69
+ export interface DeviceReadingRequest {
70
+ /** The organisation's `connectors` row of the provider's source. */
71
+ connectorId: string;
72
+ deviceId: string;
73
+ /** The readings asked for, `YYYY-MM-DD`, `to` excluded. */
74
+ from: string;
75
+ to: string;
76
+ step?: string;
77
+ quantities?: string[];
78
+ }
79
+ /**
80
+ * Reads a device through a connector and keeps what it brought as the
81
+ * measured series of the device, each carrying the connector's source. The
82
+ * device is found by its identifier in the provider's scheme; nothing is
83
+ * written when the connector, the device or its identifier is refused.
84
+ */
85
+ export declare function collectDeviceReadings(db: Db, provider: DeviceReadingsProvider, request: DeviceReadingRequest): Promise<{
86
+ stored: {
87
+ quantity_code: string;
88
+ seriesId: string;
89
+ inserted: number;
90
+ }[];
91
+ }>;
92
+ /** `actions.report()`: acknowledged, the command is done and its value stored in its series; with a failure, it failed and says why. */
93
+ export declare const reportCommand: CommandReport;
94
+ export interface CarryRequest {
95
+ /** The organisation's `connectors` row of the carrier's source: the commands that name it are carried. */
96
+ connectorId: string;
97
+ /** Carries the validated commands due at this instant or before (ISO 8601); now when absent. */
98
+ until?: string;
99
+ /**
100
+ * How an answer is recorded: `actions.report()` by default. A module that
101
+ * keeps more of a command than its value — the schedule of a charging
102
+ * profile — passes its own report, which calls `actions.report()`.
103
+ */
104
+ report?: CommandReport;
105
+ }
106
+ export interface CarriedCommand {
107
+ id: string;
108
+ device_id: string;
109
+ status: 'done' | 'failed';
110
+ acknowledged_at: string | null;
111
+ failure: string | null;
112
+ }
113
+ /**
114
+ * Carries out the validated commands of a connector that are due, the
115
+ * earliest first, and reports each answer: acknowledged, the command is done
116
+ * and its value lands in its series; refused, not acknowledged, or a carrier
117
+ * that threw, it failed with why, writes nothing and can be proposed again
118
+ * (`actions.move(action, 'proposed')`). A command whose device has no
119
+ * identifier in the carrier's scheme fails with `identifier_missing`.
120
+ * Refuses `module_not_installed` without the `actions` module,
121
+ * `connector_not_found`, `connector_source_mismatch`.
122
+ */
123
+ export declare function carryCommands(db: Db, carrier: CommandCarrier, request: CarryRequest): Promise<{
124
+ carried: CarriedCommand[];
125
+ }>;
@@ -0,0 +1,124 @@
1
+ // A device connector: what a device measures, read as its series, and what
2
+ // is asked of it, carried out as a command (decision 0061).
3
+ //
4
+ // A charger, a heat pump, an inverter, a battery or a P1 dongle is reached
5
+ // through its maker's platform, an aggregator or its local interface. The
6
+ // code that reaches it does two things and only two: it reads series of the
7
+ // device (`DeviceReadingsProvider`) and it carries out the commands of the
8
+ // `actions` module asked of the device (`CommandCarrier`). It knows the
9
+ // device by an identifier in a scheme — the `identifiers` row of the device,
10
+ // a serial or a site id at the platform — and answers in the core's terms.
11
+ //
12
+ // `collectDeviceReadings()` is the one path from a provider to the series
13
+ // of a device, as `collectMeterReadings()` is for a meter.
14
+ // `carryCommands()` is the one path from the validated commands of a
15
+ // connector to the device and back: what the device answered is reported
16
+ // through `actions.report()`, which stores the value in its series when
17
+ // the device acknowledged it. A connector never writes a setpoint itself;
18
+ // deciding when to command a device is an application's.
19
+ import { GestureError } from '../refusal.js';
20
+ import { storeSeries } from './interfaces.js';
21
+ async function connectorOf(db, connectorId, sourceCode) {
22
+ const connector = (await db.query(`select organisation_id, source_code from connectors where id = $1`, [connectorId])).rows[0];
23
+ if (!connector)
24
+ throw new GestureError(`connector_not_found: ${connectorId}`);
25
+ if (connector.source_code !== sourceCode) {
26
+ throw new GestureError(`connector_source_mismatch: connector ${connectorId} reads ${connector.source_code}, not ${sourceCode}`);
27
+ }
28
+ return connector;
29
+ }
30
+ /**
31
+ * The device as a platform knows it: its type and its identifier in the
32
+ * scheme, of the connector's organisation. Refuses `device_not_found`,
33
+ * `device_in_other_organisation`, `identifier_missing`.
34
+ */
35
+ export async function deviceOfSource(db, deviceId, scheme, organisationId) {
36
+ const device = (await db.query(`select organisation_id, device_type from devices where id = $1`, [deviceId])).rows[0];
37
+ if (!device)
38
+ throw new GestureError(`device_not_found: ${deviceId}`);
39
+ if (device.organisation_id !== organisationId) {
40
+ throw new GestureError(`device_in_other_organisation: device ${deviceId} is not of the connector's organisation`);
41
+ }
42
+ const identifier = (await db.query(`select value from identifiers
43
+ where object_kind = 'device' and object_id = $1 and scheme = $2
44
+ and (valid_from is null or valid_from <= now()) and (valid_to is null or valid_to > now())
45
+ order by valid_from desc nulls last limit 1`, [deviceId, scheme])).rows[0];
46
+ if (!identifier)
47
+ throw new GestureError(`identifier_missing: device ${deviceId} has no ${scheme} identifier`);
48
+ return { identifier: identifier.value, scheme, device_type: device.device_type };
49
+ }
50
+ /**
51
+ * Reads a device through a connector and keeps what it brought as the
52
+ * measured series of the device, each carrying the connector's source. The
53
+ * device is found by its identifier in the provider's scheme; nothing is
54
+ * written when the connector, the device or its identifier is refused.
55
+ */
56
+ export async function collectDeviceReadings(db, provider, request) {
57
+ const connector = await connectorOf(db, request.connectorId, provider.source_code);
58
+ const device = await deviceOfSource(db, request.deviceId, provider.scheme, connector.organisation_id);
59
+ const collected = await provider.readings(device, request.from, request.to, {
60
+ ...(request.step ? { step: request.step } : {}), ...(request.quantities ? { quantities: request.quantities } : {}),
61
+ });
62
+ const stored = [];
63
+ for (const series of collected) {
64
+ const { seriesId, inserted } = await storeSeries(db, {
65
+ organisationId: connector.organisation_id, objectKind: 'device', objectId: request.deviceId,
66
+ sourceCode: provider.source_code, kind: 'measured',
67
+ }, series);
68
+ stored.push({ quantity_code: series.quantity_code, seriesId, inserted });
69
+ }
70
+ return { stored };
71
+ }
72
+ /** `actions.report()`: acknowledged, the command is done and its value stored in its series; with a failure, it failed and says why. */
73
+ export const reportCommand = async (db, actionId, at, failure) => {
74
+ await db.query(`select actions.report($1, $2::timestamptz, $3)`, [actionId, at, failure]);
75
+ };
76
+ /**
77
+ * Carries out the validated commands of a connector that are due, the
78
+ * earliest first, and reports each answer: acknowledged, the command is done
79
+ * and its value lands in its series; refused, not acknowledged, or a carrier
80
+ * that threw, it failed with why, writes nothing and can be proposed again
81
+ * (`actions.move(action, 'proposed')`). A command whose device has no
82
+ * identifier in the carrier's scheme fails with `identifier_missing`.
83
+ * Refuses `module_not_installed` without the `actions` module,
84
+ * `connector_not_found`, `connector_source_mismatch`.
85
+ */
86
+ export async function carryCommands(db, carrier, request) {
87
+ const installed = (await db.query(`select to_regclass('actions.actions') is not null ok`)).rows[0].ok;
88
+ if (!installed)
89
+ throw new GestureError('module_not_installed: commands are actions of the actions module, which is not installed');
90
+ const connector = await connectorOf(db, request.connectorId, carrier.source_code);
91
+ const report = request.report ?? reportCommand;
92
+ const due = (await db.query(`select a.id, a.object_id device_id, s.quantity_code, s.kind series_kind, s.name series_name, a.value, q.unit,
93
+ to_char(a.due_at at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') due_at
94
+ from actions.actions a
95
+ join series s on s.id = a.series_id
96
+ join quantities q on q.code = s.quantity_code
97
+ where a.kind = 'command' and a.status = 'validated' and a.connector_id = $1
98
+ and a.due_at <= coalesce($2::timestamptz, now())
99
+ order by a.due_at, a.id`, [request.connectorId, request.until ?? null])).rows;
100
+ const carried = [];
101
+ for (const command of due) {
102
+ let answer;
103
+ try {
104
+ const device = await deviceOfSource(db, command.device_id, carrier.scheme, connector.organisation_id);
105
+ answer = await carrier.carry({
106
+ id: command.id, device, quantity_code: command.quantity_code, series_kind: command.series_kind,
107
+ series_name: command.series_name, value: Number(command.value), unit: command.unit, due_at: command.due_at,
108
+ });
109
+ }
110
+ catch (error) {
111
+ answer = { failure: error instanceof Error ? error.message : String(error) };
112
+ }
113
+ if ('acknowledged_at' in answer) {
114
+ await report(db, command.id, answer.acknowledged_at, null);
115
+ carried.push({ id: command.id, device_id: command.device_id, status: 'done', acknowledged_at: answer.acknowledged_at, failure: null });
116
+ }
117
+ else {
118
+ const failure = answer.failure.trim() || 'not acknowledged';
119
+ await report(db, command.id, new Date().toISOString(), failure);
120
+ carried.push({ id: command.id, device_id: command.device_id, status: 'failed', acknowledged_at: null, failure });
121
+ }
122
+ }
123
+ return { carried };
124
+ }
@@ -1,6 +1,6 @@
1
1
  // The `settlement` request kind (packages/connectors/README.md): the contracts in force
2
- // over a period, each with its price signals in the shape the proposed
3
- // `contracts` module would keep them (modules/README.md) and the series its
2
+ // over a period, each with its price signals as the `energy_contracts` module
3
+ // keeps them (modules/energy_contracts/README.md) and the series its
4
4
  // volume is read from; back, the
5
5
  // settlement lines of each contract — the energy, the price and the amount
6
6
  // over each interval a price holds, who pays and who is paid. Any engine
package/dist/db.d.ts CHANGED
@@ -9,3 +9,11 @@ export interface Db {
9
9
  rows: T[];
10
10
  }>;
11
11
  }
12
+ /**
13
+ * Runs `fn` so that what it writes lands whole or not at all. Inside the
14
+ * caller's transaction it holds a savepoint, released when `fn` returns and
15
+ * rolled back to when it throws, so the caller's transaction goes on; outside
16
+ * of one it is a transaction of its own. The throw is re-thrown either way.
17
+ * As everywhere in the core, the `Db` is one connection.
18
+ */
19
+ export declare function atomically<T>(db: Db, fn: () => Promise<T>): Promise<T>;
package/dist/db.js CHANGED
@@ -1 +1,32 @@
1
- export {};
1
+ /**
2
+ * Runs `fn` so that what it writes lands whole or not at all. Inside the
3
+ * caller's transaction it holds a savepoint, released when `fn` returns and
4
+ * rolled back to when it throws, so the caller's transaction goes on; outside
5
+ * of one it is a transaction of its own. The throw is re-thrown either way.
6
+ * As everywhere in the core, the `Db` is one connection.
7
+ */
8
+ export async function atomically(db, fn) {
9
+ let own = false;
10
+ try {
11
+ await db.query('savepoint nexgen_atomically');
12
+ }
13
+ catch (error) {
14
+ // 25P01, no_active_sql_transaction: there is no transaction to nest in.
15
+ if (error?.code !== '25P01')
16
+ throw error;
17
+ await db.query('begin');
18
+ own = true;
19
+ }
20
+ let result;
21
+ try {
22
+ result = await fn();
23
+ }
24
+ catch (error) {
25
+ await db.query(own ? 'rollback' : 'rollback to savepoint nexgen_atomically');
26
+ if (!own)
27
+ await db.query('release savepoint nexgen_atomically');
28
+ throw error;
29
+ }
30
+ await db.query(own ? 'commit' : 'release savepoint nexgen_atomically');
31
+ return result;
32
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The readings of a P1 port, once read by `@nexgen-os/dsmr`, as the series
3
+ * of a meter, ready for `storeSeries()`: the electricity meter on channel 0,
4
+ * or a gas, water or heat meter of its bus on channel 1 to 4. One mapping,
5
+ * whichever way the readings came (a telegram on the port, a P1M5 message
6
+ * through a broker, a file of them).
7
+ *
8
+ * | Reading | Quantity | Value kind | Name |
9
+ * |---|---|---|---|
10
+ * | energy register, offtake / injection | `offtake_energy` / `injection_energy` | cumulative | `tariff <n>`; none for the total |
11
+ * | power, offtake / injection | `offtake_power` / `injection_power` | instant | the phase, none for the connection |
12
+ * | voltage | `voltage` | instant | the phase |
13
+ * | volume of a meter of the bus | `volume` | cumulative, at the stamp that meter sent | none |
14
+ *
15
+ * Every value is dated by the meter's clock, never by its reception. A
16
+ * reading that cannot be dated or whose checksum does not match is left out
17
+ * whole and said in `skipped`, with its problems; a stream of readings is not
18
+ * refused for one bad telegram. Values stay in the meter's unit, which
19
+ * `store()` converts. The running quarter-hour demand and the month's
20
+ * maximum are left out: the core computes demand from the series. A current
21
+ * is left out until the core's vocabulary carries `current`.
22
+ */
23
+ import type { DsmrProblem, DsmrReading } from '@nexgen-os/dsmr';
24
+ import type { CollectedSeries } from '../connectors/interfaces.js';
25
+ export interface DsmrMeterSeries {
26
+ series: CollectedSeries[];
27
+ /** The readings left out, by their index in the input, with the problems that did it. */
28
+ skipped: {
29
+ index: number;
30
+ problems: DsmrProblem[];
31
+ }[];
32
+ }
33
+ /**
34
+ * The series of one meter in readings of a P1 port: the electricity meter
35
+ * (`channel` 0, the default) or the meter of the bus on that channel.
36
+ */
37
+ export declare function meterSeriesOfDsmr(readings: DsmrReading[], options?: {
38
+ channel?: number;
39
+ }): DsmrMeterSeries;
@@ -0,0 +1,62 @@
1
+ /** Problems that leave a whole reading out: what is left would be wrong or undated. */
2
+ const BLOCKING = new Set([
3
+ 'telegram_unreadable', 'crc_mismatch', 'time_missing', 'time_zone_required', 'date_unreadable',
4
+ 'local_time_nonexistent', 'local_time_ambiguous', 'season_mismatch',
5
+ ]);
6
+ /** The meter's units by the `units` vocabulary's codes, where its spelling is not one. */
7
+ const UNITS = { m3: 'M3' };
8
+ /**
9
+ * The series of one meter in readings of a P1 port: the electricity meter
10
+ * (`channel` 0, the default) or the meter of the bus on that channel.
11
+ */
12
+ export function meterSeriesOfDsmr(readings, options = {}) {
13
+ const channel = options.channel ?? 0;
14
+ const skipped = [];
15
+ const out = new Map();
16
+ readings.forEach((reading, index) => {
17
+ const blocking = reading.problems.filter((p) => BLOCKING.has(p.code));
18
+ if (blocking.length > 0 || reading.at === null) {
19
+ skipped.push({ index, problems: blocking });
20
+ return;
21
+ }
22
+ for (const v of reading.values) {
23
+ if (v.channel !== channel)
24
+ continue;
25
+ const shape = shapeOf(v);
26
+ if (!shape)
27
+ continue;
28
+ const at = v.measure === 'volume' ? v.at : reading.at;
29
+ if (at === null)
30
+ continue;
31
+ const unit = v.unit ? UNITS[v.unit] ?? v.unit : undefined;
32
+ const key = `${shape.quantity_code} ${shape.name ?? ''} ${unit ?? ''}`;
33
+ let s = out.get(key);
34
+ if (!s) {
35
+ s = { ...shape, step: null, ...(unit ? { unit } : {}), values: [] };
36
+ out.set(key, s);
37
+ }
38
+ s.values.push({ at, value: v.value, quality: 0 });
39
+ }
40
+ });
41
+ const series = [...out.values()];
42
+ for (const s of series) {
43
+ // One value per instant, in time order: a meter of the bus repeats its
44
+ // last volume in every telegram until it sends a new one.
45
+ const seen = new Set();
46
+ s.values = s.values.sort((a, b) => a.at.localeCompare(b.at)).filter((p) => !seen.has(p.at) && seen.add(p.at));
47
+ }
48
+ return { series, skipped };
49
+ }
50
+ function shapeOf(v) {
51
+ if (v.measure === 'energy' && v.kind === 'cumulative' && v.direction) {
52
+ return { quantity_code: `${v.direction}_energy`, value_kind: 'cumulative', name: v.tariff ? `tariff ${v.tariff}` : null };
53
+ }
54
+ if (v.measure === 'power' && v.kind === 'instant' && v.direction) {
55
+ return { quantity_code: `${v.direction}_power`, value_kind: 'instant', name: v.phase };
56
+ }
57
+ if (v.measure === 'voltage' && v.kind === 'instant')
58
+ return { quantity_code: 'voltage', value_kind: 'instant', name: v.phase };
59
+ if (v.measure === 'volume' && v.kind === 'cumulative')
60
+ return { quantity_code: 'volume', value_kind: 'cumulative', name: null };
61
+ return null;
62
+ }
@@ -19,7 +19,7 @@
19
19
  * participant's country, which must be the bill's.
20
20
  */
21
21
  import { type EnergyBillReading } from '@nexgen-os/energy-bill';
22
- import type { Db } from '../db.js';
22
+ import { type Db } from '../db.js';
23
23
  /** The file of the bill: where it is kept and its checksum, `sha256:<hex>`. */
24
24
  export interface BillFile {
25
25
  name: string;
@@ -72,8 +72,9 @@ export declare function tariffOfBill(db: Db, request: {
72
72
  }): Promise<BillAttribute[]>;
73
73
  /**
74
74
  * The three gestures of the core in their order: the bill attached, its
75
- * meter found or declared, its contract priced. What `tariffOfBill()`
76
- * refuses is checked first. Returns what was written.
75
+ * meter found or declared, its contract priced, in one transaction (or
76
+ * under a savepoint of the caller's): a bill refused writes nothing. What
77
+ * `tariffOfBill()` refuses is checked first. Returns what was written.
77
78
  */
78
79
  export declare function importEnergyBill(db: Db, request: {
79
80
  participantId: string;
@@ -19,6 +19,7 @@
19
19
  * participant's country, which must be the bill's.
20
20
  */
21
21
  import { meanProjectedPrice } from '@nexgen-os/energy-bill';
22
+ import { atomically } from '../db.js';
22
23
  const CHECKSUM = /^sha256:[0-9a-f]{64}$/;
23
24
  /**
24
25
  * Attaches the bill to the participant, with its checksum and what the
@@ -132,14 +133,18 @@ export async function tariffOfBill(db, request) {
132
133
  }
133
134
  /**
134
135
  * The three gestures of the core in their order: the bill attached, its
135
- * meter found or declared, its contract priced. What `tariffOfBill()`
136
- * refuses is checked first. Returns what was written.
136
+ * meter found or declared, its contract priced, in one transaction (or
137
+ * under a savepoint of the caller's): a bill refused writes nothing. What
138
+ * `tariffOfBill()` refuses is checked first. Returns what was written.
137
139
  */
138
140
  export async function importEnergyBill(db, request) {
139
141
  // Checked before anything is written: a bill refused writes nothing.
140
142
  await placeOfBill(db, request.participantId, request.reading);
141
- const documentId = await attachBill(db, request.participantId, request.reading, request.file);
142
- const meter = request.reading.meter ? await meterOfBill(db, request.participantId, request.reading) : null;
143
- const attributes = await tariffOfBill(db, { participantId: request.participantId, meterId: meter?.meterId ?? null, reading: request.reading, documentId });
144
- return { documentId, meterId: meter?.meterId ?? null, meterFound: meter?.found ?? false, attributes };
143
+ // And one refused half way neither: its document would refuse it again as already imported.
144
+ return atomically(db, async () => {
145
+ const documentId = await attachBill(db, request.participantId, request.reading, request.file);
146
+ const meter = request.reading.meter ? await meterOfBill(db, request.participantId, request.reading) : null;
147
+ const attributes = await tariffOfBill(db, { participantId: request.participantId, meterId: meter?.meterId ?? null, reading: request.reading, documentId });
148
+ return { documentId, meterId: meter?.meterId ?? null, meterFound: meter?.found ?? false, attributes };
149
+ });
145
150
  }
@@ -0,0 +1,102 @@
1
+ /**
2
+ * The products evcc can drive, in the catalogue.
3
+ *
4
+ * `@nexgen-os/evcc` reads the templates of evcc; these functions turn the
5
+ * products they name into catalogue entries of the core
6
+ * ([0027](../../../../docs/decisions/0027-a-product-is-a-catalogue-entry.md)),
7
+ * each carrying, under `metadata.evcc`, the templates a device of that
8
+ * model can be driven through: the connector proposed when a device of the
9
+ * model is installed.
10
+ *
11
+ * - `catalogueOfEvcc()` the entries the templates give, and what they
12
+ * leave out and why, with no database;
13
+ * - `importEvccCatalogue()` the entries written, an entry the catalogue
14
+ * already holds gaining its templates.
15
+ *
16
+ * A template evcc drives only for its sponsors is left out: what it drives
17
+ * is not open to every installation.
18
+ */
19
+ import type { EvccTemplate } from '@nexgen-os/evcc';
20
+ import type { Db } from '../db.js';
21
+ /**
22
+ * Which device type of the core a template's products are, by class: for
23
+ * `charger`, by the template's group (`''` without one); for `meter`, by
24
+ * the first of the uses the template serves found in the table, in the
25
+ * table's order (`''` for a template that names no use). A class or a group
26
+ * absent from the table, or mapped to null, gives no catalogue entry.
27
+ */
28
+ export interface EvccDeviceTypes {
29
+ charger: Record<string, string | null>;
30
+ meter: Array<[usage: string, deviceType: string | null]>;
31
+ [evccClass: string]: Record<string, string | null> | Array<[string, string | null]>;
32
+ }
33
+ /**
34
+ * The device types evcc's templates are read as by default: a charging
35
+ * station; a heating template (heat pumps and heating rods) a heat pump; a
36
+ * switch socket a controller; a meter template serving `pv` an inverter
37
+ * (a hybrid inverter included), else `battery` a battery, else a meter.
38
+ * Vehicles are not devices of a place: no entry.
39
+ */
40
+ export declare const EVCC_DEVICE_TYPES: EvccDeviceTypes;
41
+ /** The device type of a template's products, or null when the table gives none. */
42
+ export declare function deviceTypeOfEvcc(template: EvccTemplate, table?: EvccDeviceTypes): string | null;
43
+ /** A template a device of a model can be driven through. */
44
+ export interface EvccConnectorOfProduct {
45
+ class: string;
46
+ template: string;
47
+ group: string | null;
48
+ capabilities: string[];
49
+ usages: string[];
50
+ discovery: EvccTemplate['discovery'];
51
+ }
52
+ /** A catalogue entry evcc's templates give. */
53
+ export interface EvccCatalogueEntry {
54
+ manufacturer: string;
55
+ model: string;
56
+ deviceType: string;
57
+ /** Every template naming this model, in the order read. */
58
+ connectors: EvccConnectorOfProduct[];
59
+ }
60
+ /** A product left out of the catalogue, and why. */
61
+ export interface EvccLeftOut {
62
+ template: string;
63
+ brand: string;
64
+ model: string | null;
65
+ reason: 'sponsored' | 'model_missing' | 'device_type_unknown';
66
+ }
67
+ /**
68
+ * The catalogue entries the templates give: one per manufacturer and
69
+ * model, the device type of the first template naming it, every template
70
+ * naming it as its connectors. Left out: the products of a sponsored
71
+ * template, a brand named without a model, a template the table gives no
72
+ * device type.
73
+ */
74
+ export declare function catalogueOfEvcc(templates: readonly EvccTemplate[], options?: {
75
+ deviceTypes?: EvccDeviceTypes;
76
+ }): {
77
+ entries: EvccCatalogueEntry[];
78
+ leftOut: EvccLeftOut[];
79
+ };
80
+ /** Where the templates were read from: the repository and the commit. */
81
+ export interface EvccRevision {
82
+ repository: string;
83
+ commit: string;
84
+ }
85
+ /**
86
+ * Writes the catalogue entries of the templates: an organisation's own
87
+ * (`organisationId`), or shared by every organisation (null, for whoever
88
+ * installs). An entry the catalogue already holds by manufacturer and
89
+ * model keeps its values and gains `metadata.evcc`, replaced as a whole at
90
+ * each import, so importing the same templates again changes nothing. A
91
+ * new entry is published by `evcc`. Every entry says the commit it was
92
+ * read at and evcc's licence.
93
+ */
94
+ export declare function importEvccCatalogue(db: Db, templates: readonly EvccTemplate[], options: {
95
+ organisationId: string | null;
96
+ revision: EvccRevision;
97
+ deviceTypes?: EvccDeviceTypes;
98
+ }): Promise<{
99
+ created: number;
100
+ updated: number;
101
+ leftOut: EvccLeftOut[];
102
+ }>;