@camstack/addon-provider-enpal 0.1.1 → 0.1.3

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/dist/addon.mjs CHANGED
@@ -10469,20 +10469,6 @@ object({
10469
10469
  code: string().regex(/^[a-z][a-z0-9-]*(\.[a-z0-9-]+)+$/),
10470
10470
  params: record(string(), union([string(), number()])).optional()
10471
10471
  });
10472
- var CamstackError = class extends Error {
10473
- i18nCode;
10474
- i18nParams;
10475
- constructor(code, params, englishMessage) {
10476
- super(englishMessage);
10477
- this.name = "CamstackError";
10478
- this.i18nCode = code;
10479
- this.i18nParams = params;
10480
- }
10481
- };
10482
- /** `throw userError('device.not-found', { id }, 'Device 12 not found')` */
10483
- function userError(code, params, englishFallback) {
10484
- return new CamstackError(code, params, englishFallback);
10485
- }
10486
10472
  //#endregion
10487
10473
  //#region ../types/dist/err-msg-DIorGYeC.mjs
10488
10474
  var DeviceType = /* @__PURE__ */ function(DeviceType) {
@@ -21032,19 +21018,36 @@ var ResyncResultSchema = object({
21032
21018
  * provider re-derived the device. 0/absent for a normal incremental re-sync. */
21033
21019
  removedChildren: number().int().nonnegative().optional()
21034
21020
  });
21035
- method(object({ integrationId: string() }), object({ filters: array(AdoptionFilterSchema) }), { auth: "admin" }), method(ListCandidatesInputSchema, ListCandidatesOutputSchema, { auth: "admin" }), method(GetCandidateInputSchema, DiscoveredChildDeviceSchema.nullable(), { auth: "admin" }), method(object({ integrationId: string() }), AdoptionStatusSchema, {
21036
- kind: "mutation",
21037
- auth: "admin"
21038
- }), method(AdoptInputSchema, AdoptResultSchema, {
21039
- kind: "mutation",
21040
- auth: "admin"
21041
- }), method(ReleaseInputSchema, _void(), {
21042
- kind: "mutation",
21043
- auth: "admin"
21044
- }), method(ResyncInputSchema, ResyncResultSchema, {
21045
- kind: "mutation",
21046
- auth: "admin"
21047
- });
21021
+ var deviceAdoptionCapability = {
21022
+ name: "device-adoption",
21023
+ scope: "system",
21024
+ mode: "collection",
21025
+ status: {
21026
+ schema: AdoptionStatusSchema,
21027
+ kind: "poll"
21028
+ },
21029
+ methods: {
21030
+ listCandidateFilters: method(object({ integrationId: string() }), object({ filters: array(AdoptionFilterSchema) }), { auth: "admin" }),
21031
+ listCandidates: method(ListCandidatesInputSchema, ListCandidatesOutputSchema, { auth: "admin" }),
21032
+ getCandidate: method(GetCandidateInputSchema, DiscoveredChildDeviceSchema.nullable(), { auth: "admin" }),
21033
+ refresh: method(object({ integrationId: string() }), AdoptionStatusSchema, {
21034
+ kind: "mutation",
21035
+ auth: "admin"
21036
+ }),
21037
+ adopt: method(AdoptInputSchema, AdoptResultSchema, {
21038
+ kind: "mutation",
21039
+ auth: "admin"
21040
+ }),
21041
+ release: method(ReleaseInputSchema, _void(), {
21042
+ kind: "mutation",
21043
+ auth: "admin"
21044
+ }),
21045
+ resync: method(ResyncInputSchema, ResyncResultSchema, {
21046
+ kind: "mutation",
21047
+ auth: "admin"
21048
+ })
21049
+ }
21050
+ };
21048
21051
  /**
21049
21052
  * `device-export` — collection cap for addons that export camstack
21050
21053
  * devices to external ecosystems (HomeAssistant via MQTT discovery,
@@ -44106,7 +44109,7 @@ var NetworkAccessStatusSchema = object({
44106
44109
  });
44107
44110
  /**
44108
44111
  * Optional, richer endpoint shape returned by providers that expose
44109
- * MORE than one ingress concurrently (Tailscale Ingress with mixed
44112
+ * MORE than one ingress concurrently (Tailscale Funnel with mixed
44110
44113
  * serve+funnel rules, future ngrok multi-tunnel, …). Each entry carries
44111
44114
  * the originating provider config (mode + sourcePort) so the
44112
44115
  * orchestrator UI can label rows distinctly. Providers that expose only
@@ -57526,7 +57529,8 @@ var BATTERY_DEVICE_TYPES = [
57526
57529
  DeviceType.Switch,
57527
57530
  DeviceType.PetFeeder,
57528
57531
  DeviceType.Container,
57529
- DeviceType.Thermostat
57532
+ DeviceType.Thermostat,
57533
+ DeviceType.EventEmitter
57530
57534
  ];
57531
57535
  /** Generic Customize target for the percentage reading (D936). */
57532
57536
  var batteryCustomize = {
@@ -64360,9 +64364,9 @@ var PowerMeterStatusSchema = object({
64360
64364
  /** Cumulative energy in kilowatt-hours since the meter was reset. */
64361
64365
  kwhTotal: number().optional().meta(readingMeta("energy", { label: "Energy" })),
64362
64366
  /** Voltage in volts. */
64363
- volts: number().optional().meta(readingMeta("voltage")),
64367
+ volts: number().optional().meta(readingMeta("voltage", { label: "Voltage" })),
64364
64368
  /** Current in amperes. */
64365
- amps: number().optional().meta(readingMeta("current")),
64369
+ amps: number().optional().meta(readingMeta("current", { label: "Current" })),
64366
64370
  /** Apparent power in volt-amperes. */
64367
64371
  va: number().optional().meta(readingMeta("apparent-power")),
64368
64372
  /** Power factor (0..1) if reported. */
@@ -64370,17 +64374,74 @@ var PowerMeterStatusSchema = object({
64370
64374
  /** Ms epoch when the slice was last updated. */
64371
64375
  lastFetchedAt: number()
64372
64376
  });
64377
+ /**
64378
+ * Loads that draw metered mains power (D951). The reading is a feature of the
64379
+ * device itself — a plug, a lamp, a fan, an air conditioner, a boiler, a
64380
+ * vacuum dock — not a separate sensor beside it. A `Sensor` stays: a clamp
64381
+ * meter or a standalone energy monitor IS the device. Cover, lock, valve,
64382
+ * camera and the like are left out: their draw is not what anyone meters.
64383
+ */
64384
+ var POWER_METER_DEVICE_TYPES = [
64385
+ DeviceType.Sensor,
64386
+ DeviceType.Switch,
64387
+ DeviceType.Light,
64388
+ DeviceType.Fan,
64389
+ DeviceType.Climate,
64390
+ DeviceType.Thermostat,
64391
+ DeviceType.Humidifier,
64392
+ DeviceType.WaterHeater,
64393
+ DeviceType.MediaPlayer,
64394
+ DeviceType.Washer,
64395
+ DeviceType.Dryer,
64396
+ DeviceType.Dishwasher,
64397
+ DeviceType.Vacuum,
64398
+ DeviceType.LawnMower,
64399
+ DeviceType.PetFeeder
64400
+ ];
64401
+ /** Everything but a bare `Sensor`: a sensor that takes its reading from another sensor adds nothing. */
64402
+ var POWER_METER_CUSTOMIZE_DEVICE_TYPES = POWER_METER_DEVICE_TYPES.filter((type) => type !== DeviceType.Sensor);
64403
+ /** One scalar target per reading; each is sourced from a device of its own (D951). */
64404
+ function powerTarget(id, unit) {
64405
+ return {
64406
+ id,
64407
+ cardinality: "scalar",
64408
+ vocabulary: {
64409
+ cap: "power-meter",
64410
+ stateField: id
64411
+ },
64412
+ deviceTypes: POWER_METER_CUSTOMIZE_DEVICE_TYPES,
64413
+ apply: "add",
64414
+ path: id,
64415
+ sources: [{
64416
+ kind: "numeric",
64417
+ requiredUnit: unit,
64418
+ transforms: [{ kind: "identity" }]
64419
+ }],
64420
+ companions: [{
64421
+ kind: "clock",
64422
+ path: "lastFetchedAt",
64423
+ when: "always"
64424
+ }],
64425
+ sourceReport: { status: "assignment-status" },
64426
+ advancedExpression: true
64427
+ };
64428
+ }
64429
+ /** "Power and energy" extension: watts, energy, voltage and current from other devices (D951). */
64430
+ var powerMeterCustomize = {
64431
+ version: 1,
64432
+ targets: [
64433
+ powerTarget("watts", "W"),
64434
+ powerTarget("kwhTotal", "kWh"),
64435
+ powerTarget("volts", "V"),
64436
+ powerTarget("amps", "A")
64437
+ ]
64438
+ };
64373
64439
  var powerMeterCapability = {
64374
64440
  name: "power-meter",
64375
64441
  scope: "device",
64376
64442
  deviceNative: true,
64377
64443
  mode: "singleton",
64378
- deviceTypes: [
64379
- DeviceType.Sensor,
64380
- DeviceType.Washer,
64381
- DeviceType.Dryer,
64382
- DeviceType.Dishwasher
64383
- ],
64444
+ deviceTypes: POWER_METER_DEVICE_TYPES,
64384
64445
  methods: {},
64385
64446
  status: {
64386
64447
  schema: PowerMeterStatusSchema,
@@ -64437,7 +64498,8 @@ var powerMeterCapability = {
64437
64498
  } },
64438
64499
  /** Clock fields: written, but excluded from the compare that decides
64439
64500
  * whether persisting is worth a SQLite commit. */
64440
- volatileStateFields: ["lastFetchedAt"]
64501
+ volatileStateFields: ["lastFetchedAt"],
64502
+ customize: powerMeterCustomize
64441
64503
  };
64442
64504
  /**
64443
64505
  * Presence cap. Models HA `person.*` and `device_tracker.*` entities
@@ -70208,7 +70270,7 @@ function tryConvertUnit(value, from, to) {
70208
70270
  return fromCanonical(toCanonical(value, fromSpec), toSpec);
70209
70271
  }
70210
70272
  SOURCE_CAPS.filter((cap) => cap !== "switch" && cap !== "motion");
70211
- DeviceType.Camera, DeviceType.Sensor, DeviceType.Button, DeviceType.Switch, DeviceType.PetFeeder, DeviceType.Container, DeviceType.Thermostat, DeviceType.Camera, DeviceType.Hub, DeviceType.Light, DeviceType.Siren, DeviceType.Switch, DeviceType.Sensor, DeviceType.Thermostat, DeviceType.Climate, DeviceType.Button, DeviceType.EventEmitter, DeviceType.Update, DeviceType.Generic, DeviceType.Notifier, DeviceType.Script, DeviceType.Automation, DeviceType.Lock, DeviceType.Cover, DeviceType.Valve, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.Fan, DeviceType.MediaPlayer, DeviceType.AlarmPanel, DeviceType.Control, DeviceType.Presence, DeviceType.Weather, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.Container, DeviceType.Image, DeviceType.PetFeeder, DeviceType.Dishwasher, DeviceType.Washer, DeviceType.Dryer, DeviceType.Camera, DeviceType.Camera, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.MediaPlayer, DeviceType.WaterHeater, DeviceType.Humidifier, DeviceType.Fan, DeviceType.Climate, DeviceType.Thermostat, DeviceType.PetFeeder;
70273
+ DeviceType.Camera, DeviceType.Sensor, DeviceType.Button, DeviceType.Switch, DeviceType.PetFeeder, DeviceType.Container, DeviceType.Thermostat, DeviceType.EventEmitter, DeviceType.Camera, DeviceType.Hub, DeviceType.Light, DeviceType.Siren, DeviceType.Switch, DeviceType.Sensor, DeviceType.Thermostat, DeviceType.Climate, DeviceType.Button, DeviceType.EventEmitter, DeviceType.Update, DeviceType.Generic, DeviceType.Notifier, DeviceType.Script, DeviceType.Automation, DeviceType.Lock, DeviceType.Cover, DeviceType.Valve, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.Fan, DeviceType.MediaPlayer, DeviceType.AlarmPanel, DeviceType.Control, DeviceType.Presence, DeviceType.Weather, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.Container, DeviceType.Image, DeviceType.PetFeeder, DeviceType.Dishwasher, DeviceType.Washer, DeviceType.Dryer, DeviceType.Camera, DeviceType.Camera, DeviceType.Switch, DeviceType.Light, DeviceType.Fan, DeviceType.Climate, DeviceType.Thermostat, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.MediaPlayer, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.PetFeeder, DeviceType.Switch, DeviceType.Light, DeviceType.Fan, DeviceType.Climate, DeviceType.Thermostat, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.MediaPlayer, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.PetFeeder, DeviceType.Switch, DeviceType.Light, DeviceType.Fan, DeviceType.Climate, DeviceType.Thermostat, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.MediaPlayer, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.PetFeeder, DeviceType.Switch, DeviceType.Light, DeviceType.Fan, DeviceType.Climate, DeviceType.Thermostat, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.MediaPlayer, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.PetFeeder, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.MediaPlayer, DeviceType.WaterHeater, DeviceType.Humidifier, DeviceType.Fan, DeviceType.Climate, DeviceType.Thermostat, DeviceType.PetFeeder;
70212
70274
  String.raw`rose\(active(\d+), changed(\d+), (\d+(?:\.\d+)?)\)`;
70213
70275
  DeviceRole.BinarySensor, DeviceRole.MotionSensor;
70214
70276
  new Set(CAP_NAMES);
@@ -89642,9 +89704,9 @@ var MB = 1024 * 1024;
89642
89704
  //#endregion
89643
89705
  //#region src/config.ts
89644
89706
  /**
89645
- * Operator-supplied connection for ONE Enpal box. The addon runs in `standalone`
89646
- * mode (the VeSync / Ecowitt / Velux pattern): the CONNECTION lives on the box
89647
- * DEVICE config, there is no broker registry.
89707
+ * Operator-supplied connection of ONE Enpal integration (`mode: account`, broker-less): the
89708
+ * settings of the integration itself, not of a device. Every equipment the box reports is
89709
+ * adopted as a Container from it.
89648
89710
  *
89649
89711
  * Two sources behind `source`:
89650
89712
  * - `influx`: the box's InfluxDB 2.x (port 8086, org `enpal`, bucket `solar`).
@@ -89665,6 +89727,10 @@ function markerToEmpty(value) {
89665
89727
  return value === null || value === void 0 ? "" : value;
89666
89728
  }
89667
89729
  var blankToUndefined = (v) => v === "" || v === null ? void 0 : v;
89730
+ /** Names that are interpolated into a Flux string: no quote, no space, no operator. */
89731
+ var FLUX_NAME = /^[A-Za-z0-9_.-]+$/;
89732
+ /** The device-registry `system` tag every Enpal device carries. */
89733
+ var ENPAL_SYSTEM = "enpal";
89668
89734
  var enpalConnectionSchema = object({
89669
89735
  host: preprocess(cleanHost, string().min(1).regex(/^[A-Za-z0-9._-]+$/, "host name or IP address only").describe("Enpal box host name or IP address")),
89670
89736
  source: _enum([
@@ -89674,7 +89740,7 @@ var enpalConnectionSchema = object({
89674
89740
  ]).default("auto").describe("Where the readings come from"),
89675
89741
  influxPort: preprocess(blankToUndefined, number().int().min(1).max(65535).default(8086)).describe("InfluxDB port"),
89676
89742
  org: string().trim().min(1).default("enpal").describe("InfluxDB organisation"),
89677
- bucket: string().trim().regex(/^[A-Za-z0-9_.-]+$/, "letters, digits, dot, dash and underscore only").default("solar").describe("InfluxDB bucket"),
89743
+ bucket: string().trim().regex(FLUX_NAME, "letters, digits, dot, dash and underscore only").default("solar").describe("InfluxDB bucket"),
89678
89744
  token: preprocess(markerToEmpty, string().default("")).describe("InfluxDB access token (issued by Enpal support)").meta({ secret: true }),
89679
89745
  pagePort: preprocess(blankToUndefined, number().int().min(1).max(65535).default(80)).describe("Device page HTTP port"),
89680
89746
  pollIntervalMs: preprocess(blankToUndefined, number().int().min(1e4).max(36e5).default(3e4)).describe("Poll interval (ms)"),
@@ -89697,30 +89763,21 @@ function readConnection(settings) {
89697
89763
  tokenLocked: isSecretMarkerLike(raw["token"])
89698
89764
  };
89699
89765
  }
89700
- /** Persisted config for the Enpal box {@link import('@camstack/types').DeviceType.Hub} device. */
89701
- var enpalBoxSchema = object({
89702
- connection: enpalConnectionSchema,
89703
- /** Provenance marker used to scope offline / cascade helpers. */
89704
- system: literal("enpal-box").optional()
89705
- });
89706
- /**
89707
- * Persisted config every adopted Enpal device carries. `specId` selects the entry of the
89708
- * device catalog (PV, battery, grid import, ...); `boxId` selects the parent box (its Hub
89709
- * `stableId`) in the in-process resolver.
89710
- */
89711
- var enpalSensorSchema = object({
89712
- specId: string().min(1).describe("Device catalog entry id"),
89713
- boxId: string().min(1).describe("Parent box stableId"),
89714
- system: literal("enpal").optional()
89715
- });
89716
- /** Slugify a host into a readable, stable row-key fragment. */
89717
- function slugifyHost(value) {
89718
- return value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
89766
+ /** Parse an integration's settings into a connection, or null while its host is missing. */
89767
+ function connectionFromSettings(settings) {
89768
+ const raw = toRecord(settings);
89769
+ const parsed = enpalConnectionSchema.safeParse(raw);
89770
+ if (!parsed.success) return null;
89771
+ return {
89772
+ connection: parsed.data,
89773
+ tokenLocked: isSecretMarkerLike(raw["token"])
89774
+ };
89719
89775
  }
89720
- /**
89721
- * Hand-written connection form for the box device-creation UI. The connection lives on the box
89722
- * DEVICE config; a `name` field lets the operator name it at creation time.
89723
- */
89776
+ /** True when two connections would poll the box the same way. */
89777
+ function sameConnection(a, b) {
89778
+ return JSON.stringify(a) === JSON.stringify(b);
89779
+ }
89780
+ /** The integration's settings form (`globalSettingsSchema`); the integration carries the name. */
89724
89781
  function buildConnectionFormSchema() {
89725
89782
  return { sections: [
89726
89783
  {
@@ -89729,13 +89786,6 @@ function buildConnectionFormSchema() {
89729
89786
  titleKey: "provider-enpal:connection.s_identity.title",
89730
89787
  columns: 1,
89731
89788
  fields: [{
89732
- type: "text",
89733
- key: "name",
89734
- label: "Name",
89735
- labelKey: "provider-enpal:connection.s_identity.name.label",
89736
- required: true,
89737
- placeholder: "Enpal"
89738
- }, {
89739
89789
  type: "text",
89740
89790
  key: "host",
89741
89791
  label: "Box host / IP",
@@ -89890,7 +89940,7 @@ var ENPAL_SPECS = [
89890
89940
  {
89891
89941
  kind: "power-meter",
89892
89942
  id: "pv",
89893
- name: "PV production",
89943
+ name: "Production",
89894
89944
  role: DeviceRole.PowerSensor,
89895
89945
  watts: point("power", "Power.DC.Total", "Power.DC.Total.Calculated", "Power.DC.Total.Huawei", "Power.Production.Total"),
89896
89946
  kwh: point("energy", "Energy.Production.Total.Lifetime")
@@ -89909,7 +89959,7 @@ var ENPAL_SPECS = [
89909
89959
  {
89910
89960
  kind: "meter",
89911
89961
  id: "battery-charged",
89912
- name: "Battery energy charged",
89962
+ name: "Energy charged",
89913
89963
  role: DeviceRole.EnergySensor,
89914
89964
  quantity: "energy",
89915
89965
  value: point("energy", "Energy.Battery.Charge.Lifetime")
@@ -89917,7 +89967,7 @@ var ENPAL_SPECS = [
89917
89967
  {
89918
89968
  kind: "meter",
89919
89969
  id: "battery-discharged",
89920
- name: "Battery energy discharged",
89970
+ name: "Energy discharged",
89921
89971
  role: DeviceRole.EnergySensor,
89922
89972
  quantity: "energy",
89923
89973
  value: point("energy", "Energy.Battery.Discharge.Lifetime")
@@ -89925,7 +89975,7 @@ var ENPAL_SPECS = [
89925
89975
  {
89926
89976
  kind: "power-meter",
89927
89977
  id: "grid-import",
89928
- name: "Grid import",
89978
+ name: "Import",
89929
89979
  role: DeviceRole.PowerSensor,
89930
89980
  watts: point("power", "Grid.Import.Power.Total.Calculated", {
89931
89981
  key: "Power.Grid.Export",
@@ -89942,7 +89992,7 @@ var ENPAL_SPECS = [
89942
89992
  {
89943
89993
  kind: "power-meter",
89944
89994
  id: "grid-export",
89945
- name: "Grid export",
89995
+ name: "Export",
89946
89996
  role: DeviceRole.PowerSensor,
89947
89997
  watts: point("power", {
89948
89998
  key: "Power.Grid.Export",
@@ -89959,7 +90009,7 @@ var ENPAL_SPECS = [
89959
90009
  {
89960
90010
  kind: "power-meter",
89961
90011
  id: "house",
89962
- name: "House consumption",
90012
+ name: "Consumption",
89963
90013
  role: DeviceRole.PowerSensor,
89964
90014
  watts: point("power", "Power.Consumption.Total", "Power.Consumption.AC"),
89965
90015
  kwh: point("energy", "Energy.Consumption.Total.Lifetime")
@@ -89967,7 +90017,7 @@ var ENPAL_SPECS = [
89967
90017
  {
89968
90018
  kind: "power-meter",
89969
90019
  id: "heatpump",
89970
- name: "Heat pump",
90020
+ name: "Consumption",
89971
90021
  role: DeviceRole.PowerSensor,
89972
90022
  watts: point("power", "Heatpump.Power.Consumption.Total"),
89973
90023
  kwh: point("energy", "Heatpump.Energy.Consumption.Total.Lifetime")
@@ -89975,7 +90025,7 @@ var ENPAL_SPECS = [
89975
90025
  {
89976
90026
  kind: "numeric",
89977
90027
  id: "heatpump-hot-water",
89978
- name: "Heat pump hot water",
90028
+ name: "Hot water temperature",
89979
90029
  role: DeviceRole.TemperatureSensor,
89980
90030
  quantity: "temperature",
89981
90031
  value: point("temperature", "Heatpump.DomesticHotWater.Temperature")
@@ -89983,7 +90033,7 @@ var ENPAL_SPECS = [
89983
90033
  {
89984
90034
  kind: "numeric",
89985
90035
  id: "heatpump-outside",
89986
- name: "Heat pump outside temperature",
90036
+ name: "Outside temperature",
89987
90037
  role: DeviceRole.TemperatureSensor,
89988
90038
  quantity: "temperature",
89989
90039
  value: point("temperature", "Heatpump.Outside.Temperature")
@@ -89999,7 +90049,7 @@ var ENPAL_SPECS = [
89999
90049
  {
90000
90050
  kind: "numeric",
90001
90051
  id: "battery-temperature",
90002
- name: "Battery temperature",
90052
+ name: "Temperature",
90003
90053
  role: DeviceRole.TemperatureSensor,
90004
90054
  quantity: "temperature",
90005
90055
  value: point("temperature", "Temperature.Battery")
@@ -90007,7 +90057,7 @@ var ENPAL_SPECS = [
90007
90057
  {
90008
90058
  kind: "numeric",
90009
90059
  id: "battery-health",
90010
- name: "Battery health",
90060
+ name: "Health",
90011
90061
  role: DeviceRole.NumericSensor,
90012
90062
  quantity: "percentage",
90013
90063
  value: point("percentage", "Battery.SOH")
@@ -90164,36 +90214,528 @@ function computeSlices(spec, snapshot, options, now) {
90164
90214
  }
90165
90215
  }
90166
90216
  //#endregion
90167
- //#region src/enpal-discovery.ts
90168
- /** The `childNativeId` of a catalog entry on a box: namespaced so two boxes never collide. */
90169
- function specNativeId(boxId, specId) {
90170
- return `${boxId}:${specId}`;
90217
+ //#region src/enpal-counter-guard.ts
90218
+ /**
90219
+ * Smaller than the history deadband of the lifetime counters (0.01 kWh): float noise from
90220
+ * rounding or a unit conversion, never a real drop.
90221
+ */
90222
+ var NOISE = .01;
90223
+ /**
90224
+ * Keeps a lifetime counter monotonic before it reaches a `counter` history series, where a
90225
+ * drop means "the meter was reset" and re-bases every later total.
90226
+ *
90227
+ * The box occasionally reports 0 or a stale lower figure for one poll (a restart, a partly
90228
+ * written window). One such reading is held back: the previous value is published instead.
90229
+ * A lower reading that is then followed by a value at or above it is a genuine reset or a
90230
+ * replaced meter, and is accepted.
90231
+ */
90232
+ var LifetimeCounterGuard = class {
90233
+ #published = null;
90234
+ #suspect = null;
90235
+ /** The value to publish for the reading `next`. */
90236
+ accept(next) {
90237
+ const published = this.#published;
90238
+ if (published === null || next >= published - NOISE) {
90239
+ this.#published = next;
90240
+ this.#suspect = null;
90241
+ return next;
90242
+ }
90243
+ const suspect = this.#suspect;
90244
+ if (suspect !== null && next >= suspect - NOISE) {
90245
+ this.#published = next;
90246
+ this.#suspect = null;
90247
+ return next;
90248
+ }
90249
+ this.#suspect = next;
90250
+ return published;
90251
+ }
90252
+ };
90253
+ //#endregion
90254
+ //#region src/enpal-resolver.ts
90255
+ /**
90256
+ * Per-integration registry that the adopted devices use to reach the live
90257
+ * {@link EnpalIntegrationManager}. Keyed on the integration id; the client registry publishes
90258
+ * a new manager here whenever the connection changes, and the sensors read through the
90259
+ * resolver so they follow it.
90260
+ */
90261
+ var EnpalConnectionResolver = class {
90262
+ #managers = /* @__PURE__ */ new Map();
90263
+ #subs = /* @__PURE__ */ new Map();
90264
+ set(integrationId, manager) {
90265
+ if (manager === null) {
90266
+ this.#managers.delete(integrationId);
90267
+ return;
90268
+ }
90269
+ this.#managers.set(integrationId, manager);
90270
+ }
90271
+ getManager(integrationId) {
90272
+ return this.#managers.get(integrationId) ?? null;
90273
+ }
90274
+ /** The latest snapshot, or null when the box is unreachable (never stale readings). */
90275
+ getSnapshot(integrationId) {
90276
+ return this.#managers.get(integrationId)?.getSnapshot() ?? null;
90277
+ }
90278
+ /** Subscribe to poll ticks (successful or not). Returns an unsubscribe function. */
90279
+ onSnapshot(integrationId, cb) {
90280
+ let set = this.#subs.get(integrationId);
90281
+ if (set === void 0) {
90282
+ set = /* @__PURE__ */ new Set();
90283
+ this.#subs.set(integrationId, set);
90284
+ }
90285
+ set.add(cb);
90286
+ return () => {
90287
+ const current = this.#subs.get(integrationId);
90288
+ current?.delete(cb);
90289
+ if (current !== void 0 && current.size === 0) this.#subs.delete(integrationId);
90290
+ };
90291
+ }
90292
+ emitSnapshot(integrationId) {
90293
+ const set = this.#subs.get(integrationId);
90294
+ if (set === void 0) return;
90295
+ for (const cb of set) try {
90296
+ cb();
90297
+ } catch {}
90298
+ }
90299
+ clear() {
90300
+ this.#managers.clear();
90301
+ this.#subs.clear();
90302
+ }
90303
+ };
90304
+ var enpalConnections = new EnpalConnectionResolver();
90305
+ //#endregion
90306
+ //#region src/devices/enpal-sensor-device.ts
90307
+ var POWER_CAP = powerMeterCapability.name;
90308
+ var BATTERY_CAP = batteryCapability.name;
90309
+ var METER_CAP = meterCapability.name;
90310
+ var NUMERIC_CAP = numericSensorCapability.name;
90311
+ var POWER_COLD = { lastFetchedAt: 0 };
90312
+ var BATTERY_COLD = {
90313
+ percentage: null,
90314
+ charging: "unknown",
90315
+ sleeping: false,
90316
+ lastUpdated: 0
90317
+ };
90318
+ var VALUE_COLD = {
90319
+ value: null,
90320
+ lastFetchedAt: 0
90321
+ };
90322
+ /**
90323
+ * Persisted config of an Enpal Sensor. `specId` selects the entry of the catalog;
90324
+ * `integrationId` selects the integration whose box feeds it.
90325
+ */
90326
+ var enpalSensorSchema = object({
90327
+ specId: string().min(1).describe("Device catalog entry id"),
90328
+ integrationId: string().min(1).describe("Owning integration"),
90329
+ system: literal(ENPAL_SYSTEM).optional()
90330
+ });
90331
+ /**
90332
+ * One Enpal data point group (production, state of charge, grid import, ...) as a
90333
+ * {@link DeviceType.Sensor} child of an equipment Container. The catalog entry in `specId`
90334
+ * says which caps it registers and which box keys feed them; the slices are recomputed from
90335
+ * the integration's snapshot on every poll tick.
90336
+ *
90337
+ * An unreachable box marks the device offline and leaves the slices alone: a failed read is
90338
+ * a gap, never a zero (D393). A lifetime counter passes through {@link LifetimeCounterGuard}
90339
+ * so one stale low reading cannot become a history reset.
90340
+ */
90341
+ var EnpalSensorDevice = class extends BaseDevice {
90342
+ features = [];
90343
+ spec;
90344
+ integrationId;
90345
+ energyGuard = new LifetimeCounterGuard();
90346
+ meterGuard = new LifetimeCounterGuard();
90347
+ snapshotUnsub = null;
90348
+ constructor(ctx) {
90349
+ const cfg = enpalSensorSchema.parse(ctx.persistedConfig ?? {});
90350
+ super(ctx, enpalSensorSchema, { type: ctx.deviceMeta.type });
90351
+ const spec = findSpec(cfg.specId);
90352
+ if (spec === void 0) throw new Error(`Enpal: unknown device kind "${cfg.specId}"`);
90353
+ this.spec = spec;
90354
+ this.integrationId = cfg.integrationId;
90355
+ this.online = enpalConnections.getSnapshot(this.integrationId) !== null;
90356
+ this.updateSourceInfo({
90357
+ id: `${this.integrationId}:${spec.id}`,
90358
+ system: ENPAL_SYSTEM,
90359
+ ...spec.kind === "meter" || spec.kind === "numeric" ? { quantity: spec.quantity } : {}
90360
+ });
90361
+ }
90362
+ async onActivate() {
90363
+ await super.onActivate();
90364
+ this.registerCaps();
90365
+ this.snapshotUnsub = enpalConnections.onSnapshot(this.integrationId, () => {
90366
+ try {
90367
+ this.recompute();
90368
+ } catch (err) {
90369
+ this.ctx.logger.warn("enpal sensor: snapshot handler failed", {
90370
+ tags: { deviceId: this.id },
90371
+ meta: {
90372
+ spec: this.spec.id,
90373
+ error: errMsg(err)
90374
+ }
90375
+ });
90376
+ }
90377
+ });
90378
+ this.recompute();
90379
+ }
90380
+ async removeDevice() {
90381
+ this.snapshotUnsub?.();
90382
+ this.snapshotUnsub = null;
90383
+ await super.removeDevice();
90384
+ }
90385
+ recompute() {
90386
+ const snapshot = enpalConnections.getSnapshot(this.integrationId);
90387
+ if (snapshot === null) {
90388
+ if (this.online) this.markOnline(false);
90389
+ return;
90390
+ }
90391
+ if (!this.online) this.markOnline(true);
90392
+ const invert = enpalConnections.getManager(this.integrationId)?.connection.invertBatteryPower ?? false;
90393
+ const slices = computeSlices(this.spec, snapshot, { invertBatteryPower: invert }, snapshot.fetchedAt);
90394
+ this.publish(slices);
90395
+ for (const line of slices.refusals) this.ctx.logger.warn(`enpal sensor: reading not used, ${line}`, {
90396
+ tags: { deviceId: this.id },
90397
+ meta: { spec: this.spec.id }
90398
+ });
90399
+ }
90400
+ publish(slices) {
90401
+ if (slices.powerMeter !== void 0) {
90402
+ const kwh = slices.powerMeter.kwhTotal;
90403
+ this.runtimeState.setCapState(POWER_CAP, kwh === void 0 ? slices.powerMeter : {
90404
+ ...slices.powerMeter,
90405
+ kwhTotal: this.energyGuard.accept(kwh)
90406
+ });
90407
+ }
90408
+ if (slices.battery !== void 0) this.runtimeState.setCapState(BATTERY_CAP, slices.battery);
90409
+ if (slices.meter !== void 0) {
90410
+ const raw = slices.meter.value;
90411
+ this.runtimeState.setCapState(METER_CAP, {
90412
+ ...slices.meter,
90413
+ value: raw === null ? null : this.meterGuard.accept(raw)
90414
+ });
90415
+ }
90416
+ if (slices.numeric !== void 0) this.runtimeState.setCapState(NUMERIC_CAP, slices.numeric);
90417
+ }
90418
+ registerCaps() {
90419
+ switch (this.spec.kind) {
90420
+ case "power-meter":
90421
+ this.registerPowerMeter();
90422
+ return;
90423
+ case "battery":
90424
+ this.registerBattery();
90425
+ this.registerPowerMeter();
90426
+ return;
90427
+ case "meter":
90428
+ this.ctx.registerNativeCap(meterCapability, { getStatus: async () => this.runtimeState.getCapState(METER_CAP) ?? VALUE_COLD });
90429
+ this.runtimeState.setCapState(METER_CAP, VALUE_COLD);
90430
+ return;
90431
+ case "numeric":
90432
+ this.ctx.registerNativeCap(numericSensorCapability, { getStatus: async () => this.runtimeState.getCapState(NUMERIC_CAP) ?? VALUE_COLD });
90433
+ this.runtimeState.setCapState(NUMERIC_CAP, VALUE_COLD);
90434
+ return;
90435
+ }
90436
+ }
90437
+ registerPowerMeter() {
90438
+ this.ctx.registerNativeCap(powerMeterCapability, { getStatus: async () => this.runtimeState.getCapState(POWER_CAP) ?? POWER_COLD });
90439
+ this.runtimeState.setCapState(POWER_CAP, POWER_COLD);
90440
+ }
90441
+ registerBattery() {
90442
+ this.ctx.registerNativeCap(batteryCapability, {
90443
+ getStatus: async () => this.runtimeState.getCapState(BATTERY_CAP) ?? BATTERY_COLD,
90444
+ wakeForStream: async () => ({
90445
+ awoke: false,
90446
+ durationMs: 0
90447
+ })
90448
+ });
90449
+ this.runtimeState.setCapState(BATTERY_CAP, BATTERY_COLD);
90450
+ }
90451
+ };
90452
+ //#endregion
90453
+ //#region src/devices/enpal-sensor-factory.ts
90454
+ /** Constructor closure the kernel calls for every Sensor child of an equipment Container. */
90455
+ function enpalSensorFactory(ctx) {
90456
+ return new EnpalSensorDevice(ctx);
90171
90457
  }
90172
- /** The catalog entry id of a {@link specNativeId} value, or null. */
90173
- function parseSpecNativeId(boxId, childNativeId) {
90174
- const prefix = `${boxId}:`;
90175
- if (!childNativeId.startsWith(prefix)) return null;
90176
- const id = childNativeId.slice(prefix.length);
90177
- return id.length > 0 ? id : null;
90458
+ //#endregion
90459
+ //#region src/enpal-equipment.ts
90460
+ /** Order is the order the candidates are listed in. Every catalog entry belongs to one. */
90461
+ var ENPAL_EQUIPMENT = [
90462
+ {
90463
+ id: "pv",
90464
+ name: "Photovoltaic",
90465
+ specIds: ["pv", "inverter-temperature"]
90466
+ },
90467
+ {
90468
+ id: "battery",
90469
+ name: "Battery",
90470
+ specIds: [
90471
+ "battery",
90472
+ "battery-charged",
90473
+ "battery-discharged",
90474
+ "battery-temperature",
90475
+ "battery-health"
90476
+ ]
90477
+ },
90478
+ {
90479
+ id: "grid",
90480
+ name: "Grid",
90481
+ specIds: ["grid-import", "grid-export"]
90482
+ },
90483
+ {
90484
+ id: "house",
90485
+ name: "House",
90486
+ specIds: ["house"]
90487
+ },
90488
+ {
90489
+ id: "heatpump",
90490
+ name: "Heat pump",
90491
+ specIds: [
90492
+ "heatpump",
90493
+ "heatpump-hot-water",
90494
+ "heatpump-outside"
90495
+ ]
90496
+ }
90497
+ ];
90498
+ function findEquipment(id) {
90499
+ return ENPAL_EQUIPMENT.find((e) => e.id === id);
90178
90500
  }
90179
- /** One Sensor candidate per data group the box reported. Pure. */
90180
- function buildCandidates(input) {
90181
- return input.specs.map((spec) => {
90182
- const adoptedDeviceId = input.adoptedDeviceIdBySpec[spec.id] ?? null;
90183
- return {
90184
- childNativeId: specNativeId(input.boxId, spec.id),
90185
- name: `${input.boxName} ${spec.name}`,
90186
- type: DeviceType.Sensor,
90187
- status: input.online ? "online" : "offline",
90188
- metadata: {
90189
- manufacturer: "Enpal",
90190
- integration: "enpal"
90501
+ /** The `childNativeId` of a child candidate: namespaced by its container. */
90502
+ function childNativeId(equipmentId, specId) {
90503
+ return `${equipmentId}#${specId}`;
90504
+ }
90505
+ /**
90506
+ * Persisted config of an equipment Container. `specIds` are the children it was adopted with:
90507
+ * they stay, whatever the box reports later, so a restart with the box off keeps them.
90508
+ */
90509
+ var enpalEquipmentSchema = object({
90510
+ equipment: string().min(1).describe("Equipment id (pv, battery, grid, house, heatpump)"),
90511
+ specIds: array(string().min(1)).describe("Catalog entries adopted as children"),
90512
+ integrationId: string().min(1).describe("Owning integration"),
90513
+ system: literal(ENPAL_SYSTEM).optional()
90514
+ });
90515
+ /** The Sensor children the kernel spawns under an equipment Container. */
90516
+ function accessoryChildSpecs(config) {
90517
+ const out = [];
90518
+ for (const specId of config.specIds) {
90519
+ const spec = findSpec(specId);
90520
+ if (spec === void 0) continue;
90521
+ out.push({
90522
+ stableIdSuffix: spec.id,
90523
+ meta: {
90524
+ type: DeviceType.Sensor,
90525
+ name: spec.name,
90526
+ role: spec.role,
90527
+ integrationId: config.integrationId
90528
+ },
90529
+ config: {
90530
+ specId: spec.id,
90531
+ integrationId: config.integrationId,
90532
+ system: ENPAL_SYSTEM
90191
90533
  },
90192
- alreadyAdopted: adoptedDeviceId !== null,
90193
- adoptedDeviceId,
90194
- capabilities: capsOfSpec(spec)
90534
+ factory: enpalSensorFactory
90535
+ });
90536
+ }
90537
+ return out;
90538
+ }
90539
+ //#endregion
90540
+ //#region src/devices/enpal-equipment-device.ts
90541
+ /**
90542
+ * One physical piece of the installation (photovoltaic, battery, grid, house, heat pump) as a
90543
+ * {@link DeviceType.Container}. It owns no caps: it declares the Sensor children it was
90544
+ * adopted with, and the kernel spawns and restores them. Online follows the integration's
90545
+ * box; the integration marks it offline when a poll fails.
90546
+ */
90547
+ var EnpalEquipmentDevice = class extends BaseDevice {
90548
+ features = [];
90549
+ equipment;
90550
+ specIds;
90551
+ integrationId;
90552
+ constructor(ctx) {
90553
+ const cfg = enpalEquipmentSchema.parse(ctx.persistedConfig ?? {});
90554
+ super(ctx, enpalEquipmentSchema, { type: DeviceType.Container });
90555
+ this.equipment = cfg.equipment;
90556
+ this.specIds = cfg.specIds;
90557
+ this.integrationId = cfg.integrationId;
90558
+ this.online = enpalConnections.getSnapshot(this.integrationId) !== null;
90559
+ this.updateSourceInfo({
90560
+ id: `${this.integrationId}:${this.equipment}`,
90561
+ system: ENPAL_SYSTEM
90562
+ });
90563
+ }
90564
+ getAccessoryChildren() {
90565
+ return accessoryChildSpecs({
90566
+ equipment: this.equipment,
90567
+ specIds: this.specIds,
90568
+ integrationId: this.integrationId
90569
+ });
90570
+ }
90571
+ };
90572
+ //#endregion
90573
+ //#region src/enpal-discovery.ts
90574
+ var METADATA = {
90575
+ manufacturer: "Enpal",
90576
+ integration: "enpal"
90577
+ };
90578
+ /**
90579
+ * One Container candidate per equipment the box reported at least one value for, with the
90580
+ * Sensor children it reported. Pure.
90581
+ */
90582
+ function buildEnpalCandidates(input) {
90583
+ const { snapshot } = input;
90584
+ if (snapshot === null) return [];
90585
+ const reported = new Map(availableSpecs(snapshot).map((spec) => [spec.id, spec]));
90586
+ const out = [];
90587
+ for (const equipment of ENPAL_EQUIPMENT) {
90588
+ const specs = equipment.specIds.flatMap((id) => reported.get(id) ?? []);
90589
+ if (specs.length === 0) continue;
90590
+ const adoptedId = input.adopted.get(equipment.id) ?? null;
90591
+ out.push({
90592
+ childNativeId: equipment.id,
90593
+ name: equipment.name,
90594
+ type: DeviceType.Container,
90595
+ status: "online",
90596
+ metadata: METADATA,
90597
+ alreadyAdopted: adoptedId !== null,
90598
+ adoptedDeviceId: adoptedId,
90599
+ capabilities: [],
90600
+ children: specs.map((spec) => ({
90601
+ childNativeId: childNativeId(equipment.id, spec.id),
90602
+ name: spec.name,
90603
+ type: DeviceType.Sensor,
90604
+ status: "online",
90605
+ metadata: METADATA,
90606
+ alreadyAdopted: false,
90607
+ adoptedDeviceId: null,
90608
+ capabilities: capsOfSpec(spec)
90609
+ }))
90610
+ });
90611
+ }
90612
+ return out;
90613
+ }
90614
+ //#endregion
90615
+ //#region src/enpal-adoption-provider.ts
90616
+ var DEVICES_FILTER = {
90617
+ id: "devices",
90618
+ label: "Devices",
90619
+ isDefault: true
90620
+ };
90621
+ function buildEnpalAdoptionProvider(deps) {
90622
+ const { getSnapshot, hasIntegration, listIntegrations, listAdopted, logger } = deps;
90623
+ async function adoptedMap(integrationId) {
90624
+ const map = /* @__PURE__ */ new Map();
90625
+ for (const device of await listAdopted()) {
90626
+ const cfg = device.config;
90627
+ if (cfg["system"] !== "enpal" || cfg["integrationId"] !== integrationId) continue;
90628
+ const equipment = cfg["equipment"];
90629
+ if (typeof equipment === "string") map.set(equipment, device.id);
90630
+ }
90631
+ return map;
90632
+ }
90633
+ async function candidates(integrationId) {
90634
+ return buildEnpalCandidates({
90635
+ snapshot: getSnapshot(integrationId),
90636
+ adopted: await adoptedMap(integrationId)
90637
+ });
90638
+ }
90639
+ async function status(integrationId) {
90640
+ return {
90641
+ lastDiscoveryAt: Date.now(),
90642
+ candidateCount: (await candidates(integrationId)).length,
90643
+ adoptedCount: (await adoptedMap(integrationId)).size,
90644
+ lastError: null
90195
90645
  };
90196
- });
90646
+ }
90647
+ return {
90648
+ listCandidateFilters: async () => ({ filters: [DEVICES_FILTER] }),
90649
+ listCandidates: async ({ integrationId, page, pageSize }) => {
90650
+ const all = await candidates(integrationId);
90651
+ const start = (page - 1) * pageSize;
90652
+ return {
90653
+ candidates: all.slice(start, start + pageSize),
90654
+ totalCount: all.length,
90655
+ page,
90656
+ pageSize
90657
+ };
90658
+ },
90659
+ getCandidate: async ({ integrationId, childNativeId }) => {
90660
+ return (await candidates(integrationId)).find((c) => c.childNativeId === childNativeId) ?? null;
90661
+ },
90662
+ getStatus: async () => {
90663
+ try {
90664
+ let candidateCount = 0;
90665
+ let adoptedCount = 0;
90666
+ for (const integrationId of listIntegrations()) {
90667
+ const s = await status(integrationId);
90668
+ candidateCount += s.candidateCount;
90669
+ adoptedCount += s.adoptedCount;
90670
+ }
90671
+ return {
90672
+ lastDiscoveryAt: Date.now(),
90673
+ candidateCount,
90674
+ adoptedCount,
90675
+ lastError: null
90676
+ };
90677
+ } catch (err) {
90678
+ return {
90679
+ lastDiscoveryAt: null,
90680
+ candidateCount: 0,
90681
+ adoptedCount: 0,
90682
+ lastError: errMsg(err)
90683
+ };
90684
+ }
90685
+ },
90686
+ refresh: async ({ integrationId }) => status(integrationId),
90687
+ adopt: async ({ integrationId, childNativeIds, perCandidate }) => {
90688
+ if (!hasIntegration(integrationId)) throw new Error(`enpal adopt: integration ${integrationId} not found`);
90689
+ const offered = await candidates(integrationId);
90690
+ const adopted = [];
90691
+ let failures = 0;
90692
+ for (const equipmentId of childNativeIds) try {
90693
+ const candidate = offered.find((c) => c.childNativeId === equipmentId);
90694
+ const equipment = findEquipment(equipmentId);
90695
+ if (candidate === void 0 || equipment === void 0) {
90696
+ logger.warn("enpal adopt: the box reports nothing for this equipment — skipping", { meta: {
90697
+ equipment: equipmentId,
90698
+ integrationId
90699
+ } });
90700
+ failures++;
90701
+ continue;
90702
+ }
90703
+ const reported = new Set((candidate.children ?? []).map((c) => c.childNativeId));
90704
+ const specIds = equipment.specIds.filter((id) => reported.has(`${equipment.id}#${id}`));
90705
+ const { deviceId, accessoryDeviceIds } = await deps.adoptDevice({
90706
+ equipment: equipment.id,
90707
+ specIds,
90708
+ integrationId,
90709
+ name: perCandidate?.[equipmentId]?.name ?? equipment.name
90710
+ });
90711
+ adopted.push({
90712
+ childNativeId: equipmentId,
90713
+ parentDeviceId: deviceId,
90714
+ accessoryDeviceIds
90715
+ });
90716
+ } catch (err) {
90717
+ logger.warn("enpal adopt: failed to adopt equipment", { meta: {
90718
+ equipment: equipmentId,
90719
+ integrationId,
90720
+ error: errMsg(err)
90721
+ } });
90722
+ failures++;
90723
+ }
90724
+ if (adopted.length === 0 && failures > 0) throw new Error(`enpal adopt: all ${failures} adopt(s) failed`);
90725
+ return { adopted };
90726
+ },
90727
+ release: async ({ camDeviceId }) => {
90728
+ await deps.removeDevice(camDeviceId);
90729
+ },
90730
+ resync: async ({ camDeviceId }) => {
90731
+ const cfg = await deps.findDeviceConfig(camDeviceId);
90732
+ if (cfg === null || cfg["system"] !== "enpal") throw new Error(`enpal resync: device ${camDeviceId} is not an Enpal device`);
90733
+ return {
90734
+ changed: false,
90735
+ rebuiltChildren: 0
90736
+ };
90737
+ }
90738
+ };
90197
90739
  }
90198
90740
  //#endregion
90199
90741
  //#region src/enpal-device-page.ts
@@ -90549,482 +91091,309 @@ var EnpalIntegrationManager = class {
90549
91091
  }
90550
91092
  };
90551
91093
  //#endregion
90552
- //#region src/enpal-resolver.ts
91094
+ //#region src/enpal-client-registry.ts
90553
91095
  /**
90554
- * Per-box registry that the adopted devices use to reach the live
90555
- * {@link EnpalIntegrationManager}. Keyed on the box Hub device's `stableId`; the box
90556
- * publishes a new manager here whenever its connection changes, and children read through
90557
- * the resolver so they follow it.
91096
+ * Owns one poller per Enpal integration (`Map<integrationId, manager>`) and publishes each on
91097
+ * {@link enpalConnections} so the devices follow it. The caller reconciles it against the
91098
+ * live integration list at boot and on every integration lifecycle event.
90558
91099
  */
90559
- var EnpalBoxResolver = class {
90560
- #managers = /* @__PURE__ */ new Map();
90561
- #subs = /* @__PURE__ */ new Map();
90562
- set(boxId, manager) {
90563
- if (manager === null) {
90564
- this.#managers.delete(boxId);
90565
- return;
91100
+ var EnpalClientRegistry = class {
91101
+ #logger;
91102
+ #deps;
91103
+ #entries = /* @__PURE__ */ new Map();
91104
+ constructor(logger, deps) {
91105
+ this.#logger = logger;
91106
+ this.#deps = deps;
91107
+ }
91108
+ /**
91109
+ * Ensure a poller runs for `integrationId` with this connection. An unchanged connection
91110
+ * keeps the running poller; a changed one replaces it. Never throws: a box that is off is
91111
+ * an `error` status, polled again later.
91112
+ */
91113
+ async upsert(integrationId, name, connection, tokenLocked) {
91114
+ const existing = this.#entries.get(integrationId);
91115
+ if (existing !== void 0) {
91116
+ if (existing.tokenLocked === tokenLocked && sameConnection(existing.connection, connection)) return;
91117
+ await this.remove(integrationId);
91118
+ }
91119
+ const manager = new EnpalIntegrationManager({
91120
+ id: integrationId,
91121
+ name,
91122
+ connection,
91123
+ tokenLocked,
91124
+ logger: this.#logger.withTags({ integrationId }),
91125
+ fetch: this.#deps.fetch,
91126
+ now: this.#deps.now,
91127
+ onConnected: () => {
91128
+ this.#deps.onConnected(integrationId);
91129
+ },
91130
+ onDisconnected: () => {
91131
+ this.#deps.onDisconnected(integrationId);
91132
+ enpalConnections.emitSnapshot(integrationId);
91133
+ },
91134
+ onPolled: () => {
91135
+ enpalConnections.emitSnapshot(integrationId);
91136
+ }
91137
+ });
91138
+ this.#entries.set(integrationId, {
91139
+ manager,
91140
+ connection,
91141
+ tokenLocked
91142
+ });
91143
+ enpalConnections.set(integrationId, manager);
91144
+ await manager.start();
91145
+ if (manager.status === "error") {
91146
+ this.#deps.onDisconnected(integrationId);
91147
+ enpalConnections.emitSnapshot(integrationId);
90566
91148
  }
90567
- this.#managers.set(boxId, manager);
90568
91149
  }
90569
- getManager(boxId) {
90570
- return this.#managers.get(boxId) ?? null;
91150
+ async remove(integrationId) {
91151
+ const entry = this.#entries.get(integrationId);
91152
+ if (entry === void 0) return;
91153
+ this.#entries.delete(integrationId);
91154
+ enpalConnections.set(integrationId, null);
91155
+ await entry.manager.stop();
90571
91156
  }
90572
- /** The latest snapshot, or null when the box is unreachable (never stale readings). */
90573
- getSnapshot(boxId) {
90574
- return this.#managers.get(boxId)?.getSnapshot() ?? null;
91157
+ /** Stop every poller whose integration is not in `keep`. */
91158
+ async retain(keep) {
91159
+ for (const id of [...this.#entries.keys()]) if (!keep.has(id)) await this.remove(id);
90575
91160
  }
90576
- /** Subscribe to poll ticks (successful or not). Returns an unsubscribe function. */
90577
- onSnapshot(boxId, cb) {
90578
- let set = this.#subs.get(boxId);
90579
- if (set === void 0) {
90580
- set = /* @__PURE__ */ new Set();
90581
- this.#subs.set(boxId, set);
90582
- }
90583
- set.add(cb);
90584
- return () => {
90585
- const current = this.#subs.get(boxId);
90586
- current?.delete(cb);
90587
- if (current !== void 0 && current.size === 0) this.#subs.delete(boxId);
90588
- };
91161
+ async shutdown() {
91162
+ for (const id of [...this.#entries.keys()]) await this.remove(id);
90589
91163
  }
90590
- emitSnapshot(boxId) {
90591
- const set = this.#subs.get(boxId);
90592
- if (set === void 0) return;
90593
- for (const cb of set) try {
90594
- cb();
90595
- } catch {}
91164
+ has(integrationId) {
91165
+ return this.#entries.has(integrationId);
90596
91166
  }
90597
- clear() {
90598
- this.#managers.clear();
90599
- this.#subs.clear();
91167
+ list() {
91168
+ return [...this.#entries.keys()];
90600
91169
  }
90601
91170
  };
90602
- var enpalBoxes = new EnpalBoxResolver();
90603
91171
  //#endregion
90604
- //#region src/enpal-counter-guard.ts
90605
- /**
90606
- * Smaller than the history deadband of the lifetime counters (0.01 kWh): float noise from
90607
- * rounding or a unit conversion, never a real drop.
90608
- */
90609
- var NOISE = .01;
90610
- /**
90611
- * Keeps a lifetime counter monotonic before it reaches a `counter` history series, where a
90612
- * drop means "the meter was reset" and re-bases every later total.
90613
- *
90614
- * The box occasionally reports 0 or a stale lower figure for one poll (a restart, a partly
90615
- * written window). One such reading is held back: the previous value is published instead.
90616
- * A lower reading that is then followed by a value at or above it is a genuine reset or a
90617
- * replaced meter, and is accepted.
90618
- */
90619
- var LifetimeCounterGuard = class {
90620
- #published = null;
90621
- #suspect = null;
90622
- /** The value to publish for the reading `next`. */
90623
- accept(next) {
90624
- const published = this.#published;
90625
- if (published === null || next >= published - NOISE) {
90626
- this.#published = next;
90627
- this.#suspect = null;
90628
- return next;
90629
- }
90630
- const suspect = this.#suspect;
90631
- if (suspect !== null && next >= suspect - NOISE) {
90632
- this.#published = next;
90633
- this.#suspect = null;
90634
- return next;
90635
- }
90636
- this.#suspect = next;
90637
- return published;
90638
- }
90639
- };
90640
- //#endregion
90641
- //#region src/devices/enpal-sensor-device.ts
90642
- var POWER_CAP = powerMeterCapability.name;
90643
- var BATTERY_CAP = batteryCapability.name;
90644
- var METER_CAP = meterCapability.name;
90645
- var NUMERIC_CAP = numericSensorCapability.name;
90646
- var POWER_COLD = { lastFetchedAt: 0 };
90647
- var BATTERY_COLD = {
90648
- percentage: null,
90649
- charging: "unknown",
90650
- sleeping: false,
90651
- lastUpdated: 0
90652
- };
90653
- var VALUE_COLD = {
90654
- value: null,
90655
- lastFetchedAt: 0
90656
- };
90657
- /**
90658
- * One Enpal data group (PV, battery, grid import, ...) as a {@link DeviceType.Sensor}
90659
- * child of the box. The catalog entry in `specId` says which caps it registers and which
90660
- * box keys feed them; the slices are recomputed from the box snapshot on every poll tick.
90661
- *
90662
- * An unreachable box marks the device offline and leaves the slices alone: a failed read is
90663
- * a gap, never a zero (D393). A lifetime counter passes through {@link LifetimeCounterGuard}
90664
- * so one stale low reading cannot become a history reset.
90665
- */
90666
- var EnpalSensorDevice = class extends BaseDevice {
90667
- features = [];
90668
- spec;
90669
- boxId;
90670
- energyGuard = new LifetimeCounterGuard();
90671
- meterGuard = new LifetimeCounterGuard();
90672
- snapshotUnsub = null;
90673
- constructor(ctx) {
90674
- const cfg = enpalSensorSchema.parse(ctx.persistedConfig ?? {});
90675
- super(ctx, enpalSensorSchema, { type: ctx.deviceMeta.type });
90676
- const spec = findSpec(cfg.specId);
90677
- if (spec === void 0) throw new Error(`Enpal: unknown device kind "${cfg.specId}"`);
90678
- this.spec = spec;
90679
- this.boxId = cfg.boxId;
90680
- this.online = enpalBoxes.getSnapshot(this.boxId) !== null;
90681
- this.updateSourceInfo({
90682
- id: `${this.boxId}:${spec.id}`,
90683
- system: "enpal",
90684
- ...spec.kind === "meter" || spec.kind === "numeric" ? { quantity: spec.quantity } : {}
90685
- });
90686
- }
90687
- async onActivate() {
90688
- await super.onActivate();
90689
- this.registerCaps();
90690
- this.snapshotUnsub = enpalBoxes.onSnapshot(this.boxId, () => {
90691
- try {
90692
- this.recompute();
90693
- } catch (err) {
90694
- this.ctx.logger.warn("enpal sensor: snapshot handler failed", {
90695
- tags: { deviceId: this.id },
90696
- meta: {
90697
- spec: this.spec.id,
90698
- error: errMsg(err)
90699
- }
90700
- });
90701
- }
90702
- });
90703
- this.recompute();
90704
- }
90705
- async removeDevice() {
90706
- this.snapshotUnsub?.();
90707
- this.snapshotUnsub = null;
90708
- await super.removeDevice();
90709
- }
90710
- recompute() {
90711
- const snapshot = enpalBoxes.getSnapshot(this.boxId);
90712
- if (snapshot === null) {
90713
- if (this.online) this.markOnline(false);
90714
- return;
90715
- }
90716
- if (!this.online) this.markOnline(true);
90717
- const invert = enpalBoxes.getManager(this.boxId)?.connection.invertBatteryPower ?? false;
90718
- const slices = computeSlices(this.spec, snapshot, { invertBatteryPower: invert }, snapshot.fetchedAt);
90719
- this.publish(slices);
90720
- for (const line of slices.refusals) this.ctx.logger.warn(`enpal sensor: reading not used, ${line}`, {
90721
- tags: { deviceId: this.id },
90722
- meta: { spec: this.spec.id }
90723
- });
90724
- }
90725
- publish(slices) {
90726
- if (slices.powerMeter !== void 0) {
90727
- const kwh = slices.powerMeter.kwhTotal;
90728
- this.runtimeState.setCapState(POWER_CAP, kwh === void 0 ? slices.powerMeter : {
90729
- ...slices.powerMeter,
90730
- kwhTotal: this.energyGuard.accept(kwh)
90731
- });
90732
- }
90733
- if (slices.battery !== void 0) this.runtimeState.setCapState(BATTERY_CAP, slices.battery);
90734
- if (slices.meter !== void 0) {
90735
- const raw = slices.meter.value;
90736
- this.runtimeState.setCapState(METER_CAP, {
90737
- ...slices.meter,
90738
- value: raw === null ? null : this.meterGuard.accept(raw)
91172
+ //#region src/enpal-integration-device-cascade.ts
91173
+ /**
91174
+ * Remove every equipment Container of an integration that was deleted or disabled; the
91175
+ * kernel takes the Sensor children with it. Best-effort per device; returns the count removed.
91176
+ */
91177
+ async function cascadeRemoveDevicesForIntegration(input) {
91178
+ const { reg, devices, addonId, integrationId, logger } = input;
91179
+ let removed = 0;
91180
+ for (const d of reg.getAllForAddon(addonId)) {
91181
+ if (d.parentDeviceId !== null) continue;
91182
+ const cfg = await devices.loadConfig(d.id).catch(() => ({}));
91183
+ if (cfg["system"] !== "enpal" || cfg["integrationId"] !== integrationId) continue;
91184
+ try {
91185
+ await devices.remove(d.id);
91186
+ removed += 1;
91187
+ } catch (err) {
91188
+ logger.warn("enpal: integration cascade-remove failed", {
91189
+ tags: { deviceId: d.id },
91190
+ meta: {
91191
+ integrationId,
91192
+ error: errMsg(err)
91193
+ }
90739
91194
  });
90740
91195
  }
90741
- if (slices.numeric !== void 0) this.runtimeState.setCapState(NUMERIC_CAP, slices.numeric);
90742
- }
90743
- registerCaps() {
90744
- switch (this.spec.kind) {
90745
- case "power-meter":
90746
- this.registerPowerMeter();
90747
- return;
90748
- case "battery":
90749
- this.registerBattery();
90750
- this.registerPowerMeter();
90751
- return;
90752
- case "meter":
90753
- this.ctx.registerNativeCap(meterCapability, { getStatus: async () => this.runtimeState.getCapState(METER_CAP) ?? VALUE_COLD });
90754
- this.runtimeState.setCapState(METER_CAP, VALUE_COLD);
90755
- return;
90756
- case "numeric":
90757
- this.ctx.registerNativeCap(numericSensorCapability, { getStatus: async () => this.runtimeState.getCapState(NUMERIC_CAP) ?? VALUE_COLD });
90758
- this.runtimeState.setCapState(NUMERIC_CAP, VALUE_COLD);
90759
- return;
90760
- }
90761
91196
  }
90762
- registerPowerMeter() {
90763
- this.ctx.registerNativeCap(powerMeterCapability, { getStatus: async () => this.runtimeState.getCapState(POWER_CAP) ?? POWER_COLD });
90764
- this.runtimeState.setCapState(POWER_CAP, POWER_COLD);
90765
- }
90766
- registerBattery() {
90767
- this.ctx.registerNativeCap(batteryCapability, {
90768
- getStatus: async () => this.runtimeState.getCapState(BATTERY_CAP) ?? BATTERY_COLD,
90769
- wakeForStream: async () => ({
90770
- awoke: false,
90771
- durationMs: 0
90772
- })
90773
- });
90774
- this.runtimeState.setCapState(BATTERY_CAP, BATTERY_COLD);
91197
+ return removed;
91198
+ }
91199
+ //#endregion
91200
+ //#region src/enpal-integration-offline.ts
91201
+ /**
91202
+ * Set every Enpal device of `integrationId` (containers and their sensors) to `online`.
91203
+ * Churn-free: a device already in that state is left alone. Returns how many changed.
91204
+ */
91205
+ function setIntegrationDevicesOnline(devices, integrationId, online) {
91206
+ let count = 0;
91207
+ for (const dev of devices) {
91208
+ if (dev.config.get("system") !== "enpal") continue;
91209
+ if (dev.config.get("integrationId") !== integrationId) continue;
91210
+ if (dev.online === online) continue;
91211
+ dev.markOnline(online);
91212
+ count += 1;
90775
91213
  }
90776
- };
91214
+ return count;
91215
+ }
90777
91216
  //#endregion
90778
- //#region src/devices/enpal-box-device.ts
91217
+ //#region src/addon.ts
90779
91218
  /**
90780
- * One Enpal box, a {@link DeviceType.Hub} device. The connection (host, InfluxDB access,
90781
- * token) lives on this device's config; it owns the poller, publishes it on
90782
- * {@link enpalBoxes} and registers `device-discovery` so the operator adopts the data groups
90783
- * the box actually reports (PV, battery, grid, house, heat pump) as Sensor children.
91219
+ * Enpal solar box provider, `mode: account` and broker-less. An integration is one box: its
91220
+ * host, InfluxDB access and token live on the integration's settings, and the addon polls it
91221
+ * with one manager per `integrationId`. The box is not a device: discovery offers one
91222
+ * {@link DeviceType.Container} per piece of equipment it reports (photovoltaic, battery,
91223
+ * grid, house, heat pump), and adopting a container adopts its Sensor children.
91224
+ *
91225
+ * The box does not advertise itself on the network, so the integration is added by hand.
90784
91226
  */
90785
- var EnpalBoxDevice = class extends BaseDevice {
90786
- features = [];
90787
- manager = null;
90788
- eventUnsubscribers = [];
90789
- constructor(ctx) {
90790
- enpalBoxSchema.parse(ctx.persistedConfig ?? {});
90791
- super(ctx, enpalBoxSchema, { type: DeviceType.Hub });
90792
- this.online = false;
90793
- this.registerDeviceDiscovery();
90794
- this.updateSourceInfo({
90795
- id: this.stableId,
90796
- system: "enpal"
90797
- });
91227
+ var EnpalProviderAddon = class extends BaseDeviceProvider {
91228
+ addonId = "provider-enpal";
91229
+ providerName = "Enpal";
91230
+ deviceClasses = { [DeviceType.Container]: EnpalEquipmentDevice };
91231
+ clients = null;
91232
+ constructor() {
91233
+ super({});
90798
91234
  }
90799
- async onActivate() {
90800
- await super.onActivate();
90801
- this.ensureManager().catch((err) => {
90802
- this.ctx.logger.warn("Enpal box: start failed", {
90803
- tags: { deviceId: this.id },
90804
- meta: { error: errMsg(err) }
90805
- });
91235
+ async onInitialize() {
91236
+ const regs = this.providerRegistrationsFromSuper(await super.onInitialize());
91237
+ this.clients = new EnpalClientRegistry(this.ctx.logger, {
91238
+ onConnected: (integrationId) => this.setIntegrationDevicesOnline(integrationId, true),
91239
+ onDisconnected: (integrationId) => this.setIntegrationDevicesOnline(integrationId, false)
90806
91240
  });
90807
- this.eventUnsubscribers.push(this.ctx.eventBus.subscribe({ category: EventCategory.DeviceUnregistered }, (event) => {
90808
- if (event.data.parentDeviceId !== this.id) return;
90809
- this.refreshDiscovery().catch(() => void 0);
90810
- }));
91241
+ await this.reconcileIntegrations();
91242
+ this.subscribeIntegrationLifecycle();
91243
+ return [...regs, {
91244
+ capability: deviceAdoptionCapability,
91245
+ provider: this.buildAdoptionProvider()
91246
+ }];
90811
91247
  }
90812
- async removeDevice() {
90813
- for (const unsub of this.eventUnsubscribers) unsub();
90814
- this.eventUnsubscribers.length = 0;
90815
- await this.stopManager();
90816
- await super.removeDevice();
91248
+ async onShutdown() {
91249
+ try {
91250
+ await this.clients?.shutdown();
91251
+ } catch (err) {
91252
+ this.ctx.logger.warn("Enpal shutdown error", { meta: { error: errMsg(err) } });
91253
+ }
91254
+ this.clients = null;
91255
+ enpalConnections.clear();
91256
+ await super.onShutdown();
90817
91257
  }
90818
- async applySettingsPatch(patch) {
90819
- if (!("connection" in patch)) return;
90820
- const parsed = enpalBoxSchema.parse({
90821
- connection: patch["connection"],
90822
- system: "enpal-box"
90823
- });
90824
- await this.config.setAll({ connection: parsed.connection });
90825
- await this.stopManager();
90826
- await this.ensureManager();
91258
+ requireClients() {
91259
+ if (!this.clients) throw new Error("Enpal provider not initialised");
91260
+ return this.clients;
90827
91261
  }
90828
- async stopManager() {
90829
- const mgr = this.manager;
90830
- this.manager = null;
90831
- enpalBoxes.set(this.stableId, null);
90832
- if (mgr !== null) await mgr.stop();
91262
+ /** One container per equipment per integration. */
91263
+ generateStableId(_type, config) {
91264
+ const integrationId = config?.["integrationId"];
91265
+ const equipment = config?.["equipment"];
91266
+ if (typeof integrationId !== "string" || integrationId.length === 0) throw new Error("enpal generateStableId: integrationId required");
91267
+ if (typeof equipment !== "string" || equipment.length === 0) throw new Error("enpal generateStableId: equipment required");
91268
+ return `enpal:${integrationId}:${equipment}`;
90833
91269
  }
90834
- async ensureManager() {
90835
- if (this.manager !== null) return;
90836
- const { connection, tokenLocked } = readConnection(this.config.values.connection);
90837
- const mgr = new EnpalIntegrationManager({
90838
- id: this.stableId,
90839
- name: this.name,
90840
- connection,
90841
- tokenLocked,
90842
- logger: this.ctx.logger.withTags({ deviceId: this.id }),
90843
- onConnected: () => this.setOnline(true),
90844
- onDisconnected: () => {
90845
- this.setOnline(false);
90846
- enpalBoxes.emitSnapshot(this.stableId);
90847
- },
90848
- onPolled: () => {
90849
- this.refreshDiscovery().catch(() => void 0);
90850
- enpalBoxes.emitSnapshot(this.stableId);
91270
+ /**
91271
+ * Rebuild the pollers from the live integration list: upsert one per enabled integration
91272
+ * with a host, drop the ones that vanished and cascade-remove their devices. Idempotent;
91273
+ * runs at boot and on every integration lifecycle event.
91274
+ */
91275
+ async reconcileIntegrations() {
91276
+ const reg = this.requireClients();
91277
+ try {
91278
+ const mine = (await this.ctx.api.integrations.list.query()).filter((i) => i.addonId === this.ctx.id && i.enabled);
91279
+ const surviving = /* @__PURE__ */ new Set();
91280
+ for (const integration of mine) try {
91281
+ const read = connectionFromSettings(await this.ctx.api.integrations.getSettings.query({ id: integration.id }));
91282
+ if (read === null) {
91283
+ this.ctx.logger.warn("Enpal integration has no box host — skipping", { meta: { integrationId: integration.id } });
91284
+ continue;
91285
+ }
91286
+ await reg.upsert(integration.id, integration.name, read.connection, read.tokenLocked);
91287
+ surviving.add(integration.id);
91288
+ } catch (err) {
91289
+ this.ctx.logger.warn("Enpal reconcile failed for integration", { meta: {
91290
+ integrationId: integration.id,
91291
+ error: errMsg(err)
91292
+ } });
90851
91293
  }
90852
- });
90853
- this.manager = mgr;
90854
- enpalBoxes.set(this.stableId, mgr);
90855
- await mgr.start();
90856
- if (mgr.status === "error") {
90857
- this.setOnline(false);
90858
- enpalBoxes.emitSnapshot(this.stableId);
91294
+ const vanished = reg.list().filter((id) => !surviving.has(id));
91295
+ await reg.retain(surviving);
91296
+ for (const integrationId of vanished) await this.cascadeRemoveDevicesForIntegration(integrationId);
91297
+ } catch (err) {
91298
+ this.ctx.logger.warn("Enpal integration reconcile failed", { meta: { error: errMsg(err) } });
90859
91299
  }
90860
91300
  }
90861
- setOnline(online) {
90862
- if (this.online === online) return;
90863
- this.markOnline(online);
90864
- this.ctx.logger.info("Enpal box " + (online ? "online" : "offline"), { tags: { deviceId: this.id } });
91301
+ subscribeIntegrationLifecycle() {
91302
+ const handler = (event) => {
91303
+ const addonId = event.data["addonId"];
91304
+ if (typeof addonId === "string" && addonId !== this.ctx.id) return;
91305
+ this.reconcileIntegrations();
91306
+ };
91307
+ this.ctx.eventBus.subscribe({ category: EventCategory.IntegrationEnabled }, handler);
91308
+ this.ctx.eventBus.subscribe({ category: EventCategory.IntegrationDisabled }, handler);
91309
+ this.ctx.eventBus.subscribe({ category: EventCategory.IntegrationDeleted }, handler);
90865
91310
  }
90866
- registerDeviceDiscovery() {
90867
- this.ctx.registerNativeCap(deviceDiscoveryCapability, {
90868
- getStatus: async ({ deviceId }) => {
90869
- if (deviceId !== this.id) return null;
90870
- return this.runtimeState.getCapState("device-discovery") ?? null;
91311
+ async cascadeRemoveDevicesForIntegration(integrationId) {
91312
+ const reg = this.ctx.kernel.deviceRegistry;
91313
+ const devices = this.ctx.kernel.devices;
91314
+ if (!reg || !devices) return;
91315
+ await cascadeRemoveDevicesForIntegration({
91316
+ reg,
91317
+ devices,
91318
+ addonId: this.addonId,
91319
+ integrationId,
91320
+ logger: this.ctx.logger
91321
+ });
91322
+ }
91323
+ buildAdoptionProvider() {
91324
+ return buildEnpalAdoptionProvider({
91325
+ getSnapshot: (integrationId) => enpalConnections.getSnapshot(integrationId),
91326
+ hasIntegration: (integrationId) => this.requireClients().has(integrationId),
91327
+ listIntegrations: () => this.requireClients().list(),
91328
+ listAdopted: async () => {
91329
+ const reg = this.ctx.kernel.deviceRegistry;
91330
+ const devices = this.ctx.kernel.devices;
91331
+ if (!reg || !devices) return [];
91332
+ const out = [];
91333
+ for (const d of reg.getAllForAddon(this.addonId)) {
91334
+ if (d.parentDeviceId !== null) continue;
91335
+ const config = await devices.loadConfig(d.id).catch(() => ({}));
91336
+ out.push({
91337
+ id: d.id,
91338
+ config
91339
+ });
91340
+ }
91341
+ return out;
90871
91342
  },
90872
- listDiscovered: async ({ deviceId }) => {
90873
- if (deviceId !== this.id) return [];
90874
- return this.runtimeState.getCapState("device-discovery")?.discovered ?? [];
91343
+ adoptDevice: async ({ equipment, specIds, integrationId, name }) => {
91344
+ const devices = this.ctx.kernel.devices;
91345
+ if (!devices) throw new Error("enpal adopt: kernel.devices unavailable");
91346
+ const config = {
91347
+ equipment,
91348
+ specIds,
91349
+ integrationId,
91350
+ system: ENPAL_SYSTEM
91351
+ };
91352
+ const stableId = this.generateStableId(DeviceType.Container, config);
91353
+ const device = await devices.create(stableId, EnpalEquipmentDevice, config, null, {
91354
+ type: DeviceType.Container,
91355
+ name,
91356
+ integrationId
91357
+ });
91358
+ const children = await devices.getChildren(device.id);
91359
+ return {
91360
+ deviceId: device.id,
91361
+ accessoryDeviceIds: children.map((c) => c.id)
91362
+ };
90875
91363
  },
90876
- refreshDiscovery: async ({ deviceId }) => {
90877
- if (deviceId !== this.id) return [];
90878
- await this.refreshDiscovery();
90879
- return this.runtimeState.getCapState("device-discovery")?.discovered ?? [];
91364
+ removeDevice: async (id) => {
91365
+ await this.ctx.kernel.devices?.remove(id);
90880
91366
  },
90881
- adoptDevice: async ({ deviceId, childNativeId, name }) => {
90882
- if (deviceId !== this.id) throw new Error(`adoptDevice: deviceId mismatch — got ${deviceId}, expected ${this.id}`);
90883
- return this.adopt(childNativeId, name);
91367
+ findDeviceConfig: async (id) => {
91368
+ const devices = this.ctx.kernel.devices;
91369
+ if (!devices) return null;
91370
+ return devices.loadConfig(id).catch(() => null);
90884
91371
  },
90885
- releaseDevice: async ({ deviceId, childDeviceId }) => {
90886
- if (deviceId !== this.id) return;
90887
- await this.release(childDeviceId);
90888
- }
90889
- });
90890
- this.setCapSlice(deviceDiscoveryCapability, {
90891
- discovered: [],
90892
- lastDiscoveryAt: null,
90893
- lastError: null,
90894
- lastFetchedAt: 0
91372
+ logger: this.ctx.logger
90895
91373
  });
90896
91374
  }
90897
- async refreshDiscovery() {
90898
- const snapshot = enpalBoxes.getSnapshot(this.stableId);
90899
- let lastError = null;
90900
- let discovered = [];
90901
- if (snapshot === null) lastError = enpalBoxes.getManager(this.stableId)?.lastError?.message ?? null;
90902
- else try {
90903
- discovered = buildCandidates({
90904
- boxId: this.stableId,
90905
- boxName: this.name,
90906
- specs: availableSpecs(snapshot),
90907
- adoptedDeviceIdBySpec: await this.adoptedBySpec(),
90908
- online: true
90909
- });
90910
- } catch (err) {
90911
- lastError = errMsg(err);
90912
- this.ctx.logger.warn("Enpal box: discovery refresh failed", {
90913
- tags: { deviceId: this.id },
90914
- meta: { error: lastError }
90915
- });
90916
- }
90917
- this.runtimeState.setCapState(deviceDiscoveryCapability.name, {
90918
- discovered,
90919
- lastDiscoveryAt: Date.now(),
90920
- lastError,
90921
- lastFetchedAt: Date.now()
90922
- });
90923
- }
90924
- async adoptedBySpec() {
90925
- const out = {};
90926
- const children = await this.ctx.devices.getChildren(this.id).catch(() => []);
90927
- for (const child of children) {
90928
- const specId = (await this.ctx.devices.loadConfig(child.id).catch(() => ({})))["specId"];
90929
- if (typeof specId === "string") out[specId] = child.id;
90930
- }
90931
- return out;
90932
- }
90933
- async adopt(childNativeId, nameOverride) {
90934
- const specId = parseSpecNativeId(this.stableId, childNativeId);
90935
- const spec = specId === null ? void 0 : findSpec(specId);
90936
- if (spec === void 0) throw new Error(`adoptDevice: ${childNativeId} is not an Enpal device of this box`);
90937
- const existingId = (await this.adoptedBySpec())[spec.id];
90938
- if (typeof existingId === "number") {
90939
- const existing = (await this.ctx.devices.getAll()).find((d) => d.id === existingId);
90940
- if (existing) return {
90941
- deviceId: existing.id,
90942
- stableId: existing.stableId
90943
- };
90944
- }
90945
- const name = nameOverride ?? `${this.name} ${spec.name}`;
90946
- const stableId = specNativeId(this.stableId, spec.id);
90947
- const created = await this.ctx.devices.create(stableId, EnpalSensorDevice, {
90948
- specId: spec.id,
90949
- boxId: this.stableId,
90950
- system: "enpal",
90951
- name
90952
- }, this.id, {
90953
- type: DeviceType.Sensor,
90954
- name,
90955
- role: spec.role
90956
- });
90957
- this.ctx.logger.info("Enpal box: adopted device", {
90958
- tags: { deviceId: created.id },
90959
- meta: {
90960
- spec: spec.id,
90961
- stableId
90962
- }
90963
- });
90964
- await this.refreshDiscovery().catch(() => void 0);
90965
- return {
90966
- deviceId: created.id,
90967
- stableId
90968
- };
90969
- }
90970
- async release(childDeviceId) {
90971
- const child = (await this.ctx.devices.getAll()).find((d) => d.id === childDeviceId);
90972
- if (!child || child.parentDeviceId !== this.id) throw new Error(`releaseDevice: ${childDeviceId} is not a child of box ${this.id}`);
90973
- await this.ctx.devices.remove(childDeviceId);
90974
- await this.refreshDiscovery().catch(() => void 0);
90975
- }
90976
- };
90977
- //#endregion
90978
- //#region src/addon.ts
90979
- /**
90980
- * Enpal solar box provider, `mode: standalone` (the VeSync / Ecowitt pattern, no broker).
90981
- * A box is added as a {@link DeviceType.Hub} through the manual-creation form: its host,
90982
- * InfluxDB access and token live on the device. The box registers `device-discovery` and
90983
- * adopts the data groups it reports as Sensor devices. The box does not advertise itself on
90984
- * the network, so there is no auto-discovery of the box itself.
90985
- */
90986
- var EnpalProviderAddon = class extends BaseDeviceProvider {
90987
- addonId = "provider-enpal";
90988
- providerName = "Enpal";
90989
- deviceClasses = {
90990
- [DeviceType.Hub]: EnpalBoxDevice,
90991
- [DeviceType.Sensor]: EnpalSensorDevice
90992
- };
90993
- constructor() {
90994
- super({});
90995
- }
90996
- async supportsDiscovery() {
90997
- return false;
91375
+ /** The integration's settings form; the submitted values are stored per integration. */
91376
+ globalSettingsSchema() {
91377
+ return buildConnectionFormSchema();
90998
91378
  }
90999
91379
  async supportsManualCreation() {
91000
- return true;
91380
+ return false;
91001
91381
  }
91002
- async onGetCreationSchema(type) {
91003
- return type === DeviceType.Hub ? buildConnectionFormSchema() : null;
91382
+ async onGetCreationSchema(_type) {
91383
+ return null;
91004
91384
  }
91005
- async onCreateDevice(type, config) {
91006
- if (type !== DeviceType.Hub) throw new Error(`Enpal provider does not support device type: ${type}`);
91007
- const name = typeof config["name"] === "string" ? config["name"].trim() : "";
91008
- if (name.length === 0) throw userError("enpal.name-required", void 0, "Box name is required");
91009
- const parsed = enpalConnectionSchema.safeParse(config["connection"] ?? config);
91010
- if (!parsed.success || parsed.data.host.length === 0) throw userError("enpal.host-required", void 0, "The box host or IP is required");
91011
- return {
91012
- meta: {
91013
- type: DeviceType.Hub,
91014
- name
91015
- },
91016
- config: {
91017
- connection: parsed.data,
91018
- system: "enpal-box"
91019
- }
91020
- };
91385
+ async onCreateDevice(_type, _config) {
91386
+ throw new Error("Enpal devices are adopted from the integration");
91021
91387
  }
91022
- /** One row per box host: re-adding the same box reuses its persisted row. */
91023
- generateStableId(_type, config) {
91024
- const host = readConnection(config?.["connection"] ?? config).connection.host;
91025
- if (host.length > 0) return `enpal:${slugifyHost(host)}`;
91026
- throw new Error("Enpal: box resolved no host — cannot persist a stable row key.");
91388
+ setIntegrationDevicesOnline(integrationId, online) {
91389
+ const reg = this.ctx.kernel.deviceRegistry;
91390
+ if (!reg) return;
91391
+ const n = setIntegrationDevicesOnline(reg.getAllForAddon(this.addonId), integrationId, online);
91392
+ if (n > 0) this.ctx.logger.info("Enpal integration devices " + (online ? "online" : "offline"), { meta: {
91393
+ integrationId,
91394
+ count: n
91395
+ } });
91027
91396
  }
91028
91397
  };
91029
91398
  //#endregion
91030
- export { slugifyHost as C, EnpalProviderAddon, settingsToConnection as S, buildConnectionFormSchema as _, enpalBoxes as a, enpalSensorSchema as b, readEnpalSnapshot as c, specNativeId as d, ENPAL_SPECS as f, findSpec as g, computeSlices as h, EnpalBoxResolver as i, buildCandidates as l, capsOfSpec as m, EnpalSensorDevice as n, EnpalIntegrationManager as o, availableSpecs as p, LifetimeCounterGuard as r, EnpalError as s, EnpalBoxDevice as t, parseSpecNativeId as u, enpalBoxSchema as v, readConnection as x, enpalConnectionSchema as y };
91399
+ export { buildConnectionFormSchema as C, sameConnection as D, readConnection as E, EnpalProviderAddon, settingsToConnection as O, ENPAL_SYSTEM as S, enpalConnectionSchema as T, ENPAL_SPECS as _, buildEnpalAdoptionProvider as a, computeSlices as b, ENPAL_EQUIPMENT as c, findEquipment as d, EnpalSensorDevice as f, LifetimeCounterGuard as g, enpalConnections as h, readEnpalSnapshot as i, accessoryChildSpecs as l, EnpalConnectionResolver as m, EnpalIntegrationManager as n, buildEnpalCandidates as o, enpalSensorSchema as p, EnpalError as r, EnpalEquipmentDevice as s, EnpalClientRegistry as t, enpalEquipmentSchema as u, availableSpecs as v, connectionFromSettings as w, findSpec as x, capsOfSpec as y };