Repository navigation
Expand file tree
/
Copy pathdevice.js
More file actions
253 lines (227 loc) · 8.17 KB
/
Copy pathdevice.js
File metadata and controls
253 lines (227 loc) · 8.17 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
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
const { user } = require('./routes');
/* function for convert system values to Yandex (depends of capability or property type) */
function convertToYandexValue(val, actType) {
switch(actType) {
case 'range':
case 'float': {
if (val == undefined) return 0.0;
try {
const value = parseFloat(val);
return isNaN(value) ? 0.0 : value;
} catch(e) {
console.error(`Can't parse to float: ${val}`);
return 0.0;
}
}
case 'toggle':
case 'on_off': {
if (val == undefined) return false;
if (['true', 'on', '1'].indexOf(String(val).toLowerCase()) != -1) return true;
else return false;
}
default:
return val;
}
}
/* Device class defenition */
class Device {
constructor(options) {
const id = global.devices.length;
this.data = {
id: options.id || String(id),
name: options.name || 'Без названия',
description: options.description || '',
room: options.room || '',
type: options.type || 'devices.types.light',
custom_data: {
mqtt: options.mqtt || [],
valueMapping: options.valueMapping || [],
},
capabilities: (options.capabilities || []).map(c => Object.assign({}, c, {state: (c.state == undefined) ? this.initState(c) : c.state})),
properties: (options.properties || []).map(p => Object.assign({}, p, {state: (p.state == undefined) ? this.initState(p) : p.state}))
}
}
/* Create init state on device object create */
initState(cp) {
const {type, parameters} = cp;
const actType = String(type).split('.')[2];
switch(actType) {
case 'float': {
return {
instance: parameters.instance,
value: 0
}
}
case 'on_off': {
return {
instance: 'on',
value: false
}
}
case 'toggle': {
return {
instance: parameters.instance,
value: false
}
}
case 'range': {
return {
instance: parameters.instance,
value: parameters.range.min
}
}
case 'mode': {
return {
instance: parameters.instance,
value: parameters.modes[0].value
}
}
default: {
console.error(`Unsupported capability type: ${type}`)
return undefined;
}
}
}
/* Get mapped value (if exist) for capability type */
/**
*
* @param {*} val value
* @param {*} actType capability type
* @param {*} y2m mapping direction (yandex to mqtt, mqtt to yandex)
*/
getMappedValue(val, actType, y2m) {
const map = this.data.custom_data.valueMapping.find(m => m.type == actType);
if (map == undefined) return val;
var from, to;
if (y2m == true) [from, to] = map.mapping;
else [to, from] = map.mapping;
const mappedValue = to[from.indexOf(val)];
return (mappedValue != undefined) ? mappedValue : val;
}
/* Find capability by type */
findCapability(type) {
return this.data.capabilities.find(c => c.type === type);
}
/* Unused for now */
findProperty(type) {
return this.data.properties.find(p => p.type === type);
}
/* Find 'set' topic by instance*/
findTopicByInstance(instance) {
return this.data.custom_data.mqtt.find(i => i.instance === instance).set;
}
getInfo() {
const {id, name, description, room, type, capabilities, properties} = this.data;
return {id, name, description, room, type, capabilities, properties};
}
/* Get only needed for response device info (bun not full device defenition) */
getState () {
const {id, capabilities, properties} = this.data;
const device = {
id,
capabilities: (() => {
return capabilities.filter(c => c.retrievable === true).map(c => {
return {
type: c.type,
state: c.state
}
})
})() || [],
properties: (() => {
return properties.filter(p => p.retrievable === true).map(p => {
return {
type: p.type,
state: p.state
}
})
})() || [],
}
return device;
}
/* Change device capability state and publish value to MQTT topic */
setCapabilityState(val, type, instance) {
const {id} = this.data;
const actType = String(type).split('.')[2];
const value = this.getMappedValue(val, actType, true);
let message;
let topic;
try {
const capability = this.findCapability(type);
if (capability == undefined) throw new Error(`Can't find capability '${type}' in device '${id}'`);
capability.state.value = value;
topic = this.findTopicByInstance(instance);
if (topic == undefined) throw new Error(`Can't find set topic for '${type}' in device '${id}'`);
message = `${value}`;
} catch(e) {
topic = false;
console.log(e);
}
if (topic) {
global.mqttClient.publish(topic, message);
}
return {
type,
'state': {
instance,
'action_result': {
'status': 'DONE'
}
}
}
}
/* Update device capability or property state */
updateState(val, instance) {
const {id, capabilities, properties} = this.data;
try {
const cp = [].concat(capabilities, properties).find(cp => (cp.state.instance === instance));
if (cp == undefined) throw new Error(`Can't instance '${instance}' in device '${id}'`);
const actType = String(cp.type).split('.')[2];
const value = this.getMappedValue(val, actType, false);
cp.state = {instance, value: convertToYandexValue(value, actType)};
} catch(e) {
console.error(e);
}
}
/* Update device state in Yandex for each user with token*/
updateYandexState(){
const {id, capabilities, properties} = this.data;
const rp = require('request-promise');
try {
const users = global.authl.data
users.forEach(user => {
const body = {
"ts": Math.floor(Date.now()/1000),
"payload": {
"user_id": user.userId,
"devices": [{
"id":id,
"capabilities": capabilities,
"properties": properties
}]
}
}
var options = {
method: 'POST',
uri: `https://dialogs.yandex.net/api/v1/skills/${global.dialogs.skillId}/callback/state`,
headers:
{
'Content-Type': 'application/json',
'Authorization': 'OAuth ' + global.dialogs.dialogToken
},
body: body,
json: true // Automatically stringifies the body to JSON
};
rp(options)
.then(function (parsedBody) {
console.log(parsedBody)
})
.catch(function (err) {
console.error('error sending data: ',err.message)
});
});
} catch(e){
console.error(e)
}
}
}
module.exports = Device;