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