Files
Online-Topup-V1/application/modules/hsm/services/webSocket.js
T
2022-06-23 22:31:08 +07:00

202 lines
4.9 KiB
JavaScript

const WebSocket = require("ws");
const winston = require("../../../helpers/winston.logger");
const fs = require("fs");
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const generate = require("../utils/utils");
let ssl_ca_crt = "./application/assets/cert/CACerts.pem";
let ssl_client_pfx = "./application/assets/cert/FeliqClient0002-03.pfx";
let options = {
ca: fs.readFileSync(ssl_ca_crt),
agent: false,
passphrase: "GPqs+Uia78",
pfx: fs.readFileSync(ssl_client_pfx),
};
let url = "wss://gateway04.cyberware.co.jp/feliqserver/v1/wsapi";
class WebSocketClient {
ws = null;
clientAuthenticated = false;
openWebSocketStatus = false;
// Connection of WebSocket
open = () => {
try {
if (this.ws == null) {
this.ws = new WebSocket(url, [], options);
this.ws.on("open", this.onOpen);
this.ws.on("close", this.onClose);
this.ws.on("error", this.onError);
}
this.openWebSocketStatus = true;
} catch (error) {
this.openWebSocketStatus = false;
}
};
// Disconnection of WebSocket
close = () => {
this.ws.close();
// console.log('WebSocket Close');
// log info
winston.logger.info(`websocket close`);
};
// Open event
onOpen = () => {
// console.log("WebSocket Open");
// log debug
winston.logger.debug(`opening websocket`);
if (this.isOpened()) {
// log info
winston.logger.info(`websocket open successfully`);
if (!this.clientAuthenticated) {
this.clientAuth();
}
} else {
// log error
winston.logger.error(`websocket open failed`);
}
};
onClose = () => {
// console.log("WebSocket Close");
// log info
winston.logger.info(`websocket close`);
this.clientAuthenticated = false;
};
onError = () => {
// console.log("WebSocket Error");
// log info
winston.logger.info(`websocket error`);
this.clientAuthenticated = false;
};
// Connection check
isOpened = () => {
return this.ws.readyState == WebSocket.OPEN;
};
// Received data check
isReceive() {
return this.receiveData != null;
}
// Acquiring received data
getReceiveData() {
return this.receiveData;
}
clearReceiveData() {
this.receiveData = null;
}
// Send data
sendData(data) {
this.receiveData = null;
this.ws.send(data);
}
async clientAuth() {
try {
const authHead = Buffer.alloc(2);
// Set system code (when 0x0000)
authHead[0] = 0x93;
authHead[1] = 0x9e;
// Set API key
//const apiKeyBytes = Buffer.from('82002732-9148-34e5-843b-c639a0c88cc5-0TC') // T4
const apiKeyBytes = Buffer.from(
"4c6dd075-dbcb-375f-81f7-62990a5d7000-0TC"
); // Nutech
// Secret setting
//const secretBytes = Buffer.from('TdtSo/i5ZmbwPr82gt4fElK96lV9ClVo7votHKMIUuo='); // T4
const secretBytes = Buffer.from(
"U5xs7nVonhtbQ+XiYATRSg8Nk5sPu1IpVx7X40KyWiw="
); // Nutech
const authData = Buffer.concat([authHead, apiKeyBytes, secretBytes]);
let transactionId = Buffer.from([0x00, 0x00]);
let apiId = Buffer.from([0x00]);
let reqData = generate.makeRequestData(transactionId, apiId, authData);
let respData = null;
let _stopMessage = 1;
this.sendData(reqData);
this.ws.on("message", (message) => {
let __validasi = generate.buf2hex(message).slice(14, 30);
while (
message[2] == 0 &&
_stopMessage == 1 &&
message[0] == 0 &&
message[1] == 0
) {
respData = null;
// console.log("*WS MESSAGE Tenan: " + generate.buf2hex(message));
// log debug
winston.logger.debug(
`websocket message tenant: ${generate.buf2hex(message)}`
);
respData = message;
_stopMessage = 2;
}
});
while (respData == null) {
await _sleep(10);
}
let respCode = generate.getResponseCode(respData);
// console.log(`Resp Data Tenant = ${respCode}`);
// log debug
winston.logger.debug(`websocket resp data tenant: ${respCode}`);
if (respCode == "0000" || respCode == "0502") {
this.clientAuthenticated = true;
}
// console.log(`clientAuthenticated = ${this.clientAuthenticated}`);
// log debug
winston.logger.debug(
`websocket client authenticate: ${this.clientAuthenticated}`
);
} catch (error) {
// console.log(`error ${error}`);
// log error
winston.logger.error(`websocket error: ${error}`);
}
}
}
const client = new WebSocketClient();
if (!client.openWebSocketStatus) {
// log info
winston.logger.info(`first open websocket`);
client.open();
}
setInterval(function () {
// let statusConnection = client.clientAuthenticated;
// if (!statusConnection) {
// log debug
winston.logger.debug(`retry open websocket`);
client.clientAuth();
// }
}, 59000);
module.exports = {
client,
};