-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathdevice-miio.js
205 lines (178 loc) · 5.25 KB
/
device-miio.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
const EventEmitter = require('events');
const fetch = require('node-fetch');
const miioProtocol = require('./protocol-miio');
const miCloudProtocol = require('./protocol-micloud');
const sleep = time => {
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, time);
});
};
module.exports = class MiioDevice extends EventEmitter {
constructor({
id, address, token, protocol, refresh,
}) {
super();
this.id = String(id);
this.address = address;
this.token = token;
this.protocol = protocol || 'local';
this.refresh = refresh >= 0 ? refresh : 15000;
this._properties = {};
this._propertiesToMonitor = [];
this._miotSpec = null;
this._miotSpecType = null;
miioProtocol.updateDevice(address, {
id,
token,
});
}
get properties() {
return { ...this._properties };
}
async init() {
if (this._miotSpecType) {
await this.miotFetchSpec(this._miotSpecType);
}
await this.loadProperties();
await this.poll();
}
destroy() {
if (this._refreshInterval) {
clearInterval(this._refreshInterval);
}
}
async send(method, params, options = {}) {
const result = this.protocol === 'cloud' ? await this.cloudSend(method, params, options) : this.localSend(method, params, options);
return result;
}
async localSend(method, params, options = {}) {
const result = await miioProtocol.send(this.address, method, params, options);
return result;
}
async cloudSend(method, params, options) {
const result = await miCloudProtocol.miioCall(this.id, method, params, options);
return result;
}
async poll() {
if (this.refresh > 0) {
this._refreshInterval = setInterval(async () => {
await this.loadProperties();
}, this.refresh);
}
}
async loadProperties(props) {
try {
if (typeof props === 'undefined') {
props = this._propertiesToMonitor;
}
const data = {};
const propsChunks = [];
const chunkSize = 16;
for (let i = 0; i < props.length; i += chunkSize) {
propsChunks.push(props.slice(i, i + chunkSize));
}
let result = [];
for (const propChunk of propsChunks) {
const resultChunk = await this.getProperties(propChunk);
if (!resultChunk) {
throw new Error('Properties is empty');
}
if (resultChunk.length !== propChunk.length) {
throw new Error(`Result ${JSON.stringify(resultChunk)} and props ${JSON.stringify(propChunk)} does not match length`);
}
result = result.concat(resultChunk);
}
props.forEach((prop, i) => {
const value = result[i];
data[prop] = value;
});
this._properties = Object.assign(this._properties, data);
this.emit('available', true);
this.emit('properties', data);
} catch (e) {
this.emit('unavailable', e.message);
}
}
async getProperties(props) {
const result = this._miotSpec
? await this.miotGetProperties(props) : await this.miioGetProperties(props);
return result;
}
async miioGetProperties(props) {
const result = await this.send('get_prop', props, {
retries: 1,
});
return result;
}
async miotGetProperties(props) {
const did = this.id;
const params = props.map(prop => {
const { siid, piid } = this._miotSpec[prop];
return { did, siid, piid };
});
const result = await this.send('get_properties', params, {
retries: 1,
});
return result.map(({ code, value }) => {
if (code === 0) {
return value;
}
return undefined;
});
}
async miioCall(method, params, options = {}) {
const result = await this.send(method, params, options);
if (options.refresh !== false) {
await sleep(50);
await this.loadProperties(options.refresh);
}
// TODO check OK
return result;
}
async miotSetProperty(prop, value, options = {}) {
if (!this._miotSpec) {
throw new Error('This device don\'t config miot spec');
}
const def = this._miotSpec[prop];
if (!def) {
throw new Error(`Property ${prop} is not define`);
}
const { siid, piid } = def;
const did = this.id;
const result = await this.send('set_properties', [{
did, siid, piid, value,
}]);
if (!result || !result[0] || result[0].code !== 0) {
throw new Error('Could not perform operation');
}
if (options.refresh !== false) {
await sleep(50);
await this.loadProperties(options.refresh);
}
return result[0];
}
async miotFetchSpec(spec) {
const url = `https://miot-spec.org/miot-spec-v2/instance?type=${spec}`;
const res = await fetch(url);
if (!res.ok) {
throw new Error(`Get spec error with status ${res.statusText}`);
}
const { services } = await res.json();
const result = {};
services.forEach(service => {
const { properties } = service;
properties.forEach(property => {
const key = [service.type.split(':')[3], property.type.split(':')[3]].join(':');
result[key] = {
siid: service.iid,
piid: property.iid,
desc: `${service.description} - ${property.description}`,
};
});
});
this._miotSpec = result;
return result;
}
};