Debian Codegraph @

addons/iot_drivers/iot_handlers/drivers/serial_scale_driver.py

raw
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2
3 import logging
4 import re
5 import serial
6 import threading
7 import time
8
9 from odoo import http
10 from odoo.addons.iot_drivers.controllers.proxy import proxy_drivers
11 from odoo.addons.iot_drivers.event_manager import event_manager
12 from odoo.addons.iot_drivers.iot_handlers.drivers.serial_base_driver import SerialDriver, SerialProtocol, serial_connection
13
14
15 _logger = logging.getLogger(__name__)
16
17 # Only needed to expose scale via hw_proxy (used by Community edition)
18 ACTIVE_SCALE = None
19 new_weight_event = threading.Event()
20
21 # 8217 Mettler-Toledo (Weight-only) Protocol, as described in the scale's Service Manual.
22 # e.g. here: https://www.manualslib.com/manual/861274/Mettler-Toledo-Viva.html?page=51#manual
23 # Our recommended scale, the Mettler-Toledo "Ariva-S", supports this protocol on
24 # both the USB and RS232 ports, it can be configured in the setup menu as protocol option 3.
25 # We use the default serial protocol settings, the scale's settings can be configured in the
26 # scale's menu anyway.
27 Toledo8217Protocol = SerialProtocol(
28 name='Toledo 8217',
29 baudrate=9600,
30 bytesize=serial.SEVENBITS,
31 stopbits=serial.STOPBITS_ONE,
32 parity=serial.PARITY_EVEN,
33 timeout=1,
34 writeTimeout=1,
35 measureRegexp=b"\x02\\s*([0-9.]+)N?\\r",
36 statusRegexp=b"\x02\\s*\\?([^\x00])\\r",
37 commandDelay=0.2,
38 measureDelay=0.5,
39 newMeasureDelay=0.2,
40 commandTerminator=b'',
41 measureCommand=b'W',
42 emptyAnswerValid=False,
43 )
44
45
46 # HW Proxy is used by Community edition
47 class ScaleReadHardwareProxy(http.Controller):
48 @http.route('/hw_proxy/scale_read', type='jsonrpc', auth='none', cors='*')
49 def scale_read(self):
50 if ACTIVE_SCALE:
51 return {'weight': ACTIVE_SCALE._scale_read_hw_proxy()}
52 return None
53
54
55 class ScaleDriver(SerialDriver):
56 """Abstract base class for scale drivers."""
57 last_sent_value = None
58
59 def __init__(self, identifier, device):
60 super().__init__(identifier, device)
61 self.device_type = 'scale'
62 self._set_actions()
63 self._is_reading = True
64
65 # The HW Proxy can only expose one scale,
66 # only the last scale connected is kept
67 global ACTIVE_SCALE # noqa: PLW0603
68 ACTIVE_SCALE = self
69 proxy_drivers['scale'] = ACTIVE_SCALE
70
71 # Used by the HW Proxy in Community edition
72 def get_status(self):
73 """Allows `hw_proxy.Proxy` to retrieve the status of the scales"""
74
75 status = self._status
76 return {'status': status['status'], 'messages': [status['message_title']]}
77
78 def _set_actions(self):
79 """Initializes `self._actions`, a map of action keys sent by the frontend to backend action methods."""
80
81 self._actions.update({
82 'read_once': self._read_once_action,
83 'start_reading': self._start_reading_action,
84 'stop_reading': self._stop_reading_action,
85 })
86
87 def _start_reading_action(self, data):
88 """Starts asking for the scale value."""
89 self._is_reading = True
90
91 def _stop_reading_action(self, data):
92 """Stops asking for the scale value."""
93 self._is_reading = False
94
95 def _read_once_action(self, data):
96 """Reads the scale current weight value and pushes it to the frontend."""
97
98 self._read_weight()
99 self.last_sent_value = self.data['result']
100
101 @staticmethod
102 def _get_raw_response(connection):
103 """Gets raw bytes containing the updated value of the device.
104
105 :param connection: a connection to the device's serial port
106 :type connection: pyserial.Serial
107 :return: the raw response to a weight request
108 :rtype: str
109 """
110
111 answer = []
112 while True:
113 char = connection.read(1)
114 if not char:
115 break
116 else:
117 answer.append(bytes(char))
118 return b''.join(answer)
119
120 def _read_weight(self):
121 """Asks for a new weight from the scale, checks if it is valid and, if it is, makes it the current value."""
122
123 protocol = self._protocol
124 self._connection.write(protocol.measureCommand + protocol.commandTerminator)
125 answer = self._get_raw_response(self._connection)
126 match = re.search(self._protocol.measureRegexp, answer)
127 if match:
128 self.data = {
129 'result': float(match.group(1)),
130 'status': self._status
131 }
132 else:
133 self._read_status(answer)
134
135 # Ensures compatibility with Community edition
136 def _scale_read_hw_proxy(self):
137 """Used when the iot app is not installed"""
138 with self._device_lock:
139 self._read_weight()
140 return self.data['result']
141
142 def _take_measure(self):
143 """Reads the device's weight value, and pushes that value to the frontend."""
144
145 with self._device_lock:
146 self._read_weight()
147 if self.data['result'] != self.last_sent_value or self._status['status'] == self.STATUS_ERROR:
148 self.last_sent_value = self.data['result']
149 event_manager.device_changed(self)
150
151
152 class Toledo8217Driver(ScaleDriver):
153 """Driver for the Toldedo 8217 serial scale."""
154 _protocol = Toledo8217Protocol
155
156 def __init__(self, identifier, device):
157 super().__init__(identifier, device)
158 self.device_manufacturer = 'Toledo'
159
160 @classmethod
161 def supported(cls, device):
162 """Checks whether the device, which port info is passed as argument, is supported by the driver.
163
164 :param device: path to the device
165 :type device: str
166 :return: whether the device is supported by the driver
167 :rtype: bool
168 """
169
170 protocol = cls._protocol
171
172 try:
173 with serial_connection(device['identifier'], protocol, is_probing=True) as connection:
174 connection.reset_input_buffer()
175
176 connection.write(b'Ehello' + protocol.commandTerminator)
177 time.sleep(protocol.commandDelay)
178 answer = connection.read(8)
179 if answer == b'\x02E\rhello':
180 connection.write(b'F' + protocol.commandTerminator)
181 connection.reset_input_buffer()
182 return True
183 except serial.serialutil.SerialTimeoutException:
184 pass
185 except Exception:
186 _logger.exception('Error while probing %s with protocol %s', device, protocol.name)
187 return False
188
189 def _read_status(self, answer):
190 """
191 Status byte in form of an ascii character (Ex: 'D') is sent if scale is in motion, or is net/gross weight is negative or over capacity.
192 Convert the status byte to a binary string, and check its bits to see if there is an error.
193 LSB is the last char so the binary string is read in reverse and the first char is a parity bit, so we ignore it.
194 :param answer: scale answer (Example: b'\x02?D\r')
195 :type answer: bytestring
196 """
197 status_char_error_bits = (
198 'Scale in motion', # 0
199 'Over capacity', # 1
200 'Under zero', # 2
201 'Outside zero capture range', # 3
202 'Center of zero', # 4
203 'Net weight', # 5
204 'Bad Command from host', # 6
205 )
206
207 status_match = self._protocol.statusRegexp and re.search(self._protocol.statusRegexp, answer)
208 if status_match:
209 status_char = status_match.group(1).decode() # Example: b'D' extracted from b'\x02?D\r'
210 binary_status_char = format(ord(status_char), '08b') # Example: '00001101'
211 for index, bit in enumerate(binary_status_char[1:][::-1]): # Read the bits in reverse order (LSB is at the last char) + ignore the first "parity" bit
212 if int(bit):
213 _logger.debug("Scale error: %s. Status string: %s. Scale answer: %s.", status_char_error_bits[index], binary_status_char, answer)
214 self.data = {
215 'result': 0,
216 'status': self._status,
217 }
218 break