@nexgen-os/core 0.4.2 → 0.6.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.
Files changed (49) hide show
  1. package/README.md +2 -2
  2. package/dist/address.d.ts +3 -62
  3. package/dist/connectors/activations.d.ts +63 -0
  4. package/dist/connectors/activations.js +73 -0
  5. package/dist/connectors/devices.d.ts +132 -0
  6. package/dist/connectors/devices.js +125 -0
  7. package/dist/connectors/interfaces.d.ts +2 -104
  8. package/dist/connectors/interfaces.js +4 -11
  9. package/dist/connectors/measured.d.ts +12 -0
  10. package/dist/connectors/measured.js +44 -0
  11. package/dist/connectors/meter-data.d.ts +2 -39
  12. package/dist/connectors/meter-data.js +3 -13
  13. package/dist/connectors/settlement.js +2 -2
  14. package/dist/db.d.ts +8 -0
  15. package/dist/db.js +32 -1
  16. package/dist/files/dsmr.d.ts +1 -0
  17. package/dist/files/dsmr.js +5 -0
  18. package/dist/files/enedis-r6x.d.ts +1 -32
  19. package/dist/files/enedis-r6x.js +5 -86
  20. package/dist/files/energy-bill.d.ts +4 -3
  21. package/dist/files/energy-bill.js +11 -6
  22. package/dist/files/evcc.d.ts +102 -0
  23. package/dist/files/evcc.js +76 -0
  24. package/dist/files/geojson.d.ts +41 -2
  25. package/dist/files/geojson.js +61 -1
  26. package/dist/files/index.d.ts +6 -0
  27. package/dist/files/index.js +6 -0
  28. package/dist/files/project-sheet.d.ts +44 -0
  29. package/dist/files/project-sheet.js +102 -0
  30. package/dist/files/project.d.ts +108 -0
  31. package/dist/files/project.js +104 -0
  32. package/dist/files/pvsol.d.ts +64 -0
  33. package/dist/files/pvsol.js +99 -0
  34. package/dist/files/weather-files.d.ts +3 -2
  35. package/dist/files/weather-files.js +11 -7
  36. package/dist/files/wesmart-db.d.ts +229 -0
  37. package/dist/files/wesmart-db.js +412 -0
  38. package/dist/gestures.d.ts +135 -0
  39. package/dist/gestures.js +99 -1
  40. package/dist/index.d.ts +4 -1
  41. package/dist/index.js +12 -0
  42. package/dist/refusal.d.ts +2 -11
  43. package/dist/refusal.js +5 -29
  44. package/dist/series.d.ts +11 -6
  45. package/dist/series.js +6 -1
  46. package/dist/time.d.ts +1 -6
  47. package/dist/time.js +4 -25
  48. package/package.json +13 -6
  49. package/schema/geojson-export.1.json +605 -0
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`), `planWesmartImport` with `importWesmartHistory` (the history of a WeSmart Database table to table: organisations, projects, participants with their place, the meter of `smart_meter_id`, the devices of each participant, found again on a second import by the `imported_row` identifier); 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
package/dist/address.d.ts CHANGED
@@ -1,64 +1,5 @@
1
- /** The postal address, in the fields every country has (schema.org PostalAddress). */
2
- export interface Address {
3
- /** Street and number, as the country writes them. */
4
- address_line1?: string | null;
5
- /** Building, floor, unit, box: the second line, when there is one. */
6
- address_line2?: string | null;
7
- postal_code?: string | null;
8
- city?: string | null;
9
- /** ISO 3166-2 subdivision when the geocoder knows it. */
10
- region?: string | null;
11
- /** The municipality in the country's own code (INSEE, NIS, CBS) when the geocoder gives it. */
12
- municipality_code?: string | null;
13
- /** ISO 3166-1 alpha-2, upper case. */
14
- country: string;
15
- }
16
- /** How close a point is to the real place. The values of `participants.location_precision`. */
17
- export type Precision = 'rooftop' | 'parcel' | 'street' | 'postal_code' | 'city' | 'region';
18
- /** One place a geocoder answered with. */
19
- export interface Place {
20
- address: Address;
21
- lon: number;
22
- lat: number;
23
- precision: Precision;
24
- /** The `sources.code` of the geocoder, so the participant says who placed it. */
25
- source_code: string;
26
- /** What the geocoder calls it, for a list of candidates. */
27
- label: string;
28
- /** The identifier the geocoder knows the place by, in an `identifier_schemes` scheme. */
29
- identifier?: {
30
- scheme: string;
31
- value: string;
32
- };
33
- }
34
- export interface SearchOptions {
35
- /** Restrict to one country, ISO 3166-1 alpha-2 (any case). */
36
- country?: string;
37
- /** Prefer places near this point. */
38
- near?: {
39
- lon: number;
40
- lat: number;
41
- };
42
- /** At most this many places; the adapter's default otherwise. */
43
- limit?: number;
44
- /** Language of the labels, BCP 47 (`fr`, `pt-BR`). */
45
- language?: string;
46
- }
47
- export interface Geocoder {
48
- readonly source_code: string;
49
- /** Places matching a typed address or name, best first. Empty when none. */
50
- search(text: string, options?: SearchOptions): Promise<Place[]>;
51
- /** The address at a point, or null when the geocoder has none there. */
52
- reverse(lon: number, lat: number, options?: Pick<SearchOptions, 'language'>): Promise<Place | null>;
53
- }
54
- /** The subset of `fetch` the adapters use, so a test or a proxy can stand in. */
55
- export type Fetch = (url: string, init?: {
56
- headers?: Record<string, string>;
57
- }) => Promise<{
58
- ok: boolean;
59
- status: number;
60
- json(): Promise<unknown>;
61
- }>;
1
+ import type { Address, Geocoder, Place } from '@nexgen-os/connector';
2
+ export type { Address, Fetch, Geocoder, Place, Precision, SearchOptions } from '@nexgen-os/connector';
62
3
  /**
63
4
  * The place columns of `participants` a place fills: the address, the
64
5
  * municipality in its country's own code, the point as GeoJSON, the
@@ -76,7 +17,7 @@ export declare function placeFields(place: Place): {
76
17
  readonly type: "Point";
77
18
  readonly coordinates: readonly [number, number, 0];
78
19
  };
79
- location_precision: Precision;
20
+ location_precision: import("@nexgen-os/connector").Precision;
80
21
  location_source_code: string;
81
22
  };
82
23
  /**
@@ -0,0 +1,63 @@
1
+ import type { Db } from '../db.js';
2
+ import { type DeviceOfSource } from './devices.js';
3
+ /** An activation as the platform that asked it gives it. */
4
+ export interface ReceivedActivation {
5
+ /** The device, by its identifier in the provider's scheme. */
6
+ identifier: string;
7
+ /** `up`: more injection or less offtake; `down`: the reverse, as the grid sees the device. */
8
+ direction: 'up' | 'down';
9
+ /** Its start and end, ISO 8601 with an offset. */
10
+ start_at: string;
11
+ end_at: string;
12
+ /** The power asked, kW, a change from the operating point of the device. */
13
+ requested_kw: number;
14
+ /** The platform's reference of the activation: an activation is kept once per device and reference. */
15
+ external_ref: string;
16
+ }
17
+ /**
18
+ * The activations a platform asked of the devices it is given, between
19
+ * `from` and `to` (ISO 8601 instants, `to` excluded).
20
+ * `collectActivations()` calls it and keeps what it returns.
21
+ */
22
+ export interface ActivationProvider {
23
+ readonly source_code: string;
24
+ /** The identifier scheme the platform names its devices by (`identifier_schemes.code`). */
25
+ readonly scheme: string;
26
+ /** The market role of who asks through this platform: `aggregator`, `grid_operator`, `energy_manager`… */
27
+ readonly role: string;
28
+ activations(devices: DeviceOfSource[], from: string, to: string): Promise<ReceivedActivation[]>;
29
+ }
30
+ export interface ActivationRequest {
31
+ /** The organisation's `connectors` row of the provider's source. */
32
+ connectorId: string;
33
+ /** The activations asked for, ISO 8601 instants, `to` excluded. */
34
+ from: string;
35
+ to: string;
36
+ }
37
+ export interface CollectedActivation {
38
+ external_ref: string;
39
+ identifier: string;
40
+ /** The device, when the identifier names one. */
41
+ device_id: string | null;
42
+ /** The activation kept, or the one kept before for the same device and reference. */
43
+ activation_id: string | null;
44
+ /** `kept`: a new activation and its proposed command; `already_received`: kept before; `refused`: nothing written. */
45
+ status: 'kept' | 'already_received' | 'refused';
46
+ /** Why it was refused, by name: `identifier_unknown`, `external_ref_required`, or what `flexibility.activate()` refuses. */
47
+ refusal: string | null;
48
+ }
49
+ /**
50
+ * Asks the platform of a connector for the activations of the flexible
51
+ * devices of its organisation that carry an identifier in the provider's
52
+ * scheme, and keeps each as an activation of the `flexibility` module with
53
+ * the provider's role and the platform's reference; its command is proposed
54
+ * (`source = 'detector'`) and waits for a person. An activation received
55
+ * again — same device, same reference — is not kept twice. One that names
56
+ * an unknown identifier, has no reference or is refused by
57
+ * `flexibility.activate()` writes nothing and says why, the others are kept.
58
+ * Refuses `module_not_installed` without the `flexibility` module,
59
+ * `connector_not_found`, `connector_source_mismatch`.
60
+ */
61
+ export declare function collectActivations(db: Db, provider: ActivationProvider, request: ActivationRequest): Promise<{
62
+ received: CollectedActivation[];
63
+ }>;
@@ -0,0 +1,73 @@
1
+ // An aggregator connector: the activations an aggregator, a grid operator or
2
+ // an energy manager asked of the flexible devices it knows, kept as
3
+ // activations of the `flexibility` module (decision 0058).
4
+ //
5
+ // The platform knows a device by an identifier in its scheme, the
6
+ // `identifiers` row of the device, as a device connector does (decision
7
+ // 0061). A device is declared to the platform by that identifier and by
8
+ // its row in `flexibility.devices`, which says what it can be asked; nothing
9
+ // else is declared. `collectActivations()` is the one path from what the
10
+ // platform asked to the database: each activation goes through
11
+ // `flexibility.activate()`, checked against what the device declares and
12
+ // carried out as a proposed command of the `actions` module, which a person
13
+ // validates. What the device delivered is never sent back from here: it is
14
+ // read from the series of its meter.
15
+ import { GestureError } from '../refusal.js';
16
+ import { connectorOf } from './devices.js';
17
+ /**
18
+ * Asks the platform of a connector for the activations of the flexible
19
+ * devices of its organisation that carry an identifier in the provider's
20
+ * scheme, and keeps each as an activation of the `flexibility` module with
21
+ * the provider's role and the platform's reference; its command is proposed
22
+ * (`source = 'detector'`) and waits for a person. An activation received
23
+ * again — same device, same reference — is not kept twice. One that names
24
+ * an unknown identifier, has no reference or is refused by
25
+ * `flexibility.activate()` writes nothing and says why, the others are kept.
26
+ * Refuses `module_not_installed` without the `flexibility` module,
27
+ * `connector_not_found`, `connector_source_mismatch`.
28
+ */
29
+ export async function collectActivations(db, provider, request) {
30
+ const installed = (await db.query(`select to_regclass('flexibility.activations') is not null ok`)).rows[0].ok;
31
+ if (!installed)
32
+ throw new GestureError('module_not_installed: an activation is kept by the flexibility module, which is not installed');
33
+ const connector = await connectorOf(db, request.connectorId, provider.source_code);
34
+ const devices = (await db.query(`select distinct on (d.id) d.id, d.device_type, i.value identifier
35
+ from flexibility.devices f
36
+ join devices d on d.id = f.id
37
+ join identifiers i on i.object_kind = 'device' and i.object_id = d.id and i.scheme = $2
38
+ where d.organisation_id = $1
39
+ and (i.valid_from is null or i.valid_from <= now()) and (i.valid_to is null or i.valid_to > now())
40
+ order by d.id, i.valid_from desc nulls last`, [connector.organisation_id, provider.scheme])).rows;
41
+ if (devices.length === 0)
42
+ return { received: [] };
43
+ const byIdentifier = new Map(devices.map((d) => [d.identifier, d.id]));
44
+ const asked = await provider.activations(devices.map((d) => ({ identifier: d.identifier, scheme: provider.scheme, device_type: d.device_type })), request.from, request.to);
45
+ const received = [];
46
+ for (const activation of asked) {
47
+ const deviceId = byIdentifier.get(activation.identifier) ?? null;
48
+ const base = { external_ref: activation.external_ref, identifier: activation.identifier, device_id: deviceId };
49
+ if (!deviceId) {
50
+ received.push({ ...base, activation_id: null, status: 'refused', refusal: 'identifier_unknown' });
51
+ continue;
52
+ }
53
+ if (!activation.external_ref?.trim()) {
54
+ received.push({ ...base, activation_id: null, status: 'refused', refusal: 'external_ref_required' });
55
+ continue;
56
+ }
57
+ const before = (await db.query(`select id from flexibility.activations where device_id = $1 and external_ref = $2 order by created_at limit 1`, [deviceId, activation.external_ref])).rows[0];
58
+ if (before) {
59
+ received.push({ ...base, activation_id: before.id, status: 'already_received', refusal: null });
60
+ continue;
61
+ }
62
+ try {
63
+ const { id } = (await db.query(`select flexibility.activate($1, $2, $3::timestamptz, $4::timestamptz, $5, null, $6, $7, 'detector') id`, [deviceId, activation.direction, activation.start_at, activation.end_at, activation.requested_kw,
64
+ provider.role, activation.external_ref])).rows[0];
65
+ received.push({ ...base, activation_id: id, status: 'kept', refusal: null });
66
+ }
67
+ catch (error) {
68
+ const message = error instanceof Error ? error.message : String(error);
69
+ received.push({ ...base, activation_id: null, status: 'refused', refusal: message.split(':')[0].trim() });
70
+ }
71
+ }
72
+ return { received };
73
+ }
@@ -0,0 +1,132 @@
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
+ interface ConnectorRow {
64
+ organisation_id: string;
65
+ source_code: string;
66
+ }
67
+ /** The organisation's `connectors` row, checked against the source a connector reads. Refuses `connector_not_found`, `connector_source_mismatch`. */
68
+ export declare function connectorOf(db: Db, connectorId: string, sourceCode: string): Promise<ConnectorRow>;
69
+ /**
70
+ * The device as a platform knows it: its type and its identifier in the
71
+ * scheme, of the connector's organisation. Refuses `device_not_found`,
72
+ * `device_in_other_organisation`, `identifier_missing`.
73
+ */
74
+ export declare function deviceOfSource(db: Db, deviceId: string, scheme: string, organisationId: string): Promise<DeviceOfSource>;
75
+ export interface DeviceReadingRequest {
76
+ /** The organisation's `connectors` row of the provider's source. */
77
+ connectorId: string;
78
+ deviceId: string;
79
+ /** The readings asked for, `YYYY-MM-DD`, `to` excluded. */
80
+ from: string;
81
+ to: string;
82
+ step?: string;
83
+ quantities?: string[];
84
+ }
85
+ /**
86
+ * Reads a device through a connector and keeps what it brought as the
87
+ * measured series of the device, each carrying the connector's source. The
88
+ * device is found by its identifier in the provider's scheme; nothing is
89
+ * written when the connector, the device or its identifier is refused.
90
+ */
91
+ export declare function collectDeviceReadings(db: Db, provider: DeviceReadingsProvider, request: DeviceReadingRequest): Promise<{
92
+ stored: {
93
+ quantity_code: string;
94
+ seriesId: string;
95
+ inserted: number;
96
+ }[];
97
+ }>;
98
+ /** `actions.report()`: acknowledged, the command is done and its value stored in its series; with a failure, it failed and says why. */
99
+ export declare const reportCommand: CommandReport;
100
+ export interface CarryRequest {
101
+ /** The organisation's `connectors` row of the carrier's source: the commands that name it are carried. */
102
+ connectorId: string;
103
+ /** Carries the validated commands due at this instant or before (ISO 8601); now when absent. */
104
+ until?: string;
105
+ /**
106
+ * How an answer is recorded: `actions.report()` by default. A module that
107
+ * keeps more of a command than its value — the schedule of a charging
108
+ * profile — passes its own report, which calls `actions.report()`.
109
+ */
110
+ report?: CommandReport;
111
+ }
112
+ export interface CarriedCommand {
113
+ id: string;
114
+ device_id: string;
115
+ status: 'done' | 'failed';
116
+ acknowledged_at: string | null;
117
+ failure: string | null;
118
+ }
119
+ /**
120
+ * Carries out the validated commands of a connector that are due, the
121
+ * earliest first, and reports each answer: acknowledged, the command is done
122
+ * and its value lands in its series; refused, not acknowledged, or a carrier
123
+ * that threw, it failed with why, writes nothing and can be proposed again
124
+ * (`actions.move(action, 'proposed')`). A command whose device has no
125
+ * identifier in the carrier's scheme fails with `identifier_missing`.
126
+ * Refuses `module_not_installed` without the `actions` module,
127
+ * `connector_not_found`, `connector_source_mismatch`.
128
+ */
129
+ export declare function carryCommands(db: Db, carrier: CommandCarrier, request: CarryRequest): Promise<{
130
+ carried: CarriedCommand[];
131
+ }>;
132
+ export {};
@@ -0,0 +1,125 @@
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
+ /** The organisation's `connectors` row, checked against the source a connector reads. Refuses `connector_not_found`, `connector_source_mismatch`. */
22
+ export async function connectorOf(db, connectorId, sourceCode) {
23
+ const connector = (await db.query(`select organisation_id, source_code from connectors where id = $1`, [connectorId])).rows[0];
24
+ if (!connector)
25
+ throw new GestureError(`connector_not_found: ${connectorId}`);
26
+ if (connector.source_code !== sourceCode) {
27
+ throw new GestureError(`connector_source_mismatch: connector ${connectorId} reads ${connector.source_code}, not ${sourceCode}`);
28
+ }
29
+ return connector;
30
+ }
31
+ /**
32
+ * The device as a platform knows it: its type and its identifier in the
33
+ * scheme, of the connector's organisation. Refuses `device_not_found`,
34
+ * `device_in_other_organisation`, `identifier_missing`.
35
+ */
36
+ export async function deviceOfSource(db, deviceId, scheme, organisationId) {
37
+ const device = (await db.query(`select organisation_id, device_type from devices where id = $1`, [deviceId])).rows[0];
38
+ if (!device)
39
+ throw new GestureError(`device_not_found: ${deviceId}`);
40
+ if (device.organisation_id !== organisationId) {
41
+ throw new GestureError(`device_in_other_organisation: device ${deviceId} is not of the connector's organisation`);
42
+ }
43
+ const identifier = (await db.query(`select value from identifiers
44
+ where object_kind = 'device' and object_id = $1 and scheme = $2
45
+ and (valid_from is null or valid_from <= now()) and (valid_to is null or valid_to > now())
46
+ order by valid_from desc nulls last limit 1`, [deviceId, scheme])).rows[0];
47
+ if (!identifier)
48
+ throw new GestureError(`identifier_missing: device ${deviceId} has no ${scheme} identifier`);
49
+ return { identifier: identifier.value, scheme, device_type: device.device_type };
50
+ }
51
+ /**
52
+ * Reads a device through a connector and keeps what it brought as the
53
+ * measured series of the device, each carrying the connector's source. The
54
+ * device is found by its identifier in the provider's scheme; nothing is
55
+ * written when the connector, the device or its identifier is refused.
56
+ */
57
+ export async function collectDeviceReadings(db, provider, request) {
58
+ const connector = await connectorOf(db, request.connectorId, provider.source_code);
59
+ const device = await deviceOfSource(db, request.deviceId, provider.scheme, connector.organisation_id);
60
+ const collected = await provider.readings(device, request.from, request.to, {
61
+ ...(request.step ? { step: request.step } : {}), ...(request.quantities ? { quantities: request.quantities } : {}),
62
+ });
63
+ const stored = [];
64
+ for (const series of collected) {
65
+ const { seriesId, inserted } = await storeSeries(db, {
66
+ organisationId: connector.organisation_id, objectKind: 'device', objectId: request.deviceId,
67
+ sourceCode: provider.source_code, kind: 'measured',
68
+ }, series);
69
+ stored.push({ quantity_code: series.quantity_code, seriesId, inserted });
70
+ }
71
+ return { stored };
72
+ }
73
+ /** `actions.report()`: acknowledged, the command is done and its value stored in its series; with a failure, it failed and says why. */
74
+ export const reportCommand = async (db, actionId, at, failure) => {
75
+ await db.query(`select actions.report($1, $2::timestamptz, $3)`, [actionId, at, failure]);
76
+ };
77
+ /**
78
+ * Carries out the validated commands of a connector that are due, the
79
+ * earliest first, and reports each answer: acknowledged, the command is done
80
+ * and its value lands in its series; refused, not acknowledged, or a carrier
81
+ * that threw, it failed with why, writes nothing and can be proposed again
82
+ * (`actions.move(action, 'proposed')`). A command whose device has no
83
+ * identifier in the carrier's scheme fails with `identifier_missing`.
84
+ * Refuses `module_not_installed` without the `actions` module,
85
+ * `connector_not_found`, `connector_source_mismatch`.
86
+ */
87
+ export async function carryCommands(db, carrier, request) {
88
+ const installed = (await db.query(`select to_regclass('actions.actions') is not null ok`)).rows[0].ok;
89
+ if (!installed)
90
+ throw new GestureError('module_not_installed: commands are actions of the actions module, which is not installed');
91
+ const connector = await connectorOf(db, request.connectorId, carrier.source_code);
92
+ const report = request.report ?? reportCommand;
93
+ 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,
94
+ to_char(a.due_at at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') due_at
95
+ from actions.actions a
96
+ join series s on s.id = a.series_id
97
+ join quantities q on q.code = s.quantity_code
98
+ where a.kind = 'command' and a.status = 'validated' and a.connector_id = $1
99
+ and a.due_at <= coalesce($2::timestamptz, now())
100
+ order by a.due_at, a.id`, [request.connectorId, request.until ?? null])).rows;
101
+ const carried = [];
102
+ for (const command of due) {
103
+ let answer;
104
+ try {
105
+ const device = await deviceOfSource(db, command.device_id, carrier.scheme, connector.organisation_id);
106
+ answer = await carrier.carry({
107
+ id: command.id, device, quantity_code: command.quantity_code, series_kind: command.series_kind,
108
+ series_name: command.series_name, value: Number(command.value), unit: command.unit, due_at: command.due_at,
109
+ });
110
+ }
111
+ catch (error) {
112
+ answer = { failure: error instanceof Error ? error.message : String(error) };
113
+ }
114
+ if ('acknowledged_at' in answer) {
115
+ await report(db, command.id, answer.acknowledged_at, null);
116
+ carried.push({ id: command.id, device_id: command.device_id, status: 'done', acknowledged_at: answer.acknowledged_at, failure: null });
117
+ }
118
+ else {
119
+ const failure = answer.failure.trim() || 'not acknowledged';
120
+ await report(db, command.id, new Date().toISOString(), failure);
121
+ carried.push({ id: command.id, device_id: command.device_id, status: 'failed', acknowledged_at: null, failure });
122
+ }
123
+ }
124
+ return { carried };
125
+ }
@@ -1,86 +1,6 @@
1
1
  import type { Db } from '../db.js';
2
- import type { Address } from '../address.js';
3
- import { type SeriesPoint } from '../series.js';
4
- import type { MandateScope, MeterDataHub, MeterMandate } from './meter-data.js';
5
- export interface Point {
6
- lon: number;
7
- lat: number;
8
- }
9
- /** What a connector brings back for one quantity: ready for `storeSeries()`. */
10
- export interface CollectedSeries {
11
- quantity_code: string;
12
- /** What one value means: `interval` from `at` for one `step`, `instant` at `at`, `cumulative` register. */
13
- value_kind: 'interval' | 'instant' | 'cumulative';
14
- /** A Postgres interval (`1 hour`, `15 minutes`), null when irregular. */
15
- step: string | null;
16
- /** The unit the values are in, by QUDT code or symbol (`Wh`, `°C`); the quantity's own when absent. `store()` converts. */
17
- unit?: string;
18
- /** Tells apart two series of one object and quantity the connector brings at once (the dials of an index); the target's name otherwise. */
19
- name?: string | null;
20
- values: SeriesPoint[];
21
- }
22
- /** Weather observed or forecast at a point: a model, a station, an API. */
23
- export interface WeatherProvider {
24
- readonly source_code: string;
25
- /** The forecast from now on, at the hourly step the model gives, with the time it was issued. */
26
- forecast(where: Point, options?: {
27
- hours?: number;
28
- quantities?: string[];
29
- }): Promise<{
30
- issued_at: string;
31
- series: CollectedSeries[];
32
- }>;
33
- /**
34
- * Past weather, when the source has it (an archive, a reanalysis), for the
35
- * days `from` to `to` included (`YYYY-MM-DD`, UTC). Irradiance on a plane
36
- * (`poa_irradiance`) needs the plane: `tilt_deg` from horizontal and
37
- * `azimuth_deg` clockwise from true north. `model` names one of the
38
- * source's datasets (a reanalysis, a station network) when it has several.
39
- */
40
- history?(where: Point, from: string, to: string, options?: {
41
- quantities?: string[];
42
- tilt_deg?: number;
43
- azimuth_deg?: number;
44
- model?: string;
45
- }): Promise<CollectedSeries[]>;
46
- }
47
- /**
48
- * The core's azimuth (degrees clockwise from true north) counted from south,
49
- * west positive, in (-180, 180]: the convention of PVGIS (`aspect`),
50
- * Open-Meteo (`azimuth`) and PVsyst.
51
- */
52
- export declare function azimuthFromSouth(azimuthDeg: number): number;
53
- /** A meter as its operator's hub knows it: its identifier in a scheme, and what it can do. */
54
- export interface MeterOfHub {
55
- identifier: string;
56
- scheme: string;
57
- /** Take from the grid, inject into it, or both (`meters.direction`). */
58
- direction?: 'offtake' | 'injection' | 'both';
59
- }
60
- /** What a reading of a meter is given beside the meter and the period. */
61
- export interface MeterReadingOptions {
62
- /** The step asked, an ISO 8601 duration (`PT30M`); the hub's own when absent. */
63
- step?: string;
64
- /** What is read; `load_curve` by default. */
65
- scope?: MandateScope;
66
- /**
67
- * The mandate `grid.authorise_reading()` returned: a connector whose
68
- * source reads under mandate refuses without it (`requireMandate()`).
69
- */
70
- mandate?: MeterMandate | null;
71
- /** The conventions of the operator's hub, from its pack row: its time zone and its quality flags. */
72
- hub?: MeterDataHub;
73
- }
74
- /**
75
- * Readings of a meter from the grid operator's hub or a data hub, by its
76
- * identifier and scheme, from `from` to `to` (`YYYY-MM-DD`, `to` excluded).
77
- * `collectMeterReadings()` checks the mandate, calls it and stores what it
78
- * returns on the meter.
79
- */
80
- export interface MeterDataProvider {
81
- readonly source_code: string;
82
- readings(meter: MeterOfHub, from: string, to: string, options?: MeterReadingOptions): Promise<CollectedSeries[]>;
83
- }
2
+ export { azimuthFromSouth, type ChargerReading, type ChargingSessionRecord, type CollectedSeries, type MeterDataProvider, type MeterOfHub, type MeterReadingOptions, type Point, type SourceRow, type WeatherProvider, } from '@nexgen-os/connector';
3
+ import type { Address, CollectedSeries, Point, SourceRow } from '@nexgen-os/connector';
84
4
  /** A place a register or a map knows: becomes a participant or a building, with its identifiers and attributes. */
85
5
  export interface PlaceRecord {
86
6
  name: string;
@@ -132,28 +52,6 @@ export declare function storeSeries(db: Db, target: SeriesTarget, series: Collec
132
52
  seriesId: string;
133
53
  inserted: number;
134
54
  }>;
135
- /**
136
- * A `sources` row as a connector package ships it (decision 0011): what
137
- * exists outside, who serves it, its licence and how long what it gives may
138
- * be kept. The countries a source serves are data of its row, never code.
139
- */
140
- export interface SourceRow {
141
- code: string;
142
- name: string;
143
- description?: string | null;
144
- kind?: 'api' | 'file' | 'registry' | 'device' | 'manual' | 'text';
145
- base_url?: string | null;
146
- docs_url?: string | null;
147
- auth?: 'none' | 'api_key' | 'oauth2' | 'certificate' | 'mandate';
148
- countries?: string[];
149
- regions?: string[];
150
- license?: string | null;
151
- attribution?: string | null;
152
- retention_days?: number | null;
153
- redistributable?: boolean;
154
- /** The package that brings it, `@nexgen-os/<name>`. */
155
- published_by: string;
156
- }
157
55
  /**
158
56
  * Writes the `sources` row a connector package ships, once: inserted, or
159
57
  * updated where that package published it; a row another publisher owns is
@@ -15,17 +15,10 @@
15
15
  // own data service). A private package implements the same interface and
16
16
  // registers its `sources` rows; the core and the pages never import it.
17
17
  import { store } from '../series.js';
18
- /**
19
- * The core's azimuth (degrees clockwise from true north) counted from south,
20
- * west positive, in (-180, 180]: the convention of PVGIS (`aspect`),
21
- * Open-Meteo (`azimuth`) and PVsyst.
22
- */
23
- export function azimuthFromSouth(azimuthDeg) {
24
- let a = ((azimuthDeg - 180) % 360 + 360) % 360;
25
- if (a > 180)
26
- a -= 360;
27
- return a === -0 ? 0 : a;
28
- }
18
+ // What a connector speaks lives in `@nexgen-os/connector`, MIT, so
19
+ // that a connector runs without the core (decision 0064); the core
20
+ // re-exports it, one definition for both.
21
+ export { azimuthFromSouth, } from '@nexgen-os/connector';
29
22
  /**
30
23
  * Writes what a connector brought back through `store()`, the one write
31
24
  * path: the series of that object, quantity, kind, source and name, found or created once (a different value kind or step is refused
@@ -0,0 +1,12 @@
1
+ import type { MeasuredObjects } from '@nexgen-os/connector';
2
+ import type { Db } from '../db.js';
3
+ export type { MeasuredFound, MeasuredObjects, MeasuredTarget } from '@nexgen-os/connector';
4
+ /**
5
+ * The meters and devices of an installation, as a stream of readings asks
6
+ * for them: by an identifier valid now, refused by name when it names none
7
+ * (`identifier_unknown`), objects in more than one organisation
8
+ * (`identifier_ambiguous`), something else than a meter or a device
9
+ * (`object_not_measured`), or an object whose participant has no time zone
10
+ * (`time_zone_required`); written as `measured` series of that object.
11
+ */
12
+ export declare function measuredObjects(db: Db): MeasuredObjects;