-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
173 lines (143 loc) · 5.01 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
const request = require('request');
const url = require('url');
const createError = require('http-errors')
let Service, Characteristic;
const meUrl = 'https://api.butterflymx.com:443/mobile/v3/me';
const unlockUrl = 'https://api.butterflymx.com:443/mobile/v3/door_release_requests';
const refreshUrl = 'https://accounts.butterflymx.com/oauth/token';
function butterflyMx(log, config) {
this.configPrinted = false;
this.log = log;
this.clientId = config['clientId'];
this.refreshToken = config['refreshToken'];
this.authToken = config['authToken'];
this.unitId = config['unitId'];
this.panelId = config['panelId'];
}
butterflyMx.prototype = {
wrappedRequest: function(req, callback) {
const me = this;
me.log.debug(`Requesting ${req.url}`);
request(req, callback);
},
dispatchRequest: function(next, requestObject, callback) {
const me = this;
me.wrappedRequest(requestObject, function(error, response, body) {
try {
if(error) throw error;
if(response.statusCode == 401) {
me.log.warn('Attempting to obtain updated credentials');
me.doRefresh(requestObject, callback);
} else {
callback(error, response, body);
}
} catch(ex) {
me.log.error('Failed to dispatch a request', ex);
}
})
},
doRefresh: function(nextRequest, nextCallback) {
const me = this;
const requestBody = {
refresh_token: me.refreshToken,
client_id: me.clientId,
grant_type: 'refresh_token',
};
const requestObj = {
url: refreshUrl,
method: 'POST',
body: JSON.stringify(requestBody),
headers: { 'Content-Type': 'application/json' }
};
me.wrappedRequest(requestObj, function(error, response, body) {
try {
if(error) throw error;
if (response.statusCode != 200) throw createError(response.statusCode, body);
const result = JSON.parse(body);
me.authToken = result.access_token;
me.refreshToken = result.refresh_token;
nextRequest.headers['Authorization'] = `Bearer ${me.authToken}`;
me.wrappedRequest(nextRequest, nextCallback);
} catch(ex) {
me.log.error('Failed to refresh token', ex);
}
});
},
getSwitchOnCharacteristic: function(next) {
const me = this;
// take advantage of this opportunity to verify we are configured correctly
if(!this.configPrinted) {
const requestObj = {
url: meUrl,
method: 'GET',
headers: { 'Authorization': 'Bearer ' + me.authToken },
};
me.dispatchRequest(next, requestObj, function(error, response, body) {
try {
if(error) throw error;
if (response.statusCode != 200) {
throw createError(response.statusCode, response.body);
}
const result = JSON.parse(body);
const resultUnit = result.included.filter(inc => inc.type == 'units')[0];
const resultBuilding = result.included.filter(inc => inc.type == 'buildings')[0];
me.log.info(`Configured for ${resultBuilding.attributes.name} ${resultUnit.attributes.label}`);
me.configPrinted = true;
} catch(ex) {
me.log.warn('Failed to get lock status', ex);
}
return next(null, false); // we can't introspect the state of the door release so just always say that it's "off"
});
} else {
return next(null, false); // we can't introspect the state of the door release so just always say that it's "off"
}
},
setSwitchOnCharacteristic: function(on, next) {
const me = this;
me.log.info('Unlocking door...');
const requestBody = Object.entries({
'data[type]': 'door_release_requests',
'data[attributes][release_method]': 'front_door_view',
'data[relationships][unit][data][id]': me.unitId,
'data[relationships][panel][data][id]': me.panelId,
}).map(pair => `${encodeURI(pair[0])}=${encodeURI(pair[1])}`).join('&');
const requestObj = {
url: unlockUrl,
body: requestBody,
method: 'POST',
headers: {
'Authorization': 'Bearer ' + me.authToken,
'Content-Type': 'application/x-www-form-urlencoded',
}
};
me.dispatchRequest(next, requestObj, function(error, response, body) {
try {
if(error) throw error;
if (![200, 201].includes(response.statusCode)) throw createError(response.statusCode, body);
const result = JSON.parse(body);
me.log.info(`Created unlock request ${result.data.id}`);
return next();
} catch(ex) {
me.log.error('Failed to unlock door', ex);
return next(ex);
}
});
},
getServices: function() {
let informationService = new Service.AccessoryInformation();
informationService
.setCharacteristic(Characteristic.Manufacturer, 'ButterflyMx')
.setCharacteristic(Characteristic.Model, 'ButterflyMx')
let butterflyService = new Service.Switch('ButterflyMx Unlock');
butterflyService
.getCharacteristic(Characteristic.On)
.on('get', this.getSwitchOnCharacteristic.bind(this))
.on('set', this.setSwitchOnCharacteristic.bind(this));
return [informationService, butterflyService];
}
}
module.exports = function(homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
homebridge.registerAccessory('homebridge-butterfly-mx', 'ButterflyMx', butterflyMx);
}