Debian Codegraph @

addons/point_of_sale/static/src/app/utils/printer/epson_printer.js

raw
1 import { BasePrinter } from "@point_of_sale/app/utils/printer/base_printer";
2 import { _t } from "@web/core/l10n/translation";
3 import { getTemplate } from "@web/core/templates";
4 import { createElement, append, createTextNode } from "@web/core/utils/xml";
5
6 const STATUS_ROLL_PAPER_HAS_RUN_OUT = 0x00080000;
7 const STATUS_ROLL_PAPER_HAS_ALMOST_RUN_OUT = 0x00020000;
8 const ERROR_CODE_PRINTER_NOT_REACHABLE = "PRINTER_NOT_REACHABLE";
9
10 function ePOSPrint(children) {
11 let ePOSLayout = getTemplate("point_of_sale.ePOSLayout");
12 if (!ePOSLayout) {
13 throw new Error("'ePOSLayout' not loaded");
14 }
15 ePOSLayout = ePOSLayout.cloneNode(true);
16 const [eposPrintEl] = ePOSLayout.getElementsByTagName("epos-print");
17 append(eposPrintEl, children);
18 // IMPORTANT: Need to remove `xmlns=""` in the image and cut elements.
19 // > Otherwise, the print request will succeed but it the printer device won't actually do the printing.
20 return ePOSLayout.innerHTML.replaceAll(`xmlns=""`, "");
21 }
22
23 /**
24 * Sends print request to ePos printer that is directly connected to the local network.
25 */
26 export class EpsonPrinter extends BasePrinter {
27 setup({ ip }) {
28 super.setup(...arguments);
29
30 const protocol = odoo.use_lna ? "http:" : window.location.protocol;
31 this.url = protocol + "//" + ip;
32 this.address = this.url + "/cgi-bin/epos/service.cgi?devid=local_printer";
33 }
34
35 /**
36 * @override
37 * Create the raster data from a canvas
38 */
39 processCanvas(canvas) {
40 const rasterData = this.canvasToRaster(canvas);
41 const encodedData = this.encodeRaster(rasterData);
42 return ePOSPrint([
43 createElement(
44 "image",
45 {
46 width: canvas.width,
47 height: canvas.height,
48 align: "center",
49 },
50 [createTextNode(encodedData)]
51 ),
52 createElement("cut", { type: "feed" }),
53 ]);
54 }
55
56 /**
57 * @override
58 */
59 openCashbox() {
60 const pulse = ePOSPrint([createElement("pulse")]);
61 this.sendPrintingJob(pulse);
62 }
63
64 /**
65 * @override
66 */
67 async sendPrintingJob(img) {
68 const params = {
69 method: "POST",
70 body: img,
71 signal: AbortSignal.timeout(15000),
72 };
73
74 if (odoo.use_lna) {
75 params.targetAddressSpace = "local";
76 }
77
78 try {
79 const res = await fetch(this.address, params);
80 const body = await res.text();
81 const parser = new DOMParser();
82 const parsedBody = parser.parseFromString(body, "application/xml");
83 const response = parsedBody.querySelector("response");
84 return {
85 result: response.getAttribute("success") === "true",
86 errorCode: response.getAttribute("code"),
87 status: parseInt(response.getAttribute("status")) || 0,
88 canRetry: true,
89 };
90 } catch {
91 return {
92 result: false,
93 canRetry: true,
94 errorCode: ERROR_CODE_PRINTER_NOT_REACHABLE,
95 };
96 }
97 }
98
99 /**
100 * Transform a (potentially colored) canvas into a monochrome raster image.
101 * We will use Floyd-Steinberg dithering.
102 */
103 canvasToRaster(canvas) {
104 const imageData = canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height);
105 const pixels = imageData.data;
106 const width = imageData.width;
107 const height = imageData.height;
108 const errors = Array.from(Array(width), (_) => Array(height).fill(0));
109 const rasterData = new Array(width * height).fill(0);
110
111 for (let y = 0; y < height; y++) {
112 for (let x = 0; x < width; x++) {
113 let oldColor, newColor;
114
115 // Compute grayscale level. Those coefficients were found online
116 // as R, G and B have different impacts on the darkness
117 // perception (e.g. pure blue is darker than red or green).
118 const idx = (y * width + x) * 4;
119 oldColor = pixels[idx] * 0.299 + pixels[idx + 1] * 0.587 + pixels[idx + 2] * 0.114;
120
121 // Propagate the error from neighbor pixels
122 oldColor += errors[x][y];
123 oldColor = Math.min(255, Math.max(0, oldColor));
124
125 if (oldColor < 128) {
126 // This pixel should be black
127 newColor = 0;
128 rasterData[y * width + x] = 1;
129 } else {
130 // This pixel should be white
131 newColor = 255;
132 rasterData[y * width + x] = 0;
133 }
134
135 // Propagate the error to the following pixels, based on
136 // Floyd-Steinberg dithering.
137 const error = oldColor - newColor;
138 if (error) {
139 if (x < width - 1) {
140 // Pixel on the right
141 errors[x + 1][y] += (7 / 16) * error;
142 }
143 if (x > 0 && y < height - 1) {
144 // Pixel on the bottom left
145 errors[x - 1][y + 1] += (3 / 16) * error;
146 }
147 if (y < height - 1) {
148 // Pixel below
149 errors[x][y + 1] += (5 / 16) * error;
150 }
151 if (x < width - 1 && y < height - 1) {
152 // Pixel on the bottom right
153 errors[x + 1][y + 1] += (1 / 16) * error;
154 }
155 }
156 }
157 }
158
159 return rasterData.join("");
160 }
161
162 /**
163 * Base 64 encode a raster image
164 */
165 encodeRaster(rasterData) {
166 let encodedData = "";
167 for (let i = 0; i < rasterData.length; i += 8) {
168 const sub = rasterData.substr(i, 8);
169 encodedData += String.fromCharCode(parseInt(sub, 2));
170 }
171 return btoa(encodedData);
172 }
173
174 /**
175 * @override
176 */
177 getActionError() {
178 const printRes = super.getResultsError();
179 if (window.location.protocol === "https:") {
180 printRes.message.body += _t(
181 "If you are on a secure server (HTTPS) please make sure you manually accepted the certificate by accessing %s. ",
182 this.url
183 );
184 }
185 return printRes;
186 }
187
188 hasStatus(status, attribute) {
189 //The status is a bit field
190 return (status & attribute) === attribute;
191 }
192
193 /**
194 * @override
195 */
196 getResultsError(printResult) {
197 const errorCode = printResult.errorCode;
198 const status = printResult.status;
199 let message;
200 // https://download4.epson.biz/sec_pubs/pos/reference_en/epos_print/ref_epos_print_xml_en_xmlforcontrollingprinter_response.html
201 if (errorCode === "DeviceNotFound") {
202 message = _t(
203 "Check the printer configuration for the 'Device ID' setting.\nIt should be set to: local_printer"
204 );
205 } else if (errorCode === ERROR_CODE_PRINTER_NOT_REACHABLE) {
206 message = _t("The printer is not reachable.");
207 } else if (errorCode === "EPTR_COVER_OPEN") {
208 message = _t("Printer cover is open. Please close it and try again!");
209 } else if (
210 errorCode === "EPTR_REC_EMPTY" ||
211 this.hasStatus(status, STATUS_ROLL_PAPER_HAS_RUN_OUT)
212 ) {
213 message = _t("It seems that the printer runs out of paper.");
214 } else {
215 message = _t(
216 "The following error code was given by the printer: %s \nTo find more details on the error reason, please search online for: Epson Server Direct Print %s ",
217 errorCode,
218 errorCode
219 );
220 }
221 return {
222 successful: false,
223 errorCode: errorCode,
224 status: status,
225 message: {
226 title: _t("Printing failed"),
227 body: message,
228 },
229 canRetry: printResult.canRetry || false,
230 };
231 }
232
233 getResultWarningCode(printResult) {
234 const status = printResult?.status;
235 if (!status) {
236 return undefined;
237 }
238 if (this.hasStatus(status, STATUS_ROLL_PAPER_HAS_ALMOST_RUN_OUT)) {
239 return "ROLL_PAPER_HAS_ALMOST_RUN_OUT";
240 }
241 return undefined;
242 }
243 }