ts-ssp
Version:
NodeJS library to work with coin and bill acceptors under SSP protocol. Written in Typescript.
88 lines • 2.83 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const commands_1 = __importDefault(require("./commands"));
const utils_1 = require("./utils");
class SSPCommands {
constructor(socket, type, sspId, sequence) {
this.socket = socket;
this.sspId = sspId;
this.sequence = this.sequenceNumber = sequence;
this.commandsList = commands_1.default[type];
this.execStack = [];
}
async exec(commandName, ...args) {
if (commandName) {
this.stack(commandName, ...args);
}
const execLine = this.execStack.shift();
if (!execLine) {
return;
}
const writeAsync = (command) => new Promise((resolve, reject) => {
this.socket.write(command, (err, bytesWritten) => {
if (err) {
reject(err);
return;
}
resolve(bytesWritten);
});
});
await writeAsync(execLine);
const drainAsync = () => new Promise((resolve, reject) => {
this.socket.drain((err) => {
if (err) {
reject(err);
return;
}
resolve();
});
});
await drainAsync();
await utils_1.sleep(100);
void this.exec();
}
crc16(commandLine) {
const seed = 0xffff;
const poly = 0x8005;
let crc = seed;
for (const command of commandLine) {
crc ^= command << 8;
for (let j = 0; j < 8; j++) {
if (crc & 0x8000) {
crc = ((crc << 1) & 0xffff) ^ poly;
}
else {
crc <<= 1;
}
}
}
return [crc & 0xff, (crc >> 8) & 0xff];
}
getSequence() {
return (this.sspId |
(this.sequence =
this.sequence === this.sequenceNumber ? 0x00 : this.sequenceNumber));
}
stack(commandName, ...args) {
if (!this.commandsList.hasOwnProperty(commandName)) {
throw new Error(`Unknown command ${commandName}`);
}
const command = this.commandsList[commandName];
if (command.sequence) {
this.sequence = command.sequence;
}
let commandLine = [
this.getSequence(),
args.length + 1,
command.value,
...args,
];
commandLine = [0x7f, ...commandLine, ...this.crc16(commandLine)];
this.execStack.push(commandLine);
}
}
exports.default = SSPCommands;
//# sourceMappingURL=SSPCommands.js.map