-
Notifications
You must be signed in to change notification settings - Fork 2
/
gadget.js
495 lines (407 loc) · 16.3 KB
/
gadget.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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
'use strict';
var _ = require('busyman');
var utils = require('./utils.js'),
validate = utils.validate,
Device = require('./device.js'),
EVTS = require('freebird-constants').EVENTS_FROM_BOTTOM;
var baseProp = { writable: true, enumerable: false, configurable: false };
function Gadget(dev, auxId, rawGad) {
if (!(this instanceof Gadget))
return new Gadget(dev, auxId, rawGad);
validate.device(dev);
validate.stringOrNumber(auxId, 'auxId should be a number or a string.');
Object.defineProperty(this, '_recovering', _.assign({ value: false }, baseProp)); // helper, tag if it is reload from database
Object.defineProperty(this, '_id', _.assign({ value: null }, baseProp));
Object.defineProperty(this, '_auxId', _.assign({ value: auxId }, baseProp));
Object.defineProperty(this, '_dev', _.assign({ value: dev }, baseProp));
Object.defineProperty(this, '_raw', _.assign({ value: rawGad }, baseProp)); // optional
Object.defineProperty(this, '_panel', _.assign({
value: {
enabled: false, // 'enabled' cannot be set through setPanelInfo()
classId: '', // required
profile: ''
}
}, baseProp, { writable: false }));
Object.defineProperty(this, '_props', _.assign({
value: {
name: 'unknown',
description: ''
}
}, baseProp, { writable: false }));
Object.defineProperty(this, '_attrs', _.assign({ value: {} }, baseProp, { writable: false })); // other kvps from remote gadget
this.extra = null; // developer sets at will
dev._linkGad(this._auxId, this);
}
/*************************************************************************************************/
/*** Gadget Public APIs ***/
/*************************************************************************************************/
Gadget.prototype.isEnabled = function () {
return this._panel.enabled;
};
Gadget.prototype.isRegistered = function () {
return !_.isNil(this._id);
};
Gadget.prototype.enable = function () {
if (!this.isEnabled()) {
this._panel.enabled = true;
this._handoff(EVTS.GadPanelChanged, { data: { enabled: true } });
}
return this;
};
Gadget.prototype.disable = function () {
if (this.isEnabled()) {
this._panel.enabled = false;
// if disabled, cannot fire event. use this bridging event
this._handoff(EVTS.GadPanelChangedDisabled, { data: { enabled: false } });
}
return this;
};
/*************************************************************************************************/
/*** Gadget Public APIs: Protected Member Getters ***/
/*************************************************************************************************/
Gadget.prototype.get = function (name, arg) {
var result;
validate.string(name, 'name should be a string.');
switch (name) {
case 'id':
result = this._id;
break;
case 'device':
result = this._dev;
break;
case 'raw':
result = this._raw;
break;
case 'permAddr':
result = this._dev ? this._dev.get('permAddr') : undefined;
break;
case 'dynAddr':
result = this._dev ? this._dev.get('dynAddr') : undefined;
break;
case 'auxId':
result = this._auxId;
break;
case 'netcore':
result = this._dev ? this._dev.get('netcore') : undefined;
break;
case 'location':
var loc = this._dev ? this._dev.get('props', 'location') : undefined; // { location: 'xxx' }
result = _.isObject(loc) ? loc.location : undefined;
break;
case 'panel':
result = utils.getFrom(this, '_panel', arg);
break;
case 'props':
result = utils.getFrom(this, '_props', arg);
break;
case 'attrs':
result = utils.getFrom(this, '_attrs', arg);
break;
default:
break;
}
return result;
};
Gadget.prototype.set = function (name, value) {
var self = this,
oldData, delta;
validate.string(name, 'name should be a string.');
switch (name) {
case '_id':
validate.stringOrNumber(value, '_id should be a number or a string.');
this._id = value; // value = id
this.get('device')._connectGadIdToAuxId(this._id, this.get('auxId'));
break;
case '_dev':
validate.device(value);
this._dev = value; // value = dev
break;
case '_raw':
this._raw = value; // value = raw
break;
case 'panel': // setPanelInfo
validate.object(value, 'Input info should be an object');
delta = utils.getObjectDiff(value, this.get('panel')); // value = info
delete delta.enabled; // 'enabled' cannot be set through set('panel')
if (!_.isEmpty(delta)) {
// picks old data up to _data
oldData = {};
_.forEach(delta, function (v, k) {
oldData[k] = self._panel[k];
});
_.merge(this._panel, delta);
this._handoff(EVTS.GadPanelChanged, { data: delta, _data: oldData });
}
break;
case 'props': // setProps
validate.object(value, 'Input props should be an object');
delta = utils.getObjectDiff(value, this.get('props')); // value = props
if (!_.isEmpty(delta)) {
// picks old data up to _data
oldData = {};
_.forEach(delta, function (v, k) {
oldData[k] = self._props[k];
});
_.merge(this._props, delta);
this._handoff(EVTS.GadPropsChanged, { data: delta, _data: oldData });
}
break;
case 'attrs': // setAttrs
validate.object(value, 'Input attrs should be an object');
delta = utils.getObjectDiff(value, this.get('attrs')); // value = attrs
if (!_.isEmpty(delta)) {
// picks old data up to _data
oldData = {};
_.forEach(delta, function (v, k) {
oldData[k] = self._attrs[k];
});
_.merge(this._attrs, delta);
this._handoff(EVTS.GadAttrsChanged, { data: delta, _data: oldData });
}
break;
default:
break;
}
return this;
};
Gadget.prototype.dump = function () {
var nc = this.get('netcore'),
dev = this.get('device');
return {
netcore: nc ? nc.getName() : 'unknown',
id: this.get('id'),
auxId: this.get('auxId'),
dev: {
id: dev ? dev.get('id') : null,
permAddr: dev ? dev.get('permAddr') : ''
},
panel: this.get('panel'),
attrs: this.get('attrs'),
props: this.get('props')
};
};
/*************************************************************************************************/
/*** Gad Drivers ***/
/*************************************************************************************************/
Gadget.prototype.read = function (attrName, callback) {
validate.argTypes({ attrName: attrName, callback: callback });
var self = this,
nc = this.get('netcore'),
read = nc ? nc._findDriver('gad', 'read') : undefined,
err = anyEnableError.call(this),
permAddr = this.get('permAddr'),
auxId = this.get('auxId');
if (err)
return setImmediate(callback, err);
else if (!_.isFunction(read))
return setImmediate(callback, 'Gadget driver read is not implemented');
read(permAddr, auxId, attrName, function (err, data) {
var result;
if (!err) {
result = _.set({}, attrName, data);
self.set('attrs', result);
self._handoff(EVTS.GadRead, { permAddr: permAddr, auxId: auxId, data: result });
}
callback(err, data);
});
};
Gadget.prototype.write = function (attrName, val, callback) {
validate.argTypes({ attrName: attrName, val: val, callback: callback });
var self = this,
nc = this.get('netcore'),
write = nc ? nc._findDriver('gad', 'write') : undefined,
err = anyEnableError.call(this),
permAddr = this.get('permAddr'),
auxId = this.get('auxId');
if (err)
return setImmediate(callback, err);
else if (!_.isFunction(write))
return setImmediate(callback, 'Gadget driver write is not implemented');
write(permAddr, auxId, attrName, val, function (err, data) {
var result;
if (!err) {
result = _.set({}, attrName, _.isNil(data) ? val : data);
self.set('attrs', result);
self._handoff(EVTS.GadWrite, { permAddr: permAddr, auxId: auxId, data: result });
}
callback(err, _.isNil(data) ? val : data);
});
};
Gadget.prototype.exec = function (attrName, args, callback) {
if (_.isFunction(args)) {
callback = args;
args = undefined;
}
validate.argTypes({ attrName: attrName, callback: callback });
validate.array(args, 'args should be an array.');
var self = this,
nc = this.get('netcore'),
exec = nc ? nc._findDriver('gad', 'exec') : undefined,
err = anyEnableError.call(this),
permAddr = this.get('permAddr'),
auxId = this.get('auxId');
if (err)
return setImmediate(callback, err);
else if (!_.isFunction(exec))
return setImmediate(callback, 'Gadget driver exec is not implemented');
exec(permAddr, auxId, attrName, args, function (err, data) {
var result;
if (!err) {
result = _.set({}, attrName, data);
self._handoff(EVTS.GadExec, { permAddr: permAddr, auxId: auxId, data: result });
}
callback(err, data);
});
};
Gadget.prototype.readReportCfg = function (attrName, callback) {
validate.argTypes({ attrName: attrName, callback: callback });
var self = this,
nc = this.get('netcore'),
readReportCfg = nc ? nc._findDriver('gad', 'readReportCfg') : undefined,
err = anyEnableError.call(this),
permAddr = this.get('permAddr'),
auxId = this.get('auxId');
if (err)
return setImmediate(callback, err);
else if (!_.isFunction(readReportCfg))
return setImmediate(callback, 'Gadget driver readReportCfg is not implemented');
readReportCfg(permAddr, auxId, attrName, function (err, data) {
var result;
if (!err) {
result = _.set({}, attrName, data);
self._handoff(EVTS.GadReadReportCfg, { permAddr: permAddr, auxId: auxId, data: result });
}
callback(err, data);
});
};
Gadget.prototype.writeReportCfg = function (attrName, cfg, callback) {
validate.argTypes({ attrName: attrName, cfg: cfg, callback: callback });
if (_.isFunction(cfg)) {
callback = cfg;
cfg = undefined;
}
var self = this,
nc = this.get('netcore'),
writeReportCfg = nc ? nc._findDriver('gad', 'writeReportCfg') : undefined,
err = anyEnableError.call(this),
permAddr = this.get('permAddr'),
auxId = this.get('auxId');
if (err)
return setImmediate(callback, err);
else if (!_.isFunction(writeReportCfg))
return setImmediate(callback, 'Gadget driver writeReportCfg is not implemented');
writeReportCfg(permAddr, auxId, attrName, cfg, function (err, data) {
var result;
if (!err) {
result = _.set({}, attrName, data);
self._handoff(EVTS.GadWriteReportCfg, { permAddr: permAddr, auxId: auxId, data: result });
}
callback(err, data);
});
};
Gadget.prototype.maintain = function (callback) {
var self = this,
dev = this.get('device'),
nc = this.get('netcore');
callback = callback || function (err) {
if (err)
self._handoff(EVTS.GadError, { error: err });
};
if (!_.isFunction(callback))
throw new TypeError('callback should be a function if given');
if (!nc || !dev)
return setImmediate(callback, new Error('Cannot maintain. Gadget is not registered properly'));
else if (!this.isEnabled() || dev.get('status') === 'offline')
return setImmediate(callback, null); // offline or disabled, no need to maintain
var clonedAttrs = this.get('attrs'),
attrNames = _.keys(clonedAttrs),
isModified = false,
cbCalled = false;
keepReading();
function keepReading() {
var attrName;
if (cbCalled)
return;
if (dev.get('status') === 'offline') {
cbCalled = true;
return setImmediate(callback, null); // offline or disabled, no need to continue maintaining
}
if (attrNames.length === 0) {
if (isModified)
self.set('attrs', clonedAttrs);
cbCalled = true;
return callback(null);
}
attrName = attrNames.pop();
self.read(attrName, function (err, data) { // don't care error, keep reading
if (!err) {
clonedAttrs[attrName] = data;
isModified = true;
}
keepReading();
});
}
};
/*************************************************************************************************/
/*** Gadget Protected APIs ***/
/*************************************************************************************************/
Gadget.prototype._recoverFromRecord = function (rec) {
// recovering, but no raw, no extra
this._recovering = true;
this.set('_id', rec.id);
this.set('panel', rec.panel); // enabled will be ignored
this.set('attrs', rec.attrs);
this.set('props', rec.props);
// it was enabled before. Enable after all 'setXXX()' completes, to avoid changed events
if (rec.panel.enabled)
this.enable();
return this;
};
Gadget.prototype._handoff = function (evt, data) {
// validate.string(evt, 'evt should be a string.');
var nc = this.get('netcore'),
emitData = {},
isErrEvt = (evt === EVTS.GadError),
isPanelChangedDisabled = (evt === EVTS.GadPanelChangedDisabled), // 'panelChanged_Disabled' is a bridge event
isRegEn = (this.isRegistered() && this.isEnabled() && !this._recovering),
emittable = isErrEvt || isRegEn || isPanelChangedDisabled;
if (!this.isRegistered() || this._recovering)
return false;
if (!emittable)
return false;
data = data || {};
_.assign(emitData, data, { permAddr: this.get('permAddr'), auxId: this.get('auxId'), id: this.get('id') });
evt = isPanelChangedDisabled ? EVTS.GadPanelChanged : evt;
return nc._fireup(evt, emitData);
}; // { ncName: 'xxx', id: 68, ... }, ncName tagged@netcore
Gadget.prototype._clear = function () {
var dev = this.get('device');
if (dev) // this gad is not an orphan
dev._unlinkGad(this.get('id'), this.get('auxId'));
this._id = null;
this._dev = null;
this._raw = null;
this.extra = null;
};
Gadget.prototype._dangerouslyAppendAttrs = function (attrs) {
validate.object(attrs, 'Input attrs should be an object');
if (!_.isEmpty(attrs)) {
_.merge(this._attrs, attrs);
this._handoff(EVTS.GadAttrsAppend, { data: this._attrs });
}
return this;
};
/*************************************************************************************************/
/*** Private Helpers ***/
/*************************************************************************************************/
function anyEnableError() {
var err;
if (!this.isEnabled())
err = new Error('Gadget disabled.');
else if (!this.get('device').isEnabled())
err = new Error('Device disabled.');
else if (!this.get('netcore').isEnabled())
err = new Error('Netcore disabled.');
return err;
}
module.exports = Gadget;