-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
393 lines (348 loc) · 11.4 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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
'use strict';
/*
* Created with @iobroker/create-adapter v1.27.0
*/
// 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 MapHelper = require('./lib/maphelper');
const miio = require('./lib/miio');
const objects = require('./lib/objects');
const ViomiManager = require('./lib/viomi');
const VacuumManager = require('./lib/vacuum');
//const VacuumManager2 = require('./lib/vacuumsaphire');
let DeviceModel;
let connected = false;
let Miio;
let vacuum = null;
let Map;
const deviceList = {
//'mijia.vacuum.v2' : MiotVacuum, // Modell: Xiaomi mijia g1
//'dreame.vacuum.mc1808' : MiotVacuum, // Modell: Xioami mijia 1c
'viomi.vacuum.v7': ViomiManager,
'viomi.vacuum.v8': ViomiManager,
'viomi.vacuum.v19': ViomiManager, //test
'roborock.vacuum.s4': VacuumManager, // Roborock S4
'roborock.vacuum.s5': VacuumManager,
'roborock.vacuum.s5e': VacuumManager, // Roborock S5 Max
'roborock.vacuum.s6': VacuumManager,
'roborock.vacuum.m1s': VacuumManager,
'rockrobo.vacuum.v1': VacuumManager,
'roborock.vacuum.a10': VacuumManager,
'roborock.vacuum.a15': VacuumManager, // Roborock S7
// 'roborock.sweeper.e2v3': VacuumManager2,
// 'roborock.sweeper.e2v2': VacuumManager2,
// 'roborock.vacuum.e2': VacuumManager2,
// 'roborock.sweeper.c1v3': VacuumManager2,
// 'roborock.sweeper.c1v2': VacuumManager2,
// 'roborock.vacuum.c1': VacuumManager2,
// 'roborock.vacuum.a01': VacuumManager2,
// 'roborock.vacuum.a01v2': VacuumManager2,
// 'roborock.vacuum.a01v3': VacuumManager2,
// 'roborock.vacuum.a04': VacuumManager2,
// 'roborock.vacuum.a04v2': VacuumManager2,
// 'roborock.vacuum.a04v3': VacuumManager2
};
class MihomeVacuum extends utils.Adapter {
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
constructor(options) {
super({
...options,
name: 'mihome-vacuum',
});
this.on('ready', this.onReady.bind(this));
this.on('stateChange', this.onStateChange.bind(this));
this.on('message', this.onMessage.bind(this));
this.on('unload', this.onUnload.bind(this));
}
async main() {
this.config.port = parseInt(this.config.port, 10) || 54321;
this.config.ownPort = parseInt(this.config.ownPort, 10) || 53421;
this.config.pingInterval = parseInt(this.config.pingInterval, 10) || 20000;
// Abfrageintervall mindestens 10 sec.
if (this.config.pingInterval < 10000) {
this.config.pingInterval = 10000;
}
if (!this.config.token) {
this.log.warn('Token not specified!');
return
}
// create default States
await Promise.all(objects.deviceInfo.map(async o => {
await this.setObjectNotExistsAsync('deviceInfo' + (o._id ? '.' + o._id : ''), o);
this.log.debug('Create State for deviceInfo' + o._id);
}));
//create new miio class
Miio = new miio(this);
Miio.on('connect', async () => {
this.log.debug('MAIN: Connected to device, try to get model..');
await this.getModel();
this.subscribeStates('*');
});
//check if Self send Commands is enabled
if (this.config.enableSelfCommands) {
objects.customCommands.map(async o => await this.setObjectNotExistsAsync('control' + (o._id ? '.' + o._id : ''), o));
} else {
objects.customCommands.map(o => this.delObj('control' + (o._id ? '.' + o.id : '')));
}
//check if iotState is enabled
if (true || this.config.enableAlexa) {
this.log.info('IOT enabled, create state');
objects.iotState.map(o => this.setObjectNotExistsAsync('control' + (o._id ? '.' + o._id : ''), o));
} else {
this.log.info('IOT disabled, delete state');
objects.iotState.map(async o => await this.delObj('control' + (o._id ? '.' + o.id : '')));
}
}
/**
* first communication to find out the model
*/
async getModel() {
//try to get from Config
let configModel;
try {
configModel = JSON.parse(this.config.devices).model;
} catch (e) {
configModel = null;
}
const objModel = await this.getStateAsync('deviceInfo.model');
this.log.debug('GETMODELFROMAPI: objModel: ' + JSON.stringify(objModel));
let DeviceData;
// try 5 times to get data
for (let i = 0; i < 5; i++) {
DeviceData = await this.getModelFromApi();
this.log.debug('Get Device data..' + i);
if (DeviceData) {
this.log.debug('Get Device data from robot..');
await this.setModelInfoObject(DeviceData.result);
DeviceModel = DeviceData.result.model;
await this.setConnection(true);
break;
}
}
if (!DeviceData && objModel && objModel.val) {
this.log.warn('YOUR DEVICE IS CONNECTED BUT DID NOT ANSWER YET - CONNECTION CAN TAKE UP TO 10 MINUTES - PLEASE BE PATIENT AND DO NOT TURN THE ADAPTER OFF');
this.log.warn('No Answer for DeviceModel use old one');
DeviceModel = objModel.val;
}
if (!DeviceData && configModel) {
this.log.warn('No Answer for DeviceModel use model from Config');
DeviceModel = configModel;
await this.setModelInfoObject(JSON.parse(this.config.devices));
}
this.log.debug('DeviceModel selected to: ' + DeviceModel);
//we get a model so we can select a protocol
if (deviceList[DeviceModel]) {
this.device = DeviceModel;
vacuum = new deviceList[DeviceModel](this, Miio, Map);
} else {
if (typeof DeviceModel !== 'undefined') {
this.log.warn(`Model ${DeviceModel} not supported! Please open issue on git: https://github.com/iobroker-community-adapters/ioBroker.mihome-vacuum/issues`);
//try to get stock Model maybe it is working
let FirstDevMod = DeviceModel.split('.')[0]
this.device = DeviceModel;
if (FirstDevMod === 'viomi') {
vacuum = new ViomiManager(this, Miio);
} else if (FirstDevMod === 'roborock') {
vacuum = new VacuumManager(this, Miio, Map);
}
} else {
this.log.warn('Cant detect Device please select Device form Devicelist or enable the cloud of thr robot to get device infos');
this.log.warn('Fallback to Stock miio Protocol')
vacuum = new VacuumManager(this, Miio, Map);
}
}
}
/**
* function to set DeviceInfo
* @param {any} deviceInfo Model name from Xiaomi eg: viomi.vacuum.v8
*/
async setModelInfoObject(deviceInfo) {
await this.setStateAsync('deviceInfo.model', {
val: deviceInfo.model,
ack: true
});
await this.setStateAsync('deviceInfo.fw_ver', {
val: deviceInfo.fw_ver,
ack: true
});
await this.setStateAsync('deviceInfo.mac', {
val: deviceInfo.mac,
ack: true
});
return true;
}
/**
* Function to set the connection indicator
* @param {boolean} indicator could be true or false
*/
async setConnection(indicator) {
connected = indicator;
await this.setStateAsync('info.connection', {
val: indicator,
ack: true
});
}
async getModelFromApi() {
try {
const DeviceData = await Miio.sendMessage('miIO.info');
this.log.debug('GETMODELFROMAPI:Data: ' + JSON.stringify(DeviceData));
return DeviceData;
} catch (error) {
return null;
}
}
/**
* delete async function
* @param {string} id
*/
async delObj(id) {
try {
await this.delObjectAsync(id);
} catch (error) {
//... do nothing
}
}
/**
* Is called when databases are connected and adapter received configuration.
*/
async onReady() {
// Reset the connection indicator during startup
this.setConnection(false);
Map = new MapHelper(null, this);
//MAP.Init(); // for Map
this.main();
}
/**
* Is called when adapter shuts down - callback has to be called under any circumstances!
* @param {() => void} callback
*/
async onUnload(callback) {
try {
if (vacuum){
await vacuum.close();
}
if (Miio) {
Miio.close(callback);
} else {
callback();
}
} catch (e) {
callback();
}
}
// If you need to react to object changes, uncomment the following block and the corresponding line in the constructor.
// You also need to subscribe to the objects with `this.subscribeObjects`, similar to `this.subscribeStates`.
// /**
// * Is called if a subscribed object changes
// * @param {string} id
// * @param {ioBroker.Object | null | undefined} obj
// */
// onObjectChange(id, obj) {
// if (obj) {
// // The object was changed
// this.log.info(`object ${id} changed: ${JSON.stringify(obj)}`);
// } else {
// // The object was deleted
// this.log.info(`object ${id} deleted`);
// }
// }
/**
* Is called if a subscribed state changes
* @param {string} id
* @param {ioBroker.State | null | undefined} state
*/
async onStateChange(id, state) {
if (!state || state.ack) {
return;
}
// output to parser
const terms = id.split('.');
const command = terms.pop();
// Send own commands
if (command === 'X_send_command') {
const values = (state.val || '').trim().split(';');
let params = [''];
if (values[1]) {
try {
params = JSON.parse(values[1]);
} catch (e) {
return this.setState('control.X_get_response', 'Could not send these params because its not in JSON format: ' + values[1], true);
}
this.log.info(`send message: Method: ${values[0]} Params: ${values[1]}`);
} else {
this.log.info(`send message: Method: ${values[0]}`);
}
this.setStateAsync(id, state.val, true);
try {
const DeviceData = await Miio.sendMessage(values[0], params);
this.log.debug('Get self send data: ' + JSON.stringify(DeviceData));
this.setStateAsync('control.X_get_response', JSON.stringify(DeviceData.result), true);
} catch (error) {
this.setStateAsync('control.X_get_response', `[${error}]`, true);
}
}
vacuum && vacuum.stateChange(id, state);
}
/**
* Some message was sent to this instance over message box. Used by email, pushover, text2speech, ...
* Using this method requires "common.message" property to be set to true in io-package.json
* @param {ioBroker.Message} obj
*/
async onMessage(obj) {
if (typeof obj === 'object' && obj.message) {
if (obj.command === 'send') {
// e.g. send email or pushover or whatever
this.log.info('send command');
// Send response in callback if required
obj.callback && this.sendTo(obj.from, obj.command, 'Message received', obj.callback);
}
}
// responds to the adapter that sent the original message
const respond = response =>
obj.callback && this.sendTo(obj.from, obj.command, response, obj.callback);
// handle the message
if (obj) {
let params;
switch (obj.command) {
case 'discovery':
//adapter.log.info('discover' + JSON.stringify(obj))
Map.getDeviceStatus(obj.message.username, obj.message.password, obj.message.server, '{"getVirtualModel":false,"getHuamiDevices":0}')
.then(data => {
this.log.debug('discover__' + JSON.stringify(data));
respond(data);
})
.catch(err => {
this.log.info('discover ' + err);
respond({error: err});
});
return;
// ======================================================================
default:
//respond(predefinedResponses.ERROR_UNKNOWN_COMMAND);
//await vacuum.onMessage(obj)
//this.log.warn('gottosent vacuu '+ JSON.stringify(obj))
if (!vacuum) {
return respond({
error: new Error('Not initialized')
});
}
respond(await vacuum.onMessage(obj))
return
}
}
}
}
// @ts-ignore parent is a valid property on module
if (module.parent) {
// Export the constructor in compact mode
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
module.exports = (options) => new MihomeVacuum(options);
} else {
// otherwise start the instance directly
new MihomeVacuum();
}