Files
MagicMirror/js/socketclient.js
T

55 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.
*/
2020-05-11 22:22:32 +02:00
var MMSocket = function (moduleName) {
var self = this;
2016-04-05 14:35:11 -04:00
if (typeof moduleName !== "string") {
throw new Error("Please set the module name for the MMSocket.");
}
self.moduleName = moduleName;
// Private Methods
var base = "/";
2020-05-11 22:22:32 +02:00
if (typeof config !== "undefined" && typeof config.basePath !== "undefined") {
base = config.basePath;
}
2020-02-18 17:09:25 +01:00
self.socket = io("/" + self.moduleName, {
path: base + "socket.io"
2020-02-18 17:09:25 +01:00
});
2020-05-11 22:22:32 +02:00
var notificationCallback = function () {};
2016-04-19 11:04:36 +02:00
var onevent = self.socket.onevent;
2020-05-11 22:22:32 +02:00
self.socket.onevent = function (packet) {
2016-03-30 17:22:30 +02:00
var args = packet.data || [];
onevent.call(this, packet); // original call
2016-03-30 17:22:30 +02:00
packet.data = ["*"].concat(args);
onevent.call(this, 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.
2020-05-11 22:22:32 +02:00
self.socket.on("*", function (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
2020-05-11 22:22:32 +02:00
this.setNotificationCallback = function (callback) {
notificationCallback = callback;
};
2020-05-11 22:22:32 +02:00
this.sendNotification = function (notification, payload) {
2016-04-05 14:35:11 -04:00
if (typeof payload === "undefined") {
payload = {};
}
2016-04-19 11:04:36 +02:00
self.socket.emit(notification, payload);
};
2016-04-03 19:52:13 +02:00
};