| 1 |
# Part of Odoo. See LICENSE file for full copyright and licensing details. |
| 2 |
|
| 3 |
import logging |
| 4 |
import serial |
| 5 |
import time |
| 6 |
import struct |
| 7 |
import json |
| 8 |
from functools import reduce |
| 9 |
|
| 10 |
from odoo import http |
| 11 |
from odoo.addons.iot_drivers.iot_handlers.drivers.serial_base_driver import SerialDriver, SerialProtocol, serial_connection |
| 12 |
from odoo.addons.iot_drivers.main import iot_devices |
| 13 |
from odoo.addons.iot_drivers.tools import route |
| 14 |
|
| 15 |
_logger = logging.getLogger(__name__) |
| 16 |
|
| 17 |
TremolG03Protocol = SerialProtocol( |
| 18 |
name='Tremol G03', |
| 19 |
baudrate=115200, |
| 20 |
bytesize=serial.EIGHTBITS, |
| 21 |
stopbits=serial.STOPBITS_ONE, |
| 22 |
parity=serial.PARITY_NONE, |
| 23 |
timeout=4, |
| 24 |
writeTimeout=0.2, |
| 25 |
measureRegexp=None, |
| 26 |
statusRegexp=None, |
| 27 |
commandTerminator=b'', |
| 28 |
commandDelay=0.2, |
| 29 |
measureDelay=3, |
| 30 |
newMeasureDelay=0.2, |
| 31 |
measureCommand=b'', |
| 32 |
emptyAnswerValid=False, |
| 33 |
) |
| 34 |
|
| 35 |
STX = 0x02 |
| 36 |
ETX = 0x0A |
| 37 |
ACK = 0x06 |
| 38 |
NACK = 0x15 |
| 39 |
|
| 40 |
# Dictionary defining the output size of expected from various commands |
| 41 |
COMMAND_OUTPUT_SIZE = { |
| 42 |
0x30: 7, |
| 43 |
0x31: 7, |
| 44 |
0x38: 157, |
| 45 |
0x39: 155, |
| 46 |
0x60: 40, |
| 47 |
0x68: 23, |
| 48 |
} |
| 49 |
|
| 50 |
FD_ERRORS = { |
| 51 |
0x30: 'OK', |
| 52 |
0x32: 'Registers overflow', |
| 53 |
0x33: 'Clock failure or incorrect date & time', |
| 54 |
0x34: 'Opened fiscal receipt', |
| 55 |
0x39: 'Incorrect password', |
| 56 |
0x3b: '24 hours block - missing Z report', |
| 57 |
0x3d: 'Interrupt power supply in fiscal receipt (one time until status is read)', |
| 58 |
0x3e: 'Overflow EJ', |
| 59 |
0x3f: 'Insufficient conditions', |
| 60 |
} |
| 61 |
|
| 62 |
COMMAND_ERRORS = { |
| 63 |
0x30: 'OK', |
| 64 |
0x31: 'Invalid command', |
| 65 |
0x32: 'Illegal command', |
| 66 |
0x33: 'Z daily report is not zero', |
| 67 |
0x34: 'Syntax error', |
| 68 |
0x35: 'Input registers orverflow', |
| 69 |
0x36: 'Zero input registers', |
| 70 |
0x37: 'Unavailable transaction for correction', |
| 71 |
0x38: 'Insufficient amount on hand', |
| 72 |
} |
| 73 |
|
| 74 |
|
| 75 |
class TremolG03Driver(SerialDriver): |
| 76 |
"""Driver for the Kenyan Tremol G03 fiscal device.""" |
| 77 |
|
| 78 |
_protocol = TremolG03Protocol |
| 79 |
|
| 80 |
def __init__(self, identifier, device): |
| 81 |
super().__init__(identifier, device) |
| 82 |
self.device_type = 'fiscal_data_module' |
| 83 |
self.message_number = 0 |
| 84 |
|
| 85 |
@classmethod |
| 86 |
def get_default_device(cls): |
| 87 |
fiscal_devices = list(filter(lambda d: iot_devices[d].device_type == 'fiscal_data_module', iot_devices)) |
| 88 |
return len(fiscal_devices) and iot_devices[fiscal_devices[0]] |
| 89 |
|
| 90 |
@classmethod |
| 91 |
def supported(cls, device): |
| 92 |
"""Checks whether the device, which port info is passed as argument, is supported by the driver. |
| 93 |
|
| 94 |
:param device: path to the device |
| 95 |
:type device: str |
| 96 |
:return: whether the device is supported by the driver |
| 97 |
:rtype: bool |
| 98 |
""" |
| 99 |
protocol = cls._protocol |
| 100 |
try: |
| 101 |
protocol = cls._protocol |
| 102 |
with serial_connection(device['identifier'], protocol) as connection: |
| 103 |
connection.write(b'\x09') |
| 104 |
time.sleep(protocol.commandDelay) |
| 105 |
response = connection.read(1) |
| 106 |
if response == b'\x40': |
| 107 |
return True |
| 108 |
|
| 109 |
except serial.serialutil.SerialTimeoutException: |
| 110 |
pass |
| 111 |
except Exception: |
| 112 |
_logger.exception('Error while probing %s with protocol %s', device, protocol.name) |
| 113 |
|
| 114 |
# ---------------- |
| 115 |
# HELPERS |
| 116 |
# ---------------- |
| 117 |
|
| 118 |
@staticmethod |
| 119 |
def generate_checksum(message): |
| 120 |
""" Generate the checksum bytes for the bytes provided. |
| 121 |
|
| 122 |
:param message: bytes representing the part of the message from which the checksum is calculated |
| 123 |
:returns: two checksum bytes calculated from the message |
| 124 |
|
| 125 |
This checksum is calculated as: |
| 126 |
1) XOR of all bytes of the bytes |
| 127 |
2) Conversion of the one XOR byte into the two bytes of the checksum by |
| 128 |
adding 30h to each half-byte of the XOR |
| 129 |
|
| 130 |
eg. to_check = \x12\x23\x34\x45\x56 |
| 131 |
XOR of all bytes in to_check = \x16 |
| 132 |
checksum generated as \x16 -> \x31 \x36 |
| 133 |
""" |
| 134 |
xor = reduce(lambda a, b: a ^ b, message) |
| 135 |
return bytes([(xor >> 4) + 0x30, (xor & 0xf) + 0x30]) |
| 136 |
|
| 137 |
# ---------------- |
| 138 |
# COMMUNICATION |
| 139 |
# ---------------- |
| 140 |
|
| 141 |
def send(self, msgs): |
| 142 |
""" Send and receive messages to/from the fiscal device over serial connection |
| 143 |
|
| 144 |
Generate the wrapped message from the msgs and send them to the device. |
| 145 |
The wrapping contains the <STX> (starting byte) <LEN> (length byte) |
| 146 |
and <NBL> (message number byte) at the start and two <CS> (checksum |
| 147 |
bytes), and the <ETX> line-feed byte at the end. |
| 148 |
:param msgs: A list of byte strings representing the <CMD> and <DATA> |
| 149 |
components of the serial message. |
| 150 |
:return: A list of the responses (if any) from the device. If the |
| 151 |
response is an ack, it wont be part of this list. |
| 152 |
""" |
| 153 |
|
| 154 |
with self._device_lock: |
| 155 |
replies = [] |
| 156 |
for msg in msgs: |
| 157 |
self.message_number += 1 |
| 158 |
core_message = struct.pack('BB%ds' % (len(msg)), len(msg) + 34, self.message_number + 32, msg) |
| 159 |
request = struct.pack('B%ds2sB' % (len(core_message)), STX, core_message, self.generate_checksum(core_message), ETX) |
| 160 |
time.sleep(self._protocol.commandDelay) |
| 161 |
self._connection.write(request) |
| 162 |
_logger.debug('Debug send request: %s', request) |
| 163 |
# If we know the expected output size, we can set the read |
| 164 |
# buffer to match the size of the output. |
| 165 |
output_size = COMMAND_OUTPUT_SIZE.get(msg[0]) |
| 166 |
if output_size: |
| 167 |
try: |
| 168 |
response = self._connection.read(output_size) |
| 169 |
except serial.serialutil.SerialTimeoutException: |
| 170 |
_logger.exception('Timeout error while reading response to command %s', msg) |
| 171 |
self.data['status'] = "Device timeout error" |
| 172 |
else: |
| 173 |
time.sleep(self._protocol.measureDelay) |
| 174 |
response = self._connection.read_all() |
| 175 |
_logger.debug('Debug send response: %s', response) |
| 176 |
if not response: |
| 177 |
self.data['status'] = "No response" |
| 178 |
_logger.error("Sent request: %s,\n Received no response", request) |
| 179 |
self.abort_post() |
| 180 |
break |
| 181 |
if response[0] == ACK: |
| 182 |
# In the case where either byte is not 0x30, there has been an error |
| 183 |
if response[2] != 0x30 or response[3] != 0x30: |
| 184 |
self.data['status'] = response[2:4].decode('cp1251') |
| 185 |
_logger.error( |
| 186 |
"Sent request: %s,\n Received fiscal device error: %s \n Received command error: %s", |
| 187 |
request, FD_ERRORS.get(response[2], 'Unknown fiscal device error'), |
| 188 |
COMMAND_ERRORS.get(response[3], 'Unknown command error'), |
| 189 |
) |
| 190 |
self.abort_post() |
| 191 |
break |
| 192 |
replies.append('') |
| 193 |
elif response[0] == NACK: |
| 194 |
self.data['status'] = "Received NACK" |
| 195 |
_logger.error("Sent request: %s,\n Received NACK \x15", request) |
| 196 |
self.abort_post() |
| 197 |
break |
| 198 |
elif response[0] == 0x02: |
| 199 |
self.data['status'] = "ok" |
| 200 |
size = response[1] - 35 |
| 201 |
reply = response[4:4 + size] |
| 202 |
replies.append(reply.decode('cp1251')) |
| 203 |
return {'replies': replies, 'status': self.data['status']} |
| 204 |
|
| 205 |
def abort_post(self): |
| 206 |
""" Cancel the posting of the invoice |
| 207 |
|
| 208 |
In the event of an error, it is better to try to cancel the posting of |
| 209 |
the invoice, since the state of the invoice on the device will remain |
| 210 |
open otherwise, blocking further invoices being sent. |
| 211 |
""" |
| 212 |
self.message_number += 1 |
| 213 |
abort = struct.pack('BBB', 35, self.message_number + 32, 0x39) |
| 214 |
request = struct.pack('B3s2sB', STX, abort, self.generate_checksum(abort), ETX) |
| 215 |
self._connection.write(request) |
| 216 |
_logger.debug('Debug abort_post request: %s', request) |
| 217 |
response = self._connection.read(COMMAND_OUTPUT_SIZE[0x39]) |
| 218 |
_logger.debug('Debug abort_post response: %s', response) |
| 219 |
if response and response[0] == 0x02: |
| 220 |
self.data['status'] += "\n The invoice was successfully cancelled" |
| 221 |
_logger.info("Invoice successfully cancelled") |
| 222 |
else: |
| 223 |
self.data['status'] += "\n The invoice could not be cancelled." |
| 224 |
_logger.error("Failed to cancel invoice, received response: %s", response) |
| 225 |
|
| 226 |
|
| 227 |
class TremolG03Controller(http.Controller): |
| 228 |
|
| 229 |
@route.iot_route('/hw_proxy/l10n_ke_cu_send', type='http', cors='*', csrf=False, methods=['POST']) |
| 230 |
def l10n_ke_cu_send(self, messages, company_vat): |
| 231 |
""" Posts the messages sent to this endpoint to the fiscal device connected to the server |
| 232 |
|
| 233 |
:param messages: The messages (consisting of <CMD> and <DATA>) to |
| 234 |
send to the fiscal device. |
| 235 |
:returns: Dictionary containing a list of the responses from |
| 236 |
fiscal device and status of the fiscal device. |
| 237 |
""" |
| 238 |
device = TremolG03Driver.get_default_device() |
| 239 |
if device: |
| 240 |
# First run the command to get the fiscal device numbers |
| 241 |
device_numbers = device.send([b'\x60']) |
| 242 |
# If the vat doesn't match, abort |
| 243 |
if device_numbers['status'] != 'ok': |
| 244 |
return device_numbers |
| 245 |
serial_number, device_vat, _dummy = device_numbers['replies'][0].split(';') |
| 246 |
if device_vat != company_vat: |
| 247 |
return json.dumps({'status': 'The company vat number does not match that of the device'}) |
| 248 |
messages = json.loads(messages) |
| 249 |
device.message_number = 0 |
| 250 |
resp = json.dumps({**device.send([msg.encode('cp1251') for msg in messages]), 'serial_number': serial_number}) |
| 251 |
return resp |
| 252 |
else: |
| 253 |
return json.dumps({'status': 'The fiscal device is not connected to the proxy server'}) |