revbits-cip-integration
Version:
This package will integrate CIP with any product
114 lines (113 loc) • 5.31 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebSocketClient = void 0;
const ws_1 = __importDefault(require("ws"));
const socket_api_1 = __importDefault(require("../apis/socket.api"));
const logger_1 = require("../utils/logger");
class WebSocketClient {
constructor(baseUrl, url, platform, platformPrivKey, options, cb, initialReconnectInterval = 100, maxReconnectInterval = 20000, maxReconnectAttempts = 10) {
this.baseUrl = baseUrl;
this.url = url;
this.platform = platform;
this.platformPrivKey = platformPrivKey;
this.options = options;
this.cb = cb;
this.initialReconnectInterval = initialReconnectInterval;
this.maxReconnectInterval = maxReconnectInterval;
this.maxReconnectAttempts = maxReconnectAttempts;
this.handleOpen = () => {
this.currentReconnectAttempts = 0;
this.reconnectInterval = 100;
logger_1.logger.info('WebSocket connection established.');
};
this.handleMessage = (data) => {
logger_1.logger.info('Received message: ' + data.toString());
this.cb(data);
};
this.handleClose = (code, reason) => {
if (code === 1000) {
logger_1.logger.info('WebSocket connection closed gracefully.');
return;
}
logger_1.logger.info('WebSocket connection closed with code: ' + code + ' and reason: ' + reason);
if (this.currentReconnectAttempts < this.reconnectAttempts) {
const delay = Math.min(this.reconnectInterval, this.maxReconnectInterval);
logger_1.logger.info('Attempting to reconnect in ' + delay / 1000 + ' seconds...');
this.currentReconnectAttempts++;
this.reconnectInterval *= 2;
setTimeout(() => this.connect(), delay);
}
else {
logger_1.logger.info('Exceeded the maximum number of reconnect attempts.');
}
};
this.handleError = (error) => {
logger_1.logger.error('WebSocket encountered an error:', error);
};
this.websocket = null;
this.currentReconnectAttempts = 0;
this.reconnectInterval = initialReconnectInterval;
this.reconnectAttempts = maxReconnectAttempts;
this.connect();
}
connect() {
return __awaiter(this, void 0, void 0, function* () {
try {
const socketToken = yield this.generateSocketToken();
if (socketToken) {
const url = `${this.url}/${socketToken}`;
this.websocket = new ws_1.default(url);
this.websocket.on('open', this.handleOpen);
this.websocket.on('message', this.handleMessage);
this.websocket.on('close', this.handleClose);
this.websocket.on('error', this.handleError);
}
}
catch (error) {
logger_1.logger.error('Error generating socket token:', error);
if (this.currentReconnectAttempts < this.reconnectAttempts) {
const delay = Math.min(this.reconnectInterval, this.maxReconnectInterval);
logger_1.logger.info('Attempting to reconnect in ' + delay / 1000 + ' seconds...');
this.currentReconnectAttempts++;
this.reconnectInterval *= 2;
setTimeout(() => this.connect(), delay);
}
else {
logger_1.logger.info('Exceeded the maximum number of reconnect attempts.');
}
}
});
}
generateSocketToken() {
return __awaiter(this, void 0, void 0, function* () {
const socketApi = new socket_api_1.default(this.baseUrl, this.platform, this.platformPrivKey, this.options);
return socketApi.generateSocketToken();
});
}
send(message) {
if (this.websocket && this.websocket.readyState === ws_1.default.OPEN) {
this.websocket.send(message);
}
else {
logger_1.logger.warn('WebSocket is not open. Message not sent:', message);
}
}
disconnect() {
if (this.websocket) {
this.websocket.close(1000, 'Disconnect requested.');
}
}
}
exports.WebSocketClient = WebSocketClient;