homebridge-shelly-energy-meter 0.9.0-beta.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/.gitattributes ADDED
@@ -0,0 +1,2 @@
1
+ # Auto detect text files and perform LF normalization
2
+ * text=auto
package/LICENSE ADDED
@@ -0,0 +1,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
package/README.md ADDED
@@ -0,0 +1,9 @@
1
+ <p align="center">
2
+
3
+ <img src="https://github.com/homebridge/branding/raw/latest/logos/homebridge-wordmark-logo-vertical.png" width="150">
4
+
5
+ </p>
6
+
7
+ <span align="center">
8
+
9
+ # BETA
@@ -0,0 +1,62 @@
1
+ {
2
+ "pluginAlias": "ShellyMEnergyMeterHomebridgePlugin",
3
+ "pluginType": "platform",
4
+ "singular": true,
5
+ "strictValidation": false,
6
+ "schema": {
7
+ "type": "object",
8
+ "required": ["name", "devices"],
9
+ "additionalProperties": false,
10
+ "properties": {
11
+ "name": {
12
+ "title": "Name",
13
+ "type": "string",
14
+ "default": "Shelly Energy Meter"
15
+ },
16
+ "devices": {
17
+ "title": "Devices",
18
+ "type": "array",
19
+ "items": {
20
+ "type": "object",
21
+ "required": ["name", "ip"],
22
+ "properties": {
23
+ "name": {
24
+ "title": "Device Name",
25
+ "type": "string"
26
+ },
27
+ "ip": {
28
+ "title": "Device IP Address",
29
+ "type": "string"
30
+ },
31
+ "auth": {
32
+ "title": "Authentication",
33
+ "type": "object",
34
+ "properties": {
35
+ "pw": {
36
+ "title": "Password",
37
+ "type": "string"
38
+ }
39
+ },
40
+ "additionalProperties": false
41
+ },
42
+ "update_interval": {
43
+ "title": "Polling Interval (ms)",
44
+ "type": "integer",
45
+ "default": 10000,
46
+ "minimum": 1000
47
+ },
48
+ "timeout": {
49
+ "title": "Request Timeout (ms)",
50
+ "description": "Maximum time to wait for a device response. Must be lower than the polling interval.",
51
+ "type": "integer",
52
+ "default": 5000,
53
+ "minimum": 1000
54
+ }
55
+ },
56
+ "additionalProperties": false
57
+ },
58
+ "minItems": 1
59
+ }
60
+ }
61
+ }
62
+ }
@@ -0,0 +1,6 @@
1
+ import type { API } from 'homebridge';
2
+ /**
3
+ * This method registers the platform with Homebridge
4
+ */
5
+ declare const _default: (api: API) => void;
6
+ export default _default;
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ import { ShellyEnergyMeterPlatform } from './platform.js';
2
+ import { PLATFORM_NAME } from './settings.js';
3
+ /**
4
+ * This method registers the platform with Homebridge
5
+ */
6
+ export default (api) => {
7
+ api.registerPlatform(PLATFORM_NAME, ShellyEnergyMeterPlatform);
8
+ };
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,yBAAyB,EAAE,MAAM,eAAe,CAAC;AAC1D,OAAO,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAE9C;;GAEG;AACH,eAAe,CAAC,GAAQ,EAAE,EAAE;IAC1B,GAAG,CAAC,gBAAgB,CAAC,aAAa,EAAE,yBAAyB,CAAC,CAAC;AACjE,CAAC,CAAC"}
@@ -0,0 +1,30 @@
1
+ import type { API, Characteristic, DynamicPlatformPlugin, Logging, PlatformAccessory, PlatformConfig, Service } from 'homebridge';
2
+ /**
3
+ * HomebridgePlatform
4
+ * This class is the main constructor for your plugin, this is where you should
5
+ * parse the user config and discover/register accessories with Homebridge.
6
+ */
7
+ export declare class ShellyEnergyMeterPlatform implements DynamicPlatformPlugin {
8
+ readonly log: Logging;
9
+ readonly config: PlatformConfig;
10
+ readonly api: API;
11
+ readonly Service: typeof Service;
12
+ readonly Characteristic: typeof Characteristic;
13
+ readonly accessories: Map<string, PlatformAccessory>;
14
+ readonly discoveredCacheUUIDs: string[];
15
+ readonly FakeGatoHistoryService: new (type: import("fakegato-history").FakeGatoServiceType, accessory: PlatformAccessory, options?: import("fakegato-history").FakeGatoOptions) => import("fakegato-history").FakeGatoHistoryService;
16
+ private accessoryHandlers;
17
+ constructor(log: Logging, config: PlatformConfig, api: API);
18
+ /**
19
+ * This function is invoked when homebridge restores cached accessories from disk at startup.
20
+ * It should be used to set up event handlers for characteristics and update respective values.
21
+ */
22
+ configureAccessory(accessory: PlatformAccessory): void;
23
+ /**
24
+ * Discover and configure devices from config
25
+ */
26
+ discoverDevices(): Promise<void>;
27
+ private restoreAccessory;
28
+ private addAccessory;
29
+ private removeStaleAccessories;
30
+ }
@@ -0,0 +1,151 @@
1
+ import { ShellyEnergyMeterPlatformAccessory } from './platformAccessory.js';
2
+ import { PLATFORM_NAME, PLUGIN_NAME } from './settings.js';
3
+ import { getSysConfig } from './shellyAPI.js';
4
+ import fakegato from 'fakegato-history';
5
+ /**
6
+ * HomebridgePlatform
7
+ * This class is the main constructor for your plugin, this is where you should
8
+ * parse the user config and discover/register accessories with Homebridge.
9
+ */
10
+ export class ShellyEnergyMeterPlatform {
11
+ log;
12
+ config;
13
+ api;
14
+ Service;
15
+ Characteristic;
16
+ // This is used to track restored cached accessories
17
+ accessories = new Map();
18
+ discoveredCacheUUIDs = [];
19
+ FakeGatoHistoryService;
20
+ // Track accessory handlers to stop polling on shutdown/removal
21
+ accessoryHandlers = new Map();
22
+ constructor(log, config, api) {
23
+ this.log = log;
24
+ this.config = config;
25
+ this.api = api;
26
+ this.Service = api.hap.Service;
27
+ this.Characteristic = api.hap.Characteristic;
28
+ this.FakeGatoHistoryService = fakegato(this.api);
29
+ this.log.debug('Finished initializing platform:', this.config.name);
30
+ // When this event is fired it means Homebridge has restored all cached accessories from disk.
31
+ // Dynamic Platform plugins should only register new accessories after this event was fired,
32
+ // in order to ensure they weren't added to homebridge already. This event can also be used
33
+ // to start discovery of new accessories.
34
+ this.api.on('didFinishLaunching', () => {
35
+ log.debug('Executed didFinishLaunching callback');
36
+ // run the method to discover / register your devices as accessories
37
+ this.discoverDevices();
38
+ });
39
+ // Stop polling for all accessories on shutdown
40
+ this.api.on('shutdown', () => {
41
+ this.log.info('Homebridge shutdown: stopping all accessory polling');
42
+ for (const handler of this.accessoryHandlers.values()) {
43
+ handler.stopPolling?.();
44
+ }
45
+ });
46
+ }
47
+ /**
48
+ * This function is invoked when homebridge restores cached accessories from disk at startup.
49
+ * It should be used to set up event handlers for characteristics and update respective values.
50
+ */
51
+ configureAccessory(accessory) {
52
+ this.log.info('Loading accessory from cache:', accessory.displayName);
53
+ // Add the restored accessory to the accessories cache, so we can track if it has already been registered
54
+ this.accessories.set(accessory.UUID, accessory);
55
+ }
56
+ /**
57
+ * Discover and configure devices from config
58
+ */
59
+ async discoverDevices() {
60
+ const devices = this.config.devices ?? [];
61
+ if (devices.length === 0) {
62
+ this.log.warn('No devices configured. Please add at least one device in the plugin settings.');
63
+ return;
64
+ }
65
+ for (const device of devices) {
66
+ // Validate required parameters
67
+ if (!device.name || typeof device.name !== 'string') {
68
+ this.log.error('Device configuration missing required "name" parameter. Skipping device.');
69
+ continue;
70
+ }
71
+ if (!device.ip || typeof device.ip !== 'string') {
72
+ this.log.error(`Device "${device.name}" is missing required "ip" parameter. Skipping device.`);
73
+ continue;
74
+ }
75
+ if (!device.update_interval || !device.timeout || device.update_interval <= device.timeout) {
76
+ this.log.error(`[${device.name}] update_interval should be greater than timeout.`);
77
+ continue;
78
+ }
79
+ // Validate device connection and authentication
80
+ let profile;
81
+ let macAddress;
82
+ try {
83
+ const sysConfig = await getSysConfig(device, this.log);
84
+ profile = sysConfig.device.profile;
85
+ macAddress = sysConfig.device.mac;
86
+ this.log.debug(`Device "${device.name}" (${device.ip}) profile: ${profile || 'not set'}`);
87
+ }
88
+ catch (err) {
89
+ const errorMessage = err instanceof Error ? err.message : String(err);
90
+ if (errorMessage.includes('status: 401')) {
91
+ this.log.error(`Device "${device.name}" (${device.ip}) requires authentication. Please add password in config. Skipping device.`);
92
+ continue;
93
+ }
94
+ // Log other errors but don't skip the device - it might be temporarily unreachable
95
+ this.log.warn(`Device "${device.name}" (${device.ip}) validation warning: ${errorMessage}. Will retry during polling.`);
96
+ }
97
+ const uuid = this.api.hap.uuid.generate(macAddress);
98
+ const existingAccessory = this.accessories.get(uuid);
99
+ if (existingAccessory) {
100
+ this.restoreAccessory(existingAccessory, device, profile, macAddress);
101
+ }
102
+ else {
103
+ this.addAccessory(uuid, device, profile, macAddress);
104
+ }
105
+ this.discoveredCacheUUIDs.push(uuid);
106
+ }
107
+ this.removeStaleAccessories();
108
+ }
109
+ restoreAccessory(accessory, device, profile, macAddress) {
110
+ this.log.info('Restoring existing accessory from cache:', accessory.displayName);
111
+ accessory.context.device = device;
112
+ if (profile) {
113
+ accessory.context.profile = profile;
114
+ }
115
+ if (macAddress) {
116
+ accessory.context.macAddress = macAddress;
117
+ }
118
+ this.api.updatePlatformAccessories([accessory]);
119
+ const handler = new ShellyEnergyMeterPlatformAccessory(this, accessory);
120
+ this.accessoryHandlers.set(accessory.UUID, handler);
121
+ }
122
+ addAccessory(uuid, device, profile, macAddress) {
123
+ this.log.info('Adding new accessory:', device.name);
124
+ const accessory = new this.api.platformAccessory(device.name, uuid);
125
+ accessory.context.device = device;
126
+ if (profile) {
127
+ accessory.context.profile = profile;
128
+ }
129
+ if (macAddress) {
130
+ accessory.context.macAddress = macAddress;
131
+ }
132
+ const handler = new ShellyEnergyMeterPlatformAccessory(this, accessory);
133
+ this.accessories.set(uuid, accessory);
134
+ this.accessoryHandlers.set(uuid, handler);
135
+ this.api.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [accessory]);
136
+ }
137
+ removeStaleAccessories() {
138
+ for (const [uuid, accessory] of this.accessories) {
139
+ if (!this.discoveredCacheUUIDs.includes(uuid)) {
140
+ this.log.info('Removing existing accessory from cache:', accessory.displayName);
141
+ // Stop polling for this accessory before removal
142
+ const handler = this.accessoryHandlers.get(uuid);
143
+ handler?.stopPolling?.();
144
+ this.accessoryHandlers.delete(uuid);
145
+ this.accessories.delete(uuid);
146
+ this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [accessory]);
147
+ }
148
+ }
149
+ }
150
+ }
151
+ //# sourceMappingURL=platform.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"platform.js","sourceRoot":"","sources":["../src/platform.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kCAAkC,EAAE,MAAM,wBAAwB,CAAC;AAC5E,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAE3D,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,QAAQ,MAAM,kBAAkB,CAAC;AAExC;;;;GAIG;AACH,MAAM,OAAO,yBAAyB;IAclB;IACA;IACA;IAfF,OAAO,CAAiB;IACxB,cAAc,CAAwB;IAEtD,oDAAoD;IACpC,WAAW,GAAmC,IAAI,GAAG,EAAE,CAAC;IACxD,oB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5C,CAAC;QACD,MAAM,OAAO,GAAG,IAAI,kCAAkC,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;QACxE,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;QACtC,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QAC1C,IAAI,CAAC,GAAG,CAAC,2BAA2B,CAAC,WAAW,EAAE,aAAa,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC;IAChF,CAAC;IAEO,sBAAsB;QAC5B,KAAK,MAAM,CAAC,IAAI,EAAE,SAAS,CAAC,IAAI,IAAI,CAAC,WAAW,EAAE,CAAC;YACjD,IAAI,CAAC,IAAI,CAAC,oBAAoB,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;gBAC9C,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,yCAAyC,EAAE,SAAS,CAAC,WAAW,CAAC,CAAC;gBAChF,iDAAiD;gBACjD,MAAM,OAAO,GAAG,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;gBACjD,OAAO,EAAE,WAAW,EAAE,EAAE,CAAC;gBACzB,IAAI,CAAC,iBAAiB,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;gBACpC,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;gBAC9B,IAAI,CAAC,GAAG,CAAC,6BAA6B,CAAC,WAAW,EAAE,aAAa,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC;YAClF,CAAC;QACH,CAAC;IACH,CAAC;CACF"}
@@ -0,0 +1,33 @@
1
+ import type { PlatformAccessory } from 'homebridge';
2
+ import type { ShellyEnergyMeterPlatform } from './platform.js';
3
+ export declare class ShellyEnergyMeterPlatformAccessory {
4
+ private readonly platform;
5
+ private readonly accessory;
6
+ private consumptionService;
7
+ private returnService;
8
+ private energyHistoryService;
9
+ private returnEnergyHistoryService;
10
+ private macAddress;
11
+ private deviceConfig;
12
+ private total_act_power;
13
+ private total_act_energy;
14
+ private total_act_return_energy;
15
+ private total_current;
16
+ private EvePowerConsumption;
17
+ private EveTotalConsumption;
18
+ private EveAmpere;
19
+ private PowerMeterService;
20
+ private pollingEMStatusInterval?;
21
+ private pollingEMDataStatusInterval?;
22
+ private isPollingEMStatus;
23
+ private isPollingEMDataStatus;
24
+ constructor(platform: ShellyEnergyMeterPlatform, accessory: PlatformAccessory);
25
+ private registerEveCharacteristics;
26
+ private createEveCharacteristics;
27
+ private setupAccessoryInfo;
28
+ private setupService;
29
+ private startPolling;
30
+ stopPolling(): void;
31
+ private updateEMStatusFromDevice;
32
+ private updateEMDataStatusFromDevice;
33
+ }
@@ -0,0 +1,226 @@
1
+ import { getEMStatus, getEMDataStatus } from './shellyAPI.js';
2
+ const POWER_METER_SERVICE_UUID = '00000001-0000-1777-8000-775D67EC4377';
3
+ export class ShellyEnergyMeterPlatformAccessory {
4
+ platform;
5
+ accessory;
6
+ consumptionService;
7
+ returnService;
8
+ energyHistoryService;
9
+ returnEnergyHistoryService;
10
+ macAddress;
11
+ deviceConfig;
12
+ total_act_power = 0;
13
+ total_act_energy = 0;
14
+ total_act_return_energy = 0;
15
+ total_current = 0;
16
+ EvePowerConsumption;
17
+ EveTotalConsumption;
18
+ EveAmpere;
19
+ PowerMeterService;
20
+ pollingEMStatusInterval;
21
+ pollingEMDataStatusInterval;
22
+ isPollingEMStatus = false;
23
+ isPollingEMDataStatus = false;
24
+ constructor(platform, accessory) {
25
+ this.platform = platform;
26
+ this.accessory = accessory;
27
+ this.deviceConfig = this.accessory.context.device;
28
+ this.macAddress = this.accessory.context.macAddress;
29
+ this.registerEveCharacteristics();
30
+ this.setupAccessoryInfo();
31
+ this.setupService();
32
+ this.startPolling();
33
+ }
34
+ registerEveCharacteristics() {
35
+ const { EvePowerConsumption, EveTotalConsumption, EveAmpere, PowerMeterService } = this.createEveCharacteristics(this.platform.api);
36
+ this.EvePowerConsumption = EvePowerConsumption;
37
+ this.EveTotalConsumption = EveTotalConsumption;
38
+ this.EveAmpere = EveAmpere;
39
+ this.PowerMeterService = PowerMeterService;
40
+ }
41
+ createEveCharacteristics(api) {
42
+ const { Characteristic, Service, Perms } = api.hap;
43
+ class EvePowerConsumption extends Characteristic {
44
+ static UUID = 'E863F10D-079E-48FF-8F27-9C2605A29F52';
45
+ constructor() {
46
+ super('Consumption', EvePowerConsumption.UUID, {
47
+ format: 'uint16',
48
+ unit: 'W',
49
+ maxValue: 1000000000,
50
+ minValue: 0,
51
+ minStep: 0.001,
52
+ perms: ["pr" /* Perms.PAIRED_READ */, "ev" /* Perms.NOTIFY */],
53
+ });
54
+ }
55
+ }
56
+ class EveTotalConsumption extends Characteristic {
57
+ static UUID = 'E863F10C-079E-48FF-8F27-9C2605A29F52';
58
+ constructor() {
59
+ super('Energy', EveTotalConsumption.UUID, {
60
+ format: 'uint16',
61
+ unit: 'kWh',
62
+ maxValue: 1000000000,
63
+ minValue: 0,
64
+ minStep: 0.001,
65
+ perms: ["pr" /* Perms.PAIRED_READ */, "ev" /* Perms.NOTIFY */],
66
+ });
67
+ }
68
+ }
69
+ class EveAmpere extends Characteristic {
70
+ static UUID = 'E863F126-079E-48FF-8F27-9C2605A29F52';
71
+ constructor() {
72
+ super('Ampere', EveAmpere.UUID, {
73
+ format: 'float',
74
+ unit: 'A',
75
+ maxValue: 1000000000,
76
+ minValue: 0,
77
+ minStep: 0.001,
78
+ perms: ["pr" /* Perms.PAIRED_READ */, "ev" /* Perms.NOTIFY */],
79
+ });
80
+ }
81
+ }
82
+ class PowerMeterService extends Service {
83
+ constructor(name) {
84
+ super(name, POWER_METER_SERVICE_UUID);
85
+ this.addOptionalCharacteristic(EvePowerConsumption);
86
+ this.addOptionalCharacteristic(EveTotalConsumption);
87
+ this.addOptionalCharacteristic(EveAmpere);
88
+ }
89
+ }
90
+ return { EvePowerConsumption, EveTotalConsumption, EveAmpere, PowerMeterService };
91
+ }
92
+ setupAccessoryInfo() {
93
+ const info = this.accessory.getService(this.platform.api.hap.Service.AccessoryInformation);
94
+ info
95
+ .setCharacteristic(this.platform.api.hap.Characteristic.Manufacturer, 'Shelly')
96
+ .setCharacteristic(this.platform.api.hap.Characteristic.Model, '3EM')
97
+ .setCharacteristic(this.platform.api.hap.Characteristic.SerialNumber, this.macAddress);
98
+ }
99
+ setupService() {
100
+ // Use device MAC address as unique subtype to prevent UUID collisions with multiple accessories
101
+ const consumptionSubtype = `${this.macAddress}-consumption`;
102
+ const returnSubtype = `${this.macAddress}-return`;
103
+ // Setup consumption power service
104
+ let existingConsumptionService = this.accessory.services.find(service => service.UUID === POWER_METER_SERVICE_UUID && service.subtype === consumptionSubtype);
105
+ if (!existingConsumptionService) {
106
+ const service = new this.PowerMeterService(`${this.deviceConfig.name} Consumption`, POWER_METER_SERVICE_UUID);
107
+ service.subtype = consumptionSubtype;
108
+ existingConsumptionService = this.accessory.addService(service);
109
+ }
110
+ this.consumptionService = existingConsumptionService;
111
+ this.consumptionService.getCharacteristic(this.EvePowerConsumption).onGet(() => this.total_act_power);
112
+ this.consumptionService.getCharacteristic(this.EveTotalConsumption).onGet(() => this.total_act_energy);
113
+ this.consumptionService.getCharacteristic(this.EveAmpere).onGet(() => this.total_current);
114
+ this.energyHistoryService = new this.platform.FakeGatoHistoryService('energy', this.accessory, {
115
+ log: this.platform.log,
116
+ storage: 'fs',
117
+ });
118
+ // Setup return power service
119
+ let existingReturnService = this.accessory.services.find(service => service.UUID === POWER_METER_SERVICE_UUID && service.subtype === returnSubtype);
120
+ if (!existingReturnService) {
121
+ const service = new this.PowerMeterService(`${this.deviceConfig.name} Return`, POWER_METER_SERVICE_UUID);
122
+ service.subtype = returnSubtype;
123
+ existingReturnService = this.accessory.addService(service);
124
+ }
125
+ this.returnService = existingReturnService;
126
+ this.returnService.getCharacteristic(this.EveTotalConsumption).onGet(() => this.total_act_return_energy);
127
+ this.returnEnergyHistoryService = new this.platform.FakeGatoHistoryService('energy', this.accessory, {
128
+ log: this.platform.log,
129
+ storage: 'fs',
130
+ });
131
+ }
132
+ startPolling() {
133
+ void this.updateEMStatusFromDevice();
134
+ void this.updateEMDataStatusFromDevice();
135
+ this.pollingEMStatusInterval = setInterval(() => void this.updateEMStatusFromDevice(), this.deviceConfig.update_interval ?? 10000);
136
+ this.pollingEMDataStatusInterval = setInterval(() => void this.updateEMDataStatusFromDevice(), this.deviceConfig.update_interval ?? 10000);
137
+ }
138
+ stopPolling() {
139
+ if (this.pollingEMStatusInterval) {
140
+ clearInterval(this.pollingEMStatusInterval);
141
+ this.pollingEMStatusInterval = undefined;
142
+ this.platform.log.debug(`[${this.deviceConfig.name}] EMStatus polling stopped.`);
143
+ }
144
+ if (this.pollingEMDataStatusInterval) {
145
+ clearInterval(this.pollingEMDataStatusInterval);
146
+ this.pollingEMDataStatusInterval = undefined;
147
+ this.platform.log.debug(`[${this.deviceConfig.name}] EMDataStatus polling stopped.`);
148
+ }
149
+ }
150
+ async updateEMStatusFromDevice() {
151
+ if (this.isPollingEMStatus) {
152
+ return;
153
+ }
154
+ this.isPollingEMStatus = true;
155
+ try {
156
+ const data = await getEMStatus(this.deviceConfig, this.platform.log);
157
+ const phaseAPower = data.a_act_power ?? 0;
158
+ const phaseBPower = data.b_act_power ?? 0;
159
+ const phaseCPower = data.c_act_power ?? 0;
160
+ this.total_act_power = Math.max(0, phaseAPower) + Math.max(0, phaseBPower) + Math.max(0, phaseCPower);
161
+ const phaseACurrent = data.a_current ?? 0;
162
+ const phaseBCurrent = data.b_current ?? 0;
163
+ const phaseCCurrent = data.c_current ?? 0;
164
+ this.total_current = Math.max(0, phaseACurrent) + Math.max(0, phaseBCurrent) + Math.max(0, phaseCCurrent);
165
+ // Update service
166
+ this.consumptionService.getCharacteristic(this.EvePowerConsumption).updateValue(this.total_act_power);
167
+ this.consumptionService.getCharacteristic(this.EveAmpere).updateValue(this.total_current);
168
+ }
169
+ catch (err) {
170
+ let message = err instanceof Error ? err.message : String(err);
171
+ if (err instanceof Error && err.name === 'AbortError') {
172
+ message = 'Request timeout';
173
+ }
174
+ this.platform.log.error(`[${this.deviceConfig.name}] Request failed:`, message);
175
+ // write zero on error
176
+ this.total_act_power = 0;
177
+ this.total_current = 0;
178
+ this.consumptionService.getCharacteristic(this.EvePowerConsumption).updateValue(0);
179
+ this.consumptionService.getCharacteristic(this.EveAmpere).updateValue(0);
180
+ }
181
+ finally {
182
+ this.isPollingEMStatus = false;
183
+ }
184
+ }
185
+ async updateEMDataStatusFromDevice() {
186
+ if (this.isPollingEMDataStatus) {
187
+ return;
188
+ }
189
+ this.isPollingEMDataStatus = true;
190
+ try {
191
+ const data = await getEMDataStatus(this.deviceConfig, this.platform.log);
192
+ const phaseAConsumption = data.a_total_act_energy ?? 0;
193
+ const phaseBConsumption = data.b_total_act_energy ?? 0;
194
+ const phaseCConsumption = data.c_total_act_energy ?? 0;
195
+ // Sum and convert Wh to kWh
196
+ this.total_act_energy = (Math.max(0, phaseAConsumption) + Math.max(0, phaseBConsumption) + Math.max(0, phaseCConsumption)) / 1000;
197
+ const phaseAReturn = data.a_total_act_ret_energy ?? 0;
198
+ const phaseBReturn = data.b_total_act_ret_energy ?? 0;
199
+ const phaseCReturn = data.c_total_act_ret_energy ?? 0;
200
+ // Sum and convert Wh to kWh
201
+ this.total_act_return_energy = (Math.max(0, phaseAReturn) + Math.max(0, phaseBReturn) + Math.max(0, phaseCReturn)) / 1000;
202
+ this.consumptionService.getCharacteristic(this.EveTotalConsumption).updateValue(this.total_act_energy);
203
+ this.returnService.getCharacteristic(this.EveTotalConsumption).updateValue(this.total_act_return_energy);
204
+ this.energyHistoryService.addEntry({ time: Math.floor(Date.now() / 1000), totalEnergy: this.total_act_energy });
205
+ this.returnEnergyHistoryService.addEntry({ time: Math.floor(Date.now() / 1000), totalEnergy: this.total_act_return_energy });
206
+ }
207
+ catch (err) {
208
+ let message = err instanceof Error ? err.message : String(err);
209
+ if (err instanceof Error && err.name === 'AbortError') {
210
+ message = 'Request timeout';
211
+ }
212
+ this.platform.log.error(`[${this.deviceConfig.name}] Request failed:`, message);
213
+ // write zero on error
214
+ this.total_act_energy = 0;
215
+ this.total_act_return_energy = 0;
216
+ this.consumptionService.getCharacteristic(this.EveTotalConsumption).updateValue(0);
217
+ this.returnService.getCharacteristic(this.EveTotalConsumption).updateValue(0);
218
+ this.energyHistoryService.addEntry({ time: Math.floor(Date.now() / 1000), totalEnergy: 0 });
219
+ this.returnEnergyHistoryService.addEntry({ time: Math.floor(Date.now() / 1000), totalEnergy: 0 });
220
+ }
221
+ finally {
222
+ this.isPollingEMDataStatus = false;
223
+ }
224
+ }
225
+ }
226
+ //# sourceMappingURL=platformAccessory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"platformAccessory.js","sourceRoot":"","sources":["../src/platformAccessory.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAI9D,MAAM,wBAAwB,GAAG,sCAAsC,CAAC;AAMxE,MAAM,OAAO,kCAAkC;IA0B1B;IACA;IA1BX,kBAAkB,CAAW;IAC7B,aAAa,CAAW;IACxB,oBAAoB,CAA0B;IAC9C,0BAA0B,CAA0B;IACpD,UAAU,CAAS;IAEnB,YAAY,CAAe;IAE3B,eAAe,GAAG,CAAC,CAAC;IACpB,gBAAgB,GAAG,CAAC,CAAC;IACrB,uBAAuB,GAAG,CAAC,CAAC;IAC5B,aAAa,GAAG,CAAC,CAAC;IAElB,mBAAmB,CAA0B;IAC7C,mBAAmB,CAA0B;IAC7C,SAAS,CAA0B;IACnC,iBAAiB,CAA0B;IAE3C,uBAAuB,CAAkB;IACzC,2BAA2B,CAAkB;IAE7C,iBAAiB,GAAG,KAAK,CAAC;IAC1B,qBAAqB,GAAG,KAAK,CAAC;IAEtC,YACmB,QAAmC,EACnC,SAA4B;QAD5B,aAAQ,GAAR,QAAQ,CAA2B;QACnC,cAAS,GAAT,SAAS,CAAmB;QAE7C,IAA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,IAAI,GAAG,YAAY,KAAK,IAAI,GAAG,CAAC,IAAI,KAAK,YAAY,EAAE,CAAC;gBACtD,OAAO,GAAG,iBAAiB,CAAC;YAC9B,CAAC;YACD,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,IAAI,CAAC,YAAY,CAAC,IAAI,mBAAmB,EAAE,OAAO,CAAC,CAAC;YAChF,sBAAsB;YACtB,IAAI,CAAC,gBAAgB,GAAG,CAAC,CAAC;YAC1B,IAAI,CAAC,uBAAuB,GAAG,CAAC,CAAC;YACjC,IAAI,CAAC,kBAAkB,CAAC,iBAAiB,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;YACnF,IAAI,CAAC,aAAa,CAAC,iBAAiB,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;YAC9E,IAAI,CAAC,oBAAoB,CAAC,QAAQ,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,CAAC,CAAC;YAC5F,IAAI,CAAC,0BAA0B,CAAC,QAAQ,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,CAAC,CAAC;QACpG,CAAC;gBAAS,CAAC;YACT,IAAI,CAAC,qBAAqB,GAAG,KAAK,CAAC;QACrC,CAAC;IACH,CAAC;CACF"}
@@ -0,0 +1,8 @@
1
+ /**
2
+ * This is the name of the platform that users will use to register the plugin in the Homebridge config.json
3
+ */
4
+ export declare const PLATFORM_NAME = "ShellyMEnergyMeterHomebridgePlugin";
5
+ /**
6
+ * This must match the name of your plugin as defined the package.json `name` property
7
+ */
8
+ export declare const PLUGIN_NAME = "homebridge-shelly-energy-meter";
@@ -0,0 +1,9 @@
1
+ /**
2
+ * This is the name of the platform that users will use to register the plugin in the Homebridge config.json
3
+ */
4
+ export const PLATFORM_NAME = 'ShellyMEnergyMeterHomebridgePlugin';
5
+ /**
6
+ * This must match the name of your plugin as defined the package.json `name` property
7
+ */
8
+ export const PLUGIN_NAME = 'homebridge-shelly-energy-meter';
9
+ //# sourceMappingURL=settings.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"settings.js","sourceRoot":"","sources":["../src/settings.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,oCAAoC,CAAC;AAElE;;GAEG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,gCAAgC,CAAC"}
@@ -0,0 +1,23 @@
1
+ import type { ShellySysConfig, DeviceConfig, ShellyEMStatus, ShellyEMDataStatus } from './shellyTypes.js';
2
+ type Logger = {
3
+ debug: (message: string, ...parameters: unknown[]) => void;
4
+ };
5
+ /**
6
+ * Fetches the Sys.GetConfig data for a given device.
7
+ * @param deviceConfig - The device configuration.
8
+ * @param log - Optional logger for debug output.
9
+ */
10
+ export declare function getSysConfig(deviceConfig: DeviceConfig, log?: Logger): Promise<ShellySysConfig>;
11
+ /**
12
+ * Fetches the EM.GetStatus data for a given device.
13
+ * @param deviceConfig - The device configuration.
14
+ * @param log - Optional logger for debug output.
15
+ */
16
+ export declare function getEMStatus(deviceConfig: DeviceConfig, log?: Logger): Promise<ShellyEMStatus>;
17
+ /**
18
+ * Fetches the EMData.GetStatus data for a given device.
19
+ * @param deviceConfig - The device configuration.
20
+ * @param log - Optional logger for debug output.
21
+ */
22
+ export declare function getEMDataStatus(deviceConfig: DeviceConfig, log?: Logger): Promise<ShellyEMDataStatus>;
23
+ export {};
@@ -0,0 +1,73 @@
1
+ import fetch from 'node-fetch';
2
+ import DigestFetch from 'digest-fetch';
3
+ /**
4
+ * Fetches data from a Shelly device endpoint with authentication and timeout handling.
5
+ */
6
+ async function fetchShellyDevice(url, deviceConfig, log) {
7
+ const timeout = deviceConfig.timeout ?? 5000;
8
+ const controller = new AbortController();
9
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
10
+ let response;
11
+ try {
12
+ if (deviceConfig.auth) {
13
+ const client = new DigestFetch('admin', deviceConfig.auth.pw, { algorithm: 'SHA-256' });
14
+ response = await client.fetch(url, { signal: controller.signal });
15
+ if (log) {
16
+ log.debug(`[${deviceConfig.name}] Response status: ${response.status}`);
17
+ }
18
+ }
19
+ else {
20
+ response = await fetch(url, { signal: controller.signal });
21
+ }
22
+ }
23
+ finally {
24
+ clearTimeout(timeoutId);
25
+ }
26
+ return response;
27
+ }
28
+ /**
29
+ * Fetches and parses JSON from a Shelly endpoint with error handling.
30
+ */
31
+ async function fetchAndParseJSON(url, deviceConfig, log) {
32
+ const response = await fetchShellyDevice(url, deviceConfig, log);
33
+ if (!response.ok) {
34
+ const headersObj = {};
35
+ response.headers.forEach((value, key) => {
36
+ headersObj[key] = value;
37
+ });
38
+ if (log) {
39
+ log.debug(`[${deviceConfig.name}] Response headers:`, JSON.stringify(headersObj));
40
+ }
41
+ const text = await response.text();
42
+ throw new Error(`HTTP ${response.status} for ${url}: ${text}`);
43
+ }
44
+ return response.json();
45
+ }
46
+ /**
47
+ * Fetches the Sys.GetConfig data for a given device.
48
+ * @param deviceConfig - The device configuration.
49
+ * @param log - Optional logger for debug output.
50
+ */
51
+ export async function getSysConfig(deviceConfig, log) {
52
+ const url = `http://${deviceConfig.ip}/rpc/Sys.GetConfig`;
53
+ return fetchAndParseJSON(url, deviceConfig, log);
54
+ }
55
+ /**
56
+ * Fetches the EM.GetStatus data for a given device.
57
+ * @param deviceConfig - The device configuration.
58
+ * @param log - Optional logger for debug output.
59
+ */
60
+ export async function getEMStatus(deviceConfig, log) {
61
+ const url = `http://${deviceConfig.ip}/rpc/EM.GetStatus?id=0`;
62
+ return fetchAndParseJSON(url, deviceConfig, log);
63
+ }
64
+ /**
65
+ * Fetches the EMData.GetStatus data for a given device.
66
+ * @param deviceConfig - The device configuration.
67
+ * @param log - Optional logger for debug output.
68
+ */
69
+ export async function getEMDataStatus(deviceConfig, log) {
70
+ const url = `http://${deviceConfig.ip}/rpc/EMData.GetStatus?id=0`;
71
+ return fetchAndParseJSON(url, deviceConfig, log);
72
+ }
73
+ //# sourceMappingURL=shellyAPI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shellyAPI.js","sourceRoot":"","sources":["../src/shellyAPI.ts"],"names":[],"mappings":"AAAA,OAAO,KAAoC,MAAM,YAAY,CAAC;AAC9D,OAAO,WAAW,MAAM,cAAc,CAAC;AAKvC;;GAEG;AACH,KAAK,UAAU,iBAAiB,CAAC,GAAW,EAAE,YAA0B,EAAE,GAAY;IACpF,MAAM,OAAO,GAAG,YAAY,CAAC,OAAO,IAAI,IAAI,CAAC;IAC7C,MAAM,UAAU,GAAG,IAAI,eAAe,EAAE,CAAC;IACzC,MAAM,SAAS,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,UAAU,CAAC,KAAK,EAAE,EAAE,OAAO,CAAC,CAAC;IAChE,IAAI,QAAuB,CAAC;IAC5B,IAAI,CAAC;QACH,IAAI,YAAY,CAAC,IAAI,EAAE,CAAC;YACtB,MAAM,MAAM,GAAG,IAAI,WAAW,CAAC,OAAO,EAAE,YAAY,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,SAAS,EAAE,SAAS,EAAE,CAAC,CAAC;YACxF,QAAQ,GAAG,MAAM,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,CAAkB,CAAC;YACnF,IAAI,GAAG,EAAE,CAAC;gBACR,GAAG,CAAC,KAAK,CAAC,IAAI,YAAY,CAAC,IAAI,sBAAsB,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;YAC1E,CAAC;QACH,CAAC;aAAM,CAAC;YACN,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,EAAE,EAAE,MAAM,EAAE,UAA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Y;IACxE,MAAM,GAAG,GAAG,UAAU,YAAY,CAAC,EAAE,wBAAwB,CAAC;IAC9D,OAAO,iBAAiB,CAAiB,GAAG,EAAE,YAAY,EAAE,GAAG,CAAC,CAAC;AACnE,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,YAA0B,EAAE,GAAY;IAC5E,MAAM,GAAG,GAAG,UAAU,YAAY,CAAC,EAAE,4BAA4B,CAAC;IAClE,OAAO,iBAAiB,CAAqB,GAAG,EAAE,YAAY,EAAE,GAAG,CAAC,CAAC;AACvE,CAAC"}
@@ -0,0 +1,84 @@
1
+ export interface AuthConfig {
2
+ pw: string;
3
+ }
4
+ export interface DeviceConfig {
5
+ name: string;
6
+ ip: string;
7
+ auth?: AuthConfig;
8
+ timeout?: number;
9
+ update_interval?: number;
10
+ negative_handling_mode?: boolean;
11
+ }
12
+ export interface ShellyEMStatus {
13
+ id?: number;
14
+ a_current?: number;
15
+ a_voltage?: number;
16
+ a_act_power?: number;
17
+ a_aprt_power?: number;
18
+ a_pf?: number;
19
+ a_freq?: number;
20
+ b_current?: number;
21
+ b_voltage?: number;
22
+ b_act_power?: number;
23
+ b_aprt_power?: number;
24
+ b_pf?: number;
25
+ b_freq?: number;
26
+ c_current?: number;
27
+ c_voltage?: number;
28
+ c_act_power?: number;
29
+ c_aprt_power?: number;
30
+ c_pf?: number;
31
+ c_freq?: number;
32
+ n_current?: number;
33
+ total_current?: number;
34
+ total_act_power?: number;
35
+ total_aprt_power?: number;
36
+ user_calibrated_phase?: string[];
37
+ errors?: string[];
38
+ }
39
+ export interface ShellyEMDataStatus {
40
+ id?: number;
41
+ a_total_act_energy?: number;
42
+ a_total_act_ret_energy?: number;
43
+ b_total_act_energy?: number;
44
+ b_total_act_ret_energy?: number;
45
+ c_total_act_energy?: number;
46
+ c_total_act_ret_energy?: number;
47
+ total_act?: number;
48
+ total_act_ret?: number;
49
+ }
50
+ export interface ShellySysConfig {
51
+ device: {
52
+ name: string | null;
53
+ mac: string;
54
+ fw_id: string;
55
+ eco_mode?: boolean;
56
+ profile?: string;
57
+ discoverable?: boolean;
58
+ };
59
+ location?: {
60
+ tz: string;
61
+ lat: number;
62
+ lon: number;
63
+ };
64
+ debug?: {
65
+ mqtt?: {
66
+ enable: boolean;
67
+ };
68
+ websocket?: {
69
+ enable: boolean;
70
+ };
71
+ udp?: {
72
+ addr: string | null;
73
+ };
74
+ };
75
+ ui_data?: Record<string, unknown>;
76
+ rpc_udp?: {
77
+ dst_addr: string | null;
78
+ listen_port: number | null;
79
+ };
80
+ sntp?: {
81
+ server: string;
82
+ };
83
+ cfg_rev: number;
84
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=shellyTypes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shellyTypes.js","sourceRoot":"","sources":["../src/shellyTypes.ts"],"names":[],"mappings":""}
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "homebridge-shelly-energy-meter",
3
+ "displayName": "Shelly (Pro) 3EM Energy Meter",
4
+ "type": "module",
5
+ "version": "0.9.0-beta.0",
6
+ "description": "A short description about what your plugin does.",
7
+ "author": "Patrick Probst",
8
+ "license": "Apache-2.0",
9
+ "homepage": "https://github.com/pa-nic/homebridge-shelly-meter#readme",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "https://github.com/pa-nic/homebridge-shelly-meter.git"
13
+ },
14
+ "bugs": {
15
+ "url": "https://github.com/pa-nic/homebridge-shelly-meter/issues"
16
+ },
17
+ "keywords": [
18
+ "homebridge-plugin"
19
+ ],
20
+ "main": "dist/index.js",
21
+ "engines": {
22
+ "node": "^20.18.0 || ^22.10.0 || ^24.0.0",
23
+ "homebridge": "^1.8.0 || ^2.0.0-beta.0"
24
+ },
25
+ "scripts": {
26
+ "build": "rimraf ./dist && tsc",
27
+ "lint": "eslint . --max-warnings=0",
28
+ "prepublishOnly": "npm run lint && npm run build",
29
+ "watch": "npm run build && npm link && nodemon"
30
+ },
31
+ "dependencies": {
32
+ "digest-fetch": "^3.1.1",
33
+ "fakegato-history": "^0.6.7",
34
+ "node-fetch": "^3.3.2"
35
+ },
36
+ "devDependencies": {
37
+ "@eslint/js": "^9.39.1",
38
+ "@types/node": "^24.10.1",
39
+ "eslint": "^9.39.1",
40
+ "homebridge": "^2.0.0-beta.55",
41
+ "nodemon": "^3.1.11",
42
+ "rimraf": "^6.1.0",
43
+ "ts-node": "^10.9.2",
44
+ "typescript": "^5.9.3",
45
+ "typescript-eslint": "^8.46.4"
46
+ }
47
+ }