-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.js
362 lines (339 loc) · 12.9 KB
/
main.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
'use strict';
/*
* Created with @iobroker/create-adapter v2.0.1
*/
// The adapter-core module gives you access to the core ioBroker functions
// you need to create an adapter
const utils = require('@iobroker/adapter-core');
const axios = require('axios').default;
const Json2iob = require('json2iob');
const OcfDeviceFactory = require('./lib/ocf/ocfDeviceFactory');
class Smartthings extends utils.Adapter {
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
constructor(options) {
super({
...options,
name: 'smartthings',
});
this.on('ready', this.onReady.bind(this));
this.on('stateChange', this.onStateChange.bind(this));
this.on('unload', this.onUnload.bind(this));
this.requestClient = axios.create();
this.updateInterval = null;
this.reLoginTimeout = null;
this.json2iob = new Json2iob(this);
this.deviceArray = [];
this.session = {};
this.ocfDeviceFactory = new OcfDeviceFactory();
}
/**
* Is called when databases are connected and adapter received configuration.
*/
async onReady() {
// Reset the connection indicator during startup
this.setState('info.connection', false, true);
if (this.config.interval < 1) {
this.log.info('Set interval to minimum 1');
this.config.interval = 1;
}
this.subscribeStates('*');
if (this.config.token) {
await this.getDeviceList();
await this.updateDevices();
this.updateInterval = setInterval(async () => {
await this.updateDevices();
}, this.config.interval * 1000);
if (this.config.virtualInterval > 0) {
this.updateVirtualInterval = setInterval(async () => {
await this.updateDevices(true);
}, this.config.virtualInterval * 1000);
}
} else {
this.log.info('Please enter a Samsung Smartthings Token');
}
}
async getDeviceList() {
await this.requestClient({
method: 'get',
url: 'https://api.smartthings.com/v1/devices',
headers: {
'User-Agent': 'ioBroker',
Authorization: 'Bearer ' + this.config.token,
},
})
.then(async (res) => {
this.log.debug(JSON.stringify(res.data));
this.setState('info.connection', true, true);
this.log.info(res.data.items.length + ' devices detected');
for (const device of res.data.items) {
const exlcudeList = this.config.excludeDevices.replace(/ /g, '').split(',');
if (exlcudeList && exlcudeList.includes(device.deviceId)) {
this.log.info('Ignore ' + device.deviceId);
continue;
}
this.deviceArray.push({ id: device.deviceId, type: device.deviceTypeName });
await this.setObjectNotExistsAsync(device.deviceId, {
type: 'device',
common: {
name: device.label,
},
native: {},
});
await this.setObjectNotExistsAsync(device.deviceId + '.capabilities', {
type: 'channel',
common: {
name: 'Capabilities/Remote Controls',
},
native: {},
});
await this.setObjectNotExistsAsync(device.deviceId + '.general', {
type: 'channel',
common: {
name: 'General Information',
},
native: {},
});
// const remoteArray = [];
if (device.components && device.components[0] && device.components[0].capabilities) {
device.components[0].capabilities.forEach(async (capability) => {
await this.requestClient({
method: 'get',
url: 'https://api.smartthings.com/v1/capabilities/' + capability.id + '/' + capability.version,
headers: {
'User-Agent': 'ioBroker',
Authorization: 'Bearer ' + this.config.token,
},
})
.then(async (res) => {
this.log.debug(JSON.stringify(res.data));
const idName = res.data.id;
Object.keys(res.data.commands).forEach(async (element) => {
const common = {
name: '',
type: 'boolean',
role: 'boolean',
write: true,
read: true,
};
const letsubIdName = idName + '-' + element;
let commandCreated = false;
if (idName === 'ocf' && element === 'postOcfCommand') {
const ocfDevice = this.ocfDeviceFactory.getOcfDevice(device.deviceManufacturerCode, device.presentationId);
if (ocfDevice) {
const ocfDeviceCommands = ocfDevice.getOcfCommands();
for (const ocfDeviceCommandName in ocfDeviceCommands) {
const ocfDeviceCommand = ocfDeviceCommands[ocfDeviceCommandName];
const objectRaw = {
type: 'state',
common: {
name: '',
type: ocfDeviceCommand.iobroker ? ocfDeviceCommand.iobroker.type : ocfDeviceCommand.type,
role: ocfDeviceCommand.iobroker ? ocfDeviceCommand.iobroker.type : ocfDeviceCommand.type,
min: ocfDeviceCommand.iobroker && ocfDeviceCommand.iobroker.min ? ocfDeviceCommand.iobroker.min : 0,
max: ocfDeviceCommand.iobroker && ocfDeviceCommand.iobroker.max ? ocfDeviceCommand.iobroker.max : 0,
states:
ocfDeviceCommand.iobroker && ocfDeviceCommand.iobroker.states ? ocfDeviceCommand.iobroker.states : null,
write: true,
read: true,
},
native: {
type: 'OcfCommand',
deviceManufacturerCode: device.deviceManufacturerCode,
presentationId: device.presentationId,
deviceId: device.deviceId,
commandName: ocfDeviceCommandName,
},
};
await this.setObjectNotExistsAsync(
device.deviceId + '.capabilities.' + letsubIdName + '.' + ocfDeviceCommandName,
objectRaw,
);
}
commandCreated = true;
}
}
if (!commandCreated) {
if (res.data.commands[element].arguments[0]) {
common.type = res.data.commands[element].arguments[0].schema.type;
if (common.type === 'integer') {
common.type = 'number';
}
common.role = 'state';
if (res.data.commands[element].arguments[0].schema.enum) {
common.states = {};
res.data.commands[element].arguments[0].schema.enum.forEach((enumElement) => {
common.states[enumElement] = enumElement;
});
}
}
await this.setObjectNotExistsAsync(device.deviceId + '.capabilities.' + letsubIdName, {
type: 'state',
common: common,
native: {},
});
}
});
})
.catch((error) => {
this.log.error(error);
error.response && this.log.error(JSON.stringify(error.response.data));
});
});
}
await this.json2iob.parse(device.deviceId + '.general', device);
}
})
.catch((error) => {
this.log.error(error);
error.response && this.log.error(JSON.stringify(error.response.data));
});
}
async updateDevices(onlyVirtualSwitch) {
const statusArray = [
{
path: 'status',
url: 'https://api.smartthings.com/v1/devices/$id/status',
desc: 'Status of the device',
},
];
const headers = {
'User-Agent': 'ioBroker',
Authorization: 'Bearer ' + this.config.token,
};
this.deviceArray.forEach(async (device) => {
if (onlyVirtualSwitch) {
if (device.type !== 'Virtual Switch') {
return;
}
}
statusArray.forEach(async (element) => {
const url = element.url.replace('$id', device.id);
await this.requestClient({
method: 'get',
url: url,
headers: headers,
})
.then(async (res) => {
this.log.debug(JSON.stringify(res.data));
if (!res.data) {
return;
}
let data = res.data;
let keys = Object.keys(data);
if (keys.length === 1) {
data = data[keys[0]];
}
keys = Object.keys(data);
if (keys.length === 1) {
data = data[keys[0]];
}
const forceIndex = undefined;
const preferedArrayName = undefined;
await this.json2iob.parse(device.id + '.' + element.path, data, {
forceIndex: forceIndex,
preferedArrayName: preferedArrayName,
channelName: element.desc,
excludeStateWithEnding: this.config.exclude.replace(/ /g, '').split(','),
});
})
.catch((error) => {
if (error.response && error.response.status === 401) {
error.response && this.log.debug(JSON.stringify(error.response.data));
this.log.info(element.path + ' receive 401 error. Please use new Token');
return;
}
this.log.error(url);
this.log.error(error);
error.response && this.log.error(JSON.stringify(error.response.data));
});
});
});
}
/**
* Is called when adapter shuts down - callback has to be called under any circumstances!
* @param {() => void} callback
*/
onUnload(callback) {
try {
this.setState('info.connection', false, true);
clearTimeout(this.refreshTimeout);
this.updateInterval && clearInterval(this.updateInterval);
clearInterval(this.updateVirtualInterval);
callback();
} catch (e) {
callback();
}
}
/**
* Is called if a subscribed state changes
* @param {string} id
* @param {ioBroker.State | null | undefined} state
*/
async onStateChange(id, state) {
if (state) {
if (!state.ack) {
const idArray = id.split('.');
const deviceId = idArray[2];
idArray.splice(0, 4);
let capadId = idArray.join('.');
const commandId = capadId.split('-')[1];
capadId = capadId.split('-')[0];
let data = { commands: [{ capability: capadId, command: commandId }] };
if (typeof state.val !== 'boolean') {
data.commands[0].arguments = [state.val];
}
if (capadId === 'ocf' && commandId.startsWith('postOcfCommand')) {
const commandObject = await this.getForeignObjectAsync(id).then((result) => result);
if (commandObject) {
const candidate = this.ocfDeviceFactory.getOcfCommandData(
commandObject.native.deviceManufacturerCode,
commandObject.native.presentationId,
commandObject.native.deviceId,
commandObject.native.commandName,
state.val,
);
if (candidate !== null) {
data = candidate;
}
}
}
this.log.info(JSON.stringify(data));
await this.requestClient({
method: 'post',
url: 'https://api.smartthings.com/v1/devices/' + deviceId + '/commands',
headers: {
'User-Agent': 'ioBroker',
Authorization: 'Bearer ' + this.config.token,
},
data: data,
})
.then((res) => {
this.log.info(JSON.stringify(res.data));
return res.data;
})
.catch((error) => {
this.log.error(error);
if (error.response) {
this.log.error(JSON.stringify(error.response.data));
}
});
clearTimeout(this.refreshTimeout);
this.refreshTimeout = setTimeout(async () => {
await this.updateDevices();
}, 10 * 1000);
}
}
}
}
if (require.main !== module) {
// Export the constructor in compact mode
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
module.exports = (options) => new Smartthings(options);
} else {
// otherwise start the instance directly
new Smartthings();
}