├── .gitignore ├── rollup.config.js ├── package.json ├── src ├── commands.ts └── index.ts ├── output └── index.js └── tsconfig.json /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import typescript from '@rollup/plugin-typescript' 2 | 3 | export default { 4 | input: 'src/index.ts', 5 | output: { 6 | dir: 'output', 7 | format: 'cjs', 8 | }, 9 | plugins: [typescript()], 10 | } 11 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "espruino-thermalprinter", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "prettier": { 13 | "semi": false, 14 | "singleQuote": true, 15 | "printWidth": 120 16 | }, 17 | "devDependencies": { 18 | "@rollup/plugin-typescript": "^8.3.0", 19 | "@types/node": "^17.0.17", 20 | "rollup": "^2.67.2", 21 | "typescript": "^4.5.5" 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/commands.ts: -------------------------------------------------------------------------------- 1 | export function buf(...args: number[]): Uint8Array 2 | export function buf() { 3 | return new Uint8Array(Array.prototype.slice.call(arguments)) 4 | } 5 | 6 | export const resetCommand = () => buf(27, 64) 7 | export const setCharsetCommand = (charset: number) => buf(27, 82, charset) 8 | export const setCharCodeTableCommand = (code: number) => buf(27, 116, code) 9 | export const printTestPageCommand = () => buf(18, 84) 10 | export const sendPrintingParamsCommand = (mpd: number, ht: number, hi: number) => buf(27, 55, mpd, ht, hi) 11 | export const lineFeedCommand = (linesToFeed?: number) => (linesToFeed ? buf(27, 100, linesToFeed) : buf(10)) 12 | export const printModeCommand = (mode: number) => buf(27, 33, mode) 13 | export const underlineCommand = (dots: number) => buf(27, 45, dots) 14 | export const smallCommand = (onOff: 0 | 1) => buf(27, 33, onOff) 15 | export const upsideDownCommand = (onOff: 0 | 1) => buf(27, 123, onOff) 16 | export const inverseCommand = (onOff: 0 | 1) => buf(29, 66, onOff) 17 | export const alignCommand = (side: 0 | 1 | 2) => buf(27, 97, side) 18 | export const indentCommand = (columns: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9) => buf(27, 66, columns) 19 | export const setLineSpacingCommand = (lineSpacing: number) => buf(27, 51, lineSpacing) 20 | export const horizontalLineCommand = (length: number) => { 21 | const args = Array(length).fill(196) 22 | 23 | args.push(length) 24 | buf.apply(undefined, args) 25 | } 26 | // export const printTextCommand = (text: number[]) => buf(...text) 27 | export const printNewLineCommand = () => buf(10) 28 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { resetCommand, sendPrintingParamsCommand, setCharsetCommand } from './commands' 2 | 3 | export type ThermalPrinterOptions = { 4 | maxPrintingDots: number 5 | heatingTime: number 6 | heatingInterval: number 7 | commandDelay: number 8 | } 9 | 10 | const defaultOptions: ThermalPrinterOptions = { 11 | maxPrintingDots: 7, 12 | heatingTime: 80, 13 | heatingInterval: 2, 14 | commandDelay: 0, 15 | } 16 | 17 | export * from './commands' 18 | 19 | export default class ThermalPrinter { 20 | readonly options: ThermalPrinterOptions 21 | 22 | private serial: any 23 | 24 | constructor(serial: any, options: ThermalPrinterOptions = defaultOptions) { 25 | this.serial = serial 26 | this.options = options 27 | } 28 | 29 | public async start(): Promise { 30 | // this.queueReset() 31 | // this.queuePrintingParams() 32 | // this.queueSetCharset(0) 33 | 34 | this.add(resetCommand()) 35 | this.add( 36 | sendPrintingParamsCommand(this.options.maxPrintingDots, this.options.heatingTime, this.options.heatingInterval) 37 | ) 38 | this.add(setCharsetCommand(0)) 39 | await this.send() 40 | } 41 | 42 | private queue: Array = [] 43 | 44 | private async sendCommand(command: Uint8Array): Promise { 45 | await this.serial.write(command) 46 | await this.serial.drain() 47 | } 48 | 49 | private async send(): Promise { 50 | try { 51 | for (const command of this.queue) { 52 | if (this.options.commandDelay !== 0) { 53 | await this.delay(this.options.commandDelay / 1000) 54 | } 55 | 56 | await this.sendCommand(command) 57 | } 58 | } finally { 59 | this.queue = [] 60 | } 61 | } 62 | 63 | public add(command: Uint8Array) { 64 | this.queue.push(command) 65 | } 66 | 67 | private delay(amount: number): Promise { 68 | return new Promise((resolve) => setTimeout(resolve, Math.ceil(amount))) 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /output/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | Object.defineProperty(exports, '__esModule', { value: true }); 4 | 5 | /*! ***************************************************************************** 6 | Copyright (c) Microsoft Corporation. 7 | 8 | Permission to use, copy, modify, and/or distribute this software for any 9 | purpose with or without fee is hereby granted. 10 | 11 | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH 12 | REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY 13 | AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, 14 | INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM 15 | LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR 16 | OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR 17 | PERFORMANCE OF THIS SOFTWARE. 18 | ***************************************************************************** */ 19 | 20 | function __awaiter(thisArg, _arguments, P, generator) { 21 | function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 22 | return new (P || (P = Promise))(function (resolve, reject) { 23 | function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } 24 | function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } 25 | function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } 26 | step((generator = generator.apply(thisArg, _arguments || [])).next()); 27 | }); 28 | } 29 | 30 | function buf() { 31 | return new Uint8Array(Array.prototype.slice.call(arguments)); 32 | } 33 | const resetCommand = () => buf(27, 64); 34 | const setCharsetCommand = (charset) => buf(27, 82, charset); 35 | const setCharCodeTableCommand = (code) => buf(27, 116, code); 36 | const printTestPageCommand = () => buf(18, 84); 37 | const sendPrintingParamsCommand = (mpd, ht, hi) => buf(27, 55, mpd, ht, hi); 38 | const lineFeedCommand = (linesToFeed) => (linesToFeed ? buf(27, 100, linesToFeed) : buf(10)); 39 | const printModeCommand = (mode) => buf(27, 33, mode); 40 | const underlineCommand = (dots) => buf(27, 45, dots); 41 | const smallCommand = (onOff) => buf(27, 33, onOff); 42 | const upsideDownCommand = (onOff) => buf(27, 123, onOff); 43 | const inverseCommand = (onOff) => buf(29, 66, onOff); 44 | const alignCommand = (side) => buf(27, 97, side); 45 | const indentCommand = (columns) => buf(27, 66, columns); 46 | const setLineSpacingCommand = (lineSpacing) => buf(27, 51, lineSpacing); 47 | const horizontalLineCommand = (length) => { 48 | const args = Array(length).fill(196); 49 | args.push(length); 50 | buf.apply(undefined, args); 51 | }; 52 | // export const printTextCommand = (text: number[]) => buf(...text) 53 | const printNewLineCommand = () => buf(10); 54 | 55 | const defaultOptions = { 56 | maxPrintingDots: 7, 57 | heatingTime: 80, 58 | heatingInterval: 2, 59 | commandDelay: 0, 60 | }; 61 | class ThermalPrinter { 62 | constructor(serial, options = defaultOptions) { 63 | this.queue = []; 64 | this.serial = serial; 65 | this.options = options; 66 | } 67 | start() { 68 | return __awaiter(this, void 0, void 0, function* () { 69 | // this.queueReset() 70 | // this.queuePrintingParams() 71 | // this.queueSetCharset(0) 72 | this.add(resetCommand()); 73 | this.add(sendPrintingParamsCommand(this.options.maxPrintingDots, this.options.heatingTime, this.options.heatingInterval)); 74 | this.add(setCharsetCommand(0)); 75 | yield this.send(); 76 | }); 77 | } 78 | sendCommand(command) { 79 | return __awaiter(this, void 0, void 0, function* () { 80 | yield this.serial.write(command); 81 | yield this.serial.drain(); 82 | }); 83 | } 84 | send() { 85 | return __awaiter(this, void 0, void 0, function* () { 86 | try { 87 | for (const command of this.queue) { 88 | if (this.options.commandDelay !== 0) { 89 | yield this.delay(this.options.commandDelay / 1000); 90 | } 91 | yield this.sendCommand(command); 92 | } 93 | } 94 | finally { 95 | this.queue = []; 96 | } 97 | }); 98 | } 99 | add(command) { 100 | this.queue.push(command); 101 | } 102 | delay(amount) { 103 | return new Promise((resolve) => setTimeout(resolve, Math.ceil(amount))); 104 | } 105 | } 106 | 107 | exports.alignCommand = alignCommand; 108 | exports.buf = buf; 109 | exports["default"] = ThermalPrinter; 110 | exports.horizontalLineCommand = horizontalLineCommand; 111 | exports.indentCommand = indentCommand; 112 | exports.inverseCommand = inverseCommand; 113 | exports.lineFeedCommand = lineFeedCommand; 114 | exports.printModeCommand = printModeCommand; 115 | exports.printNewLineCommand = printNewLineCommand; 116 | exports.printTestPageCommand = printTestPageCommand; 117 | exports.resetCommand = resetCommand; 118 | exports.sendPrintingParamsCommand = sendPrintingParamsCommand; 119 | exports.setCharCodeTableCommand = setCharCodeTableCommand; 120 | exports.setCharsetCommand = setCharsetCommand; 121 | exports.setLineSpacingCommand = setLineSpacingCommand; 122 | exports.smallCommand = smallCommand; 123 | exports.underlineCommand = underlineCommand; 124 | exports.upsideDownCommand = upsideDownCommand; 125 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 4 | 5 | /* Projects */ 6 | // "incremental": true, /* Enable incremental compilation */ 7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ 8 | // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ 9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */ 10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ 11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ 12 | 13 | /* Language and Environment */ 14 | "target": "es6" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, 15 | // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ 16 | // "jsx": "preserve", /* Specify what JSX code is generated. */ 17 | // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ 18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ 19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */ 20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ 21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */ 22 | // "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */ 23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ 24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ 25 | 26 | /* Modules */ 27 | "module": "esnext" /* Specify what module code is generated. */, 28 | // "rootDir": "./", /* Specify the root folder within your source files. */ 29 | // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ 30 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ 31 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ 32 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ 33 | // "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */ 34 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */ 35 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 36 | // "resolveJsonModule": true, /* Enable importing .json files */ 37 | // "noResolve": true, /* Disallow `import`s, `require`s or ``s from expanding the number of files TypeScript should add to a project. */ 38 | 39 | /* JavaScript Support */ 40 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */ 41 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ 42 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */ 43 | 44 | /* Emit */ 45 | // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ 46 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */ 47 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ 48 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ 49 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */ 50 | // "outDir": "./", /* Specify an output folder for all emitted files. */ 51 | // "removeComments": true, /* Disable emitting comments. */ 52 | // "noEmit": true, /* Disable emitting files from a compilation. */ 53 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ 54 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */ 55 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ 56 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ 57 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 58 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ 59 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ 60 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ 61 | // "newLine": "crlf", /* Set the newline character for emitting files. */ 62 | // "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */ 63 | // "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */ 64 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ 65 | // "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */ 66 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ 67 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ 68 | 69 | /* Interop Constraints */ 70 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ 71 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ 72 | "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */, 73 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ 74 | "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, 75 | 76 | /* Type Checking */ 77 | "strict": true /* Enable all strict type-checking options. */, 78 | // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */ 79 | // "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */ 80 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ 81 | // "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */ 82 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ 83 | // "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */ 84 | // "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */ 85 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ 86 | // "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */ 87 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */ 88 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ 89 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ 90 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ 91 | // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ 92 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ 93 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */ 94 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ 95 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ 96 | 97 | /* Completeness */ 98 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ 99 | "skipLibCheck": true /* Skip type checking all .d.ts files. */, 100 | "lib": ["ES2016"] 101 | } 102 | } 103 | --------------------------------------------------------------------------------