-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathindex.js
executable file
·246 lines (221 loc) · 12.9 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
const fs = require('fs');
const {sleep} = require('./util/Util');
const version = require('./package').version;
const pluginName = require('./package').name;
const platformName = 'openHAB2-Complete';
const {OpenHAB} = require('./util/OpenHAB');
const {Accessory} = require('./util/Accessory');
const UUID = {
AccessoryInformationService: "0000003E-0000-1000-8000-0026BB765291",
BatteryService: "00000096-0000-1000-8000-0026BB765291"
};
const {BATTERY_CONFIG} = require('./accessory/characteristic/Battery');
module.exports = (api) => {
api.registerPlatform(platformName, OpenHABComplete);
};
const OpenHABComplete = class {
constructor(log, config, api) {
this._log = log;
this._config = config;
this.accessories = [];
if(!(this._config.host)) {
const msg = `OpenHAB host not configured!`;
this._log.error(msg);
throw new Error(msg);
} else if(!(api)) {
const msg = `API element not set, please update your homebridge installation`;
this._log.error(msg);
throw new Error(msg);
} else {
this._platform = {
openHAB: new OpenHAB(config, log),
api: api,
log: log
};
}
this._factories = {};
// Loading accessories from file system
this._log(`Loading accessory types...`);
let accessoryDirectory = `${__dirname}/accessory`;
let accessoryFiles = fs.readdirSync(accessoryDirectory, {"withFileTypes": true});
accessoryFiles.forEach(function (accessoryFile) {
if(accessoryFile.isFile()) {
let accessoryFilePath = `${accessoryDirectory}/${accessoryFile.name}`;
let accessoryFileName = accessoryFilePath.split(/[\\/]/).pop();
let accessoryType = require(accessoryFilePath).type;
if(accessoryType === undefined || !(typeof accessoryType === "string")) {
this._log.warn(`Ignoring ${accessoryFileName} due to missing 'type' definition`);
} else {
this._log.debug(`Found accessory of type ${accessoryType}`);
let accessoryFactory = require(accessoryFilePath).createAccessory;
if(accessoryFactory === undefined || !(typeof accessoryFactory === "function")) {
this._log.warn(`Ignoring ${accessoryFileName}, due to missing 'createAccessory' definition`);
} else if (this._factories[accessoryType]) {
this._log.warn(`There is already an accessory of type ${accessoryType} loaded, skipping this`);
} else {
this._log(`Loading and activating accessory type ${accessoryType}`);
this._factories[accessoryType] = require(accessoryFilePath).createAccessory;
}
}
}
}.bind(this));
this._log.info(`Waiting for openHAB host (${config.host}) to come online...`);
let online = false;
while(!online) {
sleep(2);
this._log.debug(`Checking if openHAB host (${config.host}) is online...`);
online = this._platform.openHAB.isOnline();
}
sleep(10);
this._log.info(`openHAB host (${config.host}) is online, now syncing...`);
this._platform.openHAB.syncItemTypes();
this._log.info(`'OpenHAB2 - Complete Edition' plugin loaded - Version ${version} - dev`);
this._log.info(`---`);
api.on('didFinishLaunching', function() {
let _accessories = [];
const configuration = this._config.accessories;
this._log.info(`Loading accessories from configuration, this might take a while...`);
configuration.forEach(function(acc) {
let accessory = this.parseAccessoryConfiguration(acc, _accessories);
if(accessory !== undefined) {
if(accessory instanceof Array) {
_accessories = _accessories.concat(accessory);
} else {
_accessories.push(accessory);
}
}
}.bind(this));
this._platform.openHAB.startSubscription();
this._platform.openHAB.syncItemValues();
for(let val of _accessories) {
this._platform.api.registerPlatformAccessories(pluginName, platformName, [val.getAccessory()]);
}
this._log.info(`Finished loading ${_accessories.length} accessories from configuration`);
this._log.info(`---`);
}.bind(this))
}
/**
* Homebridge will call the "configureAccessory" method once for every cached
* accessory restored
*/
configureAccessory(accessory) {
this._log.debug(`Restored ${accessory.UUID}, adding to list, in order to remove later!`)
this.accessories.push(accessory);
}
parseAccessoryConfiguration(configuration) {
try {
if (!(configuration.type)) {
throw new Error(`Invalid configuration: Accessory type is undefined: ${JSON.stringify(configuration)}`);
}
if(configuration.type === "group") {
if(configuration.items && configuration.items instanceof Array) {
let groupAccessoryConfig = {};
if (configuration.name) {
groupAccessoryConfig.serialNumber = this._platform.api.hap.uuid.generate(configuration.name + "-" + configuration.type)
groupAccessoryConfig.name = configuration.name;
groupAccessoryConfig.version = version;
if (configuration.model) {
groupAccessoryConfig.model = configuration.model;
} else {
groupAccessoryConfig.model = "Generic Accessory Group"
}
// Merging battery items
groupAccessoryConfig[BATTERY_CONFIG.batteryItem] = configuration[BATTERY_CONFIG.batteryItem];
groupAccessoryConfig[BATTERY_CONFIG.batteryItemInverted] = configuration[BATTERY_CONFIG.batteryItemInverted];
groupAccessoryConfig[BATTERY_CONFIG.batteryItemThreshold] = configuration[BATTERY_CONFIG.batteryItemThreshold];
groupAccessoryConfig[BATTERY_CONFIG.batteryItemChargingState] = configuration[BATTERY_CONFIG.batteryItemChargingState];
groupAccessoryConfig[BATTERY_CONFIG.batteryItemChargingStateInverted] = configuration[BATTERY_CONFIG.batteryItemChargingState];
} else {
throw new Error(`Invalid configuration: Accessory name is undefined: ${JSON.stringify(configuration)}`);
}
const cachedAccessory = this.accessories.find(cachedAccessory => cachedAccessory.UUID === groupAccessoryConfig.serialNumber)
if (cachedAccessory != undefined) {
this._log.debug(`Accessory group '${groupAccessoryConfig.name}' (${configuration.model}) already loaded from cache, removing!`);
this._platform.api.unregisterPlatformAccessories(pluginName, platformName, [cachedAccessory]);
}
this._log.debug(`Found accessory group in config: '${groupAccessoryConfig.name}' (${configuration.model})`);
let accessoryGroup = [];
// Get all accessory from the group
for (let i = 0; i < configuration.items.length; i++) {
let accessory = this.parseAccessoryConfiguration(configuration.items[i]);
if (accessory !== undefined) {
if (accessory instanceof Array) {
accessoryGroup = accessoryGroup.concat(accessory);
} else {
accessoryGroup.push(accessory);
}
}
}
// Merge all provided services, except battery and accessory information services
let groupAccessoryServices = [];
for (let i = 0; i < accessoryGroup.length; i++) {
let groupedAccessory = accessoryGroup[i];
for (let n = 0; n < groupedAccessory._services.length; n++) {
let groupedService = groupedAccessory._services[n];
if (groupedService.UUID === UUID.AccessoryInformationService) {
this._log.debug(`Ignoring Accessory Information Service for grouped accessory ${groupAccessoryConfig.name}`)
} else if (groupedService.UUID === UUID.BatteryService) {
this._log.debug(`Ignoring Battery Service for grouped accessory ${groupAccessoryConfig.name}`)
} else {
groupedService.subtype = `${groupedAccessory.uuid_base}`;
groupAccessoryServices.push(groupedService);
}
}
}
this._log.debug(`Creating grouped accessory ${groupAccessoryConfig.name} (${configuration.model}) with ${accessoryGroup.length} accessories and ${groupAccessoryServices.length} services`);
let groupAccessory = new Accessory(this._platform, groupAccessoryConfig);
groupAccessory._services = groupAccessory._services.concat(groupAccessoryServices);
groupAccessory._services.unshift(groupAccessory._getAccessoryInformationService(groupAccessoryConfig.model));
this._log.info(`Created grouped accessory ${groupAccessoryConfig.name} (${configuration.model}) with ${accessoryGroup.length} accessories and ${groupAccessoryServices.length} services`);
return groupAccessory;
} else {
throw new Error(`Invalid configuration: Accessory group does not define items: ${JSON.stringify(configuration)}`);
}
} else {
// Not an accessory group
const factory = this._factories[configuration.type];
if (factory === undefined) {
throw new Error(`Invalid configuration: Accessory type is unknown: ${configuration.type}`);
}
//
// Multiple items of the same type grouped in a configuration array
//
if(configuration.items && configuration.items instanceof Array) {
let accessoryTypeGroup = [];
for (let i = 0; i < configuration.items.length; i++) {
let accessoryConfiguration = configuration.items[i];
accessoryConfiguration.type = configuration.type;
let accessory = this.parseAccessoryConfiguration(accessoryConfiguration);
if(accessory !== undefined) {
accessoryTypeGroup.push(accessory);
}
}
return accessoryTypeGroup;
} else {
//
// Single item
//
if (configuration.name) {
configuration.serialNumber = this._platform.api.hap.uuid.generate(configuration.name + "-" + configuration.type)
} else {
throw new Error(`Invalid configuration: Accessory name is undefined: ${JSON.stringify(configuration)}`);
}
const cachedAccessory = this.accessories.find(cachedAccessory => cachedAccessory.UUID === configuration.serialNumber)
if (cachedAccessory != undefined) {
this._log.debug(`Accessory '${configuration.name}' (${configuration.type}) already loaded from cache, removing!`);
this._platform.api.unregisterPlatformAccessories(pluginName, platformName, [cachedAccessory]);
}
this._log.debug(`Found accessory in config: '${configuration.name}' (${configuration.type})`);
configuration.version = version;
// Checked that: 'serialNumber' 'version' 'name' exists and 'type' is valid
const accessory = factory(this._platform, configuration);
this._log(`Added accessory ${configuration.name} (Type: ${configuration.type})`);
return accessory;
}
}
} catch (e) {
this._log.warn(`Unable to add accessory ${configuration.name}: ${e}, skipping`);
return undefined;
}
}
};