2020-01-09 13:47:19 -07:00
|
|
|
const events = require('events');
|
|
|
|
const assert = require('assert');
|
|
|
|
|
|
|
|
const allowedEvents = [
|
|
|
|
'deviceRemoved', // Device has been removed
|
2020-03-04 04:55:08 -07:00
|
|
|
'deviceRenamed', // Device has been renamed
|
|
|
|
'groupRenamed', // Group has been renamed
|
2020-02-29 10:07:15 -07:00
|
|
|
'publishEntityState', // Entity state will be published
|
2020-04-05 06:48:23 -07:00
|
|
|
'stateChange', // Entity changes its state
|
2020-07-13 12:45:44 -07:00
|
|
|
'groupMembersChanged', // Members of a group has been changed
|
2020-08-04 10:11:13 -07:00
|
|
|
'reportingDisabled', // Reporting is disabled for a device
|
2020-09-15 13:13:30 -07:00
|
|
|
'devicesChanged', // Devices changed
|
2020-01-09 13:47:19 -07:00
|
|
|
];
|
|
|
|
|
|
|
|
class EventBus extends events.EventEmitter {
|
2020-07-29 14:10:03 -07:00
|
|
|
constructor() {
|
|
|
|
super();
|
|
|
|
this.callbackByExtension = {};
|
|
|
|
}
|
|
|
|
|
2020-01-09 13:47:19 -07:00
|
|
|
emit(event, data) {
|
|
|
|
assert(allowedEvents.includes(event), `Event '${event}' not supported`);
|
|
|
|
super.emit(event, data);
|
|
|
|
}
|
|
|
|
|
2020-07-29 14:10:03 -07:00
|
|
|
on(event, callback, extension=null) {
|
2020-01-09 13:47:19 -07:00
|
|
|
assert(allowedEvents.includes(event), `Event '${event}' not supported`);
|
2020-07-29 14:10:03 -07:00
|
|
|
if (extension) {
|
|
|
|
if (!this.callbackByExtension[extension]) this.callbackByExtension[extension] = [];
|
|
|
|
this.callbackByExtension[extension].push({event, callback});
|
|
|
|
}
|
|
|
|
|
2020-01-09 13:47:19 -07:00
|
|
|
super.on(event, callback);
|
|
|
|
}
|
2020-07-29 14:10:03 -07:00
|
|
|
|
|
|
|
removeListenersExtension(extension) {
|
|
|
|
for (const entry of this.callbackByExtension[extension] || []) {
|
|
|
|
super.removeListener(entry.event, entry.callback);
|
|
|
|
}
|
|
|
|
}
|
2020-01-09 13:47:19 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = EventBus;
|