Debian Codegraph @

addons/iot_drivers/iot_handlers/drivers/serial_base_driver.py

raw
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2
3 from typing import NamedTuple
4 from contextlib import contextmanager
5 import logging
6 import serial
7 from threading import Lock
8 import time
9 import traceback
10
11 from odoo.addons.iot_drivers.event_manager import event_manager
12 from odoo.addons.iot_drivers.driver import Driver
13
14 _logger = logging.getLogger(__name__)
15
16
17 class SerialProtocol(NamedTuple):
18 name: any
19 baudrate: any
20 bytesize: any
21 stopbits: any
22 parity: any
23 timeout: any
24 writeTimeout: any
25 measureRegexp: any
26 statusRegexp: any
27 commandTerminator: any
28 commandDelay: any
29 measureDelay: any
30 newMeasureDelay: any
31 measureCommand: any
32 emptyAnswerValid: any
33
34
35 @contextmanager
36 def serial_connection(path, protocol, is_probing=False):
37 """Opens a serial connection to a device and closes it automatically after use.
38
39 :param path: path to the device
40 :type path: string
41 :param protocol: an object containing the serial protocol to connect to a device
42 :type protocol: namedtuple
43 :param is_probing: a flag thet if set to `True` makes the timeouts longer, defaults to False
44 :type is_probing: bool, optional
45 """
46
47 PROBING_TIMEOUT = 1
48 port_config = {
49 'baudrate': protocol.baudrate,
50 'bytesize': protocol.bytesize,
51 'stopbits': protocol.stopbits,
52 'parity': protocol.parity,
53 'timeout': PROBING_TIMEOUT if is_probing else protocol.timeout, # longer timeouts for probing
54 'writeTimeout': PROBING_TIMEOUT if is_probing else protocol.writeTimeout # longer timeouts for probing
55 }
56 connection = serial.Serial(path, **port_config)
57 yield connection
58 connection.close()
59
60
61 class SerialDriver(Driver):
62 """Abstract base class for serial drivers."""
63
64 _protocol = None
65 connection_type = 'serial'
66
67 STATUS_CONNECTED = 'connected'
68 STATUS_ERROR = 'error'
69 STATUS_CONNECTING = 'connecting'
70 STATUS_DISCONNECTED = 'disconnected'
71
72 def __init__(self, identifier, device):
73 """ Attributes initialization method for `SerialDriver`.
74
75 :param device: path to the device
76 :type device: str
77 """
78
79 super().__init__(identifier, device)
80 self._actions.update({
81 'get_status': self._push_status,
82 })
83 self.device_connection = 'serial'
84 self._device_lock = Lock()
85 self._status = {'status': self.STATUS_CONNECTING, 'message_title': '', 'message_body': ''}
86 self._set_name()
87
88 def _get_raw_response(connection):
89 pass
90
91 def _push_status(self):
92 """Updates the current status and pushes it to the frontend."""
93
94 self.data['status'] = self._status
95
96 def _set_name(self):
97 """Tries to build the device's name based on its type and protocol name but falls back on a default name if that doesn't work."""
98
99 try:
100 name = ('%s serial %s' % (self._protocol.name, self.device_type)).title()
101 except Exception: # noqa: BLE001
102 name = 'Unknown Serial Device'
103 self.device_name = name
104
105 def _take_measure(self):
106 pass
107
108 def _do_action(self, data):
109 """Helper function that calls a specific action method on the device.
110
111 :param data: the `_actions` key mapped to the action method we want to call
112 :type data: string
113 """
114
115 with self._device_lock:
116 try:
117 self._actions[data['action']](data)
118 time.sleep(self._protocol.commandDelay)
119 self._status = {'status': self.STATUS_CONNECTED, 'message_title': '', 'message_body': ''}
120 except Exception:
121 msg = f'An error occurred while performing action "{data}" on "{self.device_name}"'
122 _logger.exception(msg)
123 self._status = {'status': self.STATUS_ERROR, 'message_title': msg, 'message_body': traceback.format_exc()}
124 self._push_status()
125
126 def action(self, data):
127 """Establish a connection with the device if needed and have it perform a specific action.
128
129 :param data: the `_actions` key mapped to the action method we want to call
130 :type data: string
131 """
132 self.data["owner"] = data.get('session_id')
133 self.data["action_args"] = {**data}
134
135 if self._connection and self._connection.isOpen():
136 self._do_action(data)
137 else:
138 with serial_connection(self.device_identifier, self._protocol) as connection:
139 self._connection = connection
140 self._do_action(data)
141 event_manager.device_changed(self, data) # Make response available to /event route or websocket
142
143 def run(self):
144 """Continuously gets new measures from the device."""
145
146 try:
147 with serial_connection(self.device_identifier, self._protocol) as connection:
148 self._connection = connection
149 self._status['status'] = self.STATUS_CONNECTED
150 self._push_status()
151 while not self._stopped.is_set():
152 self._take_measure()
153 time.sleep(self._protocol.newMeasureDelay)
154 self._status['status'] = self.STATUS_DISCONNECTED
155 self._push_status()
156 except Exception:
157 msg = 'Error while reading %s' % self.device_name
158 _logger.exception(msg)
159 self._status = {'status': self.STATUS_ERROR, 'message_title': msg, 'message_body': traceback.format_exc()}
160 self._push_status()