/* * Copyright © 2016-2017 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import 'angular-websocket'; import thingsboardTypes from '../common/types.constant'; export default angular.module('thingsboard.api.telemetryWebsocket', [thingsboardTypes]) .factory('telemetryWebsocketService', TelemetryWebsocketService) .name; const RECONNECT_INTERVAL = 2000; const WS_IDLE_TIMEOUT = 90000; /*@ngInject*/ function TelemetryWebsocketService($rootScope, $websocket, $timeout, $window, types, userService) { var isOpening = false, isOpened = false, isActive = false, isReconnect = false, reconnectSubscribers = [], lastCmdId = 0, subscribers = {}, subscribersCount = 0, commands = {}, cmdsWrapper = { tsSubCmds: [], historyCmds: [], attrSubCmds: [] }, telemetryUri, dataStream, location = $window.location, socketCloseTimer, reconnectTimer; var port = location.port; if (location.protocol === "https:") { if (!port) { port = "443"; } telemetryUri = "wss:"; } else { if (!port) { port = "80"; } telemetryUri = "ws:"; } telemetryUri += "//" + location.hostname + ":" + port; telemetryUri += "/api/ws/plugins/telemetry"; var service = { subscribe: subscribe, unsubscribe: unsubscribe } $rootScope.telemetryWsLogoutHandle = $rootScope.$on('unauthenticated', function (event, doLogout) { if (doLogout) { reset(true); } }); return service; function publishCommands () { if (isOpened && (cmdsWrapper.tsSubCmds.length > 0 || cmdsWrapper.historyCmds.length > 0 || cmdsWrapper.attrSubCmds.length > 0)) { dataStream.send(angular.copy(cmdsWrapper)).then(function () { checkToClose(); }); cmdsWrapper.tsSubCmds = []; cmdsWrapper.historyCmds = []; cmdsWrapper.attrSubCmds = []; } tryOpenSocket(); } function onError (/*message*/) { isOpening = false; } function onOpen () { isOpening = false; isOpened = true; if (reconnectTimer) { $timeout.cancel(reconnectTimer); reconnectTimer = null; } if (isReconnect) { isReconnect = false; for (var r=0; r 0) { return command.keys.split(","); } else { return []; } } function nextCmdId () { lastCmdId++; return lastCmdId; } function subscribe (subscriber) { isActive = true; var cmdId; if (angular.isDefined(subscriber.subscriptionCommands)) { for (var i=0;i