@nebulahome/integration-sdk 1.2.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -534,9 +534,9 @@ const buttonCommandSchema = z.discriminatedUnion("command", [z.object({ command:
534
534
  /**
535
535
  * A device's firmware: what it runs, what it could run, and whether it is installing it now.
536
536
  *
537
- * One entity for the whole of it, as Home Assistant has, rather than a sensor saying an update
538
- * is there and a button installing it: the installing belongs to the same state as the offer,
539
- * and an automation that installs whatever is offered must be able to see that an install is
537
+ * One entity for the whole of it, rather than a sensor saying an update is there and a button
538
+ * installing it: the installing belongs to the same state as the offer, and an automation that
539
+ * installs whatever is offered must be able to see that an install is
540
540
  * already under way - a device fetching its firmware still offers it until it reboots, and
541
541
  * asked again it may start over.
542
542
  *
@@ -595,7 +595,7 @@ const lawnMowerCommandSchema = z.discriminatedUnion("command", [
595
595
  /**
596
596
  * What a robot vacuum is doing: cleaning, paused in the middle of a job, on its way back to its
597
597
  * station, sitting in it, standing idle out of it, or stopped by a fault it cannot clear on its
598
- * own. Home Assistant's vacuum activities, the mower's words where they mean the same.
598
+ * own: the mower's words where they mean the same.
599
599
  */
600
600
  const VACUUM_ACTIVITIES = [
601
601
  "cleaning",
@@ -958,6 +958,8 @@ const entityStateSchema = z.object({
958
958
  attributes: jsonObjectSchema.default({}),
959
959
  /** False when the owning adapter cannot currently reach the device. */
960
960
  isAvailable: z.boolean().default(true),
961
+ /** True while its package or integration is being updated: the value is the last one known. */
962
+ isUpdating: z.boolean().optional(),
961
963
  /**
962
964
  * When `state` last differed from what it was.
963
965
  *
@@ -1601,7 +1603,7 @@ function pollIntervalMsOf(options) {
1601
1603
  * Apart from the manifest so that the vendors' grammar can name it without pulling the package
1602
1604
  * manifest's whole grammar - and what that imports - in with it.
1603
1605
  */
1604
- /** A service a package provides and others require: `mqtt-broker`, `object-detection`. */
1606
+ /** A service others require: `object-detection`, or `mqtt-broker`, which the platform runs. */
1605
1607
  const packageServiceNameSchema = z.string().regex(/^[a-z][a-z0-9-]{1,63}$/, "Must be a lower-case service name");
1606
1608
  /**
1607
1609
  * What a package - or a vendor, in its `manifest.json` - needs besides itself: the platform, by
@@ -1771,14 +1773,18 @@ const TRANSPORT_WIRES = [
1771
1773
  ];
1772
1774
  /**
1773
1775
  * How a device can be heard announcing itself: the platform's mDNS browser, a vendor's own
1774
- * listener, or the house's Matter fabric - a node commissioned and not yet added. Declared here
1776
+ * listener, the house's Matter fabric - a node commissioned and not yet added - or the house's
1777
+ * MQTT broker - a device that announced itself on it, or that the owner mapped - or the house's
1778
+ * Modbus client - a device the owner added at an address. Declared here
1775
1779
  * rather than beside the discovered devices, because a vendor lists the ways it can be found and
1776
1780
  * the discovery module already reads this file.
1777
1781
  */
1778
1782
  const DISCOVERY_SOURCES = [
1779
1783
  "mdns",
1780
1784
  "module",
1781
- "matter"
1785
+ "matter",
1786
+ "mqtt",
1787
+ "modbus"
1782
1788
  ];
1783
1789
  /**
1784
1790
  * Who adds a device discovery found: the owner, from its card - the ordinary way - or the
@@ -1823,8 +1829,8 @@ z.strictObject({ vendorId: z.string().regex(VENDOR_ID_PATTERN$1) });
1823
1829
  z.object({ isLoaded: z.boolean() });
1824
1830
  /**
1825
1831
  * Where `hub` read a vendor from: the data directory, where the platform installs vendors, a
1826
- * directory of bundles under development, read outside production - or nowhere, for the one vendor
1827
- * the platform is itself: `matter`, the Matter devices no integration claims.
1832
+ * directory of bundles under development, read outside production - or nowhere, for the vendors
1833
+ * the platform is itself: `matter` and `mqtt`, the devices of its brokers no integration claims.
1828
1834
  */
1829
1835
  const BUNDLE_ORIGINS = [
1830
1836
  "installed",
@@ -2024,13 +2030,13 @@ const integrationVendorSchema = z.object({
2024
2030
  */
2025
2031
  containers: z.array(vendorContainerSchema).default([]),
2026
2032
  /**
2027
- * The packages and services its devices need - the MQTT broker, for Zigbee2MQTT - as its
2028
- * manifest's `requires` says. Nothing when it needs none.
2033
+ * The packages and services its devices need - the MQTT broker the platform runs, for
2034
+ * Zigbee2MQTT - as its manifest's `requires` says. Nothing when it needs none.
2029
2035
  */
2030
2036
  requires: packageRequiresSchema,
2031
2037
  /**
2032
- * What of that is not installed or not running, in sentences naming both - "Zigbee2MQTT needs a
2033
- * package that provides mqtt-broker, and none is running". Empty when all of it runs.
2038
+ * What of that is not installed or not running, in sentences naming both - "NVR needs a
2039
+ * package that provides object-detection, and none does". Empty when all of it runs.
2034
2040
  */
2035
2041
  packageProblems: z.array(z.string().max(512)).max(16).default([]),
2036
2042
  /** How the vendor's own listener is getting on; null before it said, or for one without. */
@@ -3876,7 +3882,7 @@ var sensor_classes_default = { classes: [
3876
3882
  * profile wrote.
3877
3883
  */
3878
3884
  /** How history should aggregate a numeric entity - mirrored from registration, kept local to avoid a cycle. */
3879
- const STATE_CLASSES = [
3885
+ const STATE_CLASSES$1 = [
3880
3886
  "measurement",
3881
3887
  "total",
3882
3888
  "total_increasing"
@@ -3918,7 +3924,7 @@ const sensorClassSchema = z.object({
3918
3924
  * Copied onto the entity when the profile omits `stateClass`. Not a second identifier.
3919
3925
  * Absent for date / timestamp / uptime.
3920
3926
  */
3921
- stateClassDefault: z.enum(STATE_CLASSES).optional(),
3927
+ stateClassDefault: z.enum(STATE_CLASSES$1).optional(),
3922
3928
  /** Molar mass (g/mol) for gas density conversions. */
3923
3929
  molarMass: z.number().positive().optional(),
3924
3930
  units: z.array(sensorUnitSchema)
@@ -3964,6 +3970,8 @@ const parsedCatalog = sensorClassesCatalogSchema.parse(sensor_classes_default);
3964
3970
  /** Every class in the catalogue, keyed by id. */
3965
3971
  const SENSOR_CLASSES = new Map(parsedCatalog.classes.map((entry) => [entry.id, entry]));
3966
3972
  parsedCatalog.classes;
3973
+ /** Every unit the catalogue knows, once each - an id is also its symbol. */
3974
+ const SENSOR_UNIT_IDS = new Set(parsedCatalog.classes.flatMap((entry) => entry.units.map((unit) => unit.id)));
3967
3975
  /**
3968
3976
  * Looks up a sensor class by id.
3969
3977
  *
@@ -4536,6 +4544,42 @@ const linkSuggestionViewSchema = z.object({
4536
4544
  z.object({ items: z.array(linkSuggestionViewSchema) });
4537
4545
  z.object({ isDismissed: z.boolean() });
4538
4546
  //#endregion
4547
+ //#region ../contracts/dist/brokers.js
4548
+ /**
4549
+ * The platform's brokers, as the Brokers page lists them: the house's Matter fabric, its MQTT
4550
+ * broker and its Modbus client, all run by the hub.
4551
+ *
4552
+ * A broker reaches every device of one protocol, whoever makes it. Each has a page of its own -
4553
+ * `matter.ts`, `mqtt.ts` and `modbus.ts` say what it holds - and a card here, which says how it stands and how
4554
+ * many devices the house has through it.
4555
+ */
4556
+ /** How a broker stands: coming up, running, stopped by a failure, or turned off. */
4557
+ const BROKER_STATES = [
4558
+ "starting",
4559
+ "running",
4560
+ "failed",
4561
+ "disabled"
4562
+ ];
4563
+ /** One broker, for its card. */
4564
+ const brokerSummarySchema = z.object({
4565
+ id: z.enum([
4566
+ "matter",
4567
+ "mqtt",
4568
+ "modbus"
4569
+ ]),
4570
+ state: z.enum(BROKER_STATES),
4571
+ /**
4572
+ * The devices the house has through it, how many of them answer, and how many are also
4573
+ * reached another way.
4574
+ */
4575
+ devices: z.object({
4576
+ total: z.int().min(0),
4577
+ online: z.int().min(0),
4578
+ linked: z.int().min(0).default(0)
4579
+ })
4580
+ });
4581
+ z.object({ items: z.array(brokerSummarySchema) });
4582
+ //#endregion
4539
4583
  //#region ../contracts/dist/matter.js
4540
4584
  /**
4541
4585
  * The house's Matter fabric, as the hub runs it and the Brokers page shows it.
@@ -4552,8 +4596,6 @@ z.object({ isDismissed: z.boolean() });
4552
4596
  */
4553
4597
  /** The platform transport every Matter device is reached through. */
4554
4598
  const MATTER_TRANSPORT = "matter";
4555
- /** The platform's own vendor: the Matter devices no integration claims. */
4556
- const MATTER_VENDOR = "matter";
4557
4599
  /** The UDP port the controller listens on, which the engine does not let anyone change. */
4558
4600
  const MATTER_PORT = 5540;
4559
4601
  /** A node id, in decimal: a 64-bit number, which JSON cannot carry as a number. */
@@ -4565,7 +4607,7 @@ const matterNodeIdSchema = z.string().regex(/^[0-9]{1,20}$/u, "Must be a node id
4565
4607
  */
4566
4608
  const matterPairingCodeSchema = z.string().trim().max(128).transform((code) => code.startsWith("MT:") ? code : code.replaceAll(/[\s-]/gu, "")).pipe(z.string().regex(/^(?:[0-9]{11}|[0-9]{21}|MT:[0-9A-Z.-]{19,})$/u, "Must be the 11 or 21 digits of a pairing code, or the text of its QR code (MT:…)"));
4567
4609
  /** How many items a list in an identity holds at most. */
4568
- const MAXIMUM_LIST = 64;
4610
+ const MAXIMUM_LIST$1 = 64;
4569
4611
  /**
4570
4612
  * Who a Matter device says it is: what an integration's rules match and the Brokers page shows.
4571
4613
  *
@@ -4589,9 +4631,9 @@ const matterIdentitySchema = z.object({
4589
4631
  softwareVersion: z.int().min(0).nullable(),
4590
4632
  softwareVersionString: z.string().max(256).nullable(),
4591
4633
  /** The hardware addresses of its network interfaces, lower-case and colon-separated. */
4592
- macAddresses: z.array(z.string().max(64)).max(MAXIMUM_LIST),
4634
+ macAddresses: z.array(z.string().max(64)).max(MAXIMUM_LIST$1),
4593
4635
  /** The Matter device types it declares, by number: `256` an on/off light. */
4594
- deviceTypes: z.array(z.int().min(0)).max(MAXIMUM_LIST),
4636
+ deviceTypes: z.array(z.int().min(0)).max(MAXIMUM_LIST$1),
4595
4637
  /** The clusters its endpoints serve, by number, each once. */
4596
4638
  clusters: z.array(z.int().min(0)).max(256),
4597
4639
  /** Whether the node is a bridge, with devices of its own behind it. */
@@ -4599,22 +4641,17 @@ const matterIdentitySchema = z.object({
4599
4641
  /** Whether this is a device behind a bridge. */
4600
4642
  isBridged: z.boolean()
4601
4643
  });
4602
- /** How the controller stands. */
4603
- const MATTER_CONTROLLER_STATES = [
4604
- "starting",
4605
- "running",
4606
- "failed",
4607
- "disabled"
4608
- ];
4609
4644
  /**
4610
4645
  * How a commissioning goes. `needs-answer` is a job that stopped before the node joined and waits
4611
4646
  * for the owner: a device whose certificate is a test one, added only when they say so.
4647
+ * `cancelled` is a job the owner stopped before the device joined.
4612
4648
  */
4613
4649
  const MATTER_COMMISSIONING_STATES = [
4614
4650
  "running",
4615
4651
  "needs-answer",
4616
4652
  "succeeded",
4617
- "failed"
4653
+ "failed",
4654
+ "cancelled"
4618
4655
  ];
4619
4656
  /**
4620
4657
  * The steps of a commissioning, in order: the code read, the device found on the network, its
@@ -4679,7 +4716,7 @@ const matterCommissioningSchema = z.object({
4679
4716
  deviceId: integrationIdSchema.nullable().default(null)
4680
4717
  });
4681
4718
  z.object({
4682
- state: z.enum(MATTER_CONTROLLER_STATES),
4719
+ state: z.enum(BROKER_STATES),
4683
4720
  /** Why it failed or is off, in a sentence; null while it runs. */
4684
4721
  error: z.string().max(2048).nullable(),
4685
4722
  /** The fabric's id, in hex; null before the controller has one. */
@@ -4736,6 +4773,74 @@ const matterNodeSchema = z.object({
4736
4773
  z.object({});
4737
4774
  z.object({});
4738
4775
  z.object({ items: z.array(matterNodeSchema) });
4776
+ /**
4777
+ * What a point of the fabric's network is, as the controller works it out: a node of the fabric;
4778
+ * a Thread border router found over mDNS; a Thread device some node hears that is not on this
4779
+ * fabric (a border router too, when the house does not look for them); a Wi-Fi access point, made
4780
+ * up from the BSSID its stations report.
4781
+ */
4782
+ const MATTER_NETWORK_KINDS = [
4783
+ "matter",
4784
+ "border_router",
4785
+ "thread_unknown",
4786
+ "wifi_ap"
4787
+ ];
4788
+ /** How a point reaches the network. */
4789
+ const MATTER_NETWORKS = [
4790
+ "thread",
4791
+ "wifi",
4792
+ "ethernet",
4793
+ "unknown"
4794
+ ];
4795
+ /** How good a link is: Thread by LQI, Wi-Fi by RSSI; `unknown` is a link nobody measured. */
4796
+ const MATTER_LINK_STRENGTHS = [
4797
+ "strong",
4798
+ "medium",
4799
+ "weak",
4800
+ "none",
4801
+ "unknown"
4802
+ ];
4803
+ /** One point of the fabric's network. */
4804
+ const matterNetworkNodeSchema = z.object({
4805
+ /** The controller's id for it: the node id for a node, `ap_<BSSID>`, `unknown_<address>`. */
4806
+ id: z.string().min(1).max(64),
4807
+ kind: z.enum(MATTER_NETWORK_KINDS),
4808
+ network: z.enum(MATTER_NETWORKS),
4809
+ /** The node, for a node of the fabric. */
4810
+ nodeId: matterNodeIdSchema.nullable(),
4811
+ /** Leader, router, end device, sleepy end device, station...; null when it did not say. */
4812
+ role: z.string().max(32).nullable(),
4813
+ /** Whether it answers; null for what is not a node of the fabric. */
4814
+ isAvailable: z.boolean().nullable(),
4815
+ isBridge: z.boolean(),
4816
+ /** The Thread network's name. */
4817
+ networkName: z.string().max(64).nullable(),
4818
+ /** The Thread or Wi-Fi channel. */
4819
+ channel: z.number().int().min(0).max(255).nullable(),
4820
+ /** The Wi-Fi network a station is on, and the access point's address. */
4821
+ ssid: z.string().max(64).nullable(),
4822
+ bssid: z.string().max(32).nullable(),
4823
+ /** The Thread extended address: a Thread point's MAC. */
4824
+ extAddress: z.string().max(32).nullable()
4825
+ });
4826
+ /** One link between two points, as the better of its two ends reported it. */
4827
+ const matterNetworkLinkSchema = z.object({
4828
+ source: z.string().min(1).max(64),
4829
+ target: z.string().min(1).max(64),
4830
+ network: z.enum(["thread", "wifi"]),
4831
+ strength: z.enum(MATTER_LINK_STRENGTHS),
4832
+ /** Thread's link quality, 0 to 3 on OpenThread. */
4833
+ lqi: z.number().int().nullable(),
4834
+ /** The signal, in dBm. */
4835
+ rssi: z.number().int().nullable()
4836
+ });
4837
+ z.object({});
4838
+ z.object({
4839
+ /** When the controller put it together; null while the fabric is not open. */
4840
+ collectedAt: timestampSchema.nullable(),
4841
+ nodes: z.array(matterNetworkNodeSchema).max(2048),
4842
+ links: z.array(matterNetworkLinkSchema).max(8192)
4843
+ });
4739
4844
  z.object({ code: matterPairingCodeSchema });
4740
4845
  z.object({ nodeId: matterNodeIdSchema });
4741
4846
  z.object({ isRemoved: z.boolean() });
@@ -4748,23 +4853,779 @@ z.object({
4748
4853
  jobId: z.string().min(1).max(64),
4749
4854
  isAccepted: z.boolean()
4750
4855
  });
4751
- /** The brokers the platform runs, as the Brokers page lists them. */
4752
- const BROKER_IDS = [MATTER_VENDOR];
4753
- /** One broker, for its card. */
4754
- const brokerSummarySchema = z.object({
4755
- id: z.enum(BROKER_IDS),
4756
- state: z.enum(MATTER_CONTROLLER_STATES),
4757
- /**
4758
- * The devices the house has through it, how many of them answer, and how many are also
4759
- * reached another way.
4760
- */
4856
+ z.object({ jobId: z.string().min(1).max(64) });
4857
+ z.object({});
4858
+ //#endregion
4859
+ //#region ../contracts/dist/modbus.js
4860
+ /**
4861
+ * The house's Modbus broker, as the hub runs it and the Brokers page shows it.
4862
+ *
4863
+ * Modbus is one of the platform's brokers: the hub is the house's Modbus TCP client. Every
4864
+ * gateway - a Modbus TCP device, or a transparent RS485 adapter carrying RTU frames over TCP - is
4865
+ * reached through one connection, one request at a time, whoever's devices are behind it. A
4866
+ * gateway answers one client; two of them asking at once is how a dongle stops answering both.
4867
+ *
4868
+ * Modbus says nothing about what a register means, so a device is read through a **template**: its
4869
+ * entities, each capability mapped to the register it is read from and the command it is written
4870
+ * with. The owner writes templates of their own; an integration ships its own as drivers of kind
4871
+ * `modbus`. A device is a template at an address - host, port, unit - and becomes a device of the
4872
+ * house through the platform's own `modbus` vendor, or of the integration whose template it is.
4873
+ *
4874
+ * The broker recognises nothing on its own. A server found on the network is named only by an
4875
+ * integration whose `discovery.json` `modbus` rules read it and match.
4876
+ */
4877
+ /** The platform transport every Modbus device is reached through. */
4878
+ const MODBUS_TRANSPORT = "modbus";
4879
+ /** How frames travel: Modbus TCP, or RTU frames carried over TCP by a transparent adapter. */
4880
+ const MODBUS_FRAMINGS = ["tcp", "rtu"];
4881
+ /** How registers hold a value: one or two registers as integers or a float, or ASCII text. */
4882
+ const MODBUS_VALUE_TYPES = [
4883
+ "u16",
4884
+ "s16",
4885
+ "u32",
4886
+ "s32",
4887
+ "f32",
4888
+ "string"
4889
+ ];
4890
+ /** The domains a template's entity can be. */
4891
+ const MODBUS_DOMAINS = [
4892
+ "sensor",
4893
+ "binary_sensor",
4894
+ "switch",
4895
+ "light",
4896
+ "number",
4897
+ "select",
4898
+ "button"
4899
+ ];
4900
+ /** The capabilities a template maps. */
4901
+ const MODBUS_CAPABILITIES = [
4902
+ "sensor_numeric",
4903
+ "sensor_text",
4904
+ "sensor_binary",
4905
+ "on_off",
4906
+ "level",
4907
+ "number",
4908
+ "select",
4909
+ "button"
4910
+ ];
4911
+ /**
4912
+ * The capabilities each domain takes: those it must have, and those it may add.
4913
+ *
4914
+ * A sensor is a number or a text; a light switches and may dim.
4915
+ */
4916
+ const MODBUS_DOMAIN_CAPABILITIES = {
4917
+ sensor: {
4918
+ oneOf: ["sensor_numeric", "sensor_text"],
4919
+ may: []
4920
+ },
4921
+ binary_sensor: {
4922
+ oneOf: ["sensor_binary"],
4923
+ may: []
4924
+ },
4925
+ switch: {
4926
+ oneOf: ["on_off"],
4927
+ may: []
4928
+ },
4929
+ light: {
4930
+ oneOf: ["on_off"],
4931
+ may: ["level"]
4932
+ },
4933
+ number: {
4934
+ oneOf: ["number"],
4935
+ may: []
4936
+ },
4937
+ select: {
4938
+ oneOf: ["select"],
4939
+ may: []
4940
+ },
4941
+ button: {
4942
+ oneOf: ["button"],
4943
+ may: []
4944
+ }
4945
+ };
4946
+ /** The capabilities whose value is on or off, read from a bit. */
4947
+ const BOOLEAN_CAPABILITIES = /* @__PURE__ */ new Set(["sensor_binary", "on_off"]);
4948
+ /** The capabilities only read, never written. */
4949
+ const READ_ONLY_CAPABILITIES = /* @__PURE__ */ new Set([
4950
+ "sensor_numeric",
4951
+ "sensor_text",
4952
+ "sensor_binary"
4953
+ ]);
4954
+ /** A register's address or a 16-bit word: 0 to 65535, or written as `0x` and up to four hex digits. */
4955
+ const modbusWordSchema = z.union([z.int().min(0).max(65535), z.string().regex(/^0x[0-9a-fA-F]{1,4}$/u, "A number from 0 to 65535, or 0x0000 to 0xFFFF")]);
4956
+ /**
4957
+ * The number an address or a word is, however it was written.
4958
+ *
4959
+ * @param word - As the template says it.
4960
+ * @returns The number.
4961
+ */
4962
+ function modbusWordOf(word) {
4963
+ return typeof word === "number" ? word : Number.parseInt(word.slice(2), 16);
4964
+ }
4965
+ /**
4966
+ * How many registers a value of a type takes.
4967
+ *
4968
+ * @param type - How the registers hold it.
4969
+ * @param count - How many a text takes.
4970
+ * @returns Two for 32 bits, `count` for text, one otherwise.
4971
+ */
4972
+ function modbusRegistersOf(type, count = 1) {
4973
+ return type === "string" ? count : type === "u32" || type === "s32" || type === "f32" ? 2 : 1;
4974
+ }
4975
+ /** Where a capability's value is read from, and how it is turned into one. */
4976
+ const modbusReadSchema = z.strictObject({
4977
+ function: z.union([
4978
+ z.literal(1),
4979
+ z.literal(2),
4980
+ z.literal(3),
4981
+ z.literal(4)
4982
+ ]),
4983
+ address: modbusWordSchema,
4984
+ /** How the registers hold it; one unsigned register unless said. Not for coils and inputs. */
4985
+ type: z.enum(MODBUS_VALUE_TYPES).optional(),
4986
+ /** How many registers a text takes. */
4987
+ count: z.int().min(1).max(64).optional(),
4988
+ /** The bit of a register an on/off value is, 0 the lowest. */
4989
+ bit: z.int().min(0).max(15).optional(),
4990
+ /** What the raw number is multiplied by: 0.1 for tenths. */
4991
+ scale: z.number().refine((scale) => scale !== 0, "Not zero").optional(),
4992
+ /** One of the units the platform knows (`SENSOR_UNIT_IDS`): `W`, `kWh`, `°C`. */
4993
+ unit: z.string().refine((unit) => SENSOR_UNIT_IDS.has(unit), "Not a unit the platform knows").optional(),
4994
+ /** What each raw number means, for a choice or a text: `{ "0": "Off", "1": "Eco" }`. */
4995
+ options: z.record(z.string().regex(/^-?\d{1,10}$/u, "A whole number"), z.string().trim().min(1).max(64)).optional()
4996
+ });
4997
+ /** What a capability's command writes, and within what. */
4998
+ const modbusWriteSchema = z.strictObject({
4999
+ function: z.union([
5000
+ z.literal(5),
5001
+ z.literal(6),
5002
+ z.literal(15),
5003
+ z.literal(16)
5004
+ ]),
5005
+ /** Where; the read's address when left out, if the read's table can be written. */
5006
+ address: modbusWordSchema.optional(),
5007
+ /** The words on and off are written as; 0xFF00 and 0 for a coil, 1 and 0 for a register. */
5008
+ on: modbusWordSchema.optional(),
5009
+ off: modbusWordSchema.optional(),
5010
+ /** The values a number may be set to; a value outside them never reaches the device. */
5011
+ min: z.number().optional(),
5012
+ max: z.number().optional(),
5013
+ step: z.number().positive().optional(),
5014
+ /** The word a button writes when pressed. */
5015
+ value: modbusWordSchema.optional()
5016
+ });
5017
+ /** One capability of an entity: where it is read, and what its command writes. */
5018
+ const modbusCapabilityMapSchema = z.strictObject({
5019
+ read: modbusReadSchema.optional(),
5020
+ write: modbusWriteSchema.optional()
5021
+ });
5022
+ /** An entity's own part of its identifier: what stays when it is renamed. */
5023
+ const MODBUS_ENTITY_ID_PATTERN = /^[a-z0-9][a-z0-9_]{0,39}$/u;
5024
+ /**
5025
+ * The identifier an entity of that name is given: lower case, words joined by `_`.
5026
+ *
5027
+ * @param name - The entity's name.
5028
+ * @returns Its identifier, `entity` when the name has no letter or digit.
5029
+ */
5030
+ function modbusEntityIdOf(name) {
5031
+ const slug = name.normalize("NFKD").toLowerCase().replaceAll(/[^a-z0-9]+/gu, "_").replaceAll(/^_+|_+$/gu, "").slice(0, 40).replace(/_+$/u, "");
5032
+ return slug === "" ? "entity" : slug;
5033
+ }
5034
+ /** One entity of a template. */
5035
+ const modbusEntitySchema = z.strictObject({
5036
+ /** What it stays when renamed; given from the name when saved. */
5037
+ id: z.string().regex(MODBUS_ENTITY_ID_PATTERN, "Lower-case letters, digits and _").optional(),
5038
+ name: z.string().trim().min(1, "Needed: a name").max(64),
5039
+ /** The catalogue icon it starts with; the domain's when left out. */
5040
+ icon: iconIdSchema.optional(),
5041
+ domain: z.enum(MODBUS_DOMAINS),
5042
+ capabilities: z.partialRecord(z.enum(MODBUS_CAPABILITIES), modbusCapabilityMapSchema)
5043
+ });
5044
+ /**
5045
+ * A template's fields, before the rules that tie them together: what the editor reads a file with
5046
+ * to show a refused template's problems on its blocks.
5047
+ */
5048
+ const modbusTemplateFieldsSchema = z.strictObject({
5049
+ name: z.string().trim().min(1, "Needed: a name").max(64),
5050
+ /** The device it is for, as its maker names it. */
5051
+ device: z.string().trim().max(128).default(""),
5052
+ /** Where such a device usually listens, offered when one is added. */
5053
+ port: z.int().min(1).max(65535).default(502),
5054
+ unitId: z.int().min(1).max(247).default(1),
5055
+ /** Which register of a 32-bit value holds the high word: the first, or the second. */
5056
+ wordOrder: z.enum(["high", "low"]).default("high"),
5057
+ /** How often the device is read. */
5058
+ pollSeconds: z.int().min(1).max(3600).default(10),
5059
+ entities: z.array(modbusEntitySchema).min(1, "Add at least one entity").max(256)
5060
+ });
5061
+ /**
5062
+ * Says what is wrong with one capability's mapping, or nothing.
5063
+ *
5064
+ * @param capability - The capability.
5065
+ * @param map - Its read and write.
5066
+ * @param add - Reports a problem at a path below the capability.
5067
+ */
5068
+ function checkCapability(capability, map, add) {
5069
+ const { read, write } = map;
5070
+ const isBoolean = BOOLEAN_CAPABILITIES.has(capability);
5071
+ if (read === void 0 && capability !== "button" && capability !== "level") add(["read"], "Needed: where the value is read from");
5072
+ if (read !== void 0) {
5073
+ const isBitTable = read.function === 1 || read.function === 2;
5074
+ if (capability === "button") add(["read"], "A button is only pressed: leave the read out");
5075
+ else if (isBitTable && !isBoolean) add(["read", "function"], capability === "sensor_text" ? "A text is read from registers: use 03 or 04" : "A number is read from registers: use 03 or 04");
5076
+ if (isBitTable && read.type !== void 0) add(["read", "type"], "Coils and inputs are bits: leave the type out");
5077
+ if (read.bit !== void 0 && (isBitTable || !isBoolean)) add(["read", "bit"], "A bit is read from a register, for an on/off value");
5078
+ if (read.type === "string" && read.count === void 0) add(["read", "count"], "Needed: how many registers the text takes");
5079
+ if (read.count !== void 0 && read.type !== "string") add(["read", "count"], "Only a text takes several registers");
5080
+ if (read.type === "string" && capability !== "sensor_text") add(["read", "type"], "Only a text sensor reads a string");
5081
+ if (capability === "sensor_text" && read.type !== "string" && read.options === void 0) add(["read", "type"], "A text is a string, or a number with options");
5082
+ if (capability === "select" && read.options === void 0) add(["read", "options"], "Needed: what each value means");
5083
+ }
5084
+ if (write === void 0) {
5085
+ if (capability === "button" || capability === "number" || capability === "select") add(["write"], "Needed: what the command writes");
5086
+ if (capability === "level" && read === void 0) add(["read"], "Needed: where the value is read from, or what is written");
5087
+ return;
5088
+ }
5089
+ if (READ_ONLY_CAPABILITIES.has(capability)) {
5090
+ add(["write"], "A sensor is only read: leave the write out");
5091
+ return;
5092
+ }
5093
+ const isCoilWrite = write.function === 5 || write.function === 15;
5094
+ if (isCoilWrite && !isBoolean && capability !== "button") add(["write", "function"], "A number is written to registers: use 06 or 16");
5095
+ if (write.address === void 0) {
5096
+ if (read === void 0) add(["write", "address"], "Needed: there is no read to take it from");
5097
+ else if (read.function === 2 || read.function === 4) add(["write", "address"], `Needed: function 0${String(read.function)} reads a table that cannot be written`);
5098
+ else if (read.function === 1 && !isCoilWrite) add(["write", "function"], "The read is a coil: write it with 05 or 15");
5099
+ else if (read.function === 3 && isCoilWrite) add(["write", "function"], "The read is a register: write it with 06 or 16");
5100
+ }
5101
+ const type = read?.type ?? "u16";
5102
+ if (write.function === 6 && modbusRegistersOf(type) === 2) add(["write", "function"], "A 32-bit value takes two registers: use 16");
5103
+ if (capability === "number") {
5104
+ if (write.min === void 0) add(["write", "min"], "Needed: the lowest value");
5105
+ if (write.max === void 0) add(["write", "max"], "Needed: the highest value");
5106
+ if (write.min !== void 0 && write.max !== void 0 && write.min >= write.max) add(["write", "max"], "Must be above min");
5107
+ } else if (write.min !== void 0 && write.max !== void 0 && write.min >= write.max) add(["write", "max"], "Must be above min");
5108
+ }
5109
+ /**
5110
+ * A template: the device's entities, each capability mapped to the register it is read from and
5111
+ * the command it is written with.
5112
+ *
5113
+ * Every rule that ties fields together is here, so the editor's blocks, its file and the hub
5114
+ * refuse the same templates with the same words.
5115
+ */
5116
+ const modbusTemplateSchema = modbusTemplateFieldsSchema.superRefine((template, context) => {
5117
+ const ids = /* @__PURE__ */ new Set();
5118
+ template.entities.forEach((entity, index) => {
5119
+ /**
5120
+ * Reports a problem of this entity.
5121
+ *
5122
+ * @param path - Where, below the entity.
5123
+ * @param message - What, in a sentence.
5124
+ */
5125
+ const add = (path, message) => {
5126
+ context.addIssue({
5127
+ code: "custom",
5128
+ path: [
5129
+ "entities",
5130
+ index,
5131
+ ...path
5132
+ ],
5133
+ message
5134
+ });
5135
+ };
5136
+ const id = entity.id ?? modbusEntityIdOf(entity.name);
5137
+ if (ids.has(id)) add([entity.id === void 0 ? "name" : "id"], "Another entity has the same id");
5138
+ ids.add(id);
5139
+ const rule = MODBUS_DOMAIN_CAPABILITIES[entity.domain];
5140
+ const mapped = Object.keys(entity.capabilities);
5141
+ if (mapped.filter((capability) => rule.oneOf.includes(capability)).length !== 1) add(["capabilities"], `A ${entity.domain} has ${rule.oneOf.join(" or ")}`);
5142
+ for (const capability of mapped) {
5143
+ if (!rule.oneOf.includes(capability) && !rule.may.includes(capability)) {
5144
+ add(["capabilities", capability], `A ${entity.domain} has no ${capability}`);
5145
+ continue;
5146
+ }
5147
+ const map = entity.capabilities[capability];
5148
+ if (map !== void 0) checkCapability(capability, map, (path, message) => {
5149
+ add([
5150
+ "capabilities",
5151
+ capability,
5152
+ ...path
5153
+ ], message);
5154
+ });
5155
+ }
5156
+ });
5157
+ });
5158
+ /**
5159
+ * The template with every entity's id filled in from its name, as it is saved: renaming an entity
5160
+ * afterwards keeps its id, so the entity of the house it is stays the same.
5161
+ *
5162
+ * @param template - The template.
5163
+ * @returns The same, every entity with an id.
5164
+ */
5165
+ function withModbusEntityIds(template) {
5166
+ return {
5167
+ ...template,
5168
+ entities: template.entities.map((entity) => entity.id === void 0 ? {
5169
+ ...entity,
5170
+ id: modbusEntityIdOf(entity.name)
5171
+ } : entity)
5172
+ };
5173
+ }
5174
+ /** The widest network a range may name: a /16. */
5175
+ const NARROWEST_PREFIX = 16;
5176
+ /** The most addresses one range may hold, and all of them together. */
5177
+ const MODBUS_SEARCH_MAXIMUM = 65536;
5178
+ /**
5179
+ * The number an IPv4 address is.
5180
+ *
5181
+ * @param text - Dotted, `192.168.1.7`.
5182
+ * @returns The number, or null for anything that is not an address.
5183
+ */
5184
+ function ipv4Of(text) {
5185
+ const parts = text.trim().split(".");
5186
+ if (parts.length !== 4 || parts.some((part) => !/^\d{1,3}$/u.test(part) || Number(part) > 255)) return null;
5187
+ return parts.reduce((total, part) => total * 256 + Number(part), 0);
5188
+ }
5189
+ /**
5190
+ * The addresses a range the owner wrote names.
5191
+ *
5192
+ * @param text - A network `10.0.0.0/24` (a /16 to a /32), a span `10.0.0.20-10.0.0.40` of at most
5193
+ * 65536 addresses, or one address.
5194
+ * @returns The first and last address as numbers, or null when it is none of those.
5195
+ */
5196
+ function ipv4RangeOf(text) {
5197
+ const trimmed = text.trim();
5198
+ const network = /^([\d.]+)\/(\d{1,2})$/u.exec(trimmed);
5199
+ if (network !== null) {
5200
+ const base = ipv4Of(network[1] ?? "");
5201
+ const prefix = Number(network[2]);
5202
+ if (base === null || prefix < NARROWEST_PREFIX || prefix > 32) return null;
5203
+ const size = 2 ** (32 - prefix);
5204
+ const first = base - base % size;
5205
+ return {
5206
+ first,
5207
+ last: first + size - 1
5208
+ };
5209
+ }
5210
+ const span = /^([\d.]+)\s*-\s*([\d.]+)$/u.exec(trimmed);
5211
+ if (span !== null) {
5212
+ const first = ipv4Of(span[1] ?? "");
5213
+ const last = ipv4Of(span[2] ?? "");
5214
+ return first === null || last === null || last < first || last - first + 1 > 65536 ? null : {
5215
+ first,
5216
+ last
5217
+ };
5218
+ }
5219
+ const single = ipv4Of(trimmed);
5220
+ return single === null ? null : {
5221
+ first: single,
5222
+ last: single
5223
+ };
5224
+ }
5225
+ /** The owner's settings: whether and where the network is searched, and how often. */
5226
+ const modbusSettingsSchema = z.object({
5227
+ isSearchEnabled: z.boolean().default(false),
5228
+ /** Where to search; the networks the hub is on, up to a /22 each, when there is none. */
5229
+ ranges: z.array(z.string().trim().max(64).refine((range) => ipv4RangeOf(range) !== null, "Not a range: write 10.0.0.0/24, 10.0.0.20-10.0.0.40 or 10.0.0.7")).max(16).default([]),
5230
+ intervalMinutes: z.int().min(15).max(1440).default(120)
5231
+ }).refine((settings) => settings.ranges.reduce((total, range) => {
5232
+ const span = ipv4RangeOf(range);
5233
+ return total + (span === null ? 0 : span.last - span.first + 1);
5234
+ }, 0) <= MODBUS_SEARCH_MAXIMUM, {
5235
+ message: `At most ${String(MODBUS_SEARCH_MAXIMUM)} addresses in all`,
5236
+ path: ["ranges"]
5237
+ });
5238
+ /** A host: an IPv4 address or a name. */
5239
+ const hostSchema = z.string().trim().min(1).max(253).regex(/^[A-Za-z0-9.-]+$/u, "An address or a host name");
5240
+ /** One device behind a server: the server, and its unit. */
5241
+ const modbusTargetSchema = z.object({
5242
+ host: hostSchema,
5243
+ port: z.int().min(1).max(65535).default(502),
5244
+ framing: z.enum(MODBUS_FRAMINGS).default("tcp")
5245
+ }).extend({ unitId: z.int().min(1).max(247).default(1) });
5246
+ /** One search of the network, as it ended. */
5247
+ const modbusSearchRunSchema = z.object({
5248
+ at: timestampSchema,
5249
+ durationMs: z.int().min(0),
5250
+ /** How many addresses it knocked on, and how many answered on the port. */
5251
+ addresses: z.int().min(0),
5252
+ answered: z.int().min(0)
5253
+ });
5254
+ z.object({
5255
+ state: z.enum(BROKER_STATES),
5256
+ error: z.string().max(2048).nullable(),
5257
+ startedAt: timestampSchema.nullable(),
5258
+ settings: modbusSettingsSchema,
5259
+ search: z.object({
5260
+ isRunning: z.boolean(),
5261
+ lastRun: modbusSearchRunSchema.nullable(),
5262
+ /** When the next one starts; null while searching is off. */
5263
+ nextAt: timestampSchema.nullable()
5264
+ }),
4761
5265
  devices: z.object({
4762
5266
  total: z.int().min(0),
4763
- online: z.int().min(0),
4764
- linked: z.int().min(0).default(0)
5267
+ online: z.int().min(0)
5268
+ }),
5269
+ /** How many servers the hub holds a connection to. */
5270
+ gateways: z.int().min(0),
5271
+ /** Requests in the last minute, and how long they took on average; null before any. */
5272
+ requestsPerMinute: z.int().min(0),
5273
+ averageMs: z.number().min(0).nullable()
5274
+ });
5275
+ /** A device of the house, with how it answers. */
5276
+ const modbusDeviceSchema = modbusTargetSchema.extend({
5277
+ /** Its id; a new one is given one. */
5278
+ id: z.uuid().optional(),
5279
+ name: z.string().trim().min(1).max(128),
5280
+ /** The template it is read with: one of the owner's, by id, or an integration's driver. */
5281
+ template: z.union([z.uuid(), integrationKindIdSchema]),
5282
+ /** How often it is read, instead of what the template says; null for the template's. */
5283
+ pollSeconds: z.int().min(1).max(3600).nullable().default(null)
5284
+ }).extend({
5285
+ id: z.uuid(),
5286
+ /** The template's name; null when it is gone - an integration removed. */
5287
+ templateName: z.string().max(64).nullable(),
5288
+ /** The integration whose template it is; null for one of the owner's. */
5289
+ vendorId: z.string().regex(VENDOR_ID_PATTERN$1).nullable(),
5290
+ /** How often it is read now. */
5291
+ everySeconds: z.int().min(1),
5292
+ state: z.enum([
5293
+ "online",
5294
+ "offline",
5295
+ "waiting"
5296
+ ]),
5297
+ lastReadAt: timestampSchema.nullable(),
5298
+ /** Why the last read failed, in a sentence; null when it did not. */
5299
+ lastError: z.string().max(512).nullable(),
5300
+ /** The device added for it; null until it is. */
5301
+ deviceId: integrationIdSchema.nullable()
5302
+ });
5303
+ z.object({ items: z.array(modbusDeviceSchema) });
5304
+ z.object({ id: z.uuid() });
5305
+ z.object({ isRemoved: z.boolean() });
5306
+ /** A template, with whose it is and who uses it. */
5307
+ const modbusTemplateRecordSchema = z.object({
5308
+ /** One of the owner's by uuid, or an integration's by its driver: `vendor/driver`. */
5309
+ id: z.string().min(1).max(160),
5310
+ /** The integration that ships it, and its name; null for one of the owner's. */
5311
+ vendorId: z.string().regex(VENDOR_ID_PATTERN$1).nullable(),
5312
+ vendorName: z.string().max(128).nullable(),
5313
+ document: modbusTemplateSchema,
5314
+ /** An integration's is read-only: it is duplicated to be changed. */
5315
+ isReadOnly: z.boolean(),
5316
+ usedBy: z.int().min(0),
5317
+ updatedAt: timestampSchema.nullable()
5318
+ });
5319
+ z.object({ items: z.array(modbusTemplateRecordSchema) });
5320
+ z.object({
5321
+ id: z.uuid().optional(),
5322
+ document: modbusTemplateSchema
5323
+ });
5324
+ /** An integration that recognises a server, and the driver it would read it with. */
5325
+ const modbusClaimSchema = z.object({
5326
+ vendorId: z.string().regex(VENDOR_ID_PATTERN$1),
5327
+ vendorName: z.string().max(128),
5328
+ /** The driver it would be added as; null when the integration has no template for it. */
5329
+ kind: integrationKindIdSchema.nullable(),
5330
+ model: z.string().max(128).nullable(),
5331
+ unitId: z.int().min(1).max(247)
5332
+ });
5333
+ /** A server the network search found that is not a device of the house. */
5334
+ const modbusFoundSchema = z.object({
5335
+ host: z.string().max(253),
5336
+ port: z.int().min(1).max(65535),
5337
+ foundAt: timestampSchema,
5338
+ claims: z.array(modbusClaimSchema).max(16)
5339
+ });
5340
+ /** A server the owner ignores: it is never offered again. */
5341
+ const modbusIgnoredSchema = z.object({
5342
+ host: z.string().max(253),
5343
+ port: z.int().min(1).max(65535),
5344
+ at: timestampSchema
5345
+ });
5346
+ z.object({
5347
+ items: z.array(modbusFoundSchema),
5348
+ ignored: z.array(modbusIgnoredSchema)
5349
+ });
5350
+ z.object({
5351
+ host: hostSchema,
5352
+ port: z.int().min(1).max(65535),
5353
+ isIgnored: z.boolean()
5354
+ });
5355
+ z.object({ count: z.int().min(0) });
5356
+ z.object({ target: modbusTargetSchema });
5357
+ z.object({
5358
+ isAnswering: z.boolean(),
5359
+ ms: z.int().min(0).nullable(),
5360
+ /** Why it did not answer, or the exception it answered with, in a sentence. */
5361
+ error: z.string().max(512).nullable(),
5362
+ claims: z.array(modbusClaimSchema).max(16)
5363
+ });
5364
+ /** What a test read or write sent and got back. */
5365
+ const exchangeShape = {
5366
+ /** The request's PDU, hex: `01 00 00 00 01`. */
5367
+ request: z.string().max(1024),
5368
+ /** The answer's PDU, hex; null when none came. */
5369
+ response: z.string().max(1024).nullable(),
5370
+ /** Why it failed, in a sentence; null when it did not. */
5371
+ error: z.string().max(512).nullable(),
5372
+ ms: z.int().min(0)
5373
+ };
5374
+ /** A value as a test shows it. */
5375
+ const testValueSchema = z.union([
5376
+ z.number(),
5377
+ z.string(),
5378
+ z.boolean()
5379
+ ]).nullable();
5380
+ z.object({
5381
+ target: modbusTargetSchema,
5382
+ wordOrder: z.enum(["high", "low"]).default("high"),
5383
+ read: modbusReadSchema
5384
+ });
5385
+ z.object({
5386
+ ...exchangeShape,
5387
+ raw: z.array(z.int()).max(128).nullable(),
5388
+ value: testValueSchema
5389
+ });
5390
+ z.object({
5391
+ target: modbusTargetSchema,
5392
+ wordOrder: z.enum(["high", "low"]).default("high"),
5393
+ entity: modbusEntitySchema,
5394
+ capability: z.enum(MODBUS_CAPABILITIES),
5395
+ command: z.record(z.string(), z.unknown())
5396
+ });
5397
+ z.object(exchangeShape);
5398
+ z.object({
5399
+ target: modbusTargetSchema,
5400
+ document: modbusTemplateSchema
5401
+ });
5402
+ z.object({
5403
+ at: timestampSchema,
5404
+ ms: z.int().min(0),
5405
+ values: z.array(z.object({
5406
+ entity: z.int().min(0),
5407
+ capability: z.enum(MODBUS_CAPABILITIES),
5408
+ value: testValueSchema,
5409
+ error: z.string().max(512).nullable()
5410
+ }))
5411
+ });
5412
+ //#endregion
5413
+ //#region ../contracts/dist/mqtt.js
5414
+ /**
5415
+ * The house's MQTT broker, as the hub runs it and the Brokers page shows it.
5416
+ *
5417
+ * MQTT is one of the platform's brokers: the hub listens on the house's network - port 1883 - and
5418
+ * every MQTT device and program of the house meets on it. Who may connect is the broker's to say:
5419
+ * the hub, a container the platform runs (Zigbee2MQTT), and each client the owner adds, held to
5420
+ * the topics it was given.
5421
+ *
5422
+ * What it carries becomes devices of the house two ways. A device that announces itself - the
5423
+ * MQTT discovery convention most firmware speaks, a retained JSON document on
5424
+ * `<prefix>/<component>/[<node>/]<object>/config` - is added at once, and so is one the owner
5425
+ * maps by hand from the topic it publishes on. Each is a device of the integration whose
5426
+ * `discovery.json` recognises it from {@link mqttIdentitySchema}, or of the platform's own `mqtt`
5427
+ * vendor when none does.
5428
+ */
5429
+ /** The platform transport every device the broker hears is reached through. */
5430
+ const MQTT_HOUSE_TRANSPORT = "mqtt-house";
5431
+ /** The components of an announcement the broker turns into entities. */
5432
+ const MQTT_COMPONENTS = [
5433
+ "sensor",
5434
+ "binary_sensor",
5435
+ "switch",
5436
+ "light",
5437
+ "cover",
5438
+ "button",
5439
+ "number",
5440
+ "select",
5441
+ "lock"
5442
+ ];
5443
+ /** What the owner maps by hand: a sensor, a binary sensor or a switch. */
5444
+ const MQTT_MAPPING_COMPONENTS = [
5445
+ "sensor",
5446
+ "binary_sensor",
5447
+ "switch"
5448
+ ];
5449
+ /** How many items a list in an identity holds at most. */
5450
+ const MAXIMUM_LIST = 64;
5451
+ /** The owner's settings of the broker. */
5452
+ const mqttSettingsSchema = z.object({
5453
+ /** Whether a client may connect without a username. */
5454
+ allowAnonymous: z.boolean().default(false),
5455
+ /** Whether devices that announce themselves are added. */
5456
+ isDiscoveryEnabled: z.boolean().default(true),
5457
+ /** The topic announcements are published under: what the devices' firmware uses. */
5458
+ discoveryPrefix: z.string().trim().max(64).regex(/^[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*$/u, "Topic levels of letters, digits, - and _").default("homeassistant")
5459
+ });
5460
+ /**
5461
+ * Who a device the broker hears says it is: what an integration's rules match and the Brokers
5462
+ * page shows.
5463
+ *
5464
+ * What an announcement's `device` and `origin` blocks say, each field null when it does not say
5465
+ * it. `deviceKey` is the device's own identifier - its first identifier, or its first connection
5466
+ * - which is also its external id.
5467
+ */
5468
+ const mqttIdentitySchema = z.object({
5469
+ deviceKey: z.string().min(1).max(256),
5470
+ source: z.enum([
5471
+ "announced",
5472
+ "mapped",
5473
+ "broker"
5474
+ ]),
5475
+ name: z.string().max(256),
5476
+ manufacturer: z.string().max(256).nullable(),
5477
+ model: z.string().max(256).nullable(),
5478
+ modelId: z.string().max(256).nullable(),
5479
+ swVersion: z.string().max(256).nullable(),
5480
+ hwVersion: z.string().max(256).nullable(),
5481
+ serialNumber: z.string().max(256).nullable(),
5482
+ /** Every identifier it announces. */
5483
+ identifiers: z.array(z.string().max(256)).max(MAXIMUM_LIST),
5484
+ /** The hardware addresses among its connections, lower-case and colon-separated. */
5485
+ macAddresses: z.array(z.string().max(64)).max(MAXIMUM_LIST),
5486
+ /** The device it is reached through, by that device's identifier. */
5487
+ viaDevice: z.string().max(256).nullable(),
5488
+ /** The firmware or program that announced it - `Tasmota`, `Zigbee2MQTT` - and its version. */
5489
+ originName: z.string().max(256).nullable(),
5490
+ originSwVersion: z.string().max(256).nullable(),
5491
+ /** The components its entities are, each once. */
5492
+ components: z.array(z.enum(MQTT_COMPONENTS)).max(MQTT_COMPONENTS.length)
5493
+ });
5494
+ /** An announcement the broker did not take, and why. */
5495
+ const mqttSkippedSchema = z.object({
5496
+ topic: z.string().max(512),
5497
+ reason: z.string().max(512)
5498
+ });
5499
+ z.object({
5500
+ state: z.enum(BROKER_STATES),
5501
+ /** Why it failed, in a sentence; null while it runs. */
5502
+ error: z.string().max(2048).nullable(),
5503
+ /** The TCP port it listens on, or is to. */
5504
+ port: z.int().min(0).max(65535),
5505
+ /** When it last started listening; null while it is not. */
5506
+ startedAt: timestampSchema.nullable(),
5507
+ settings: mqttSettingsSchema,
5508
+ clientsOnline: z.int().min(0),
5509
+ messagesPerSecond: z.number().min(0),
5510
+ /** What it makes of what it carries: the entities announced and mapped, and their devices. */
5511
+ discovery: z.object({
5512
+ announced: z.int().min(0),
5513
+ mapped: z.int().min(0),
5514
+ devices: z.int().min(0),
5515
+ /** The latest announcements it did not take, the newest last. */
5516
+ skipped: z.array(mqttSkippedSchema).max(50)
4765
5517
  })
4766
5518
  });
4767
- z.object({ items: z.array(brokerSummarySchema) });
5519
+ /** One device the broker hears, with the device it is in the house. */
5520
+ const mqttDeviceSchema = z.object({
5521
+ identity: mqttIdentitySchema,
5522
+ /** How many entities it has. */
5523
+ entityCount: z.int().min(0),
5524
+ /** The device added for it; null while it is not, or after it was removed from the house. */
5525
+ deviceId: integrationIdSchema.nullable(),
5526
+ /** The driver it was added as; null while it is not added. */
5527
+ kind: integrationKindIdSchema.nullable(),
5528
+ /**
5529
+ * The integrations whose rules all take it. One is the integration it belongs to; several, and
5530
+ * it is added as the platform's own and the page says who else wants it.
5531
+ */
5532
+ claimedBy: z.array(z.string().regex(VENDOR_ID_PATTERN$1)).max(16),
5533
+ /** Removed from the house while the broker still hears it: the page offers it back. */
5534
+ isRemoved: z.boolean()
5535
+ });
5536
+ z.object({ items: z.array(mqttDeviceSchema) });
5537
+ z.object({ deviceKey: z.string().min(1).max(256) });
5538
+ z.object({ isRestored: z.boolean() });
5539
+ /** Who a username is: the hub, a container the platform runs, or a client the owner added. */
5540
+ const MQTT_PRINCIPAL_KINDS = [
5541
+ "hub",
5542
+ "container",
5543
+ "client"
5544
+ ];
5545
+ /** One connection to the broker. */
5546
+ const mqttSessionSchema = z.object({
5547
+ clientId: z.string().max(256),
5548
+ username: z.string().max(64).nullable(),
5549
+ address: z.string().max(256).nullable(),
5550
+ connectedAt: timestampSchema
5551
+ });
5552
+ /** One username, what it may reach, and its connections now. */
5553
+ const mqttPrincipalSchema = z.object({
5554
+ username: z.string().max(64),
5555
+ kind: z.enum(MQTT_PRINCIPAL_KINDS),
5556
+ label: z.string().max(128),
5557
+ publish: z.array(z.string().max(256)).max(32),
5558
+ subscribe: z.array(z.string().max(256)).max(32),
5559
+ createdAt: timestampSchema,
5560
+ sessions: z.array(mqttSessionSchema)
5561
+ });
5562
+ z.object({
5563
+ items: z.array(mqttPrincipalSchema),
5564
+ anonymous: z.array(mqttSessionSchema)
5565
+ });
5566
+ /** The usernames the platform keeps for itself begin with this. */
5567
+ const MQTT_PLATFORM_PREFIX = "nebula-";
5568
+ z.object({
5569
+ username: z.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/u, "Lower-case letters, digits, - and _").refine((username) => !username.startsWith(MQTT_PLATFORM_PREFIX), { message: `Usernames beginning with ${MQTT_PLATFORM_PREFIX} are the platform's` }),
5570
+ label: z.string().trim().max(64).default(""),
5571
+ access: z.enum(["prefix", "all"]).default("prefix")
5572
+ });
5573
+ z.object({
5574
+ username: z.string().max(64),
5575
+ password: z.string().min(1)
5576
+ });
5577
+ z.object({ username: z.string().min(1).max(64) });
5578
+ z.object({ isRemoved: z.boolean() });
5579
+ z.object({
5580
+ prefix: z.string().max(256).default(""),
5581
+ limit: z.int().min(1).max(2e3).default(500)
5582
+ });
5583
+ /** One topic, and its last message. */
5584
+ const mqttTopicSchema = z.object({
5585
+ topic: z.string(),
5586
+ /** Its last payload as text, cut; `<n bytes>` for one that is not text. */
5587
+ payload: z.string(),
5588
+ size: z.int().min(0),
5589
+ isRetained: z.boolean(),
5590
+ updatedAt: timestampSchema,
5591
+ /** How many messages it carried since the broker started. */
5592
+ count: z.int().min(0)
5593
+ });
5594
+ z.object({
5595
+ items: z.array(mqttTopicSchema),
5596
+ total: z.int().min(0)
5597
+ });
5598
+ /** A topic a client may publish on: no wildcards, no `$`. */
5599
+ const mappedTopicSchema = z.string().trim().min(1).max(256).regex(/^[^#+$][^#+]*$/u, "A topic, without wildcards");
5600
+ /** A mapping, saved. */
5601
+ const mqttMappingSchema = z.strictObject({
5602
+ /** Its id; a new one is given one. */
5603
+ id: z.string().regex(/^[a-z0-9-]{1,40}$/u).optional(),
5604
+ name: z.string().trim().min(1).max(64),
5605
+ component: z.enum(MQTT_MAPPING_COMPONENTS),
5606
+ stateTopic: mappedTopicSchema,
5607
+ /** Where the value is in a JSON payload, dotted: `AM2301.Temperature`. Empty for the payload. */
5608
+ valuePath: z.string().trim().max(128).regex(/^$|^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/u, "Keys separated by dots").default(""),
5609
+ unit: z.string().trim().max(16).default(""),
5610
+ deviceClass: z.string().trim().max(32).default(""),
5611
+ commandTopic: mappedTopicSchema.optional(),
5612
+ payloadOn: z.string().max(64).default("ON"),
5613
+ payloadOff: z.string().max(64).default("OFF")
5614
+ }).extend({ id: z.string().regex(/^[a-z0-9-]{1,40}$/u) });
5615
+ z.object({ items: z.array(mqttMappingSchema) });
5616
+ z.object({ id: z.string().min(1).max(64) });
5617
+ z.object({ isRemoved: z.boolean() });
5618
+ z.strictObject({
5619
+ /** Whose container: `vendor:zigbee2mqtt`, `package:nvr`. */
5620
+ owner: z.string().regex(/^(?:vendor:[a-z]|package:[a-z0-9])[a-z0-9-]{1,63}$/u),
5621
+ /** The topics it may use; every topic when not said. */
5622
+ topics: z.array(z.string().min(1).max(256)).max(16).optional()
5623
+ });
5624
+ z.object({
5625
+ username: z.string().min(1),
5626
+ password: z.string().min(1),
5627
+ port: z.int().min(1).max(65535)
5628
+ });
4768
5629
  //#endregion
4769
5630
  //#region ../package-runtime/dist/containers.js
4770
5631
  /** A vendor setting a value is filled from: `{setup.serialPath}`. */
@@ -4830,14 +5691,23 @@ function containerDependencyProblems(deps, setup) {
4830
5691
  * requires of executable content.
4831
5692
  */
4832
5693
  /**
4833
- * Bundle kind, which is both how it is written and how far it is trusted. `matter` is a driver
4834
- * the platform's Matter mapping runs: no profile and no code, so as far trusted as a profile.
5694
+ * Bundle kind, which is both how it is written and how far it is trusted. `matter`, `mqtt` and
5695
+ * `modbus` are drivers one of the platform's broker mappings runs: no profile and no code, so as
5696
+ * far trusted as a profile. A `modbus` driver names its template, which the mapping reads.
4835
5697
  */
4836
5698
  const BUNDLE_KINDS = [
4837
5699
  "declarative",
4838
5700
  "code",
4839
- "matter"
5701
+ "matter",
5702
+ "mqtt",
5703
+ "modbus"
4840
5704
  ];
5705
+ /** The transport each kind the platform's mappings run is reached on. */
5706
+ const MAPPED_KINDS = {
5707
+ matter: MATTER_TRANSPORT,
5708
+ mqtt: MQTT_HOUSE_TRANSPORT,
5709
+ modbus: MODBUS_TRANSPORT
5710
+ };
4841
5711
  /** Validates a vendor id. */
4842
5712
  const vendorIdSchema = z.string().regex(/^[a-z][a-z0-9-]{1,63}$/, "Must be a vendor id");
4843
5713
  /** Validates a driver id. */
@@ -4950,8 +5820,9 @@ const vendorManifestSchema = z.strictObject({
4950
5820
  /**
4951
5821
  * The packages and services the vendor's devices need, in the grammar a package's
4952
5822
  * manifest names its own with (PACKAGES.md 7) - `{ "services": ["mqtt-broker"] }` for a vendor
4953
- * that talks through the broker. Until what it needs runs, the vendor waits: its devices are
4954
- * not added and its instances are not started, and its page says which package it waits for.
5823
+ * that talks through the house's broker, which the platform runs and is always met. Until what
5824
+ * it needs runs, the vendor waits: its devices are not added and its instances are not started,
5825
+ * and its page says which package it waits for.
4955
5826
  */
4956
5827
  requires: packageRequiresSchema,
4957
5828
  /**
@@ -5028,6 +5899,8 @@ const driverShape = {
5028
5899
  profile: bundlePathSchema.optional(),
5029
5900
  /** Path to the entry point, relative to the driver. Code drivers only. */
5030
5901
  entry: bundlePathSchema.optional(),
5902
+ /** Path to the Modbus template, relative to the driver. Modbus drivers only. */
5903
+ template: bundlePathSchema.optional(),
5031
5904
  /**
5032
5905
  * Path to `setup.json`, relative to the driver: what setting up an instance asks.
5033
5906
  *
@@ -5043,16 +5916,27 @@ const driverShape = {
5043
5916
  * @param ctx - Where to record what is wrong.
5044
5917
  */
5045
5918
  function checkKindFiles(manifest, ctx) {
5046
- if (manifest.kind === "matter") {
5919
+ const mapped = MAPPED_KINDS[manifest.kind];
5920
+ if (manifest.kind === "modbus" && manifest.template === void 0) ctx.addIssue({
5921
+ code: "custom",
5922
+ path: ["template"],
5923
+ message: "A modbus driver must name its template"
5924
+ });
5925
+ if (manifest.kind !== "modbus" && manifest.template !== void 0) ctx.addIssue({
5926
+ code: "custom",
5927
+ path: ["template"],
5928
+ message: `A ${manifest.kind} driver must not name a template`
5929
+ });
5930
+ if (mapped !== void 0) {
5047
5931
  for (const named of ["profile", "entry"]) if (manifest[named] !== void 0) ctx.addIssue({
5048
5932
  code: "custom",
5049
5933
  path: [named],
5050
- message: `A matter driver must not name an ${named}`
5934
+ message: `A ${manifest.kind} driver must not name an ${named}`
5051
5935
  });
5052
- if (manifest.transport !== "matter") ctx.addIssue({
5936
+ if (manifest.transport !== mapped) ctx.addIssue({
5053
5937
  code: "custom",
5054
5938
  path: ["transport"],
5055
- message: `A matter driver runs on the ${MATTER_TRANSPORT} transport`
5939
+ message: `A ${manifest.kind} driver runs on the ${mapped} transport`
5056
5940
  });
5057
5941
  return;
5058
5942
  }
@@ -5167,6 +6051,7 @@ function resolveManifest(vendor, driver) {
5167
6051
  ...driver.webPagePath === void 0 ? {} : { webPagePath: driver.webPagePath },
5168
6052
  ...driver.profile === void 0 ? {} : { profile: driver.profile },
5169
6053
  ...driver.entry === void 0 ? {} : { entry: driver.entry },
6054
+ ...driver.template === void 0 ? {} : { template: driver.template },
5170
6055
  setup: driver.setup
5171
6056
  };
5172
6057
  }
@@ -5511,7 +6396,7 @@ function readStateSource(value, payload) {
5511
6396
  if (typeof value === "string") return resolvePath(payload, value);
5512
6397
  if ("present" in value) return resolvePresence(payload, value.path);
5513
6398
  const resolved = resolvePath(payload, value.path);
5514
- const found = resolved === void 0 || value.bits === void 0 && value.base === void 0 ? resolved : numberOf$1(resolved, value.bits, value.base ?? 10);
6399
+ const found = resolved === void 0 || value.bits === void 0 && value.base === void 0 ? resolved : numberOf$2(resolved, value.bits, value.base ?? 10);
5515
6400
  if (found === void 0) return;
5516
6401
  if ("map" in value) {
5517
6402
  const key = typeof found === "string" || typeof found === "number" || typeof found === "boolean" ? String(found) : void 0;
@@ -5529,7 +6414,7 @@ function readStateSource(value, payload) {
5529
6414
  * @returns The number, or its bits unsigned; undefined when the value is no number, or no integer
5530
6415
  * where bits are read.
5531
6416
  */
5532
- function numberOf$1(value, bits, base) {
6417
+ function numberOf$2(value, bits, base) {
5533
6418
  const text = typeof value === "string" ? value.trim() : void 0;
5534
6419
  const number = typeof value === "number" ? value : text === void 0 || text === "" ? NaN : base === 16 ? /^[0-9a-f]+$/iu.test(text) ? Number.parseInt(text, 16) : NaN : Number(text);
5535
6420
  if (!Number.isFinite(number)) return;
@@ -6298,29 +7183,78 @@ const discoveryProbeSchema = z.strictObject({
6298
7183
  timeoutMs: z.int().min(500).max(3e4).optional()
6299
7184
  });
6300
7185
  /**
6301
- * Which of the house's Matter devices are the vendor's: rules on who each says it is - its
6302
- * `vendorId`, `productName`, `macAddresses`, `deviceTypes`, every field of the platform's
6303
- * `MatterIdentity` - and where it says its model, looked up in the `modelCodes` of the vendor's
6304
- * drivers that say `"kind": "matter"`.
7186
+ * Which of the devices one of the platform's brokers holds are the vendor's: rules on who each
7187
+ * says it is, and where it says its model, looked up in the `modelCodes` of the vendor's drivers
7188
+ * of that broker's kind.
7189
+ *
7190
+ * A device is in the house through the broker already - commissioned by the owner, or announced
7191
+ * on the house's network - so it is added at once to the one vendor whose rules all hold, or to
7192
+ * the platform's own vendor of the broker when none - or more than one - do.
7193
+ *
7194
+ * @param model - Where a device says its model when the vendor does not say.
7195
+ * @returns The schema of one broker's block.
7196
+ */
7197
+ function brokerDiscoverySchema(model) {
7198
+ return z.strictObject({
7199
+ /** Every condition must hold. All-of, and at least one: a vendor does not take every device. */
7200
+ match: z.array(claimConditionSchema).min(1).max(MAXIMUM_MATCH),
7201
+ /** Where the device says its model. */
7202
+ model: identityPathSchema.default(model)
7203
+ });
7204
+ }
7205
+ /**
7206
+ * Which of the house's Matter devices are the vendor's: rules on its `vendorId`, `productName`,
7207
+ * `macAddresses`, `deviceTypes`, every field of the platform's `MatterIdentity`; the model is its
7208
+ * product id unless said, in the drivers that say `"kind": "matter"`.
7209
+ */
7210
+ const matterDiscoverySchema = brokerDiscoverySchema("productId");
7211
+ /**
7212
+ * Which of the devices the house's MQTT broker hears are the vendor's: rules on its
7213
+ * `manufacturer`, `model`, `originName`, `identifiers`, every field of the platform's
7214
+ * `MqttIdentity`; the model is its `model` unless said, in the drivers that say `"kind": "mqtt"`.
7215
+ */
7216
+ const mqttDiscoverySchema = brokerDiscoverySchema("model");
7217
+ /** What a Modbus rule may call a value it reads: `serial`, `model`. */
7218
+ const MODBUS_VALUE_NAME = /^[a-z][a-zA-Z0-9_]{0,31}$/u;
7219
+ /** How many values a Modbus rule may read: every one is a request to a server that is not yet known. */
7220
+ const MAXIMUM_MODBUS_READS = 8;
7221
+ /**
7222
+ * Which of the Modbus servers found on the network are the vendor's: the values to read from
7223
+ * them - registers, as a template reads them - and rules on `values.<name>`, `host`, `port` and
7224
+ * `unitId`; the model is `values.model` unless said, in the drivers that say `"kind": "modbus"`.
6305
7225
  *
6306
- * A device is commissioned into the house by the owner, so it is added at once to the one vendor
6307
- * whose rules all hold, or to the platform's own `matter` vendor when none - or more than one - do.
7226
+ * The platform recognises no server on its own: a server is named only by an integration whose
7227
+ * rules hold.
6308
7228
  */
6309
- const matterDiscoverySchema = z.strictObject({
6310
- /** Every condition must hold. All-of, and at least one: a vendor does not take every device. */
6311
- match: z.array(claimConditionSchema).min(1).max(MAXIMUM_MATCH),
6312
- /** Where the device says its model; its product id when not said. */
6313
- model: identityPathSchema.default("productId")
7229
+ const modbusDiscoverySchema = brokerDiscoverySchema("values.model").extend({
7230
+ /** The unit asked; the one a server answers for on its own unless said. */
7231
+ unitId: z.int().min(1).max(247).default(1),
7232
+ /** What to read, by the name the rules use. */
7233
+ read: z.record(z.string().regex(MODBUS_VALUE_NAME, "A name of letters and digits"), modbusReadSchema).refine((read) => Object.keys(read).length <= MAXIMUM_MODBUS_READS, { message: `At most ${String(MAXIMUM_MODBUS_READS)} values` }).default({})
6314
7234
  });
7235
+ /** The platform's brokers a vendor may take devices of, and the transport each reaches them on. */
7236
+ const BROKER_TRANSPORTS = {
7237
+ matter: MATTER_TRANSPORT,
7238
+ mqtt: MQTT_HOUSE_TRANSPORT,
7239
+ modbus: MODBUS_TRANSPORT
7240
+ };
7241
+ /** Where each broker's device says its model, when the vendor's block does not say. */
7242
+ const BROKER_MODELS = {
7243
+ matter: "productId",
7244
+ mqtt: "model",
7245
+ modbus: "values.model"
7246
+ };
6315
7247
  /** Validates a whole `discovery.json`. */
6316
7248
  const vendorDiscoverySchema = z.strictObject({
6317
- /** Where the vendor's devices announce themselves; none for one found only through Matter. */
7249
+ /** Where the vendor's devices announce themselves; none for one found only through a broker. */
6318
7250
  listen: z.array(listenSourceSchema).max(MAXIMUM_SOURCES).default([]),
6319
7251
  /** Every condition must hold of an announcement for it to be the vendor's. All-of. */
6320
7252
  match: z.array(claimConditionSchema).max(MAXIMUM_MATCH).default([]),
6321
7253
  probe: discoveryProbeSchema.optional(),
6322
7254
  identity: discoveryIdentitySchema.default({}),
6323
7255
  matter: matterDiscoverySchema.optional(),
7256
+ mqtt: mqttDiscoverySchema.optional(),
7257
+ modbus: modbusDiscoverySchema.optional(),
6324
7258
  /**
6325
7259
  * Who adds a device found. `owner` - the default - proposes it on the vendor's
6326
7260
  * page; `automatic` adds it as soon as it is heard, for devices the owner already chose
@@ -6341,10 +7275,10 @@ const vendorDiscoverySchema = z.strictObject({
6341
7275
  state: z.string().min(1).max(64)
6342
7276
  }).optional()
6343
7277
  }).superRefine((discovery, ctx) => {
6344
- if (discovery.listen.length === 0 && discovery.matter === void 0) ctx.addIssue({
7278
+ if (discovery.listen.length === 0 && discovery.matter === void 0 && discovery.mqtt === void 0 && discovery.modbus === void 0) ctx.addIssue({
6345
7279
  code: "custom",
6346
7280
  path: ["listen"],
6347
- message: "A vendor listens somewhere, or says which Matter devices are its own, or both"
7281
+ message: "A vendor listens somewhere, or says which Matter, MQTT or Modbus devices are its own, or both"
6348
7282
  });
6349
7283
  if (discovery.listen.length > 0 && discovery.probe === void 0 && discovery.identity.model === void 0) ctx.addIssue({
6350
7284
  code: "custom",
@@ -6459,7 +7393,8 @@ function choicesOf(driver) {
6459
7393
  * @returns The association, or null when no driver of the vendor takes the device.
6460
7394
  */
6461
7395
  function associateModel(plan, modelCode, claimedBy) {
6462
- const reached = new Set(plan.drivers.filter((driver) => driver.transport !== MATTER_TRANSPORT).map(({ id }) => id));
7396
+ const brokers = Object.values(BROKER_TRANSPORTS);
7397
+ const reached = new Set(plan.drivers.filter((driver) => !brokers.includes(driver.transport)).map(({ id }) => id));
6463
7398
  const coded = modelCode === null ? [] : (plan.codes.get(modelCode) ?? []).filter((entry) => reached.has(entry.driverId));
6464
7399
  if (coded.length > 0) {
6465
7400
  const found = claimedBy === void 0 ? coded.length === 1 ? coded[0] : void 0 : coded.find((entry) => claimedBy(entry.driverId));
@@ -6481,28 +7416,31 @@ function associateModel(plan, modelCode, claimedBy) {
6481
7416
  };
6482
7417
  }
6483
7418
  /**
6484
- * Whether a Matter device is the vendor's, by the rules of its `matter` block.
7419
+ * Whether a device of one of the platform's brokers is the vendor's, by the rules of its block.
6485
7420
  *
6486
7421
  * @param plan - The vendor's discovery.
7422
+ * @param broker - Which broker holds the device: `matter`, `mqtt`.
6487
7423
  * @param identity - Who the device says it is.
6488
- * @returns True when the vendor has a `matter` block and every one of its conditions holds.
7424
+ * @returns True when the vendor has the broker's block and every one of its conditions holds.
6489
7425
  */
6490
- function matchesMatter(plan, identity) {
6491
- return plan.discovery.matter?.match.every((condition) => conditionHolds(condition, identity)) ?? false;
7426
+ function matchesBroker(plan, broker, identity) {
7427
+ return plan.discovery[broker]?.match.every((condition) => conditionHolds(condition, identity)) ?? false;
6492
7428
  }
6493
7429
  /**
6494
- * Finds the driver of the vendor's that runs a Matter device of its, and its model.
7430
+ * Finds the driver of the vendor's that runs a device of one of the platform's brokers, and its
7431
+ * model.
6495
7432
  *
6496
- * The model the device says is looked up in the `modelCodes` of the vendor's Matter drivers; one
6497
- * it does not map goes to the vendor's Matter driver when it has only one.
7433
+ * The model the device says is looked up in the `modelCodes` of the vendor's drivers on that
7434
+ * broker's transport; one it does not map goes to the vendor's driver there when it has only one.
6498
7435
  *
6499
7436
  * @param plan - The vendor's discovery.
7437
+ * @param broker - Which broker holds the device: `matter`, `mqtt`.
6500
7438
  * @param identity - Who the device says it is.
6501
- * @returns The association, or null when no Matter driver of the vendor takes it.
7439
+ * @returns The association, or null when no driver of the vendor on the broker takes it.
6502
7440
  */
6503
- function associateMatter(plan, identity) {
6504
- const drivers = plan.drivers.filter((driver) => driver.transport === MATTER_TRANSPORT);
6505
- const modelCode = textAt(identity, plan.discovery.matter?.model ?? "productId");
7441
+ function associateBroker(plan, broker, identity) {
7442
+ const drivers = plan.drivers.filter((driver) => driver.transport === BROKER_TRANSPORTS[broker]);
7443
+ const modelCode = textAt(identity, plan.discovery[broker]?.model ?? BROKER_MODELS[broker]);
6506
7444
  const [first] = modelCode === null ? [] : (plan.codes.get(modelCode) ?? []).filter((entry) => drivers.some((driver) => driver.id === entry.driverId));
6507
7445
  if (first !== void 0) return {
6508
7446
  driverId: first.driverId,
@@ -8103,7 +9041,7 @@ CLUSTER.onOff, CLUSTER.levelControl, CLUSTER.colorControl, CLUSTER.windowCoverin
8103
9041
  * @param value - The attribute.
8104
9042
  * @returns It, or undefined when it is not a finite number - null included.
8105
9043
  */
8106
- function numberOf(value) {
9044
+ function numberOf$1(value) {
8107
9045
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
8108
9046
  }
8109
9047
  /**
@@ -8171,11 +9109,11 @@ function onOffEntity(attributes, endpoint) {
8171
9109
  DEVICE_TYPE.mountedDimmableLoadControl
8172
9110
  ].some((type) => types.includes(type));
8173
9111
  const hasLevel = isLight && serves(attributes, endpoint, CLUSTER.levelControl);
8174
- const colorFeatures = serves(attributes, endpoint, CLUSTER.colorControl) ? numberOf(attributeOf(attributes, endpoint, CLUSTER.colorControl, FEATURE_MAP)) ?? 0 : 0;
9112
+ const colorFeatures = serves(attributes, endpoint, CLUSTER.colorControl) ? numberOf$1(attributeOf(attributes, endpoint, CLUSTER.colorControl, FEATURE_MAP)) ?? 0 : 0;
8175
9113
  const hasHs = isLight && (colorFeatures & 1) !== 0;
8176
9114
  const hasTemperature = isLight && (colorFeatures & 16) !== 0;
8177
- const minMireds = clamp(numberOf(attributeOf(attributes, endpoint, CLUSTER.colorControl, 16395)) ?? 153, 1, 1e3);
8178
- const maxMireds = clamp(numberOf(attributeOf(attributes, endpoint, CLUSTER.colorControl, 16396)) ?? 500, minMireds, 1e3);
9115
+ const minMireds = clamp(numberOf$1(attributeOf(attributes, endpoint, CLUSTER.colorControl, 16395)) ?? 153, 1, 1e3);
9116
+ const maxMireds = clamp(numberOf$1(attributeOf(attributes, endpoint, CLUSTER.colorControl, 16396)) ?? 500, minMireds, 1e3);
8179
9117
  const capabilities = {
8180
9118
  on_off: { hasTransition: false },
8181
9119
  ...hasLevel ? { level: { hasTransition: true } } : {},
@@ -8208,10 +9146,10 @@ function onOffEntity(attributes, endpoint) {
8208
9146
  stateOf: (read) => {
8209
9147
  const isOn = attributeOf(read, endpoint, CLUSTER.onOff, 0);
8210
9148
  if (typeof isOn !== "boolean") return;
8211
- const level = numberOf(attributeOf(read, endpoint, CLUSTER.levelControl, 0));
8212
- const hue = numberOf(attributeOf(read, endpoint, CLUSTER.colorControl, 0));
8213
- const saturation = numberOf(attributeOf(read, endpoint, CLUSTER.colorControl, 1));
8214
- const mireds = numberOf(attributeOf(read, endpoint, CLUSTER.colorControl, 7));
9149
+ const level = numberOf$1(attributeOf(read, endpoint, CLUSTER.levelControl, 0));
9150
+ const hue = numberOf$1(attributeOf(read, endpoint, CLUSTER.colorControl, 0));
9151
+ const saturation = numberOf$1(attributeOf(read, endpoint, CLUSTER.colorControl, 1));
9152
+ const mireds = numberOf$1(attributeOf(read, endpoint, CLUSTER.colorControl, 7));
8215
9153
  return {
8216
9154
  on_off: { isOn },
8217
9155
  ...hasLevel && level !== void 0 ? { level: { level: clamp(Math.round(level / 254 * 100), 0, 100) } } : {},
@@ -8235,7 +9173,7 @@ function onOffEntity(attributes, endpoint) {
8235
9173
  case "turn_off": return invoke(endpoint, CLUSTER.onOff, "off");
8236
9174
  case "toggle": return invoke(endpoint, CLUSTER.onOff, "toggle");
8237
9175
  case "set_level": {
8238
- const level = numberOf(command["level"]) ?? 0;
9176
+ const level = numberOf$1(command["level"]) ?? 0;
8239
9177
  return level <= 0 ? invoke(endpoint, CLUSTER.onOff, "off") : invoke(endpoint, CLUSTER.levelControl, "moveToLevelWithOnOff", {
8240
9178
  level: clamp(Math.round(level / 100 * 254), 1, 254),
8241
9179
  transitionTime: tenthsOf(command["transitionMs"]),
@@ -8243,13 +9181,13 @@ function onOffEntity(attributes, endpoint) {
8243
9181
  });
8244
9182
  }
8245
9183
  case "set_color": return invoke(endpoint, CLUSTER.colorControl, "moveToHueAndSaturation", {
8246
- hue: clamp(Math.round((numberOf(command["hue"]) ?? 0) / 360 * 254), 0, 254),
8247
- saturation: clamp(Math.round((numberOf(command["saturation"]) ?? 0) / 100 * 254), 0, 254),
9184
+ hue: clamp(Math.round((numberOf$1(command["hue"]) ?? 0) / 360 * 254), 0, 254),
9185
+ saturation: clamp(Math.round((numberOf$1(command["saturation"]) ?? 0) / 100 * 254), 0, 254),
8248
9186
  transitionTime: tenthsOf(command["transitionMs"]),
8249
9187
  ...NO_OPTIONS
8250
9188
  });
8251
9189
  case "set_color_temp": return invoke(endpoint, CLUSTER.colorControl, "moveToColorTemperature", {
8252
- colorTemperatureMireds: clamp(Math.round(numberOf(command["mireds"]) ?? minMireds), minMireds, maxMireds),
9190
+ colorTemperatureMireds: clamp(Math.round(numberOf$1(command["mireds"]) ?? minMireds), minMireds, maxMireds),
8253
9191
  transitionTime: tenthsOf(command["transitionMs"]),
8254
9192
  ...NO_OPTIONS
8255
9193
  });
@@ -8267,7 +9205,7 @@ function onOffEntity(attributes, endpoint) {
8267
9205
  * @returns The entity.
8268
9206
  */
8269
9207
  function coverEntity(attributes, endpoint) {
8270
- const features = numberOf(attributeOf(attributes, endpoint, CLUSTER.windowCovering, FEATURE_MAP)) ?? 0;
9208
+ const features = numberOf$1(attributeOf(attributes, endpoint, CLUSTER.windowCovering, FEATURE_MAP)) ?? 0;
8271
9209
  const hasPosition = (features & 4) !== 0;
8272
9210
  const hasTilt = (features & 2) !== 0 && (features & 16) !== 0;
8273
9211
  /**
@@ -8296,9 +9234,9 @@ function coverEntity(attributes, endpoint) {
8296
9234
  * @returns The state, or undefined while the device has not said enough.
8297
9235
  */
8298
9236
  stateOf: (read) => {
8299
- const closed = numberOf(attributeOf(read, endpoint, CLUSTER.windowCovering, 14));
8300
- const tilt = numberOf(attributeOf(read, endpoint, CLUSTER.windowCovering, 15));
8301
- const status = (numberOf(attributeOf(read, endpoint, CLUSTER.windowCovering, 10)) ?? 0) & 3;
9237
+ const closed = numberOf$1(attributeOf(read, endpoint, CLUSTER.windowCovering, 14));
9238
+ const tilt = numberOf$1(attributeOf(read, endpoint, CLUSTER.windowCovering, 15));
9239
+ const status = (numberOf$1(attributeOf(read, endpoint, CLUSTER.windowCovering, 10)) ?? 0) & 3;
8302
9240
  if (closed === void 0) return;
8303
9241
  return { cover: {
8304
9242
  position: openOf(closed),
@@ -8318,8 +9256,8 @@ function coverEntity(attributes, endpoint) {
8318
9256
  case "open": return invoke(endpoint, CLUSTER.windowCovering, "upOrOpen");
8319
9257
  case "close": return invoke(endpoint, CLUSTER.windowCovering, "downOrClose");
8320
9258
  case "stop": return invoke(endpoint, CLUSTER.windowCovering, "stopMotion");
8321
- case "set_position": return invoke(endpoint, CLUSTER.windowCovering, "goToLiftPercentage", { liftPercent100thsValue: Math.round((100 - (numberOf(command["position"]) ?? 0)) * 100) });
8322
- case "set_tilt": return invoke(endpoint, CLUSTER.windowCovering, "goToTiltPercentage", { tiltPercent100thsValue: Math.round((100 - (numberOf(command["tilt"]) ?? 0)) * 100) });
9259
+ case "set_position": return invoke(endpoint, CLUSTER.windowCovering, "goToLiftPercentage", { liftPercent100thsValue: Math.round((100 - (numberOf$1(command["position"]) ?? 0)) * 100) });
9260
+ case "set_tilt": return invoke(endpoint, CLUSTER.windowCovering, "goToTiltPercentage", { tiltPercent100thsValue: Math.round((100 - (numberOf$1(command["tilt"]) ?? 0)) * 100) });
8323
9261
  default: return;
8324
9262
  }
8325
9263
  }
@@ -8348,7 +9286,7 @@ function lockEntity(endpoint) {
8348
9286
  * @returns The state, or undefined while the device has not said enough.
8349
9287
  */
8350
9288
  stateOf: (read) => {
8351
- switch (numberOf(attributeOf(read, endpoint, CLUSTER.doorLock, 0))) {
9289
+ switch (numberOf$1(attributeOf(read, endpoint, CLUSTER.doorLock, 0))) {
8352
9290
  case 0: return { lock: { lockState: "jammed" } };
8353
9291
  case 1: return { lock: { lockState: "locked" } };
8354
9292
  case 2:
@@ -8401,7 +9339,7 @@ const MODE_VALUES = {
8401
9339
  * @returns The entity.
8402
9340
  */
8403
9341
  function thermostatEntity(attributes, endpoint) {
8404
- const features = numberOf(attributeOf(attributes, endpoint, CLUSTER.thermostat, FEATURE_MAP)) ?? 1;
9342
+ const features = numberOf$1(attributeOf(attributes, endpoint, CLUSTER.thermostat, FEATURE_MAP)) ?? 1;
8405
9343
  const canHeat = (features & 1) !== 0;
8406
9344
  const canCool = (features & 2) !== 0;
8407
9345
  const hasAuto = (features & 32) !== 0;
@@ -8413,7 +9351,7 @@ function thermostatEntity(attributes, endpoint) {
8413
9351
  * @returns The degrees, or undefined.
8414
9352
  */
8415
9353
  const degreesOf = (read, attribute) => {
8416
- const value = numberOf(attributeOf(read, endpoint, CLUSTER.thermostat, attribute));
9354
+ const value = numberOf$1(attributeOf(read, endpoint, CLUSTER.thermostat, attribute));
8417
9355
  return value === void 0 ? void 0 : value / 100;
8418
9356
  };
8419
9357
  const min = degreesOf(attributes, canHeat ? 21 : 23) ?? 7;
@@ -8445,10 +9383,10 @@ function thermostatEntity(attributes, endpoint) {
8445
9383
  */
8446
9384
  stateOf: (read) => {
8447
9385
  const current = degreesOf(read, 0);
8448
- const mode = SYSTEM_MODES[numberOf(attributeOf(read, endpoint, CLUSTER.thermostat, 28)) ?? 0];
9386
+ const mode = SYSTEM_MODES[numberOf$1(attributeOf(read, endpoint, CLUSTER.thermostat, 28)) ?? 0];
8449
9387
  const target = degreesOf(read, mode === "cool" ? 17 : 18) ?? degreesOf(read, 17);
8450
- const running = numberOf(attributeOf(read, endpoint, CLUSTER.thermostat, 41)) ?? 0;
8451
- const humidity = numberOf(attributeOf(read, endpoint, CLUSTER.relativeHumidityMeasurement, 0));
9388
+ const running = numberOf$1(attributeOf(read, endpoint, CLUSTER.thermostat, 41)) ?? 0;
9389
+ const humidity = numberOf$1(attributeOf(read, endpoint, CLUSTER.relativeHumidityMeasurement, 0));
8452
9390
  if (current === void 0 || target === void 0 || mode === void 0) return;
8453
9391
  return { thermostat: {
8454
9392
  currentTemperature: current,
@@ -8475,7 +9413,7 @@ function thermostatEntity(attributes, endpoint) {
8475
9413
  endpoint,
8476
9414
  cluster: CLUSTER.thermostat,
8477
9415
  attribute: isCooling ? 17 : 18,
8478
- value: Math.round((numberOf(command["temperature"]) ?? 0) * 100)
9416
+ value: Math.round((numberOf$1(command["temperature"]) ?? 0) * 100)
8479
9417
  }
8480
9418
  };
8481
9419
  }
@@ -8500,7 +9438,7 @@ function thermostatEntity(attributes, endpoint) {
8500
9438
  * @returns It divided by 100.
8501
9439
  */
8502
9440
  function hundredths(value) {
8503
- const number = numberOf(value);
9441
+ const number = numberOf$1(value);
8504
9442
  return number === void 0 ? void 0 : number / 100;
8505
9443
  }
8506
9444
  /** The sensors read as one value of one attribute. */
@@ -8540,7 +9478,7 @@ const NUMERIC_SENSORS = [
8540
9478
  * @returns The number, or undefined.
8541
9479
  */
8542
9480
  scale: (value) => {
8543
- const measured = numberOf(value);
9481
+ const measured = numberOf$1(value);
8544
9482
  return measured === void 0 ? void 0 : measured === 0 ? 0 : 10 ** ((measured - 1) / 1e4);
8545
9483
  }
8546
9484
  },
@@ -8552,7 +9490,7 @@ const NUMERIC_SENSORS = [
8552
9490
  deviceClass: "atmospheric_pressure",
8553
9491
  unit: "hPa",
8554
9492
  displayPrecision: 0,
8555
- scale: numberOf
9493
+ scale: numberOf$1
8556
9494
  },
8557
9495
  {
8558
9496
  key: "carbon_dioxide",
@@ -8562,7 +9500,7 @@ const NUMERIC_SENSORS = [
8562
9500
  deviceClass: "carbon_dioxide",
8563
9501
  unit: "ppm",
8564
9502
  displayPrecision: 0,
8565
- scale: numberOf
9503
+ scale: numberOf$1
8566
9504
  },
8567
9505
  {
8568
9506
  key: "battery",
@@ -8579,7 +9517,7 @@ const NUMERIC_SENSORS = [
8579
9517
  * @returns The number, or undefined.
8580
9518
  */
8581
9519
  scale: (value) => {
8582
- const halves = numberOf(value);
9520
+ const halves = numberOf$1(value);
8583
9521
  return halves === void 0 ? void 0 : clamp(halves / 2, 0, 100);
8584
9522
  }
8585
9523
  },
@@ -8591,7 +9529,7 @@ const NUMERIC_SENSORS = [
8591
9529
  deviceClass: "power",
8592
9530
  unit: "mW",
8593
9531
  displayPrecision: 1,
8594
- scale: numberOf
9532
+ scale: numberOf$1
8595
9533
  },
8596
9534
  {
8597
9535
  key: "voltage",
@@ -8601,7 +9539,7 @@ const NUMERIC_SENSORS = [
8601
9539
  deviceClass: "voltage",
8602
9540
  unit: "mV",
8603
9541
  displayPrecision: 1,
8604
- scale: numberOf
9542
+ scale: numberOf$1
8605
9543
  },
8606
9544
  {
8607
9545
  key: "current",
@@ -8611,7 +9549,7 @@ const NUMERIC_SENSORS = [
8611
9549
  deviceClass: "current",
8612
9550
  unit: "mA",
8613
9551
  displayPrecision: 2,
8614
- scale: numberOf
9552
+ scale: numberOf$1
8615
9553
  },
8616
9554
  {
8617
9555
  key: "energy",
@@ -8628,7 +9566,7 @@ const NUMERIC_SENSORS = [
8628
9566
  * @param value - The attribute.
8629
9567
  * @returns The number, or undefined.
8630
9568
  */
8631
- scale: (value) => numberOf(value?.["0"])
9569
+ scale: (value) => numberOf$1(value?.["0"])
8632
9570
  }
8633
9571
  ];
8634
9572
  /**
@@ -8739,10 +9677,10 @@ function firmwareEntity() {
8739
9677
  */
8740
9678
  stateOf: (read, update) => {
8741
9679
  const text = attributeOf(read, 0, CLUSTER.basicInformation, 10);
8742
- const number = numberOf(attributeOf(read, 0, CLUSTER.basicInformation, 9));
9680
+ const number = numberOf$1(attributeOf(read, 0, CLUSTER.basicInformation, 9));
8743
9681
  const installed = typeof text === "string" && text !== "" ? text : number === void 0 ? null : String(number);
8744
- const updating = numberOf(attributeOf(read, 0, CLUSTER.otaRequestor, 2));
8745
- const progress = numberOf(attributeOf(read, 0, CLUSTER.otaRequestor, 3));
9682
+ const updating = numberOf$1(attributeOf(read, 0, CLUSTER.otaRequestor, 2));
9683
+ const progress = numberOf$1(attributeOf(read, 0, CLUSTER.otaRequestor, 3));
8746
9684
  const isInstalling = updating === 4 || updating === 5;
8747
9685
  return { update: {
8748
9686
  installedVersion: installed?.slice(0, 64) ?? null,
@@ -8801,7 +9739,7 @@ function draftsOf(attributes, endpoint) {
8801
9739
  * @returns Whether it is on, or undefined.
8802
9740
  */
8803
9741
  isOn: (value) => {
8804
- const bits = numberOf(value);
9742
+ const bits = numberOf$1(value);
8805
9743
  return bits === void 0 ? void 0 : (bits & 1) !== 0;
8806
9744
  }
8807
9745
  }));
@@ -8871,7 +9809,7 @@ const deviceSnapshotSchema = z.object({
8871
9809
  attributes: z.record(z.string(), z.unknown())
8872
9810
  });
8873
9811
  /** Reads what the transport delivers. */
8874
- const inboundSchema = z.object({
9812
+ const inboundSchema$2 = z.object({
8875
9813
  device: deviceSnapshotSchema,
8876
9814
  changed: z.array(z.string()).nullable(),
8877
9815
  update: z.object({
@@ -8885,7 +9823,7 @@ const inboundSchema = z.object({
8885
9823
  * @param value - What it holds.
8886
9824
  * @returns The device, or undefined when it is not one.
8887
9825
  */
8888
- function deviceOf(value) {
9826
+ function deviceOf$1(value) {
8889
9827
  const parsed = deviceSnapshotSchema.safeParse(value);
8890
9828
  return parsed.success ? parsed.data : void 0;
8891
9829
  }
@@ -8919,7 +9857,7 @@ function createMatterIntegration(manifest) {
8919
9857
  * @throws {ValidationError} When the claim holds no device - which identification never makes.
8920
9858
  */
8921
9859
  const claimed = (context) => {
8922
- const device = deviceOf(context.claim.descriptor);
9860
+ const device = deviceOf$1(context.claim.descriptor);
8923
9861
  if (device === void 0) throw new ValidationError(`${manifest.id} holds a claim that is not a Matter device`, { details: { integration: manifest.id } });
8924
9862
  return device;
8925
9863
  };
@@ -8935,7 +9873,7 @@ function createMatterIntegration(manifest) {
8935
9873
  * @returns The claim, or null for anything that is not a Matter device.
8936
9874
  */
8937
9875
  claim: (discovered) => {
8938
- const device = deviceOf(discovered.payload);
9876
+ const device = deviceOf$1(discovered.payload);
8939
9877
  return device === void 0 ? null : {
8940
9878
  deviceKey: discovered.deviceKey,
8941
9879
  externalId: matterDeviceKey(device.nodeId, device.endpoint),
@@ -8956,7 +9894,7 @@ function createMatterIntegration(manifest) {
8956
9894
  * @throws {ValidationError} When the claim holds no Matter device.
8957
9895
  */
8958
9896
  describe: (claim) => {
8959
- const device = deviceOf(claim.descriptor);
9897
+ const device = deviceOf$1(claim.descriptor);
8960
9898
  if (device === void 0) throw new ValidationError(`${manifest.id} cannot describe a claim with no Matter device`, { details: { integration: manifest.id } });
8961
9899
  const { identity } = device;
8962
9900
  const mac = identity.macAddresses.map(normalizeMac).find((each) => each !== null);
@@ -8981,7 +9919,7 @@ function createMatterIntegration(manifest) {
8981
9919
  * @returns The reports.
8982
9920
  */
8983
9921
  toState: (message, context) => {
8984
- const parsed = inboundSchema.safeParse(message.payload);
9922
+ const parsed = inboundSchema$2.safeParse(message.payload);
8985
9923
  if (!parsed.success) return [];
8986
9924
  const { device, changed, update } = parsed.data;
8987
9925
  return matterEntitiesOf(device).flatMap((entity) => {
@@ -9023,233 +9961,1775 @@ function createMatterIntegration(manifest) {
9023
9961
  * @returns The version, when the device says it.
9024
9962
  */
9025
9963
  deviceInfo: (message) => {
9026
- const parsed = inboundSchema.safeParse(message.payload);
9964
+ const parsed = inboundSchema$2.safeParse(message.payload);
9027
9965
  const version = parsed.success ? parsed.data.device.identity.softwareVersionString : null;
9028
9966
  return version === null ? void 0 : { swVersion: version.slice(0, 64) };
9029
9967
  }
9030
9968
  };
9031
9969
  }
9032
9970
  //#endregion
9033
- //#region ../package-runtime/dist/loader.js
9971
+ //#region ../package-runtime/dist/modbus-mapping.js
9972
+ /**
9973
+ * How a Modbus device is read and commanded through its template: pure.
9974
+ *
9975
+ * A template says, for each capability of each entity, the register its value is read from and
9976
+ * the command its changes are written with. This module plans the reads into blocks, turns what
9977
+ * the registers hold into canonical state, and turns a canonical command into the words to
9978
+ * write. It is the one interpreter of templates: the platform's own `modbus/generic` driver and
9979
+ * every integration driver of kind `modbus` are this, so an integration's template and the owner's
9980
+ * mean the same thing.
9981
+ *
9982
+ * The template travels in the claim: the broker hands each device over with its template
9983
+ * resolved, so the blocks a device is polled for and the way they are read are always the same
9984
+ * template's.
9985
+ */
9986
+ /** How many registers or bits one read may ask for. */
9987
+ const MAXIMUM_BLOCK = 100;
9988
+ /** How many unread addresses between two reads still go in one block. */
9989
+ const MAXIMUM_GAP = 16;
9990
+ /** A Modbus device as the broker hands it over: where it is, how often, and its template. */
9991
+ const modbusDeviceSnapshotSchema = z.object({
9992
+ /** The device's external id: `modbus-<row id>`. */
9993
+ deviceKey: z.string().min(1).max(160),
9994
+ /** The driver it is read as: `modbus/generic`, or an integration's. */
9995
+ kind: z.string().min(1).max(160),
9996
+ name: z.string().min(1).max(128),
9997
+ host: z.string().min(1).max(253),
9998
+ port: z.int().min(1).max(65535),
9999
+ unitId: z.int().min(1).max(247),
10000
+ framing: z.enum(MODBUS_FRAMINGS),
10001
+ pollSeconds: z.int().min(1).max(3600),
10002
+ template: modbusTemplateSchema
10003
+ });
9034
10004
  /**
9035
- * Reading integrations off disk: the loader `hub` runs and the integration SDK checks a bundle
9036
- * with, so that what passes `nebulahome-integration validate` is what `hub` loads.
9037
- *
9038
- * A bundle is a vendor directory - `manifest.json`, a logo, optionally a `setup.json` of what
9039
- * every device of the vendor shares - holding one driver directory per profile or entry point,
9040
- * each with `driver.json`, its own `setup.json` and the profile or code. It is read in two steps:
9041
- *
9042
- * 1. {@link readVendorDirectory} reads and checks every file - the schemas, the ids against the
9043
- * folders, the runtime range, the logo, the containers, that every module named is there -
9044
- * and imports nothing. It is all a source tree needs to be checked.
9045
- * 2. {@link instantiateVendor} imports the code and hands it the {@link BundleSdk}: the vendor's
9046
- * own transports, stream sources and account, each driver, and the discovery modules. Who
9047
- * builds the SDK is the caller's - `hub` hands the real one, the SDK's tests a fake.
10005
+ * How many registers or bits a read takes.
9048
10006
  *
9049
- * **It is also the seam the catalogue arrives through.** `verify` and `verifyVendor` are called
9050
- * before code is imported, and nothing passes them today. When the catalogue stamps a signature on
9051
- * an approved code bundle, the verifier that checks it is injected there and nothing else changes.
10007
+ * @param read - The read.
10008
+ * @returns One bit for a coil or an input; the type's registers otherwise.
10009
+ */
10010
+ function modbusSizeOf(read) {
10011
+ return read.function === 1 || read.function === 2 ? 1 : modbusRegistersOf(read.type ?? "u16", read.count);
10012
+ }
10013
+ /**
10014
+ * Every read of a template, each once.
9052
10015
  *
9053
- * One broken driver never stops its siblings, and one broken vendor never stops the others. A
9054
- * failure is collected and reported so the interface can say which directory and why, because
9055
- * the alternative - refusing to start - means one bad download takes the whole house offline.
9056
- * The same goes one level down for a vendor's `discovery.json`: discovery is a convenience on top
9057
- * of adding a device by address, so a broken one is reported and the vendor loads without it.
10016
+ * @param template - The template.
10017
+ * @returns The reads, in the template's order.
9058
10018
  */
9059
- /** The file every vendor is recognised by. */
9060
- const MANIFEST_FILE = "manifest.json";
9061
- /** The file every driver is recognised by. */
9062
- const DRIVER_FILE = "driver.json";
9063
- /** The file a discoverable vendor says how its devices are found in. */
9064
- const DISCOVERY_FILE = "discovery.json";
10019
+ function readsOf(template) {
10020
+ return template.entities.flatMap((entity) => Object.values(entity.capabilities).flatMap((map) => map.read === void 0 ? [] : [map.read]));
10021
+ }
9065
10022
  /**
9066
- * The most a logo may weigh.
10023
+ * Plans the reads of a template into as few requests as the device takes.
9067
10024
  *
9068
- * It rides inside every catalogue reply, base64-encoded, so a large one slows every page that
9069
- * lists vendors. Generous for an SVG mark or a small PNG, and found at startup rather than on
9070
- * somebody's page.
10025
+ * Reads of one table go together while what lies between them is a short run of unread addresses,
10026
+ * and no request asks for more than a hundred units: a gateway that answers 125 registers on paper
10027
+ * often answers fewer.
10028
+ *
10029
+ * @param template - The template.
10030
+ * @returns The blocks, each table in address order.
9071
10031
  */
9072
- const LOGO_MAXIMUM_BYTES = 65536;
9073
- /** The image types a logo may be, by the extension the manifest names. */
9074
- const LOGO_TYPES = {
9075
- ".svg": "image/svg+xml",
9076
- ".png": "image/png"
9077
- };
9078
- /** A vendor that asks for nothing at setup. */
9079
- const NO_SETUP = {
9080
- transport: {
9081
- constants: {},
9082
- fields: []
9083
- },
9084
- options: {
9085
- constants: {},
9086
- fields: []
10032
+ function planModbusBlocks(template) {
10033
+ const spans = readsOf(template).map((read) => ({
10034
+ function: read.function,
10035
+ start: modbusWordOf(read.address),
10036
+ size: modbusSizeOf(read)
10037
+ }));
10038
+ const blocks = [];
10039
+ for (const table of [
10040
+ 1,
10041
+ 2,
10042
+ 3,
10043
+ 4
10044
+ ]) {
10045
+ const sorted = spans.filter((span) => span.function === table).sort((left, right) => left.start - right.start);
10046
+ let start = -1;
10047
+ let end = -1;
10048
+ for (const span of sorted) {
10049
+ const spanEnd = Math.min(span.start + span.size - 1, 65535);
10050
+ if (start >= 0 && span.start - (end + 1) <= MAXIMUM_GAP && Math.max(end, spanEnd) - start + 1 <= MAXIMUM_BLOCK) {
10051
+ end = Math.max(end, spanEnd);
10052
+ continue;
10053
+ }
10054
+ if (start >= 0) blocks.push({
10055
+ function: table,
10056
+ start,
10057
+ count: end - start + 1
10058
+ });
10059
+ start = span.start;
10060
+ end = spanEnd;
10061
+ }
10062
+ if (start >= 0) blocks.push({
10063
+ function: table,
10064
+ start,
10065
+ count: end - start + 1
10066
+ });
9087
10067
  }
9088
- };
10068
+ return blocks;
10069
+ }
9089
10070
  /**
9090
- * The message of something thrown.
10071
+ * Where a unit read lands in what the transport delivers.
9091
10072
  *
9092
- * @param error - What was thrown.
9093
- * @returns Its message.
10073
+ * @param fn - The table's read function.
10074
+ * @param address - The address.
10075
+ * @returns `3:16`.
9094
10076
  */
9095
- function messageOf(error) {
9096
- return error instanceof Error ? error.message : String(error);
10077
+ function modbusKeyOf(fn, address) {
10078
+ return `${String(fn)}:${String(address)}`;
9097
10079
  }
9098
10080
  /**
9099
- * Reads and parses one JSON file of a bundle. A `$schema` at its top - which an editor reads, and
9100
- * which a bundle's sources carry for one - is not the bundle's and is dropped.
10081
+ * What a read's registers hold, before scale and meaning: a bit, a number or a text.
9101
10082
  *
9102
- * @param directory - The bundle.
9103
- * @param file - The file, relative to it.
9104
- * @returns Whatever the file held.
9105
- * @throws {Error} When the file cannot be read or is not JSON.
10083
+ * @param read - The read.
10084
+ * @param wordOrder - Which register of a 32-bit value holds the high word.
10085
+ * @param registers - What the transport read.
10086
+ * @returns The raw value, or undefined when a register it needs was not read.
9106
10087
  */
9107
- async function readBundleJson(directory, file) {
9108
- const parsed = JSON.parse(await readFile(path.join(directory, file), "utf8"));
9109
- if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) && "$schema" in parsed) return Object.fromEntries(Object.entries(parsed).filter(([key]) => key !== "$schema"));
9110
- return parsed;
10088
+ function modbusRawOf(read, wordOrder, registers) {
10089
+ const address = modbusWordOf(read.address);
10090
+ const words = [];
10091
+ for (let offset = 0; offset < modbusSizeOf(read); offset += 1) {
10092
+ const word = registers[modbusKeyOf(read.function, address + offset)];
10093
+ if (word === void 0) return;
10094
+ words.push(word & 65535);
10095
+ }
10096
+ const [first = 0, second = 0] = words;
10097
+ if (read.function === 1 || read.function === 2) return first !== 0;
10098
+ if (read.bit !== void 0) return (first >> read.bit & 1) === 1;
10099
+ switch (read.type ?? "u16") {
10100
+ case "u16": return first;
10101
+ case "s16": return first >= 32768 ? first - 65536 : first;
10102
+ case "string": return String.fromCharCode(...words.flatMap((word) => [word >> 8, word & 255])).replaceAll("\0", "").trim();
10103
+ default: {
10104
+ const [high, low] = wordOrder === "high" ? [first, second] : [second, first];
10105
+ const view = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(4));
10106
+ view.setUint16(0, high);
10107
+ view.setUint16(2, low);
10108
+ return read.type === "u32" ? view.getUint32(0) : read.type === "s32" ? view.getInt32(0) : view.getFloat32(0);
10109
+ }
10110
+ }
9111
10111
  }
9112
- /** How many of a schema's complaints a message names. */
9113
- const ISSUES_NAMED = 4;
9114
10112
  /**
9115
- * A file's name as a message says it: `relay/setup.json`, not `./setup.json` or a Windows path.
10113
+ * A raw number times the read's scale, without the float noise the multiplication leaves.
9116
10114
  *
9117
- * @param file - The name, as the bundle writes it.
9118
- * @returns It, tidied.
10115
+ * @param raw - The raw number.
10116
+ * @param read - The read, for its scale.
10117
+ * @returns The value.
9119
10118
  */
9120
- function nameOf(file) {
9121
- return path.normalize(file).split(path.sep).join("/");
10119
+ function scaled(raw, read) {
10120
+ return Number((raw * (read.scale ?? 1)).toPrecision(12));
9122
10121
  }
9123
10122
  /**
9124
- * Reads one JSON file of a bundle and checks it, saying which file and which field when it does
9125
- * not hold - a sentence an author can act on, rather than a dump of the schema's findings.
10123
+ * The value a capability reads as a test shows it: a number scaled, a choice's or a text's
10124
+ * meaning, on or off.
10125
+ *
10126
+ * @param capability - The capability.
10127
+ * @param map - Its read and write.
10128
+ * @param raw - What {@link modbusRawOf} read.
10129
+ * @returns The value.
10130
+ */
10131
+ function modbusValueOf(capability, map, raw) {
10132
+ const { read } = map;
10133
+ if (read === void 0 || typeof raw === "string") return raw;
10134
+ if (typeof raw === "boolean") return raw;
10135
+ switch (capability) {
10136
+ case "sensor_binary":
10137
+ case "on_off": return map.write?.off === void 0 ? raw !== 0 : raw !== modbusWordOf(map.write.off);
10138
+ case "sensor_text":
10139
+ case "select": return read.options?.[String(raw)] ?? String(raw);
10140
+ default: return scaled(raw, read);
10141
+ }
10142
+ }
10143
+ /**
10144
+ * The range a level is spread over, in the read's units: the write's min and max, 0 to 100 unless
10145
+ * said.
9126
10146
  *
9127
- * @param schema - What the file must be.
9128
- * @param directory - The folder it is in.
9129
- * @param file - The file, relative to it.
9130
- * @returns What it holds, checked.
9131
- * @throws {Error} When it is not there, is not JSON, or does not hold.
10147
+ * @param map - The level's read and write.
10148
+ * @returns The lowest and highest value.
9132
10149
  */
9133
- async function readBundleFile(schema, directory, file) {
9134
- let raw;
9135
- try {
9136
- raw = await readBundleJson(directory, file);
9137
- } catch (error) {
9138
- const code = error?.code;
9139
- throw new Error(code === "ENOENT" ? `${nameOf(file)} is missing` : `${nameOf(file)} could not be read: ${messageOf(error)}`, { cause: error });
10150
+ function levelRangeOf(map) {
10151
+ return {
10152
+ min: map.write?.min ?? 0,
10153
+ max: map.write?.max ?? 100
10154
+ };
10155
+ }
10156
+ /**
10157
+ * One capability's state from what the registers hold.
10158
+ *
10159
+ * @param capability - The capability.
10160
+ * @param map - Its read and write.
10161
+ * @param wordOrder - Which register of a 32-bit value holds the high word.
10162
+ * @param registers - What the transport read.
10163
+ * @returns The capability's state, or undefined when its registers were not read.
10164
+ */
10165
+ function capabilityStateOf(capability, map, wordOrder, registers) {
10166
+ if (capability === "button") return {};
10167
+ if (map.read === void 0) return;
10168
+ const raw = modbusRawOf(map.read, wordOrder, registers);
10169
+ if (raw === void 0) return;
10170
+ const value = modbusValueOf(capability, map, raw);
10171
+ switch (capability) {
10172
+ case "sensor_binary":
10173
+ case "on_off": return { isOn: value === true };
10174
+ case "sensor_numeric":
10175
+ case "number": return typeof value === "number" ? { value } : void 0;
10176
+ case "sensor_text": return { value: String(value).slice(0, 512) };
10177
+ case "select": return typeof raw === "number" ? { option: String(raw) } : void 0;
10178
+ case "level": {
10179
+ if (typeof value !== "number") return;
10180
+ const { min, max } = levelRangeOf(map);
10181
+ const level = (value - min) / (max - min) * 100;
10182
+ return { level: Math.round(Math.min(100, Math.max(0, level)) * 10) / 10 };
10183
+ }
10184
+ default: return;
9140
10185
  }
9141
- return parseBundleValue(schema, raw, file);
9142
10186
  }
9143
10187
  /**
9144
- * Checks what one file of a bundle holds, saying which file and which field when it does not.
10188
+ * An entity's identifier within its device: what stays when it is renamed.
9145
10189
  *
9146
- * @param schema - What it must be.
9147
- * @param value - What it holds.
9148
- * @param file - The file, for the message.
9149
- * @returns The value, checked.
9150
- * @throws {Error} When it does not hold.
10190
+ * @param entity - The entity.
10191
+ * @returns Its id, or the one its name gives.
9151
10192
  */
9152
- function parseBundleValue(schema, value, file) {
9153
- const parsed = schema.safeParse(value);
9154
- if (parsed.success) return parsed.data;
9155
- const { issues } = parsed.error;
9156
- const named = issues.slice(0, ISSUES_NAMED).map((issue) => issue.path.length === 0 ? issue.message : `${issue.path.map(String).join(".")}: ${issue.message}`);
9157
- const more = issues.length > ISSUES_NAMED ? `; and ${String(issues.length - ISSUES_NAMED)} more` : "";
9158
- throw new Error(`${nameOf(file)}: ${named.join("; ")}${more}`, { cause: parsed.error });
10193
+ function modbusObjectIdOf(entity) {
10194
+ return entity.id ?? modbusEntityIdOf(entity.name);
9159
10195
  }
9160
10196
  /**
9161
- * Whether a file is there to be read.
10197
+ * What a capability declares to the house: a number's limits, a choice's options.
9162
10198
  *
9163
- * @param file - The file.
9164
- * @returns True when it is a file.
10199
+ * @param capability - The capability.
10200
+ * @param map - Its read and write.
10201
+ * @returns Its params.
9165
10202
  */
9166
- async function isFile(file) {
9167
- try {
9168
- return (await stat(file)).isFile();
9169
- } catch {
9170
- return false;
10203
+ function paramsOf(capability, map) {
10204
+ switch (capability) {
10205
+ case "level": return { hasTransition: false };
10206
+ case "on_off": return { hasTransition: false };
10207
+ case "number": return {
10208
+ min: map.write?.min ?? 0,
10209
+ max: map.write?.max ?? 1,
10210
+ step: map.write?.step ?? 1
10211
+ };
10212
+ case "select": return { options: Object.entries(map.read?.options ?? {}).map(([value, label]) => ({
10213
+ value,
10214
+ label
10215
+ })) };
10216
+ default: return {};
9171
10217
  }
9172
10218
  }
9173
10219
  /**
9174
- * The subdirectories of one directory.
10220
+ * An entity of a template as the house registers it.
9175
10221
  *
9176
- * @param directory - Where to look.
9177
- * @returns Their names, or none when the directory does not exist.
10222
+ * @param entity - The template's entity.
10223
+ * @returns Its descriptor.
9178
10224
  */
9179
- async function subdirectories(directory) {
9180
- try {
9181
- return (await readdir(directory, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
9182
- } catch {
9183
- return [];
10225
+ function modbusEntityDescriptorOf(entity) {
10226
+ const capabilities = Object.fromEntries(Object.entries(entity.capabilities).map(([capability, map]) => [capability, paramsOf(capability, map)]));
10227
+ const unit = (entity.capabilities.sensor_numeric ?? entity.capabilities.number)?.read?.unit;
10228
+ return {
10229
+ domain: entity.domain,
10230
+ objectId: modbusObjectIdOf(entity),
10231
+ name: entity.name,
10232
+ capabilities,
10233
+ ...entity.icon === void 0 ? {} : { icon: entity.icon },
10234
+ ...unit === void 0 || unit === "" ? {} : { unitOfMeasurement: unit }
10235
+ };
10236
+ }
10237
+ /**
10238
+ * Every capability's state of an entity from what the registers hold.
10239
+ *
10240
+ * A capability whose registers were not read - its block refused - keeps the state it had.
10241
+ *
10242
+ * @param entity - The entity.
10243
+ * @param wordOrder - Which register of a 32-bit value holds the high word.
10244
+ * @param registers - What the transport read.
10245
+ * @param previous - The entity's last state.
10246
+ * @returns Its state, or undefined when nothing of it was read and nothing was known.
10247
+ */
10248
+ function modbusEntityStateOf(entity, wordOrder, registers, previous) {
10249
+ const state = {};
10250
+ let isRead = false;
10251
+ for (const [capability, map] of Object.entries(entity.capabilities)) {
10252
+ const read = capabilityStateOf(capability, map, wordOrder, registers);
10253
+ const kept = previous?.[capability];
10254
+ if (read !== void 0) {
10255
+ state[capability] = read;
10256
+ isRead ||= capability !== "button";
10257
+ } else if (kept !== void 0) state[capability] = kept;
9184
10258
  }
10259
+ return isRead || previous !== void 0 ? state : void 0;
9185
10260
  }
9186
10261
  /**
9187
- * Finds a module where the bundle says it is, as an installed or built bundle holds it.
10262
+ * The words a raw number is written as, in the read's type.
10263
+ *
10264
+ * @param raw - The raw number.
10265
+ * @param type - How the registers hold it.
10266
+ * @param wordOrder - Which register of a 32-bit value holds the high word.
10267
+ * @returns The words.
10268
+ * @throws {ValidationError} When the number does not fit the type.
10269
+ */
10270
+ function wordsOf(raw, type, wordOrder) {
10271
+ const view = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(4));
10272
+ const limits = {
10273
+ u16: [0, 65535],
10274
+ s16: [-32768, 32767],
10275
+ u32: [0, 4294967295],
10276
+ s32: [-2147483648, 2147483647],
10277
+ f32: [-Infinity, Infinity]
10278
+ }[type];
10279
+ if (raw < (limits[0] ?? 0) || raw > (limits[1] ?? 0)) throw new ValidationError(`${String(raw)} does not fit a ${type} register`, { details: {
10280
+ raw,
10281
+ type
10282
+ } });
10283
+ if (type === "u16" || type === "s16") return [raw & 65535];
10284
+ if (type === "f32") view.setFloat32(0, raw);
10285
+ else if (type === "u32") view.setUint32(0, raw);
10286
+ else view.setInt32(0, raw);
10287
+ const high = view.getUint16(0);
10288
+ const low = view.getUint16(2);
10289
+ return wordOrder === "high" ? [high, low] : [low, high];
10290
+ }
10291
+ /**
10292
+ * The words or bits a register write carries, for 05, 06, 15 or 16.
9188
10293
  *
9189
- * @param directory - The folder the name is relative to.
9190
- * @param file - The name.
9191
- * @returns Its path, or null when it is not there.
10294
+ * @param fn - The write function.
10295
+ * @param word - The word: what 05 or 06 writes.
10296
+ * @param words - Every register, for 16.
10297
+ * @returns What goes in the request.
9192
10298
  */
9193
- const fileAsNamed = async (directory, file) => {
9194
- const found = path.join(directory, file);
9195
- return await isFile(found) ? found : null;
9196
- };
10299
+ function valuesFor(fn, word, words) {
10300
+ return fn === 15 ? [word === 0 ? 0 : 1] : fn === 16 ? [...words] : [word];
10301
+ }
9197
10302
  /**
9198
- * Reads a vendor's logo as a data URL.
10303
+ * The number a command sets, checked against what the template allows.
10304
+ *
10305
+ * @param value - The value commanded.
10306
+ * @param map - The capability's read and write.
10307
+ * @returns The raw number to write.
10308
+ * @throws {ValidationError} When it is outside min and max.
10309
+ */
10310
+ function rawOfValue(value, map) {
10311
+ const { write, read } = map;
10312
+ if (write?.min !== void 0 && value < write.min || write?.max !== void 0 && value > write.max) throw new ValidationError(`${String(value)} is outside ${String(write.min ?? "-∞")} to ${String(write.max ?? "∞")}`, { details: {
10313
+ value,
10314
+ min: write.min ?? null,
10315
+ max: write.max ?? null
10316
+ } });
10317
+ const raw = value / (read?.scale ?? 1);
10318
+ return read?.type === "f32" ? raw : Math.round(raw);
10319
+ }
10320
+ /**
10321
+ * Turns a canonical command into the write that performs it.
9199
10322
  *
9200
- * @param directory - The vendor.
9201
- * @param file - The logo, relative to it, as the manifest names it.
9202
- * @returns The data URL.
9203
- * @throws {Error} When the file is not an SVG or a PNG, is too large, or cannot be read.
9204
- */
9205
- async function readLogo(directory, file) {
9206
- const type = LOGO_TYPES[path.extname(file).toLowerCase()];
9207
- if (type === void 0) throw new Error(`The logo ${file} must be an .svg or a .png`);
9208
- const bytes = await readFile(path.join(directory, file));
9209
- if (bytes.byteLength > 65536) throw new Error(`The logo ${file} is ${String(bytes.byteLength)} bytes, and the most a logo may be is ${String(LOGO_MAXIMUM_BYTES)}`);
9210
- return `data:${type};base64,${bytes.toString("base64")}`;
10323
+ * Refuses a value outside the capability's min and max here, so it never reaches the device.
10324
+ *
10325
+ * @param entity - The entity.
10326
+ * @param capability - The capability commanded.
10327
+ * @param command - The command, already checked against the capability.
10328
+ * @param wordOrder - Which register of a 32-bit value holds the high word.
10329
+ * @param previous - The entity's last state, for a toggle.
10330
+ * @returns The write.
10331
+ * @throws {ValidationError} When the capability is not written, or the value is refused.
10332
+ */
10333
+ function encodeModbusWrite(entity, capability, command, wordOrder, previous) {
10334
+ const map = entity.capabilities[capability];
10335
+ const write = map?.write;
10336
+ if (map === void 0 || write === void 0) throw new ValidationError(`${entity.name} cannot be commanded: ${capability} is only read`, { details: {
10337
+ entity: entity.name,
10338
+ capability
10339
+ } });
10340
+ const fn = write.function;
10341
+ const isCoil = fn === 5 || fn === 15;
10342
+ const address = modbusWordOf(write.address ?? map.read?.address ?? 0);
10343
+ const type = map.read?.type === void 0 || map.read.type === "string" ? "u16" : map.read.type;
10344
+ /**
10345
+ * The write of one raw number, in the type the register holds.
10346
+ *
10347
+ * @param raw - The raw number.
10348
+ * @returns The write.
10349
+ */
10350
+ const ofRaw = (raw) => {
10351
+ const words = wordsOf(raw, fn === 6 ? type === "s16" ? "s16" : "u16" : type, wordOrder);
10352
+ return {
10353
+ function: fn,
10354
+ address,
10355
+ values: valuesFor(fn, words[0] ?? 0, words)
10356
+ };
10357
+ };
10358
+ switch (capability) {
10359
+ case "on_off": {
10360
+ const word = (command["command"] === "toggle" ? previous?.on_off?.isOn !== true : command["command"] === "turn_on") ? modbusWordOf(write.on ?? (fn === 5 ? 65280 : 1)) : modbusWordOf(write.off ?? 0);
10361
+ return {
10362
+ function: fn,
10363
+ address,
10364
+ values: valuesFor(fn, word, [word])
10365
+ };
10366
+ }
10367
+ case "button": {
10368
+ const word = modbusWordOf(write.value ?? (isCoil ? 65280 : 1));
10369
+ return {
10370
+ function: fn,
10371
+ address,
10372
+ values: valuesFor(fn, word, [word])
10373
+ };
10374
+ }
10375
+ case "level": {
10376
+ const { min, max } = levelRangeOf(map);
10377
+ const level = Number(command["level"]);
10378
+ return ofRaw(rawOfValue(min + Math.min(100, Math.max(0, level)) / 100 * (max - min), {
10379
+ ...map,
10380
+ write: {
10381
+ ...write,
10382
+ min,
10383
+ max
10384
+ }
10385
+ }));
10386
+ }
10387
+ case "number": return ofRaw(rawOfValue(Number(command["value"]), map));
10388
+ case "select": {
10389
+ const option = typeof command["option"] === "string" ? command["option"] : "";
10390
+ if (map.read?.options?.[option] === void 0) throw new ValidationError(`${entity.name} has no option ${option}`, { details: {
10391
+ entity: entity.name,
10392
+ option
10393
+ } });
10394
+ return ofRaw(Number(option));
10395
+ }
10396
+ default: throw new ValidationError(`${entity.name} cannot be commanded: ${capability} is only read`, { details: {
10397
+ entity: entity.name,
10398
+ capability
10399
+ } });
10400
+ }
9211
10401
  }
10402
+ /** What the transport delivers for one poll: the registers read, or why none were. */
10403
+ const inboundSchema$1 = z.union([z.object({ registers: z.record(z.string(), z.number()) }), z.object({ error: z.string() })]);
9212
10404
  /**
9213
- * Finds a module the bundle names, or says it is not there.
10405
+ * The device a claim was made for.
9214
10406
  *
9215
- * @param resolve - How modules are found.
9216
- * @param directory - The folder the name is relative to.
9217
- * @param file - The name.
9218
- * @param what - What names it, for the message.
9219
- * @returns The module's path.
9220
- * @throws {Error} When it is not there.
10407
+ * @param descriptor - The claim's descriptor.
10408
+ * @returns The device, or undefined for anything that is not one.
9221
10409
  */
9222
- async function moduleOf(resolve, directory, file, what) {
9223
- const found = await resolve(directory, file);
9224
- if (found === null) throw new Error(`${what} names ${file}, which is not in the bundle`);
9225
- return found;
10410
+ function snapshotOf(descriptor) {
10411
+ const parsed = modbusDeviceSnapshotSchema.safeParse(descriptor);
10412
+ return parsed.success ? parsed.data : void 0;
9226
10413
  }
9227
10414
  /**
9228
- * The wires a vendor's devices are reached over: each platform transport a driver speaks that is
9229
- * a wire itself - `http`, `mqtt` - and what each of the vendor's own transports a driver speaks
9230
- * declares it goes over, since `shelly/rpc` says nothing to a person and HTTP does.
10415
+ * What a poll of a device asks the transport: where it is, how often, and the blocks.
9231
10416
  *
9232
- * @param vendor - The vendor's manifest.
9233
- * @param transports - The transport of every driver.
9234
- * @returns The wires, each once, in {@link TRANSPORT_WIRES}' order.
10417
+ * @param device - The device.
10418
+ * @returns The poll's arguments.
9235
10419
  */
9236
- function wiresOf(vendor, transports) {
9237
- const found = /* @__PURE__ */ new Set();
9238
- for (const transport of transports) {
9239
- const own = transport.startsWith(`${vendor.id}/`) ? vendor.transports[transport.slice(vendor.id.length + 1)] : void 0;
9240
- if (own === void 0) found.add(transport);
9241
- else for (const wire of transportWiresOf(own)) found.add(wire);
9242
- }
9243
- return TRANSPORT_WIRES.filter((wire) => found.has(wire));
10420
+ function modbusPollOf(device) {
10421
+ return {
10422
+ deviceKey: device.deviceKey,
10423
+ host: device.host,
10424
+ port: device.port,
10425
+ unitId: device.unitId,
10426
+ framing: device.framing,
10427
+ everyMs: device.pollSeconds * 1e3,
10428
+ blocks: planModbusBlocks(device.template).map((block) => ({ ...block }))
10429
+ };
9244
10430
  }
9245
10431
  /**
9246
- * Reads one driver directory.
10432
+ * Builds the Modbus driver of a vendor: the platform's own, or one whose `driver.json` says
10433
+ * `"kind": "modbus"`.
9247
10434
  *
9248
- * @param vendor - The vendor it belongs to, already checked.
9249
- * @param directory - The driver.
9250
- * @param resolve - How modules are found.
9251
- * @returns What its files say.
9252
- * @throws {Error} When the driver is malformed or cannot be read.
10435
+ * @param manifest - The driver's.
10436
+ * @param manifest.id - Its kind, `vendor/driver`.
10437
+ * @returns The integration.
10438
+ */
10439
+ function createModbusIntegration(manifest) {
10440
+ /**
10441
+ * The device a claim was made for.
10442
+ *
10443
+ * @param context - The instance's mapping context.
10444
+ * @returns The device.
10445
+ * @throws {ValidationError} When the claim holds no device - which identification never makes.
10446
+ */
10447
+ const claimed = (context) => {
10448
+ const device = snapshotOf(context.claim.descriptor);
10449
+ if (device === void 0) throw new ValidationError(`${manifest.id} holds a claim that is not a Modbus device`, { details: { integration: manifest.id } });
10450
+ return device;
10451
+ };
10452
+ return {
10453
+ id: manifest.id,
10454
+ transport: MODBUS_TRANSPORT,
10455
+ optionsSchema: jsonObjectSchema,
10456
+ discovery: {},
10457
+ /**
10458
+ * Claims a device the broker hands over as this driver's.
10459
+ *
10460
+ * @param discovered - What the transport handed over.
10461
+ * @returns The claim, or null for anything that is not one of this driver's devices.
10462
+ */
10463
+ claim: (discovered) => {
10464
+ const device = snapshotOf(discovered.payload);
10465
+ return device?.kind !== manifest.id ? null : {
10466
+ deviceKey: device.deviceKey,
10467
+ externalId: device.deviceKey,
10468
+ descriptor: device
10469
+ };
10470
+ },
10471
+ /**
10472
+ * Polls each device at its pace, for the blocks its template reads.
10473
+ *
10474
+ * @param claims - The devices.
10475
+ * @returns One poll per device.
10476
+ */
10477
+ subscriptions: (claims) => claims.flatMap((claim) => {
10478
+ const device = snapshotOf(claim.descriptor);
10479
+ return device === void 0 ? [] : [{
10480
+ op: "poll",
10481
+ args: modbusPollOf(device)
10482
+ }];
10483
+ }),
10484
+ /**
10485
+ * Describes the device and its entities, from its template.
10486
+ *
10487
+ * @param claim - The claim.
10488
+ * @returns The device.
10489
+ * @throws {ValidationError} When the claim holds no Modbus device.
10490
+ */
10491
+ describe: (claim) => {
10492
+ const device = snapshotOf(claim.descriptor);
10493
+ if (device === void 0) throw new ValidationError(`${manifest.id} cannot describe a claim with no Modbus device`, { details: { integration: manifest.id } });
10494
+ const { template } = device;
10495
+ return {
10496
+ externalId: claim.externalId,
10497
+ name: device.name,
10498
+ model: (template.device === "" ? template.name : template.device).slice(0, 128),
10499
+ entities: template.entities.map(modbusEntityDescriptorOf)
10500
+ };
10501
+ },
10502
+ /**
10503
+ * Turns what a poll read into reports, one per entity; every entity unavailable when the
10504
+ * device did not answer.
10505
+ *
10506
+ * @param message - What the transport delivered.
10507
+ * @param context - The identifiers the hub assigned, and the last states.
10508
+ * @returns The reports.
10509
+ */
10510
+ toState: (message, context) => {
10511
+ const parsed = inboundSchema$1.safeParse(message.payload);
10512
+ const device = snapshotOf(context.claim.descriptor);
10513
+ if (!parsed.success || device === void 0) return [];
10514
+ return device.template.entities.flatMap((entity) => {
10515
+ const entityId = context.entities.get(modbusObjectIdOf(entity));
10516
+ if (entityId === void 0) return [];
10517
+ const previous = context.lastState(entityId);
10518
+ if ("error" in parsed.data) return [{
10519
+ entityId,
10520
+ state: previous ?? {},
10521
+ attributes: {},
10522
+ isAvailable: false
10523
+ }];
10524
+ const state = modbusEntityStateOf(entity, device.template.wordOrder, parsed.data.registers, previous);
10525
+ return state === void 0 ? [] : [{
10526
+ entityId,
10527
+ state,
10528
+ attributes: {},
10529
+ isAvailable: true
10530
+ }];
10531
+ });
10532
+ },
10533
+ /**
10534
+ * Turns a command into the write that performs it.
10535
+ *
10536
+ * @param target - The entity, the capability and the command.
10537
+ * @param context - The claim and the last states.
10538
+ * @returns The request.
10539
+ * @throws {ValidationError} When the entity does not take the command, or the value is
10540
+ * outside its min and max.
10541
+ */
10542
+ toCommand: (target, context) => {
10543
+ const device = claimed(context);
10544
+ const entity = device.template.entities.find((candidate) => context.entities.get(modbusObjectIdOf(candidate)) === target.entityId);
10545
+ if (entity === void 0) throw new ValidationError(`${manifest.id} has no entity ${target.entityId}`, { details: {
10546
+ integration: manifest.id,
10547
+ entityId: target.entityId
10548
+ } });
10549
+ const write = encodeModbusWrite(entity, target.capability, target.command, device.template.wordOrder, context.lastState(target.entityId));
10550
+ return {
10551
+ deviceKey: device.deviceKey,
10552
+ op: "write",
10553
+ args: {
10554
+ host: device.host,
10555
+ port: device.port,
10556
+ unitId: device.unitId,
10557
+ framing: device.framing,
10558
+ function: write.function,
10559
+ address: write.address,
10560
+ values: [...write.values]
10561
+ }
10562
+ };
10563
+ }
10564
+ };
10565
+ }
10566
+ //#endregion
10567
+ //#region ../package-runtime/dist/mqtt-announcement.js
10568
+ /**
10569
+ * What a device says of itself on the house's MQTT broker, read: the MQTT discovery convention.
10570
+ *
10571
+ * A device announces each of its entities with a retained JSON document on
10572
+ * `<prefix>/<component>/[<node_id>/]<object_id>/config` - its name, the topics it reports and is
10573
+ * commanded on, the device it belongs to, the firmware that sent it - and takes it back with an
10574
+ * empty one. Tasmota, ESPHome, OpenMQTTGateway and most others speak it, under the prefix
10575
+ * `homeassistant` unless told otherwise. This module reads one announcement into an
10576
+ * {@link MqttEntity}: the abbreviations expanded, `~` put in place of the base topic, the device
10577
+ * and its origin found. A device the owner maps by hand is read into the same entity, so one
10578
+ * mapping (`mqtt-mapping.ts`) draws, reads and commands both.
10579
+ *
10580
+ * **Value templates are read as paths.** Announcements carry Jinja templates; the platform does
10581
+ * not render Jinja and does not pretend to. The templates nearly every device announces are a
10582
+ * value itself or one key of its JSON - `{{ value }}`, `{{ value_json.temperature }}`,
10583
+ * `{{ value_json['temperature'] }}`, `{{ value_json.a.b }}` - and those are read as the path they
10584
+ * name. Anything else - a filter, arithmetic, a condition - is skipped, and the Brokers page says
10585
+ * why, rather than showing a wrong value.
10586
+ */
10587
+ /** One step of a path: `.key`, `['key']`, `["key"]` or `[0]`. */
10588
+ const STEP = /^(?:\.([A-Za-z_][A-Za-z0-9_]*)|\[\s*'([^']*)'\s*\]|\[\s*"([^"]*)"\s*\]|\[\s*(\d+)\s*\])/u;
10589
+ /**
10590
+ * Reads a template as a path.
10591
+ *
10592
+ * @param template - The template the device announced; none is the value itself.
10593
+ * @returns The path, or that it is not supported.
10594
+ */
10595
+ function readTemplate(template) {
10596
+ if (template === void 0 || template.trim() === "") return {
10597
+ kind: "path",
10598
+ path: []
10599
+ };
10600
+ const inner = /^\s*\{\{\s*(.*?)\s*\}\}\s*$/su.exec(template)?.[1];
10601
+ if (inner === void 0) return {
10602
+ kind: "unsupported",
10603
+ template
10604
+ };
10605
+ if (inner === "value") return {
10606
+ kind: "path",
10607
+ path: []
10608
+ };
10609
+ if (!inner.startsWith("value_json")) return {
10610
+ kind: "unsupported",
10611
+ template
10612
+ };
10613
+ const path = [];
10614
+ let rest = inner.slice(10);
10615
+ while (rest !== "") {
10616
+ const step = STEP.exec(rest);
10617
+ if (step === null) return {
10618
+ kind: "unsupported",
10619
+ template
10620
+ };
10621
+ path.push(step[1] ?? step[2] ?? step[3] ?? step[4] ?? "");
10622
+ rest = rest.slice(step[0].length);
10623
+ }
10624
+ return path.length === 0 ? {
10625
+ kind: "unsupported",
10626
+ template
10627
+ } : {
10628
+ kind: "path",
10629
+ path
10630
+ };
10631
+ }
10632
+ /**
10633
+ * Reads a value from a payload along a path.
10634
+ *
10635
+ * @param payload - What was published, as text.
10636
+ * @param path - Where the value is; none for the payload itself.
10637
+ * @returns The value, or undefined when the payload has nothing there.
10638
+ */
10639
+ function valueAt(payload, path) {
10640
+ if (path.length === 0) return payload;
10641
+ let value;
10642
+ try {
10643
+ value = JSON.parse(payload);
10644
+ } catch {
10645
+ return;
10646
+ }
10647
+ for (const key of path) {
10648
+ if (typeof value !== "object" || value === null) return;
10649
+ value = value[key];
10650
+ }
10651
+ return value;
10652
+ }
10653
+ /**
10654
+ * A text value, or nothing.
10655
+ *
10656
+ * @param value - The value.
10657
+ * @returns It, when it is non-empty text.
10658
+ */
10659
+ function textOf(value) {
10660
+ return typeof value === "string" && value !== "" ? value : void 0;
10661
+ }
10662
+ /** One entity of a device, as a claim keeps it. */
10663
+ const mqttEntitySnapshotSchema = z.object({
10664
+ key: z.string().min(1),
10665
+ objectId: z.string().min(1).max(64),
10666
+ name: z.string().max(128),
10667
+ component: z.enum(MQTT_COMPONENTS),
10668
+ config: z.record(z.string(), z.unknown())
10669
+ });
10670
+ /**
10671
+ * A device the broker hears, whole: who it says it is and every entity it has. What discovery
10672
+ * proposes, what a claim keeps and what the transport delivers.
10673
+ */
10674
+ const mqttDeviceSnapshotSchema = z.object({
10675
+ deviceKey: z.string().min(1).max(256),
10676
+ identity: mqttIdentitySchema,
10677
+ entities: z.array(mqttEntitySnapshotSchema).max(256)
10678
+ });
10679
+ //#endregion
10680
+ //#region ../package-runtime/dist/mqtt-mapping.js
10681
+ /**
10682
+ * The platform's mapping of a device the house's MQTT broker hears onto entities: the one driver
10683
+ * every announced or mapped device can be run by, whoever's integration it is.
10684
+ *
10685
+ * An announcement describes its entity - a component, the topics it reports and is commanded on,
10686
+ * the payloads it speaks - so one mapping covers what any firmware announces, and a vendor whose
10687
+ * `driver.json` says `"kind": "mqtt"` gets it without writing code: its devices are its own, on
10688
+ * its page, and mapped here.
10689
+ *
10690
+ * **What is mapped.** A sensor (a number when it announces a unit or how its numbers add up,
10691
+ * text otherwise), a binary sensor, a switch, a light (on/off, brightness, white; plain or JSON),
10692
+ * a cover, a button, a number, a select and a lock. A number is registered in its class's unit -
10693
+ * a power in watts, however the device counts it - and converted on the way.
10694
+ *
10695
+ * **Pure throughout**, like every integration: what the transport hands over is the device whole
10696
+ * and the last text of every topic its entities read, with the topics that changed, so a state is
10697
+ * always computed from every topic it needs - a light's brightness with whether it is on, a
10698
+ * cover's position with its motion. An entity with no state topic is read from its command
10699
+ * topic: what the hub last published there is what it was told to be.
10700
+ */
10701
+ /** Reads what the transport delivers. */
10702
+ const inboundSchema = z.object({
10703
+ device: mqttDeviceSnapshotSchema,
10704
+ texts: z.record(z.string(), z.string()),
10705
+ changed: z.array(z.string()).nullable()
10706
+ });
10707
+ /** How a sensor's numbers add up, as an announcement may say it. */
10708
+ const STATE_CLASSES = [
10709
+ "measurement",
10710
+ "total",
10711
+ "total_increasing"
10712
+ ];
10713
+ /**
10714
+ * One of an entity's settings, as text, with a default.
10715
+ *
10716
+ * @param entity - The entity.
10717
+ * @param key - The setting.
10718
+ * @param fallback - What it is when not announced.
10719
+ * @returns It.
10720
+ */
10721
+ function textSetting(entity, key, fallback) {
10722
+ const value = entity.config[key];
10723
+ return typeof value === "string" ? value : typeof value === "number" ? String(value) : fallback;
10724
+ }
10725
+ /**
10726
+ * One of an entity's settings, as a number, with a default.
10727
+ *
10728
+ * @param entity - The entity.
10729
+ * @param key - The setting.
10730
+ * @param fallback - What it is when not announced.
10731
+ * @returns It.
10732
+ */
10733
+ function numberSetting(entity, key, fallback) {
10734
+ const value = entity.config[key];
10735
+ const number = typeof value === "number" ? value : Number(value ?? NaN);
10736
+ return Number.isFinite(number) ? number : fallback;
10737
+ }
10738
+ /**
10739
+ * A topic the entity names.
10740
+ *
10741
+ * @param entity - The entity.
10742
+ * @param key - Which: `state_topic`.
10743
+ * @returns It, when announced.
10744
+ */
10745
+ function topicOf(entity, key) {
10746
+ return textOf(entity.config[key]);
10747
+ }
10748
+ /**
10749
+ * Whether a light speaks JSON.
10750
+ *
10751
+ * @param entity - The light.
10752
+ * @returns True for `schema: json`.
10753
+ */
10754
+ function isJsonLight(entity) {
10755
+ return entity.component === "light" && entity.config["schema"] === "json";
10756
+ }
10757
+ /**
10758
+ * Whether a JSON light announces a feature: `brightness: true`, or a colour mode that has it.
10759
+ *
10760
+ * @param entity - The light.
10761
+ * @param flag - `brightness`, `color_temp`.
10762
+ * @returns True when it does.
10763
+ */
10764
+ function jsonLightHas(entity, flag) {
10765
+ if (entity.config[flag] === true) return true;
10766
+ const modes = entity.config["supported_color_modes"];
10767
+ if (!Array.isArray(modes)) return false;
10768
+ return flag === "color_temp" ? modes.includes("color_temp") : modes.some((mode) => mode !== "onoff");
10769
+ }
10770
+ /**
10771
+ * Whether an entity reports nothing of its own: no state topic, so it is what it was told to be,
10772
+ * read from its command topic.
10773
+ *
10774
+ * @param entity - The entity.
10775
+ * @returns True for one.
10776
+ */
10777
+ function isOptimistic(entity) {
10778
+ return topicOf(entity, "state_topic") === void 0 && entity.component !== "button";
10779
+ }
10780
+ /**
10781
+ * A sensor's measurement, as it is registered: in its class's unit, with the class's default
10782
+ * state class - or without the class, when its unit cannot be brought to the class's.
10783
+ *
10784
+ * @param entity - The sensor.
10785
+ * @returns What it is registered with, and the unit its numbers are converted from.
10786
+ */
10787
+ function measurementOf(entity) {
10788
+ const unit = textOf(entity.config["unit_of_measurement"]);
10789
+ const deviceClass = textOf(entity.config["device_class"]);
10790
+ const said = textOf(entity.config["state_class"]);
10791
+ const stateClass = STATE_CLASSES.find((each) => each === said);
10792
+ const unitOnly = {
10793
+ ...unit === void 0 ? {} : { unitOfMeasurement: unit },
10794
+ ...stateClass === void 0 ? {} : { stateClass }
10795
+ };
10796
+ if (deviceClass === void 0 || getSensorClass(deviceClass)?.valueKind !== "number") return { fields: unitOnly };
10797
+ const canonical = resolveCanonicalUnit(deviceClass);
10798
+ const registered = canonical ?? unit;
10799
+ if (!(unit === void 0 || canonical === void 0 || unit === canonical || toCanonical(deviceClass, 1, unit) !== void 0) || sensorRegistrationIssue({
10800
+ deviceClass,
10801
+ unitOfMeasurement: registered
10802
+ }) !== void 0) return { fields: unitOnly };
10803
+ const resolved = resolveStateClass(deviceClass, stateClass);
10804
+ return {
10805
+ fields: {
10806
+ deviceClass,
10807
+ ...registered === void 0 ? {} : { unitOfMeasurement: registered },
10808
+ ...resolved === void 0 ? {} : { stateClass: resolved }
10809
+ },
10810
+ ...unit !== void 0 && canonical !== void 0 && unit !== canonical ? { conversion: {
10811
+ deviceClass,
10812
+ unit
10813
+ } } : {}
10814
+ };
10815
+ }
10816
+ /**
10817
+ * What one entity is registered as.
10818
+ *
10819
+ * @param entity - The entity.
10820
+ * @returns Its shape.
10821
+ */
10822
+ function mqttShapeOf(entity) {
10823
+ const deviceClass = textOf(entity.config["device_class"]);
10824
+ const withClass = deviceClass === void 0 ? {} : { deviceClass };
10825
+ const precision = entity.config["suggested_display_precision"];
10826
+ const withPrecision = typeof precision === "number" && Number.isInteger(precision) && precision >= 0 ? { displayPrecision: Math.min(precision, 10) } : {};
10827
+ switch (entity.component) {
10828
+ case "sensor": {
10829
+ const { fields } = measurementOf(entity);
10830
+ return fields.unitOfMeasurement === void 0 && fields.stateClass === void 0 ? {
10831
+ domain: "sensor",
10832
+ capabilities: { sensor_text: {} }
10833
+ } : {
10834
+ domain: "sensor",
10835
+ capabilities: { sensor_numeric: {} },
10836
+ ...fields,
10837
+ ...withPrecision
10838
+ };
10839
+ }
10840
+ case "binary_sensor": return {
10841
+ domain: "binary_sensor",
10842
+ capabilities: { sensor_binary: {} },
10843
+ ...withClass
10844
+ };
10845
+ case "switch": return {
10846
+ domain: "switch",
10847
+ capabilities: { on_off: {} },
10848
+ ...withClass
10849
+ };
10850
+ case "light": {
10851
+ const json = isJsonLight(entity);
10852
+ const hasLevel = json ? jsonLightHas(entity, "brightness") : topicOf(entity, "brightness_command_topic") !== void 0;
10853
+ const hasWhite = json ? jsonLightHas(entity, "color_temp") : topicOf(entity, "color_temp_command_topic") !== void 0;
10854
+ return {
10855
+ domain: "light",
10856
+ capabilities: {
10857
+ on_off: {},
10858
+ ...hasLevel ? { level: { hasTransition: false } } : {},
10859
+ ...hasWhite ? { color_temp: {
10860
+ minMireds: Math.round(numberSetting(entity, "min_mireds", 153)),
10861
+ maxMireds: Math.round(numberSetting(entity, "max_mireds", 500))
10862
+ } } : {}
10863
+ }
10864
+ };
10865
+ }
10866
+ case "cover": return {
10867
+ domain: "cover",
10868
+ capabilities: { cover: {
10869
+ hasPosition: topicOf(entity, "position_topic") !== void 0 || topicOf(entity, "set_position_topic") !== void 0,
10870
+ hasTilt: false
10871
+ } },
10872
+ ...withClass
10873
+ };
10874
+ case "button": return {
10875
+ domain: "button",
10876
+ capabilities: { button: {} },
10877
+ ...withClass
10878
+ };
10879
+ case "number": {
10880
+ const min = numberSetting(entity, "min", 1);
10881
+ const max = numberSetting(entity, "max", 100);
10882
+ const unit = textOf(entity.config["unit_of_measurement"]);
10883
+ return {
10884
+ domain: "number",
10885
+ capabilities: { number: {
10886
+ min,
10887
+ max: max > min ? max : min + 1,
10888
+ step: numberSetting(entity, "step", 1)
10889
+ } },
10890
+ ...unit === void 0 ? {} : { unitOfMeasurement: unit }
10891
+ };
10892
+ }
10893
+ case "select": {
10894
+ const options = Array.isArray(entity.config["options"]) ? [...new Set(entity.config["options"].map(String))].filter((option) => option !== "" && option.length <= 64) : [];
10895
+ return {
10896
+ domain: "select",
10897
+ capabilities: { select: { options: (options.length === 0 ? ["—"] : options).slice(0, 64).map((option) => ({
10898
+ value: option,
10899
+ label: option
10900
+ })) } }
10901
+ };
10902
+ }
10903
+ case "lock": return {
10904
+ domain: "lock",
10905
+ capabilities: { lock: { hasCode: false } }
10906
+ };
10907
+ }
10908
+ }
10909
+ /**
10910
+ * The path a template of an entity names.
10911
+ *
10912
+ * @param entity - The entity.
10913
+ * @param key - The template's key.
10914
+ * @returns The path; the payload itself for none, or one that is not read.
10915
+ */
10916
+ function pathOf(entity, key) {
10917
+ const template = readTemplate(textOf(entity.config[key]));
10918
+ return template.kind === "path" ? template.path : [];
10919
+ }
10920
+ /**
10921
+ * Which template reads an entity's state: its value template, a light's state value template, or
10922
+ * its state template, the first it announces.
10923
+ *
10924
+ * @param config - The announcement.
10925
+ * @returns The key.
10926
+ */
10927
+ function stateTemplateKeyOf(config) {
10928
+ return [
10929
+ "value_template",
10930
+ "state_value_template",
10931
+ "state_template"
10932
+ ].find((key) => textOf(config[key]) !== void 0) ?? "value_template";
10933
+ }
10934
+ /**
10935
+ * The availability topics of an entity, with the payloads that say it is and is not there.
10936
+ *
10937
+ * @param entity - The entity.
10938
+ * @returns The topics.
10939
+ */
10940
+ function availabilityOf(entity) {
10941
+ const shared = {
10942
+ available: textSetting(entity, "payload_available", "online"),
10943
+ notAvailable: textSetting(entity, "payload_not_available", "offline")
10944
+ };
10945
+ const single = topicOf(entity, "availability_topic");
10946
+ const topics = (Array.isArray(entity.config["availability"]) ? entity.config["availability"] : []).flatMap((entry) => {
10947
+ if (typeof entry !== "object" || entry === null) return [];
10948
+ const record = entry;
10949
+ const topic = textOf(record["topic"]);
10950
+ const template = readTemplate(textOf(record["value_template"]));
10951
+ return topic === void 0 ? [] : [{
10952
+ topic,
10953
+ available: textOf(record["payload_available"]) ?? shared.available,
10954
+ notAvailable: textOf(record["payload_not_available"]) ?? shared.notAvailable,
10955
+ path: template.kind === "path" ? template.path : []
10956
+ }];
10957
+ });
10958
+ return single === void 0 ? topics : [{
10959
+ topic: single,
10960
+ ...shared,
10961
+ path: pathOf(entity, "availability_template")
10962
+ }, ...topics];
10963
+ }
10964
+ /**
10965
+ * The topics one entity is read from: its state (its command topic, when it has none), its
10966
+ * availability, a plain light's brightness and white, a cover's position.
10967
+ *
10968
+ * @param entity - The entity.
10969
+ * @returns Them, each with what it carries.
10970
+ */
10971
+ function readersOf(entity) {
10972
+ const optimistic = isOptimistic(entity);
10973
+ const readers = [];
10974
+ /**
10975
+ * Notes one topic, when the entity has it.
10976
+ *
10977
+ * @param topic - The topic.
10978
+ * @param reading - What it carries.
10979
+ * @param path - Where the value is.
10980
+ */
10981
+ const add = (topic, reading, path) => {
10982
+ if (topic !== void 0) readers.push({
10983
+ topic,
10984
+ reading,
10985
+ path
10986
+ });
10987
+ };
10988
+ add(topicOf(entity, optimistic ? "command_topic" : "state_topic"), "state", optimistic ? [] : pathOf(entity, stateTemplateKeyOf(entity.config)));
10989
+ for (const availability of availabilityOf(entity)) add(availability.topic, "availability", availability.path);
10990
+ if (entity.component === "light" && !isJsonLight(entity)) {
10991
+ add(topicOf(entity, optimistic ? "brightness_command_topic" : "brightness_state_topic"), "brightness", optimistic ? [] : pathOf(entity, "brightness_value_template"));
10992
+ add(topicOf(entity, optimistic ? "color_temp_command_topic" : "color_temp_state_topic"), "color_temp", optimistic ? [] : pathOf(entity, "color_temp_value_template"));
10993
+ }
10994
+ if (entity.component === "cover" && !optimistic) add(topicOf(entity, "position_topic"), "position", pathOf(entity, "position_template"));
10995
+ return readers;
10996
+ }
10997
+ /**
10998
+ * Every topic an entity is read from.
10999
+ *
11000
+ * @param entity - The entity.
11001
+ * @returns The topics, each once.
11002
+ */
11003
+ function mqttTopicsOf(entity) {
11004
+ return [...new Set(readersOf(entity).map((reader) => reader.topic))];
11005
+ }
11006
+ /**
11007
+ * A number from what a template read.
11008
+ *
11009
+ * @param value - What it read.
11010
+ * @returns The number, or undefined when it is not one.
11011
+ */
11012
+ function numberOf(value) {
11013
+ const number = typeof value === "number" ? value : typeof value === "string" ? Number(value) : NaN;
11014
+ return Number.isFinite(number) ? number : void 0;
11015
+ }
11016
+ /**
11017
+ * Text from what a template read.
11018
+ *
11019
+ * @param value - What it read.
11020
+ * @returns The text, or undefined for nothing.
11021
+ */
11022
+ function stringOf(value) {
11023
+ if (typeof value === "string") return value;
11024
+ return typeof value === "number" || typeof value === "boolean" ? String(value) : void 0;
11025
+ }
11026
+ /**
11027
+ * A brightness, as a level out of 100.
11028
+ *
11029
+ * @param value - The brightness, on the device's scale.
11030
+ * @param scale - The scale's top.
11031
+ * @returns The level, or undefined when it is not a number.
11032
+ */
11033
+ function levelOf(value, scale) {
11034
+ const brightness = numberOf(value);
11035
+ return brightness === void 0 || scale <= 0 ? void 0 : Math.max(0, Math.min(100, brightness / scale * 100));
11036
+ }
11037
+ /**
11038
+ * A colour temperature, in mireds the platform takes.
11039
+ *
11040
+ * @param value - The temperature, in mireds.
11041
+ * @returns It, or undefined when it is not a number.
11042
+ */
11043
+ function miredsOf(value) {
11044
+ const mireds = numberOf(value);
11045
+ return mireds === void 0 ? void 0 : Math.max(1, Math.min(1e3, Math.round(mireds)));
11046
+ }
11047
+ /**
11048
+ * Whether a text is the entity's "on" or "off", by its state payloads - or, read from its command
11049
+ * topic, by the payloads it is commanded with.
11050
+ *
11051
+ * @param entity - The entity.
11052
+ * @param text - What its state topic carried.
11053
+ * @returns True, false, or undefined for neither.
11054
+ */
11055
+ function isOnOf(entity, text) {
11056
+ const onPayload = textSetting(entity, "payload_on", "ON");
11057
+ const offPayload = textSetting(entity, "payload_off", "OFF");
11058
+ const on = isOptimistic(entity) ? onPayload : textSetting(entity, "state_on", onPayload);
11059
+ const off = isOptimistic(entity) ? offPayload : textSetting(entity, "state_off", offPayload);
11060
+ return text === on ? true : text === off ? false : void 0;
11061
+ }
11062
+ /**
11063
+ * A JSON light's state, from its state document, what the document leaves out kept as it was.
11064
+ *
11065
+ * @param entity - The light.
11066
+ * @param text - Its state topic's text.
11067
+ * @param previous - What it was.
11068
+ * @returns The capabilities it says, or nothing.
11069
+ */
11070
+ function jsonLightState(entity, text, previous) {
11071
+ let document;
11072
+ try {
11073
+ document = text === void 0 ? void 0 : JSON.parse(text);
11074
+ } catch {
11075
+ return {};
11076
+ }
11077
+ if (typeof document !== "object" || document === null) return {};
11078
+ const record = document;
11079
+ const shape = mqttShapeOf(entity);
11080
+ const state = stringOf(record["state"]);
11081
+ const level = levelOf(record["brightness"], numberSetting(entity, "brightness_scale", 255));
11082
+ const mireds = miredsOf(record["color_temp"]);
11083
+ return {
11084
+ ...state === void 0 ? previous?.on_off === void 0 ? {} : { on_off: previous.on_off } : { on_off: { isOn: state.toUpperCase() === "ON" } },
11085
+ ...shape.capabilities.level === void 0 ? {} : level === void 0 ? previous?.level === void 0 ? {} : { level: previous.level } : { level: { level } },
11086
+ ...shape.capabilities.color_temp === void 0 ? {} : mireds === void 0 ? previous?.color_temp === void 0 ? {} : { color_temp: previous.color_temp } : { color_temp: { mireds } }
11087
+ };
11088
+ }
11089
+ /**
11090
+ * A cover's state: its motion from its state topic, its position from its position topic - or,
11091
+ * for a cover with none, from where its state says it stopped.
11092
+ *
11093
+ * @param entity - The cover.
11094
+ * @param stateText - What its state topic carried.
11095
+ * @param position - What its position topic read, as a value.
11096
+ * @param previous - What it was.
11097
+ * @returns The cover's state.
11098
+ */
11099
+ function coverState(entity, stateText, position, previous) {
11100
+ const current = previous?.cover ?? {
11101
+ position: 0,
11102
+ motion: "stopped"
11103
+ };
11104
+ const states = {
11105
+ [textSetting(entity, "state_open", "open")]: {
11106
+ motion: "stopped",
11107
+ position: 100
11108
+ },
11109
+ [textSetting(entity, "state_closed", "closed")]: {
11110
+ motion: "stopped",
11111
+ position: 0
11112
+ },
11113
+ [textSetting(entity, "state_opening", "opening")]: { motion: "opening" },
11114
+ [textSetting(entity, "state_closing", "closing")]: { motion: "closing" },
11115
+ [textSetting(entity, "state_stopped", "stopped")]: { motion: "stopped" }
11116
+ };
11117
+ const said = stateText === void 0 ? void 0 : states[stateText];
11118
+ const raw = numberOf(position);
11119
+ const open = numberSetting(entity, "position_open", 100);
11120
+ const closed = numberSetting(entity, "position_closed", 0);
11121
+ const reported = raw === void 0 || open === closed ? void 0 : Math.max(0, Math.min(100, (raw - closed) / (open - closed) * 100));
11122
+ const hasPosition = topicOf(entity, "position_topic") !== void 0;
11123
+ return { cover: {
11124
+ position: reported ?? (hasPosition ? current.position : said?.position ?? current.position),
11125
+ motion: said?.motion ?? current.motion
11126
+ } };
11127
+ }
11128
+ /**
11129
+ * What one entity's topics say it is now.
11130
+ *
11131
+ * @param entity - The entity.
11132
+ * @param textOfTopic - The last text a topic carried.
11133
+ * @param previous - What it was last reported as; undefined before it ever was.
11134
+ * @returns Its state and whether it is there, or undefined while it has nothing to say.
11135
+ */
11136
+ function mqttStateOf(entity, textOfTopic, previous) {
11137
+ const readers = readersOf(entity);
11138
+ /**
11139
+ * What one reading's topic carries, at its path.
11140
+ *
11141
+ * @param reading - Which.
11142
+ * @returns The value, or undefined.
11143
+ */
11144
+ const read = (reading) => {
11145
+ const reader = readers.find((each) => each.reading === reading);
11146
+ const text = reader === void 0 ? void 0 : textOfTopic(reader.topic);
11147
+ return reader === void 0 || text === void 0 ? void 0 : valueAt(text, reader.path);
11148
+ };
11149
+ const stateValue = read("state");
11150
+ const stateText = stringOf(stateValue);
11151
+ let state;
11152
+ switch (entity.component) {
11153
+ case "sensor": {
11154
+ if (mqttShapeOf(entity).capabilities.sensor_text !== void 0) {
11155
+ state = stateText === void 0 ? {} : { sensor_text: { value: stateText.slice(0, 512) } };
11156
+ break;
11157
+ }
11158
+ const number = numberOf(stateValue);
11159
+ const { conversion } = measurementOf(entity);
11160
+ const value = number === void 0 || conversion === void 0 ? number : toCanonical(conversion.deviceClass, number, conversion.unit);
11161
+ state = value === void 0 ? {} : { sensor_numeric: { value } };
11162
+ break;
11163
+ }
11164
+ case "binary_sensor": {
11165
+ const isOn = stateText === textSetting(entity, "payload_on", "ON") ? true : stateText === textSetting(entity, "payload_off", "OFF") ? false : void 0;
11166
+ state = isOn === void 0 ? {} : { sensor_binary: { isOn } };
11167
+ break;
11168
+ }
11169
+ case "switch": {
11170
+ const isOn = isOnOf(entity, stateText);
11171
+ state = isOn === void 0 ? {} : { on_off: { isOn } };
11172
+ break;
11173
+ }
11174
+ case "lock": {
11175
+ const states = isOptimistic(entity) ? {
11176
+ [textSetting(entity, "payload_lock", "LOCK")]: "locked",
11177
+ [textSetting(entity, "payload_unlock", "UNLOCK")]: "unlocked"
11178
+ } : {
11179
+ [textSetting(entity, "state_locked", "LOCKED")]: "locked",
11180
+ [textSetting(entity, "state_unlocked", "UNLOCKED")]: "unlocked",
11181
+ [textSetting(entity, "state_jammed", "JAMMED")]: "jammed"
11182
+ };
11183
+ const lockState = stateText === void 0 ? void 0 : states[stateText];
11184
+ state = lockState === void 0 ? {} : { lock: { lockState } };
11185
+ break;
11186
+ }
11187
+ case "select":
11188
+ state = { select: { option: stateText === void 0 || stateText === "" ? null : stateText.slice(0, 64) } };
11189
+ break;
11190
+ case "number":
11191
+ state = { number: { value: numberOf(stateValue) ?? null } };
11192
+ break;
11193
+ case "button":
11194
+ state = { button: {} };
11195
+ break;
11196
+ case "cover":
11197
+ state = coverState(entity, stateText, read("position"), previous);
11198
+ break;
11199
+ case "light": {
11200
+ if (isJsonLight(entity)) {
11201
+ state = jsonLightState(entity, stateText, previous);
11202
+ break;
11203
+ }
11204
+ const shape = mqttShapeOf(entity);
11205
+ const isOn = isOnOf(entity, stateText);
11206
+ const level = levelOf(read("brightness"), numberSetting(entity, "brightness_scale", 255));
11207
+ const mireds = miredsOf(read("color_temp"));
11208
+ state = {
11209
+ ...isOn === void 0 ? {} : { on_off: { isOn } },
11210
+ ...level === void 0 || shape.capabilities.level === void 0 ? {} : { level: { level } },
11211
+ ...mireds === void 0 || shape.capabilities.color_temp === void 0 ? {} : { color_temp: { mireds } }
11212
+ };
11213
+ break;
11214
+ }
11215
+ }
11216
+ if (Object.keys(state).length === 0 || entity.component === "light" && state["on_off"] === void 0) return;
11217
+ const parsed = capabilityStateSchema.safeParse(state);
11218
+ return parsed.success ? {
11219
+ state: parsed.data,
11220
+ isAvailable: isAvailableOf(entity, textOfTopic)
11221
+ } : void 0;
11222
+ }
11223
+ /**
11224
+ * Whether an entity's device says it is there: always, for one with no availability topic;
11225
+ * otherwise once one of its topics said so and none says it is not.
11226
+ *
11227
+ * @param entity - The entity.
11228
+ * @param textOfTopic - The last text a topic carried.
11229
+ * @returns True when it is there.
11230
+ */
11231
+ function isAvailableOf(entity, textOfTopic) {
11232
+ const entries = availabilityOf(entity);
11233
+ if (entries.length === 0) return true;
11234
+ const said = entries.flatMap((entry) => {
11235
+ const text = textOfTopic(entry.topic);
11236
+ const value = text === void 0 ? void 0 : stringOf(valueAt(text, entry.path));
11237
+ return value === entry.available ? [true] : value === entry.notAvailable ? [false] : [];
11238
+ });
11239
+ return said.includes(true) && !said.includes(false);
11240
+ }
11241
+ /**
11242
+ * One field of a command, as text.
11243
+ *
11244
+ * @param value - The field.
11245
+ * @returns It as text; empty for anything that is not a string or a number.
11246
+ */
11247
+ function textOfCommand(value) {
11248
+ return typeof value === "string" ? value : typeof value === "number" ? String(value) : "";
11249
+ }
11250
+ /**
11251
+ * What a command publishes.
11252
+ *
11253
+ * @param entity - The entity.
11254
+ * @param capability - Which capability.
11255
+ * @param command - The command, as the contract has it.
11256
+ * @param current - What the entity is now, for a toggle.
11257
+ * @returns The messages, in order.
11258
+ * @throws {ValidationError} When the entity takes no such command, or fills its payloads with a
11259
+ * template the platform cannot render.
11260
+ */
11261
+ function mqttCommandOf(entity, capability, command, current) {
11262
+ const name = textOfCommand(command["command"]);
11263
+ /**
11264
+ * A refusal.
11265
+ *
11266
+ * @param message - Why.
11267
+ * @returns The error.
11268
+ */
11269
+ const refusal = (message) => new ValidationError(message, { details: {
11270
+ entity: entity.key,
11271
+ capability,
11272
+ command: name
11273
+ } });
11274
+ if (textOf(entity.config["command_template"]) !== void 0) throw refusal(`${entity.name} announces a command template, which the platform cannot fill`);
11275
+ /**
11276
+ * A topic the entity is commanded on.
11277
+ *
11278
+ * @param key - Which.
11279
+ * @param what - What it is, for the refusal.
11280
+ * @returns The topic.
11281
+ * @throws {ValidationError} When the entity announces none.
11282
+ */
11283
+ const commandTopic = (key = "command_topic", what = "command topic") => {
11284
+ const topic = topicOf(entity, key);
11285
+ if (topic === void 0) throw refusal(`${entity.name} announces no ${what}`);
11286
+ return topic;
11287
+ };
11288
+ const isOn = current?.on_off?.isOn === true;
11289
+ if (isJsonLight(entity)) {
11290
+ const scale = numberSetting(entity, "brightness_scale", 255);
11291
+ const document = name === "turn_on" ? { state: "ON" } : name === "turn_off" ? { state: "OFF" } : name === "toggle" ? { state: isOn ? "OFF" : "ON" } : name === "set_level" ? {
11292
+ state: "ON",
11293
+ brightness: Math.round(Number(command["level"]) / 100 * scale)
11294
+ } : name === "set_color_temp" ? {
11295
+ state: "ON",
11296
+ color_temp: Number(command["mireds"])
11297
+ } : void 0;
11298
+ if (document === void 0) throw refusal(`${entity.name} takes no ${name}`);
11299
+ return [{
11300
+ topic: commandTopic(),
11301
+ payload: JSON.stringify(document)
11302
+ }];
11303
+ }
11304
+ switch (capability) {
11305
+ case "on_off": {
11306
+ const wantsOn = name === "turn_on" || name === "toggle" && !isOn;
11307
+ return [{
11308
+ topic: commandTopic(),
11309
+ payload: wantsOn ? textSetting(entity, "payload_on", "ON") : textSetting(entity, "payload_off", "OFF")
11310
+ }];
11311
+ }
11312
+ case "level": {
11313
+ const scale = numberSetting(entity, "brightness_scale", 255);
11314
+ return [{
11315
+ topic: commandTopic("brightness_command_topic", "brightness topic"),
11316
+ payload: String(Math.round(Number(command["level"]) / 100 * scale))
11317
+ }];
11318
+ }
11319
+ case "color_temp": return [{
11320
+ topic: commandTopic("color_temp_command_topic", "colour temperature topic"),
11321
+ payload: String(Math.round(Number(command["mireds"])))
11322
+ }];
11323
+ case "cover": {
11324
+ if (name === "set_position") {
11325
+ const open = numberSetting(entity, "position_open", 100);
11326
+ const closed = numberSetting(entity, "position_closed", 0);
11327
+ return [{
11328
+ topic: commandTopic("set_position_topic", "position topic"),
11329
+ payload: String(Math.round(closed + Number(command["position"]) / 100 * (open - closed)))
11330
+ }];
11331
+ }
11332
+ const payload = {
11333
+ open: textSetting(entity, "payload_open", "OPEN"),
11334
+ close: textSetting(entity, "payload_close", "CLOSE"),
11335
+ stop: textSetting(entity, "payload_stop", "STOP")
11336
+ }[name];
11337
+ if (payload === void 0) throw refusal(`${entity.name} takes no ${name}`);
11338
+ return [{
11339
+ topic: commandTopic(),
11340
+ payload
11341
+ }];
11342
+ }
11343
+ case "button": return [{
11344
+ topic: commandTopic(),
11345
+ payload: textSetting(entity, "payload_press", "PRESS")
11346
+ }];
11347
+ case "number": return [{
11348
+ topic: commandTopic(),
11349
+ payload: textOfCommand(command["value"])
11350
+ }];
11351
+ case "select": return [{
11352
+ topic: commandTopic(),
11353
+ payload: textOfCommand(command["option"])
11354
+ }];
11355
+ case "lock": return [{
11356
+ topic: commandTopic(),
11357
+ payload: name === "lock" ? textSetting(entity, "payload_lock", "LOCK") : textSetting(entity, "payload_unlock", "UNLOCK")
11358
+ }];
11359
+ default: throw refusal(`${entity.name} takes no ${capability} command`);
11360
+ }
11361
+ }
11362
+ /**
11363
+ * A device, read from what identification or a claim holds.
11364
+ *
11365
+ * @param value - What it holds.
11366
+ * @returns The device, or undefined when it is not one.
11367
+ */
11368
+ function deviceOf(value) {
11369
+ const parsed = mqttDeviceSnapshotSchema.safeParse(value);
11370
+ return parsed.success ? parsed.data : void 0;
11371
+ }
11372
+ /**
11373
+ * One entity, as the device describes it.
11374
+ *
11375
+ * @param entity - The entity.
11376
+ * @returns Its descriptor.
11377
+ */
11378
+ function entityDescriptorOf(entity) {
11379
+ return {
11380
+ ...mqttShapeOf(entity),
11381
+ objectId: entity.objectId,
11382
+ name: entity.name
11383
+ };
11384
+ }
11385
+ /**
11386
+ * Builds the MQTT driver of a vendor: the platform's own, or one whose `driver.json` says
11387
+ * `"kind": "mqtt"`.
11388
+ *
11389
+ * @param manifest - The driver's.
11390
+ * @param manifest.id - Its kind, `vendor/driver`.
11391
+ * @returns The integration.
11392
+ */
11393
+ function createMqttIntegration(manifest) {
11394
+ /**
11395
+ * The device a claim was made for.
11396
+ *
11397
+ * @param context - The instance's mapping context.
11398
+ * @returns The device.
11399
+ * @throws {ValidationError} When the claim holds no device - which identification never makes.
11400
+ */
11401
+ const claimed = (context) => {
11402
+ const device = deviceOf(context.claim.descriptor);
11403
+ if (device === void 0) throw new ValidationError(`${manifest.id} holds a claim that is not an MQTT device`, { details: { integration: manifest.id } });
11404
+ return device;
11405
+ };
11406
+ return {
11407
+ id: manifest.id,
11408
+ transport: MQTT_HOUSE_TRANSPORT,
11409
+ optionsSchema: jsonObjectSchema,
11410
+ discovery: {},
11411
+ /**
11412
+ * Claims a device the broker hears.
11413
+ *
11414
+ * @param discovered - What the transport handed over.
11415
+ * @returns The claim, or null for anything that is not one.
11416
+ */
11417
+ claim: (discovered) => {
11418
+ const device = deviceOf(discovered.payload);
11419
+ return device === void 0 ? null : {
11420
+ deviceKey: discovered.deviceKey,
11421
+ externalId: device.deviceKey,
11422
+ descriptor: device
11423
+ };
11424
+ },
11425
+ /**
11426
+ * Subscribes to nothing: the broker hands over every topic its devices read.
11427
+ *
11428
+ * @returns Nothing.
11429
+ */
11430
+ subscriptions: () => [],
11431
+ /**
11432
+ * Describes the device and its entities.
11433
+ *
11434
+ * @param claim - The claim.
11435
+ * @returns The device.
11436
+ * @throws {ValidationError} When the claim holds no MQTT device.
11437
+ */
11438
+ describe: (claim) => {
11439
+ const device = deviceOf(claim.descriptor);
11440
+ if (device === void 0) throw new ValidationError(`${manifest.id} cannot describe a claim with no MQTT device`, { details: { integration: manifest.id } });
11441
+ const { identity } = device;
11442
+ const mac = identity.macAddresses.map(normalizeMac).find((each) => each !== null);
11443
+ return {
11444
+ externalId: claim.externalId,
11445
+ name: identity.name.slice(0, 128),
11446
+ ...mac === void 0 ? {} : { mac },
11447
+ ...identity.serialNumber === null ? {} : { serialNumber: identity.serialNumber },
11448
+ ...identity.manufacturer === null ? {} : { manufacturer: identity.manufacturer },
11449
+ ...identity.model === null ? {} : { model: identity.model },
11450
+ ...identity.swVersion === null ? {} : { swVersion: identity.swVersion.slice(0, 64) },
11451
+ ...identity.hwVersion === null ? {} : { hwVersion: identity.hwVersion.slice(0, 64) },
11452
+ ...identity.viaDevice === null ? {} : { viaExternalId: identity.viaDevice },
11453
+ entities: device.entities.map(entityDescriptorOf)
11454
+ };
11455
+ },
11456
+ /**
11457
+ * Turns what the topics say into reports, one per entity a changed topic is read for.
11458
+ *
11459
+ * @param message - What the transport delivered.
11460
+ * @param context - The identifiers the hub assigned, and the last states.
11461
+ * @returns The reports.
11462
+ */
11463
+ toState: (message, context) => {
11464
+ const parsed = inboundSchema.safeParse(message.payload);
11465
+ if (!parsed.success) return [];
11466
+ const { device, texts, changed } = parsed.data;
11467
+ /**
11468
+ * The last text of a topic.
11469
+ *
11470
+ * @param topic - The topic.
11471
+ * @returns It, if the topic carried text.
11472
+ */
11473
+ const textOfTopic = (topic) => texts[topic];
11474
+ return device.entities.flatMap((entity) => {
11475
+ const entityId = context.entities.get(entity.objectId);
11476
+ if (entityId === void 0 || changed !== null && !mqttTopicsOf(entity).some((topic) => changed.includes(topic))) return [];
11477
+ const read = mqttStateOf(entity, textOfTopic, context.lastState(entityId));
11478
+ return read === void 0 ? [] : [{
11479
+ entityId,
11480
+ state: read.state,
11481
+ attributes: {},
11482
+ isAvailable: read.isAvailable
11483
+ }];
11484
+ });
11485
+ },
11486
+ /**
11487
+ * Turns a command into the messages it publishes.
11488
+ *
11489
+ * @param target - The entity, the capability and the command.
11490
+ * @param context - The claim and the last states.
11491
+ * @returns The request.
11492
+ * @throws {ValidationError} When the entity does not take the command.
11493
+ */
11494
+ toCommand: (target, context) => {
11495
+ const entity = claimed(context).entities.find((candidate) => context.entities.get(candidate.objectId) === target.entityId);
11496
+ if (entity === void 0) throw new ValidationError(`${manifest.id} has no entity ${target.entityId}`, { details: {
11497
+ integration: manifest.id,
11498
+ entityId: target.entityId
11499
+ } });
11500
+ const messages = mqttCommandOf(entity, target.capability, target.command, context.lastState(target.entityId));
11501
+ return {
11502
+ deviceKey: context.claim.deviceKey,
11503
+ op: "publish",
11504
+ args: { messages: messages.map(({ topic, payload }) => ({
11505
+ topic,
11506
+ payload
11507
+ })) }
11508
+ };
11509
+ }
11510
+ };
11511
+ }
11512
+ //#endregion
11513
+ //#region ../package-runtime/dist/loader.js
11514
+ /**
11515
+ * Reading integrations off disk: the loader `hub` runs and the integration SDK checks a bundle
11516
+ * with, so that what passes `nebulahome-integration validate` is what `hub` loads.
11517
+ *
11518
+ * A bundle is a vendor directory - `manifest.json`, a logo, optionally a `setup.json` of what
11519
+ * every device of the vendor shares - holding one driver directory per profile or entry point,
11520
+ * each with `driver.json`, its own `setup.json` and the profile or code. It is read in two steps:
11521
+ *
11522
+ * 1. {@link readVendorDirectory} reads and checks every file - the schemas, the ids against the
11523
+ * folders, the runtime range, the logo, the containers, that every module named is there -
11524
+ * and imports nothing. It is all a source tree needs to be checked.
11525
+ * 2. {@link instantiateVendor} imports the code and hands it the {@link BundleSdk}: the vendor's
11526
+ * own transports, stream sources and account, each driver, and the discovery modules. Who
11527
+ * builds the SDK is the caller's - `hub` hands the real one, the SDK's tests a fake.
11528
+ *
11529
+ * **It is also the seam the catalogue arrives through.** `verify` and `verifyVendor` are called
11530
+ * before code is imported, and nothing passes them today. When the catalogue stamps a signature on
11531
+ * an approved code bundle, the verifier that checks it is injected there and nothing else changes.
11532
+ *
11533
+ * One broken driver never stops its siblings, and one broken vendor never stops the others. A
11534
+ * failure is collected and reported so the interface can say which directory and why, because
11535
+ * the alternative - refusing to start - means one bad download takes the whole house offline.
11536
+ * The same goes one level down for a vendor's `discovery.json`: discovery is a convenience on top
11537
+ * of adding a device by address, so a broken one is reported and the vendor loads without it.
11538
+ */
11539
+ /** The file every vendor is recognised by. */
11540
+ const MANIFEST_FILE = "manifest.json";
11541
+ /** The file every driver is recognised by. */
11542
+ const DRIVER_FILE = "driver.json";
11543
+ /** The file a discoverable vendor says how its devices are found in. */
11544
+ const DISCOVERY_FILE = "discovery.json";
11545
+ /**
11546
+ * The most a logo may weigh.
11547
+ *
11548
+ * It rides inside every catalogue reply, base64-encoded, so a large one slows every page that
11549
+ * lists vendors. Generous for an SVG mark or a small PNG, and found at startup rather than on
11550
+ * somebody's page.
11551
+ */
11552
+ const LOGO_MAXIMUM_BYTES = 65536;
11553
+ /** The image types a logo may be, by the extension the manifest names. */
11554
+ const LOGO_TYPES = {
11555
+ ".svg": "image/svg+xml",
11556
+ ".png": "image/png"
11557
+ };
11558
+ /** A vendor that asks for nothing at setup. */
11559
+ const NO_SETUP = {
11560
+ transport: {
11561
+ constants: {},
11562
+ fields: []
11563
+ },
11564
+ options: {
11565
+ constants: {},
11566
+ fields: []
11567
+ }
11568
+ };
11569
+ /**
11570
+ * The message of something thrown.
11571
+ *
11572
+ * @param error - What was thrown.
11573
+ * @returns Its message.
11574
+ */
11575
+ function messageOf(error) {
11576
+ return error instanceof Error ? error.message : String(error);
11577
+ }
11578
+ /**
11579
+ * Reads and parses one JSON file of a bundle. A `$schema` at its top - which an editor reads, and
11580
+ * which a bundle's sources carry for one - is not the bundle's and is dropped.
11581
+ *
11582
+ * @param directory - The bundle.
11583
+ * @param file - The file, relative to it.
11584
+ * @returns Whatever the file held.
11585
+ * @throws {Error} When the file cannot be read or is not JSON.
11586
+ */
11587
+ async function readBundleJson(directory, file) {
11588
+ const parsed = JSON.parse(await readFile(path.join(directory, file), "utf8"));
11589
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) && "$schema" in parsed) return Object.fromEntries(Object.entries(parsed).filter(([key]) => key !== "$schema"));
11590
+ return parsed;
11591
+ }
11592
+ /** How many of a schema's complaints a message names. */
11593
+ const ISSUES_NAMED = 4;
11594
+ /**
11595
+ * A file's name as a message says it: `relay/setup.json`, not `./setup.json` or a Windows path.
11596
+ *
11597
+ * @param file - The name, as the bundle writes it.
11598
+ * @returns It, tidied.
11599
+ */
11600
+ function nameOf(file) {
11601
+ return path.normalize(file).split(path.sep).join("/");
11602
+ }
11603
+ /**
11604
+ * Reads one JSON file of a bundle and checks it, saying which file and which field when it does
11605
+ * not hold - a sentence an author can act on, rather than a dump of the schema's findings.
11606
+ *
11607
+ * @param schema - What the file must be.
11608
+ * @param directory - The folder it is in.
11609
+ * @param file - The file, relative to it.
11610
+ * @returns What it holds, checked.
11611
+ * @throws {Error} When it is not there, is not JSON, or does not hold.
11612
+ */
11613
+ async function readBundleFile(schema, directory, file) {
11614
+ let raw;
11615
+ try {
11616
+ raw = await readBundleJson(directory, file);
11617
+ } catch (error) {
11618
+ const code = error?.code;
11619
+ throw new Error(code === "ENOENT" ? `${nameOf(file)} is missing` : `${nameOf(file)} could not be read: ${messageOf(error)}`, { cause: error });
11620
+ }
11621
+ return parseBundleValue(schema, raw, file);
11622
+ }
11623
+ /**
11624
+ * Checks what one file of a bundle holds, saying which file and which field when it does not.
11625
+ *
11626
+ * @param schema - What it must be.
11627
+ * @param value - What it holds.
11628
+ * @param file - The file, for the message.
11629
+ * @returns The value, checked.
11630
+ * @throws {Error} When it does not hold.
11631
+ */
11632
+ function parseBundleValue(schema, value, file) {
11633
+ const parsed = schema.safeParse(value);
11634
+ if (parsed.success) return parsed.data;
11635
+ const { issues } = parsed.error;
11636
+ const named = issues.slice(0, ISSUES_NAMED).map((issue) => issue.path.length === 0 ? issue.message : `${issue.path.map(String).join(".")}: ${issue.message}`);
11637
+ const more = issues.length > ISSUES_NAMED ? `; and ${String(issues.length - ISSUES_NAMED)} more` : "";
11638
+ throw new Error(`${nameOf(file)}: ${named.join("; ")}${more}`, { cause: parsed.error });
11639
+ }
11640
+ /**
11641
+ * Whether a file is there to be read.
11642
+ *
11643
+ * @param file - The file.
11644
+ * @returns True when it is a file.
11645
+ */
11646
+ async function isFile(file) {
11647
+ try {
11648
+ return (await stat(file)).isFile();
11649
+ } catch {
11650
+ return false;
11651
+ }
11652
+ }
11653
+ /**
11654
+ * The subdirectories of one directory.
11655
+ *
11656
+ * @param directory - Where to look.
11657
+ * @returns Their names, or none when the directory does not exist.
11658
+ */
11659
+ async function subdirectories(directory) {
11660
+ try {
11661
+ return (await readdir(directory, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
11662
+ } catch {
11663
+ return [];
11664
+ }
11665
+ }
11666
+ /**
11667
+ * Finds a module where the bundle says it is, as an installed or built bundle holds it.
11668
+ *
11669
+ * @param directory - The folder the name is relative to.
11670
+ * @param file - The name.
11671
+ * @returns Its path, or null when it is not there.
11672
+ */
11673
+ const fileAsNamed = async (directory, file) => {
11674
+ const found = path.join(directory, file);
11675
+ return await isFile(found) ? found : null;
11676
+ };
11677
+ /**
11678
+ * Reads a vendor's logo as a data URL.
11679
+ *
11680
+ * @param directory - The vendor.
11681
+ * @param file - The logo, relative to it, as the manifest names it.
11682
+ * @returns The data URL.
11683
+ * @throws {Error} When the file is not an SVG or a PNG, is too large, or cannot be read.
11684
+ */
11685
+ async function readLogo(directory, file) {
11686
+ const type = LOGO_TYPES[path.extname(file).toLowerCase()];
11687
+ if (type === void 0) throw new Error(`The logo ${file} must be an .svg or a .png`);
11688
+ const bytes = await readFile(path.join(directory, file));
11689
+ if (bytes.byteLength > 65536) throw new Error(`The logo ${file} is ${String(bytes.byteLength)} bytes, and the most a logo may be is ${String(LOGO_MAXIMUM_BYTES)}`);
11690
+ return `data:${type};base64,${bytes.toString("base64")}`;
11691
+ }
11692
+ /**
11693
+ * Finds a module the bundle names, or says it is not there.
11694
+ *
11695
+ * @param resolve - How modules are found.
11696
+ * @param directory - The folder the name is relative to.
11697
+ * @param file - The name.
11698
+ * @param what - What names it, for the message.
11699
+ * @returns The module's path.
11700
+ * @throws {Error} When it is not there.
11701
+ */
11702
+ async function moduleOf(resolve, directory, file, what) {
11703
+ const found = await resolve(directory, file);
11704
+ if (found === null) throw new Error(`${what} names ${file}, which is not in the bundle`);
11705
+ return found;
11706
+ }
11707
+ /**
11708
+ * The wires a vendor's devices are reached over: each platform transport a driver speaks that is
11709
+ * a wire itself - `http`, `mqtt` - and what each of the vendor's own transports a driver speaks
11710
+ * declares it goes over, since `shelly/rpc` says nothing to a person and HTTP does.
11711
+ *
11712
+ * @param vendor - The vendor's manifest.
11713
+ * @param transports - The transport of every driver.
11714
+ * @returns The wires, each once, in {@link TRANSPORT_WIRES}' order.
11715
+ */
11716
+ function wiresOf(vendor, transports) {
11717
+ const found = /* @__PURE__ */ new Set();
11718
+ for (const transport of transports) {
11719
+ const own = transport.startsWith(`${vendor.id}/`) ? vendor.transports[transport.slice(vendor.id.length + 1)] : void 0;
11720
+ if (own === void 0) found.add(transport);
11721
+ else for (const wire of transportWiresOf(own)) found.add(wire);
11722
+ }
11723
+ return TRANSPORT_WIRES.filter((wire) => found.has(wire));
11724
+ }
11725
+ /**
11726
+ * Reads one driver directory.
11727
+ *
11728
+ * @param vendor - The vendor it belongs to, already checked.
11729
+ * @param directory - The driver.
11730
+ * @param resolve - How modules are found.
11731
+ * @returns What its files say.
11732
+ * @throws {Error} When the driver is malformed or cannot be read.
9253
11733
  */
9254
11734
  async function readDriver(vendor, directory, resolve) {
9255
11735
  const driver = await readBundleFile(driverManifestSchema, directory, DRIVER_FILE);
@@ -9273,7 +11753,14 @@ async function readDriver(vendor, directory, resolve) {
9273
11753
  profile
9274
11754
  };
9275
11755
  }
9276
- if (manifest.kind === "matter") return identity;
11756
+ if (manifest.kind === "matter" || manifest.kind === "mqtt") return identity;
11757
+ if (manifest.kind === "modbus") {
11758
+ const template = await readBundleFile(modbusTemplateSchema, directory, manifest.template ?? "");
11759
+ return {
11760
+ ...identity,
11761
+ modbusTemplate: withModbusEntityIds(template)
11762
+ };
11763
+ }
9277
11764
  return {
9278
11765
  ...identity,
9279
11766
  entry: await moduleOf(resolve, directory, manifest.entry ?? "", manifest.id)
@@ -9461,6 +11948,14 @@ async function instantiateDriver(driver, sdk, options) {
9461
11948
  ...identity,
9462
11949
  integration: createMatterIntegration(driver.manifest)
9463
11950
  };
11951
+ if (driver.manifest.kind === "mqtt") return {
11952
+ ...identity,
11953
+ integration: createMqttIntegration(driver.manifest)
11954
+ };
11955
+ if (driver.manifest.kind === "modbus") return {
11956
+ ...identity,
11957
+ integration: createModbusIntegration(driver.manifest)
11958
+ };
9464
11959
  const exported = await defaultOf(options.importModule ?? importFile, entry ?? "");
9465
11960
  const integration = typeof exported === "function" ? exported(sdk) : exported;
9466
11961
  if (integration === null || typeof integration !== "object") throw new Error(`${driver.manifest.id} does not default-export an integration`);
@@ -9605,4 +12100,4 @@ async function instantiateVendor(declaration, options) {
9605
12100
  };
9606
12101
  }
9607
12102
  //#endregion
9608
- export { associateModel as a, matchesMatter as c, accountDeclarationSchema as d, defineAccount as f, composeEntityId as g, integrationSetupSchema as h, associateMatter as i, vendorDiscoverySchema as l, vendorManifestSchema as m, readVendorDirectory as n, identifySighting as o, driverManifestSchema as p, require_semver as r, matchesAnnouncement as s, instantiateVendor as t, integrationProfileSchema as u };
12103
+ export { composeEntityId as _, associateModel as a, matchesBroker as c, accountDeclarationSchema as d, defineAccount as f, integrationSetupSchema as g, modbusTemplateSchema as h, associateBroker as i, vendorDiscoverySchema as l, vendorManifestSchema as m, readVendorDirectory as n, identifySighting as o, driverManifestSchema as p, require_semver as r, matchesAnnouncement as s, instantiateVendor as t, integrationProfileSchema as u };