Debian Codegraph @

src/fenrirscreenreader/speechDriver/hardwareSerialDriver.py

raw
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3
4 # Fenrir TTY screen reader
5 # By Chrys, Storm Dragon, and contributors.
6
7 import os
8 import termios
9 import threading
10 import tty
11 from queue import Empty
12 from queue import Queue
13
14 from fenrirscreenreader.core import debug
15 from fenrirscreenreader.core.speechDriver import speech_driver
16
17
18 class SpeakQueue(Queue):
19 def clear(self):
20 try:
21 while True:
22 self.get_nowait()
23 except Empty:
24 pass
25
26
27 class hardware_serial_driver(speech_driver):
28 cancel_command = b""
29 default_baud_rate = 9600
30 use_xon_xoff = False
31
32 def __init__(self):
33 speech_driver.__init__(self)
34 self.device = ""
35 self.baud_rate = self.default_baud_rate
36 self.serial_port = None
37 self.text_queue = SpeakQueue()
38 self.lock = threading.Lock()
39 self.worker_thread = None
40 self._stop_worker = False
41 self._setting_cache = {}
42
43 def initialize(self, environment):
44 self.env = environment
45 self._is_initialized = False
46 self._reset_setting_cache()
47 settings_manager = self.env["runtime"]["SettingsManager"]
48 self.device = self._clean_device_setting(
49 settings_manager.get_setting("speech", "hardware_device")
50 )
51 self.baud_rate = settings_manager.get_setting_as_int(
52 "speech", "hardware_baud_rate"
53 )
54 self._debug(
55 "Hardware speech initialize: "
56 f"requested_device={self.device}, baud_rate={self.baud_rate}",
57 debug.DebugLevel.INFO,
58 on_any_level=True,
59 )
60 self._open_serial_port()
61 self._is_initialized = self.serial_port is not None
62 if not self._is_initialized:
63 raise RuntimeError("hardware speech device is not available")
64 if self._is_initialized:
65 self._stop_worker = False
66 self.worker_thread = threading.Thread(
67 target=self._worker, daemon=True
68 )
69 self.worker_thread.start()
70
71 def _clean_device_setting(self, device):
72 if not isinstance(device, str):
73 return ""
74 device = device.split("#", 1)[0].split(";", 1)[0].strip()
75 return device
76
77 def shutdown(self):
78 if not self._is_initialized:
79 return
80 self._stop_worker = True
81 self.clear_buffer()
82 self.text_queue.put(None)
83 if self.worker_thread:
84 self.worker_thread.join(timeout=0.5)
85 self._close_serial_port()
86 self._is_initialized = False
87
88 def speak(self, text, queueable=True, ignore_punctuation=False):
89 if not self._is_initialized:
90 return
91 if not queueable:
92 self.cancel()
93 if not isinstance(text, str) or text == "":
94 return
95 self._debug(
96 "Hardware speech queued text: "
97 f"{len(text)} chars, queue_size={self.text_queue.qsize()}",
98 debug.DebugLevel.INFO,
99 on_any_level=True,
100 )
101 self.text_queue.put(text)
102
103 def cancel(self):
104 if not self._is_initialized:
105 return
106 self.clear_buffer()
107 if self.cancel_command:
108 self._write_bytes(self.cancel_command, "cancel")
109
110 def clear_buffer(self):
111 if not self._is_initialized:
112 return
113 self.text_queue.clear()
114
115 def set_rate(self, rate):
116 if not self._is_initialized:
117 return
118 if not isinstance(rate, float):
119 return
120 self._write_setting_command("rate", self._rate_command(rate))
121
122 def set_pitch(self, pitch):
123 if not self._is_initialized:
124 return
125 if not isinstance(pitch, float):
126 return
127 self._write_setting_command("pitch", self._pitch_command(pitch))
128
129 def set_volume(self, volume):
130 if not self._is_initialized:
131 return
132 if not isinstance(volume, float):
133 return
134 self._write_setting_command("volume", self._volume_command(volume))
135
136 def _reset_setting_cache(self):
137 self._setting_cache = {}
138
139 def _write_setting_command(self, setting, command):
140 if self._setting_cache.get(setting) == command:
141 return
142 if self._write_bytes(command, setting):
143 self._setting_cache[setting] = command
144
145 def _worker(self):
146 while not self._stop_worker:
147 text = self.text_queue.get()
148 if text is None:
149 return
150 try:
151 data = self._speak_bytes(text)
152 self._debug(
153 "Hardware speech worker prepared speech bytes: "
154 f"{len(data)} bytes",
155 debug.DebugLevel.INFO,
156 on_any_level=True,
157 )
158 self._write_bytes(data, "speech")
159 except Exception as error:
160 self._debug(
161 f"Hardware speech worker failed: {error}",
162 debug.DebugLevel.ERROR,
163 on_any_level=True,
164 )
165
166 def _open_serial_port(self):
167 if not self.device or self.device == "auto":
168 self._debug(
169 "Hardware speech requires an explicit serial device",
170 debug.DebugLevel.ERROR,
171 on_any_level=True,
172 )
173 return
174
175 port = self._open_configured_serial_port(self.device)
176 if port is not None:
177 self._activate_serial_port(self.device, port)
178
179 def _open_configured_serial_port(self, device):
180 port = None
181 try:
182 port = os.open(device, os.O_RDWR | os.O_NOCTTY)
183 tty.setraw(port)
184 attrs = termios.tcgetattr(port)
185 attrs[2] |= termios.CLOCAL | termios.CREAD
186 baud_rate = self._termios_baud_rate(self.baud_rate)
187 attrs[4] = baud_rate
188 attrs[5] = baud_rate
189 attrs[6][termios.VMIN] = 0
190 attrs[6][termios.VTIME] = 0
191 if self.use_xon_xoff:
192 attrs[0] |= termios.IXON
193 attrs[0] &= ~(termios.IXOFF | termios.IXANY)
194 else:
195 attrs[0] &= ~(termios.IXON | termios.IXOFF | termios.IXANY)
196 termios.tcsetattr(port, termios.TCSANOW, attrs)
197 return port
198 except (OSError, termios.error) as error:
199 self._close_port(port)
200 self._debug(
201 f"Hardware speech device open failed: {device}: {error}",
202 debug.DebugLevel.ERROR,
203 on_any_level=True,
204 )
205 return None
206
207 def _activate_serial_port(self, device, port):
208 self.serial_port = port
209 self.device = device
210 self._debug(
211 "Hardware speech device opened: "
212 f"{device}, baud_rate={self.baud_rate}",
213 debug.DebugLevel.INFO,
214 on_any_level=True,
215 )
216
217 def _close_serial_port(self):
218 with self.lock:
219 if self.serial_port is None:
220 return
221 self._close_port(self.serial_port)
222 self.serial_port = None
223
224 def _close_port(self, port):
225 if port is None:
226 return
227 try:
228 os.close(port)
229 except OSError as error:
230 self._debug(
231 f"Hardware speech device close failed: {error}",
232 debug.DebugLevel.WARNING,
233 )
234
235 def _write_bytes(self, data, description="data"):
236 if not data:
237 return False
238 with self.lock:
239 if self.serial_port is None:
240 return False
241 try:
242 total_written = 0
243 while total_written < len(data):
244 bytes_written = os.write(
245 self.serial_port, data[total_written:]
246 )
247 if bytes_written == 0:
248 raise OSError("serial write returned 0 bytes")
249 total_written += bytes_written
250 preview = self._format_bytes_preview(data)
251 self._debug(
252 "Hardware speech wrote "
253 f"{total_written} {description} bytes: {preview}",
254 debug.DebugLevel.INFO,
255 on_any_level=True,
256 )
257 return True
258 except OSError as error:
259 self._debug(
260 f"Hardware speech write failed: {error}",
261 debug.DebugLevel.ERROR,
262 on_any_level=True,
263 )
264 return False
265
266 def _termios_baud_rate(self, baud_rate):
267 baud_name = f"B{baud_rate}"
268 if hasattr(termios, baud_name):
269 return getattr(termios, baud_name)
270 self._debug(
271 f"Unsupported hardware speech baud rate {baud_rate}; using 9600",
272 debug.DebugLevel.WARNING,
273 )
274 return termios.B9600
275
276 def _clean_text(self, text):
277 text = text.replace("\r", " ").replace("\n", " ")
278 return "".join(
279 char if 0x20 <= ord(char) <= 0x7E else " "
280 for char in text
281 )
282
283 def _scale(self, value, minimum, maximum):
284 value = max(0.0, min(1.0, value))
285 return int(round(minimum + value * (maximum - minimum)))
286
287 def _format_bytes_preview(self, data, limit=32):
288 preview = data[:limit]
289 hex_preview = " ".join(f"{byte:02x}" for byte in preview)
290 ascii_preview = "".join(
291 chr(byte) if 0x20 <= byte <= 0x7E else "."
292 for byte in preview
293 )
294 suffix = "" if len(data) <= limit else " ..."
295 return (
296 f"hex=[{hex_preview}{suffix}] "
297 f"ascii=[{ascii_preview}{suffix}]"
298 )
299
300 def _debug(self, message, level, on_any_level=False):
301 try:
302 self.env["runtime"]["DebugManager"].write_debug_out(
303 message, level, on_any_level=on_any_level
304 )
305 except Exception:
306 pass
307
308 def _speak_bytes(self, text):
309 raise NotImplementedError
310
311 def _rate_command(self, rate):
312 return b""
313
314 def _pitch_command(self, pitch):
315 return b""
316
317 def _volume_command(self, volume):
318 return b""