MagicMirror/js/socketclient.js

54 lines
1.3 KiB
JavaScript
Raw Normal View History

2020-05-02 10:39:09 +02:00
/* global io */
/* Magic Mirror
* TODO add description
*
* By Michael Teeuw https://michaelteeuw.nl
* MIT Licensed.
*/
2021-04-10 08:21:27 +02:00
const MMSocket = function (moduleName) {
2016-04-05 14:35:11 -04:00
if (typeof moduleName !== "string") {
throw new Error("Please set the module name for the MMSocket.");
}
2021-04-10 08:21:27 +02:00
this.moduleName = moduleName;
// Private Methods
2021-04-10 08:21:27 +02:00
let base = "/";
if (typeof config !== "undefined" && typeof config.basePath !== "undefined") {
base = config.basePath;
}
2021-04-10 08:21:27 +02:00
this.socket = io("/" + this.moduleName, {
path: base + "socket.io"
});
2021-04-10 08:21:27 +02:00
let notificationCallback = function () {};
const onevent = this.socket.onevent;
this.socket.onevent = (packet) => {
const args = packet.data || [];
onevent.call(this.socket, packet); // original call
2016-03-30 17:22:30 +02:00
packet.data = ["*"].concat(args);
2021-04-10 08:21:27 +02:00
onevent.call(this.socket, packet); // additional call to catch-all
2016-03-30 17:22:30 +02:00
};
2016-03-30 17:22:30 +02:00
// register catch all.
2021-04-10 08:21:27 +02:00
this.socket.on("*", (notification, payload) => {
2016-04-05 14:35:11 -04:00
if (notification !== "*") {
2016-03-30 17:22:30 +02:00
notificationCallback(notification, payload);
}
});
// Public Methods
2021-04-10 08:21:27 +02:00
this.setNotificationCallback = (callback) => {
notificationCallback = callback;
};
2021-04-10 08:21:27 +02:00
this.sendNotification = (notification, payload) => {
2016-04-05 14:35:11 -04:00
if (typeof payload === "undefined") {
payload = {};
}
2021-04-10 08:21:27 +02:00
this.socket.emit(notification, payload);
};
};