-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
363 lines (322 loc) · 12.1 KB
/
index.js
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
import request from 'request';
import crypto from 'crypto';
import open from 'open';
import http from 'http';
import { internalIpV4 } from 'internal-ip';
let Service, Characteristic, Accessory, UUIDGen;
export default (homebridge) => {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
Accessory = homebridge.platformAccessory;
UUIDGen = homebridge.hap.uuid;
homebridge.registerPlatform('homebridge-vicare', 'ViCareThermostatPlatform', ViCareThermostatPlatform, true);
};
class ViCareThermostatPlatform {
constructor(log, config, api) {
this.log = log;
this.config = config;
this.api = api;
this.clientId = config.clientId;
this.apiEndpoint = config.apiEndpoint;
this.devices = config.devices;
this.accessories = [];
this.codeVerifier = this.generateCodeVerifier();
this.codeChallenge = this.generateCodeChallenge(this.codeVerifier);
this.server = null;
this.api.on('didFinishLaunching', async () => {
this.log('Starting authentication process...');
this.hostIp = await internalIpV4(); // Ermittelt die lokale IP-Adresse
this.redirectUri = `http://${this.hostIp}:4200`;
this.log(`Using redirect URI: ${this.redirectUri}`);
this.authenticate((err, accessToken) => {
if (!err) {
this.log('Authentication successful, received access token.');
this.accessToken = accessToken;
this.retrieveIds((err, installationId, gatewaySerial) => {
if (!err) {
this.log('Retrieved installation and gateway IDs.');
this.installationId = installationId;
this.gatewaySerial = gatewaySerial;
this.devices.forEach(deviceConfig => {
this.addAccessory(deviceConfig);
});
this.retrieveSmartComponents();
} else {
this.log('Error retrieving installation or gateway IDs:', err);
}
});
} else {
this.log('Error during authentication:', err);
}
});
});
}
configureAccessory(accessory) {
this.accessories.push(accessory);
}
generateCodeVerifier() {
return crypto.randomBytes(32).toString('base64url');
}
generateCodeChallenge(codeVerifier) {
return crypto.createHash('sha256').update(codeVerifier).digest('base64url');
}
authenticate(callback) {
const authUrl = `https://iam.viessmann.com/idp/v3/authorize?client_id=${this.clientId}&redirect_uri=${encodeURIComponent(this.redirectUri)}&scope=IoT%20User%20offline_access&response_type=code&code_challenge_method=S256&code_challenge=${this.codeChallenge}`;
this.log(`Opening browser for authentication: ${authUrl}`);
open(authUrl);
this.startServer(callback);
}
startServer(callback) {
this.server = http.createServer((req, res) => {
const url = new URL(req.url, `http://${req.headers.host}`);
const authCode = url.searchParams.get('code');
if (authCode) {
this.log('Received authorization code:', authCode);
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Authorization successful. You can close this window.');
this.exchangeCodeForToken(authCode, (err, accessToken) => {
this.server.close();
callback(err, accessToken);
});
} else {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('Authorization code not found.');
}
}).listen(4200, this.hostIp, () => {
this.log(`Server is listening on ${this.hostIp}:4200`);
});
}
exchangeCodeForToken(authCode, callback) {
const tokenUrl = 'https://iam.viessmann.com/idp/v3/token';
const params = {
client_id: this.clientId,
redirect_uri: this.redirectUri,
grant_type: 'authorization_code',
code_verifier: this.codeVerifier,
code: authCode
};
this.log('Exchanging authorization code for access token...');
request.post({
url: tokenUrl,
form: params,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}, (error, response, body) => {
if (error || response.statusCode !== 200) {
this.log('Error exchanging code for token:', error || body);
callback(error || new Error(body));
return;
}
this.log('Successfully exchanged code for access token.');
const tokenResponse = JSON.parse(body);
callback(null, tokenResponse.access_token);
});
}
retrieveIds(callback) {
const options = {
url: `${this.apiEndpoint}/equipment/installations`,
headers: {
'Authorization': `Bearer ${this.accessToken}`,
},
json: true
};
this.log('Retrieving installation IDs...');
request.get(options, (error, response, body) => {
if (error || response.statusCode !== 200) {
this.log('Error retrieving installations:', error || body);
callback(error || new Error(body));
return;
}
this.log('Successfully retrieved installations:', body);
const installation = body.data[0];
const installationId = installation.id;
const gatewayOptions = {
url: `${this.apiEndpoint}/equipment/installations/${installationId}/gateways`,
headers: {
'Authorization': `Bearer ${this.accessToken}`,
},
json: true
};
this.log('Retrieving gateway IDs...');
request.get(gatewayOptions, (error, response, body) => {
if (error || response.statusCode !== 200) {
this.log('Error retrieving gateways:', error || body);
callback(error || new Error(body));
return;
}
this.log('Successfully retrieved gateways:', body);
if (!body.data || body.data.length === 0) {
this.log('No gateway data available.');
callback(new Error('No gateway data available.'));
return;
}
const gateway = body.data[0];
const gatewaySerial = gateway.serial;
callback(null, installationId, gatewaySerial);
});
});
}
retrieveSmartComponents() {
const options = {
url: `${this.apiEndpoint}/equipment/installations/${this.installationId}/smartComponents`,
headers: {
'Authorization': `Bearer ${this.accessToken}`,
},
json: true
};
this.log('Retrieving smart components...');
request.get(options, (error, response, body) => {
if (error || response.statusCode !== 200) {
this.log('Error retrieving smart components:', error || body);
return;
}
this.log('Successfully retrieved smart components:', body);
body.data.forEach(component => {
this.log(`Component ID: ${component.id}, Name: ${component.name}, Selected: ${component.selected}, Deleted: ${component.deleted}`);
});
});
}
selectSmartComponents(componentIds, callback) {
const options = {
url: `${this.apiEndpoint}/equipment/installations/${this.installationId}/smartComponents`,
headers: {
'Authorization': `Bearer ${this.accessToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ selected: componentIds })
};
this.log('Selecting smart components...');
request.put(options, (error, response, body) => {
if (error || response.statusCode !== 200) {
this.log('Error selecting smart components:', error || body);
callback(error || new Error(body));
return;
}
const result = JSON.parse(body);
this.log('Successfully selected smart components:', result);
callback(null, result);
});
}
addAccessory(deviceConfig) {
const uuid = UUIDGen.generate(deviceConfig.name);
let accessory = this.accessories.find(acc => acc.UUID === uuid);
if (!accessory) {
accessory = new Accessory(deviceConfig.name, uuid);
this.api.registerPlatformAccessories('homebridge-vicare', 'ViCareThermostatPlatform', [accessory]);
this.accessories.push(accessory);
this.log(`Added new accessory: ${deviceConfig.name}`);
}
const vicareAccessory = new ViCareThermostatAccessory(
this.log,
deviceConfig,
this.api,
this.accessToken,
this.apiEndpoint,
this.installationId,
this.gatewaySerial
);
accessory.context.deviceConfig = deviceConfig;
accessory.getService(Service.AccessoryInformation)
.setCharacteristic(Characteristic.Manufacturer, 'Viessmann')
.setCharacteristic(Characteristic.Model, 'ViCare')
.setCharacteristic(Characteristic.SerialNumber, 'Default-Serial');
vicareAccessory.getServices().forEach(service => {
const existingService = accessory.getServiceById(service.UUID, service.subtype);
if (existingService) {
accessory.removeService(existingService);
}
accessory.addService(service);
});
this.api.updatePlatformAccessories([accessory]);
}
}
class ViCareThermostatAccessory {
constructor(log, config, api, accessToken, apiEndpoint, installationId, gatewaySerial) {
this.log = log;
this.name = config.name;
this.feature = config.feature;
this.apiEndpoint = apiEndpoint;
this.accessToken = accessToken;
this.deviceId = config.deviceId;
this.installationId = installationId;
this.gatewaySerial = gatewaySerial;
this.temperatureService = new Service.TemperatureSensor(this.name, `temperatureService_${this.name}_${this.feature}_${UUIDGen.generate(this.name + this.feature)}`);
this.temperatureService
.getCharacteristic(Characteristic.CurrentTemperature)
.on('get', this.getTemperature.bind(this));
if (config.feature.includes('burners')) {
this.switchService = new Service.Switch(this.name, `switchService_${this.name}_${this.feature}_${UUIDGen.generate(this.name + this.feature)}`);
this.switchService
.getCharacteristic(Characteristic.On)
.on('get', this.getBurnerStatus.bind(this))
.on('set', this.setBurnerStatus.bind(this));
}
this.services = [this.temperatureService];
if (this.switchService) {
this.services.push(this.switchService);
}
}
getTemperature(callback) {
const url = `${this.apiEndpoint}/features/installations/${this.installationId}/gateways/${this.gatewaySerial}/devices/${this.deviceId}/features/${this.feature}`;
this.log(`Fetching temperature from ${url}`);
request.get(
{
url: url,
headers: {
Authorization: `Bearer ${this.accessToken}`,
},
json: true,
},
(error, response, body) => {
if (!error && response.statusCode === 200) {
const data = body.data || body;
if (data.properties && data.properties.value && data.properties.value.value !== undefined) {
const temp = data.properties.value.value;
callback(null, temp);
} else {
this.log('Unexpected response structure:', data);
callback(new Error('Unexpected response structure.'));
}
} else {
this.log('Error fetching temperature:', error || body);
callback(error || new Error(body));
}
}
);
}
getBurnerStatus(callback) {
const url = `${this.apiEndpoint}/features/installations/${this.installationId}/gateways/${this.gatewaySerial}/devices/${this.deviceId}/features/${this.feature}`;
this.log(`Fetching burner status from ${url}`);
request.get(
{
url: url,
headers: {
Authorization: `Bearer ${this.accessToken}`,
},
json: true,
},
(error, response, body) => {
if (!error && response.statusCode === 200) {
const data = body.data || body;
if (data.properties && data.properties.active && data.properties.active.value !== undefined) {
const isActive = data.properties.active.value;
callback(null, isActive);
} else {
this.log('Unexpected response structure:', data);
callback(new Error('Unexpected response structure.'));
}
} else {
this.log('Error fetching burner status:', error || body);
callback(error || new Error(body));
}
}
);
}
setBurnerStatus(value, callback) {
callback(null);
}
getServices() {
return this.services;
}
}