forked from n0rt0nthec4t/Nest_accfactory
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHomeKitDevice.js
More file actions
229 lines (189 loc) · 11.7 KB
/
HomeKitDevice.js
File metadata and controls
229 lines (189 loc) · 11.7 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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
// HomeKitDevice class
//
// This is the base class for all HomeKit accessories we code to
//
// The deviceData structure should, at a minimum contain the following elements. These also need to be a "string" type
// mac_address
// serial_number
// software_version
// description
// location
// manufacturer
// model
//
// Following constants should be overridden in the module loading this class file
//
// HomeKitDevice.HOMEKITHISTORY - HomeKit History module
//
// Code version 13/7/2023
// Mark Hulskamp
"use strict";
// Define HAP-NodeJS requirements
var HAP = require("hap-nodejs");
// Define nodejs module requirements
var util = require("util");
class HomeKitDevice {
constructor(HomeKitAccessoryName, HomeKitPairingCode, HomeKitMDNSAdvertiser, uniqueUUIDForDevice, currentDeviceData, globalEventEmitter) {
this.eventEmitter = null; // Event emitter to use. Allow comms from other objects
this.deviceUUID = uniqueUUIDForDevice; // Unique UUID for this device. Used for event messaging to this device4
this.deviceData = currentDeviceData; // Current data for the device
this.HomeKitAccessory = null; // HomeKit Accessory object
this.HomeKitManufacturerName = HomeKitAccessoryName; // HomeKit device manufacturer name. Used for logging output prefix also
this.HomeKitHistory = null; // History logging service
this.HomeKitPairingCode = HomeKitPairingCode; // HomeKit pairing code
this.mDNSAdvertiser = HomeKitMDNSAdvertiser; // MDNS Provider to use for this device
// Validate if globalEventEmitter object passed to us is an instance of EventEmitter
if (globalEventEmitter instanceof require("events").EventEmitter == true) {
this.eventEmitter = globalEventEmitter; // Store
// Setup event listener to process "messages" to/from our device
this.eventEmitter.addListener(this.deviceUUID, this.#message.bind(this));
}
}
// Class functions
add(mDNSAdvertiseName, HomeKitAccessoryCategory, useHistoryService) {
if (typeof this.deviceData != "object" || typeof HAP.Accessory.Categories[HomeKitAccessoryCategory] == "undefined" || typeof mDNSAdvertiseName != "string" || typeof useHistoryService != "boolean" ||
(this.deviceData.hasOwnProperty("mac_address") == false && typeof this.deviceData.mac_address != "string" && this.deviceData.mac_address == "") ||
(this.deviceData.hasOwnProperty("serial_number") == false && typeof this.deviceData.serial_number != "string" && this.deviceData.serial_number == "") ||
(this.deviceData.hasOwnProperty("software_version") == false && typeof this.deviceData.software_version != "string" && this.deviceData.software_version == "") ||
(this.deviceData.hasOwnProperty("description") == false && typeof this.deviceData.description != "string" && this.deviceData.description == "") ||
(this.deviceData.hasOwnProperty("location") == false && typeof this.deviceData.location != "string") ||
(this.deviceData.hasOwnProperty("model") == false && typeof this.deviceData.model != "string" && this.deviceData.model == "") ||
this.HomeKitAccessory != null ||
mDNSAdvertiseName == "") {
return;
}
this.HomeKitAccessory = exports.accessory = new HAP.Accessory(mDNSAdvertiseName, HAP.uuid.generate("hap-nodejs:accessories:" + this.deviceData.manufacturer.toLowerCase() + "_" + this.deviceData.serial_number));
this.HomeKitAccessory.username = this.deviceData.mac_address;
this.HomeKitAccessory.pincode = this.HomeKitPairingCode;
this.HomeKitAccessory.category = HomeKitAccessoryCategory;
this.HomeKitAccessory.getService(HAP.Service.AccessoryInformation).updateCharacteristic(HAP.Characteristic.Manufacturer, this.deviceData.manufacturer);
this.HomeKitAccessory.getService(HAP.Service.AccessoryInformation).updateCharacteristic(HAP.Characteristic.Model, this.deviceData.model);
this.HomeKitAccessory.getService(HAP.Service.AccessoryInformation).updateCharacteristic(HAP.Characteristic.SerialNumber, this.deviceData.serial_number);
this.HomeKitAccessory.getService(HAP.Service.AccessoryInformation).updateCharacteristic(HAP.Characteristic.FirmwareRevision, this.deviceData.software_version);
if (useHistoryService == true && typeof HomeKitDevice.HOMEKITHISTORY != "undefined" && this.HomeKitHistory == null) {
// Setup logging service as requsted
this.HomeKitHistory = new HomeKitDevice.HOMEKITHISTORY(this.HomeKitAccessory, {});
}
try {
this.addHomeKitServices((this.deviceData.location == "" ? this.deviceData.description : this.deviceData.description + " - " + this.deviceData.location));
} catch (error) {
this.#outputLogging("addHomeKitServices call for device '%s' on '%s' failed. Error was", this.HomeKitAccessory.displayName, this.HomeKitAccessory.username, error);
}
this.update(this.deviceData, true); // perform an initial update using current data
// Publish accessory on local network and push onto export array for HAP-NodeJS "accessory factory"
this.HomeKitAccessory.publish({username: this.HomeKitAccessory.username, pincode: this.HomeKitAccessory.pincode, category: this.HomeKitAccessory.category, advertiser: this.mDNSAdvertiser});
this.#outputLogging("Advertising '%s (%s)' as '%s' to local network for HomeKit", (this.deviceData.location == "" ? this.deviceData.description : this.deviceData.description + " - " + this.deviceData.location), this.HomeKitAccessory.username, this.HomeKitAccessory.displayName);
}
remove() {
this.#outputLogging("Device '%s' on '%s' has been removed", this.HomeKitAccessory.displayName, this.HomeKitAccessory.username);
if (this.eventEmitter != null) {
// Remove listener for "messages"
this.eventEmitter.removeAllListeners(this.deviceUUID);
}
try {
this.removeHomeKitServices();
} catch (error) {
this.#outputLogging("removeHomeKitServices call for device '%s' on '%s' failed. Error was", this.HomeKitAccessory.displayName, this.HomeKitAccessory.username, error);
}
this.HomeKitAccessory.unpublish();
this.deviceData = null;
this.HomeKitAccessory = null;
this.eventEmitter = null;
this.HomeKitHistory = null;
// Do we destroy this object??
// this = null;
// delete this;
}
update(updatedDeviceData, forceHomeKitUpdate) {
if (typeof updatedDeviceData != "object" || typeof forceHomeKitUpdate != "boolean") {
return;
}
// Updated data may only contain selected fields, so we'll handle that here by taking our internally stored data
// and merge with the updates to ensure we have a complete data object
Object.entries(this.deviceData).forEach(([key, value]) => {
if (typeof updatedDeviceData[key] == "undefined") {
// Updated data doesn't have this key, so add it to our internally stored data
updatedDeviceData[key] = value;
}
});
// Check to see what data elements have changed
var changedObjectElements = {};
Object.entries(updatedDeviceData).forEach(([key, value]) => {
if (JSON.stringify(updatedDeviceData[key]) !== JSON.stringify(this.deviceData[key])) {
changedObjectElements[key] = updatedDeviceData[key];
}
});
// If we have any changed data elements OR we've been requested to force an update, do so
if (Object.keys(changedObjectElements).length != 0 || forceHomeKitUpdate == true) {
if (updatedDeviceData.hasOwnProperty("software_version") == true && updatedDeviceData.software_version != this.deviceData.software_version) {
// Update software version
this.HomeKitAccessory.getService(HAP.Service.AccessoryInformation).updateCharacteristic(HAP.Characteristic.FirmwareRevision, updatedDeviceData.software_version);
}
if (updatedDeviceData.hasOwnProperty("online") == true && updatedDeviceData.online != this.deviceData.online) {
// Update online/offline status
this.#outputLogging("Device '%s' on '%s' is %s", this.HomeKitAccessory.displayName, this.HomeKitAccessory.username, (updatedDeviceData.online == true ? "online" : "offline"));
}
try {
this.updateHomeKitServices(updatedDeviceData); // Pass updated data on for accessory to process as it needs
} catch (error) {
this.#outputLogging("updateHomeKitServices call for device '%s' on '%s' failed. Error was", this.HomeKitAccessory.displayName, this.HomeKitAccessory.username, error);
}
this.deviceData = updatedDeviceData; // Finally, update our internally stored data about the device
}
}
set(keyValues) {
if (typeof keyValues != "object" || this.eventEmitter == null) {
return;
}
// Send event with data to set
this.eventEmitter.emit(HomeKitDevice.SET, this.deviceUUID, keyValues);
}
get() {
// <---- To Implement
}
addHomeKitServices(serviceName) {
// <---- override in class which extends this class
}
removeHomeKitServices() {
// <---- override in class which extends this class
}
updateHomeKitServices(updatedDeviceData) {
// <---- override in class which extends this class
}
messageHomeKitServices(messageType, messageData) {
// <---- override in class which extends this class
}
#message(messageType, messageData) {
switch (messageType) {
case HomeKitDevice.UPDATE : {
this.update(messageData, false); // Got some device data, so process any updates
break;
}
case HomeKitDevice.REMOVE : {
this.remove(); // Got message for device removal
break
}
default : {
// This is not a message we know about, so pass onto accessory for it to perform any processing
try {
this.messageHomeKitServices(messageType, messageData);
} catch (error) {
this.#outputLogging("messageHomeKitServices call for device '%s' on '%s' failed. Error was", this.HomeKitAccessory.displayName, this.HomeKitAccessory.username, error);
}
break;
}
}
}
#outputLogging(...outputMessage) {
var timeStamp = String(new Date().getFullYear()).padStart(4, "0") + "-" + String(new Date().getMonth() + 1).padStart(2, "0") + "-" + String(new Date().getDate()).padStart(2, "0") + " " + String(new Date().getHours()).padStart(2, "0") + ":" + String(new Date().getMinutes()).padStart(2, "0") + ":" + String(new Date().getSeconds()).padStart(2, "0");
console.log(timeStamp + " [" + this.HomeKitManufacturerName + "] " + util.format(...outputMessage));
}
}
// Export defines for this module
HomeKitDevice.UPDATE = "HomeKitDevice.update"; // Device update message
HomeKitDevice.REMOVE = "HomeKitDevice.remove"; // Device remove message
HomeKitDevice.SET = "HomeKitDevice.set"; // Device set property message
HomeKitDevice.GET = "HomeKitDevice.get"; // Device get property message
HomeKitDevice.UNPUBLISH = "HomeKitDevice.unpublish"; // Device unpublish message
HomeKitDevice.HOMEKITHISTORY = undefined; // HomeKit History module
module.exports = HomeKitDevice;