const WebSocket = require('ws') 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; // Connection of WebSocket open = () => { this.ws = new WebSocket(url, [], options); this.ws.on('open', this.onOpen); this.ws.on('close', this.onClose); } // Disconnection of WebSocket close = () => { this.ws.close(); console.log('WebSocket Close'); } // Open event onOpen = () => { console.log('WebSocket Open'); this.isOpened(); if(!this.clientAuthenticated){ this.clientAuth(); } } onClose = () => { console.log('WebSocket Close'); this.clientAuthenticated = false; this.isOpened(); this.open(); } // 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)); respData = message; _stopMessage = 2; } }) while(respData == null){ await _sleep(10); } let respCode = generate.getResponseCode(respData); console.log(`Resp Data Tenant = ${respCode}`) if (respCode == "0000" || respCode == "0502") this.clientAuthenticated = true; console.log(`clientAuthenticated = ${this.clientAuthenticated}`); }catch (error) { console.log(`error ${error}`) } } } const client = new WebSocketClient(); client.open(); setInterval(function(){ client.clientAuth() }, 59000); module.exports = { client };