summaryrefslogtreecommitdiff
path: root/kvmd/plugins/hid/otg/device.py
blob: 112d8bec6a279c7a2bf61eec50a39375607f56de (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# ========================================================================== #
#                                                                            #
#    KVMD - The main PiKVM daemon.                                           #
#                                                                            #
#    Copyright (C) 2018-2022  Maxim Devaev <[email protected]>               #
#                                                                            #
#    This program is free software: you can redistribute it and/or modify    #
#    it under the terms of the GNU General Public License as published by    #
#    the Free Software Foundation, either version 3 of the License, or       #
#    (at your option) any later version.                                     #
#                                                                            #
#    This program is distributed in the hope that it will be useful,         #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of          #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           #
#    GNU General Public License for more details.                            #
#                                                                            #
#    You should have received a copy of the GNU General Public License       #
#    along with this program.  If not, see <https://www.gnu.org/licenses/>.  #
#                                                                            #
# ========================================================================== #


import os
import select
import multiprocessing
import queue
import errno
import time

from typing import Dict
from typing import Generator

from ....logging import get_logger

from .... import tools
from .... import aiomulti
from .... import aioproc
from .... import usb

from .events import BaseEvent


# =====
class BaseDeviceProcess(multiprocessing.Process):  # pylint: disable=too-many-instance-attributes
    def __init__(  # pylint: disable=too-many-arguments
        self,
        name: str,
        read_size: int,
        initial_state: Dict,
        notifier: aiomulti.AioProcessNotifier,

        device_path: str,
        select_timeout: float,
        queue_timeout: float,
        write_retries: int,
        noop: bool,
    ) -> None:

        super().__init__(daemon=True)

        self.__name = name
        self.__read_size = read_size

        self.__device_path = device_path
        self.__select_timeout = select_timeout
        self.__queue_timeout = queue_timeout
        self.__write_retries = write_retries
        self.__noop = noop

        self.__udc_state_path = ""
        self.__fd = -1
        self.__events_queue: "multiprocessing.Queue[BaseEvent]" = multiprocessing.Queue()
        self.__state_flags = aiomulti.AioSharedFlags({"online": True, **initial_state}, notifier)
        self.__stop_event = multiprocessing.Event()

    def start(self, udc: str) -> None:  # type: ignore  # pylint: disable=arguments-differ
        self.__udc_state_path = usb.get_udc_path(udc, usb.U_STATE)
        super().start()

    def run(self) -> None:  # pylint: disable=too-many-branches
        logger = aioproc.settle(f"HID-{self.__name}", f"hid-{self.__name}")
        report = b""
        retries = 0
        while not self.__stop_event.is_set():
            try:
                while not self.__stop_event.is_set():
                    if self.__ensure_device():
                        self.__read_all_reports()

                    try:
                        event = self.__events_queue.get(timeout=self.__queue_timeout)
                    except queue.Empty:
                        # Проблема в том, что устройство может отвечать EAGAIN или ESHUTDOWN,
                        # если оно было отключено физически. См:
                        #    - https://github.com/raspberrypi/linux/issues/3870
                        #    - https://github.com/raspberrypi/linux/pull/3151
                        # Так что нам нужно проверять состояние контроллера, чтобы не спамить
                        # в устройство и отслеживать его состояние.
                        if not self.__is_udc_configured():
                            self.__state_flags.update(online=False)
                    else:
                        # Посылка свежих репортов важнее старого
                        for report in self._process_event(event):
                            retries = self.__write_retries
                            if self.__ensure_device():
                                if self.__write_report(report):
                                    retries = 0
                        continue

                    # Повторение последнего репорта до победного или пока не кончатся попытки
                    if retries > 0 and self.__ensure_device():
                        if self.__write_report(report):
                            retries = 0
                        else:
                            retries -= 1

            except Exception:
                logger.exception("Unexpected HID-%s error", self.__name)
                time.sleep(1)

        self.__close_device()

    async def get_state(self) -> Dict:
        return (await self.__state_flags.get())

    # =====

    def _process_event(self, event: BaseEvent) -> Generator[bytes, None, None]:  # pylint: disable=unused-argument
        if self is not None:  # XXX: Vulture and pylint hack
            raise NotImplementedError()
        yield

    def _process_read_report(self, report: bytes) -> None:
        pass

    def _update_state(self, **kwargs: bool) -> None:
        assert "online" not in kwargs
        self.__state_flags.update(**kwargs)

    # =====

    def _stop(self) -> None:
        if self.is_alive():
            get_logger().info("Stopping HID-%s daemon ...", self.__name)
            self.__stop_event.set()
        if self.is_alive() or self.exitcode is not None:
            self.join()

    def _queue_event(self, event: BaseEvent) -> None:
        self.__events_queue.put_nowait(event)

    def _clear_queue(self) -> None:
        tools.clear_queue(self.__events_queue)

    def _cleanup_write(self, report: bytes) -> None:
        assert not self.is_alive()
        assert self.__fd < 0
        if self.__ensure_device():
            self.__write_report(report)
            self.__close_device()

    # =====

    def __is_udc_configured(self) -> bool:
        with open(self.__udc_state_path) as udc_state_file:
            return (udc_state_file.read().strip().lower() == "configured")

    def __write_report(self, report: bytes) -> bool:
        assert report

        if self.__noop:
            return True

        assert self.__fd >= 0
        logger = get_logger()

        try:
            written = os.write(self.__fd, report)
            if written == len(report):
                self.__state_flags.update(online=True)
                return True
            else:
                logger.error("HID-%s write() error: written (%s) != report length (%d)",
                             self.__name, written, len(report))
        except Exception as err:
            if isinstance(err, OSError) and (
                # https://github.com/raspberrypi/linux/commit/61b7f805dc2fd364e0df682de89227e94ce88e25
                err.errno == errno.EAGAIN  # pylint: disable=no-member
                or err.errno == errno.ESHUTDOWN  # pylint: disable=no-member
            ):
                logger.debug("HID-%s busy/unplugged (write): %s", self.__name, tools.efmt(err))
            else:
                logger.exception("Can't write report to HID-%s", self.__name)

        self.__state_flags.update(online=False)
        return False

    def __read_all_reports(self) -> None:
        if self.__noop or self.__read_size == 0:
            return

        assert self.__fd >= 0
        logger = get_logger()

        read = True
        while read:
            try:
                read = bool(select.select([self.__fd], [], [], 0)[0])
            except Exception as err:
                logger.error("Can't select() for read HID-%s: %s", self.__name, tools.efmt(err))
                break

            if read:
                try:
                    report = os.read(self.__fd, self.__read_size)
                except Exception as err:
                    if isinstance(err, OSError) and err.errno == errno.EAGAIN:  # pylint: disable=no-member
                        logger.debug("HID-%s busy/unplugged (read): %s", self.__name, tools.efmt(err))
                    else:
                        logger.exception("Can't read report from HID-%s", self.__name)
                else:
                    self._process_read_report(report)

    def __ensure_device(self) -> bool:
        if self.__noop:
            return True

        logger = get_logger()

        if self.__fd < 0:
            if os.path.exists(self.__device_path):
                try:
                    flags = os.O_NONBLOCK
                    flags |= (os.O_RDWR if self.__read_size else os.O_WRONLY)
                    self.__fd = os.open(self.__device_path, flags)
                except Exception as err:
                    logger.error("Can't open HID-%s device %s: %s",
                                 self.__name, self.__device_path, tools.efmt(err))
                    time.sleep(1)
            else:
                time.sleep(1)

        if self.__fd >= 0:
            try:
                if select.select([], [self.__fd], [], self.__select_timeout)[1]:
                    # Закомментировано, потому что иногда запись доступна, но устройство отключено
                    # self.__state_flags.update(online=True)
                    return True
                else:
                    # Если запись недоступна, то скорее всего устройство отключено
                    logger.debug("HID-%s is busy/unplugged (write select)", self.__name)
            except Exception as err:
                logger.error("Can't select() for write HID-%s: %s", self.__name, tools.efmt(err))

        self.__state_flags.update(online=False)
        return False

    def __close_device(self) -> None:
        if self.__fd >= 0:
            try:
                os.close(self.__fd)
            except Exception:
                pass
            finally:
                self.__fd = -1