-
-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathplatform.ts
More file actions
212 lines (183 loc) · 8.24 KB
/
Copy pathplatform.ts
File metadata and controls
212 lines (183 loc) · 8.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import { API, DynamicPlatformPlugin, Logger, PlatformAccessory, PlatformConfig, Service, Characteristic } from 'homebridge';
import { PLATFORM_NAME, PLUGIN_NAME, PLUGIN_VERSION } from './settings';
import { FanAccessory } from './accessories/FanAccessory';
import { HeaterAccessory } from './accessories/HeaterAccessory';
import { HumidifierAccessory } from './accessories/HumidifierAccessory';
import DreoAPI from './DreoAPI';
/**
* HomebridgePlatform
* This class is the main constructor for your plugin, this is where you should
* parse the user config and discover/register accessories with Homebridge.
*/
export class DreoPlatform implements DynamicPlatformPlugin {
public readonly Service: typeof Service = this.api.hap.Service;
public readonly Characteristic: typeof Characteristic = this.api.hap.Characteristic;
public readonly webHelper = new DreoAPI(this);
// This is used to track restored cached accessories
public readonly accessories: PlatformAccessory[] = [];
constructor(
public readonly log: Logger,
public readonly config: PlatformConfig,
public readonly api: API,
) {
this.log.info('Homebridge Dreo plugin version:', PLUGIN_VERSION);
this.log.debug('Finished initializing platform:', this.config.name);
// When this event is fired it means Homebridge has restored all cached accessories from disk.
// Dynamic Platform plugins should only register new accessories after this event was fired,
// in order to ensure they weren't added to homebridge already. This event can also be used
// to start discovery of new accessories.
this.api.on('didFinishLaunching', async () => {
log.debug('Executed didFinishLaunching callback');
// Run the method to discover / register your devices as accessories
this.discoverDevices();
});
}
/**
* This function is invoked when homebridge restores cached accessories from disk at startup.
* It should be used to setup event handlers for characteristics and update respective values.
*/
configureAccessory(accessory: PlatformAccessory) {
this.log.info('Loading accessory from cache:', accessory.displayName);
// Add the restored accessory to the accessories cache so we can track if it has already been registered
this.accessories.push(accessory);
}
/**
* Log into Dreo services, retrieve the user's devices, and register them as accessories
* Also remove accessories that are no longer present on the user's account
*/
async discoverDevices() {
// Validate config values
if (!this.config.options || !this.config.options.email || !this.config.options.password) {
this.log.error('error: Invalid email and/or password');
return;
}
// Request access token from Dreo server
let auth = await this.webHelper.authenticate();
// Check if access_token is valid
if (auth === undefined) {
this.log.error('Authentication error: Failed to obtain access_token');
return;
}
this.log.info('Country:', auth.countryCode);
this.log.info('Region:', auth.region);
// Re-authenticate with EU server if european account is detected
if (auth.region === 'EU') {
this.webHelper.server = 'eu';
auth = await this.webHelper.authenticate();
} else if (auth.region !== 'NA') {
this.log.error('error, unknown region');
this.log.error('Please open a github issue and provide your Country and Region (shown above)');
return;
}
// Use access token to retrieve user's devices
const dreoDevices = await this.webHelper.getDevices();
// Make sure devices were retrieved successfully
if (dreoDevices === undefined) {
return;
}
// Mask sensitive information and print the device list
const maskedDevices = dreoDevices.map(device => ({
...device,
sn: '********',
deviceId: '********',
familyId: '********',
familyName: '********',
roomId: '********',
roomName: '********',
}));
this.log.debug('\n\nDevices:\n', maskedDevices);
// Create a set of UUIDs for the currently discovered devices
const discoveredDeviceUUIDs = new Set(dreoDevices.map(device => this.api.hap.uuid.generate(device.sn)));
// Unregister accessories that are no longer present
const accessoriesToRemove = this.accessories.filter(accessory => !discoveredDeviceUUIDs.has(accessory.UUID));
if (accessoriesToRemove.length > 0) {
this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, accessoriesToRemove);
this.log.info('Removing accessories:', accessoriesToRemove.map(accessory => accessory.displayName).join(', '));
}
// Open WebSocket (used to control devices later)
await this.webHelper.startWebSocket();
// Loop over the discovered devices and register each one if it has not already been registered
for (const device of dreoDevices) {
// Print device info:
this.log.debug('Control config: ', JSON.stringify(device.controlsConf, null, 2));
// Generate a unique id for the accessory this should be generated from
// something globally unique, but constant, for example, the device serial
// number or MAC address
const uuid = this.api.hap.uuid.generate(device.sn);
// See if an accessory with the same uuid has already been registered and restored from
// the cached devices we stored in the `configureAccessory` method above
const existingAccessory = this.accessories.find(accessory => accessory.UUID === uuid);
let accessory: PlatformAccessory;
if (existingAccessory) {
// The accessory already exists
this.log.info('Restoring existing accessory from cache:', device.deviceName);
accessory = existingAccessory;
} else {
// The accessory does not yet exist, so we need to create it
this.log.info('Adding new accessory:', device.deviceName);
// Create a new accessory
accessory = new this.api.platformAccessory(device.deviceName, uuid);
// Store a copy of the device object in the `accessory.context`
accessory.context.device = device;
}
// Get initial device state
const state = await this.webHelper.getState(device.sn);
if (state === undefined) {
this.log.error('error: Failed to retrieve device state');
return;
}
this.log.debug('Accessory state:', state);
// Create the accessory handler for new/restored accessory
// This is imported from `platformAccessory.ts`
// List of supported model prefixes
const SUPPORTED_MODEL_PREFIXES = [
'DR-HTF', // Tower Fan
'DR-HAF', // Air Circulator
'DR-HPF', // Air Circulator
'DR-HCF', // Ceiling Fan
'DR-HAP', // Air Purifier
'DR-HSH', // Heater
'WH', // Heater
'DR-HAC', // Air Conditioner
'DR-HHM', // Humidifier
];
// Find the matching prefix
let modelPrefix = SUPPORTED_MODEL_PREFIXES.find(prefix => device.model.startsWith(prefix));
// Determine device type based on the matched prefix
switch (modelPrefix) {
case 'DR-HTF':
case 'DR-HAF':
case 'DR-HPF':
case 'DR-HCF':
case 'DR-HAP':
// Tower Fan, Air Circulator, Ceiling Fan, Air Purifier
accessory.category = this.api.hap.Categories.FAN;
new FanAccessory(this, accessory, state);
break;
case 'DR-HSH':
case 'WH':
// Heater
accessory.category = this.api.hap.Categories.AIR_HEATER;
new HeaterAccessory(this, accessory, state);
break;
case 'DR-HAC':
// Air Conditioner
// new CoolerAccessory(this, accessory, state);
this.log.info('Air Conditioner not yet supported');
modelPrefix = undefined;
break;
case 'DR-HHM':
// Humidifier
accessory.category = this.api.hap.Categories.AIR_HUMIDIFIER;
new HumidifierAccessory(this, accessory, state);
break;
default:
this.log.error('Error, unknown device type:', device.productName, device.model);
}
if (!existingAccessory && modelPrefix) {
// Link accessory to the platform if model is supported
this.api.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [accessory]);
}
}
}
}