Skip to content

Instantly share code, notes, and snippets.

@codebykyle
Created March 25, 2019 04:42
Show Gist options
  • Save codebykyle/5965644d781f6ba47312c7b25fbe7c2a to your computer and use it in GitHub Desktop.
Save codebykyle/5965644d781f6ba47312c7b25fbe7c2a to your computer and use it in GitHub Desktop.
Serial port thermal printer / cash register control for Electron/NodeJS
const fs = require('fs');
const SerialPort = require('serialport');
const _ = require('lodash');
const BARCODE_TYPES = {
upc_a: 0,
epc_e: 1,
ean13: 2,
ean8: 3,
code39: 4,
i25: 5,
codebar: 6,
code93: 7,
code128: 8,
code11: 9,
msi: 10,
};
let CashRegister = function () {
console.log(this);
this.serial_connection = null;
Object.defineProperties(this, {
serial_connection: {
enumerable: true,
value: this.serial_connection
}
});
};
CashRegister.prototype.connect_to_register = function (port) {
this.serial_connection = new SerialPort(port);
};
CashRegister.prototype.print_barcode = function (data, barcode_type="upc_a", large=true) {
if (large) {
this.serial_connection.write([29, 119, 3]);
} else {
this.serial_connection.write([29, 119, 2]);
}
const printer_code = BARCODE_TYPES[barcode_type];
const barcode_buffer = Buffer.from(data, 'utf-8');
this.serial_connection.write([29, 107, printer_code]);
this.serial_connection.write(barcode_buffer);
this.serial_connection.write([0]);
this.new_line();
};
CashRegister.prototype.reset = function () {
this.serial_connection.write([27, 64]);
};
CashRegister.prototype.indent = function (columns) {
if (columns < 0 || columns > 31) {
columns = 0;
}
this.serial_connection.write([27, 66, columns]);
};
CashRegister.prototype.set_size = function (width, height) {
const value = (width * 0xF0) + (height * 0x0F);
this.serial_connection.write([29, 33, value])
};
CashRegister.prototype.line_feed = function (lines) {
this.serial_connection.write([27, 100, lines])
};
CashRegister.prototype.set_line_spacing = function (spacing) {
this.serial_connection.write([27, 51, spacing]);
};
CashRegister.prototype.set_align_left = function () {
this.serial_connection.write([27, 97, 0])
};
CashRegister.prototype.set_align_center = function () {
this.serial_connection.write([27, 97, 1])
};
CashRegister.prototype.set_align_right = function () {
this.serial_connection.write([27, 97, 2])
};
CashRegister.prototype.print_horizontal_line = function (length=32) {
_.range(length).forEach(() => {
this.serial_connection.write([196]);
});
};
CashRegister.prototype.new_line = function () {
this.serial_connection.write([10]);
};
CashRegister.prototype.open_drawer = function () {
this.serial_connection.write([27, 112, 0, 25, 250]);
};
export default CashRegister
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment