refactoring

This commit is contained in:
Devaev Maxim 2020-09-08 05:24:47 +03:00
parent 4cc60e4d52
commit 605b67ca76
8 changed files with 35 additions and 35 deletions

View File

@ -172,7 +172,7 @@ class Streamer: # pylint: disable=too-many-instance-attributes
self.__snapshot: Optional[StreamerSnapshot] = None self.__snapshot: Optional[StreamerSnapshot] = None
self.__state_notifier = aiotools.AioNotifier() self.__notifier = aiotools.AioNotifier()
# ===== # =====
@ -277,7 +277,7 @@ class Streamer: # pylint: disable=too-many-instance-attributes
async def poll_state(self) -> AsyncGenerator[Dict, None]: async def poll_state(self) -> AsyncGenerator[Dict, None]:
def signal_handler(*_: Any) -> None: def signal_handler(*_: Any) -> None:
get_logger(0).info("Got SIGUSR2, checking the stream state ...") get_logger(0).info("Got SIGUSR2, checking the stream state ...")
asyncio.ensure_future(self.__state_notifier.notify()) asyncio.ensure_future(self.__notifier.notify())
get_logger(0).info("Installing SIGUSR2 streamer handler ...") get_logger(0).info("Installing SIGUSR2 streamer handler ...")
asyncio.get_event_loop().add_signal_handler(signal.SIGUSR2, signal_handler) asyncio.get_event_loop().add_signal_handler(signal.SIGUSR2, signal_handler)
@ -291,7 +291,7 @@ class Streamer: # pylint: disable=too-many-instance-attributes
prev_state = state prev_state = state
if waiter_task is None: if waiter_task is None:
waiter_task = asyncio.create_task(self.__state_notifier.wait()) waiter_task = asyncio.create_task(self.__notifier.wait())
if waiter_task in (await aiotools.wait_first(asyncio.sleep(self.__state_poll), waiter_task))[0]: if waiter_task in (await aiotools.wait_first(asyncio.sleep(self.__state_poll), waiter_task))[0]:
waiter_task = None waiter_task = None
@ -328,7 +328,7 @@ class Streamer: # pylint: disable=too-many-instance-attributes
) )
if save: if save:
self.__snapshot = snapshot self.__snapshot = snapshot
await self.__state_notifier.notify() await self.__notifier.notify()
return snapshot return snapshot
logger.error("Stream is offline, no signal or so") logger.error("Stream is offline, no signal or so")
except (aiohttp.ClientConnectionError, aiohttp.ServerConnectionError) as err: except (aiohttp.ClientConnectionError, aiohttp.ServerConnectionError) as err:

View File

@ -215,12 +215,12 @@ class UserGpio:
def __init__(self, config: Section) -> None: def __init__(self, config: Section) -> None:
self.__view = config.view self.__view = config.view
self.__state_notifier = aiotools.AioNotifier() self.__notifier = aiotools.AioNotifier()
self.__drivers = { self.__drivers = {
driver: get_ugpio_driver_class(drv_config.type)( driver: get_ugpio_driver_class(drv_config.type)(
instance_name=driver, instance_name=driver,
notifier=self.__state_notifier, notifier=self.__notifier,
**drv_config._unpack(ignore=["instance_name", "notifier", "type"]), **drv_config._unpack(ignore=["instance_name", "notifier", "type"]),
) )
for (driver, drv_config) in config.drivers.items() for (driver, drv_config) in config.drivers.items()
@ -236,7 +236,7 @@ class UserGpio:
if ch_config.mode == "input": if ch_config.mode == "input":
self.__inputs[channel] = _GpioInput(channel, ch_config, driver) self.__inputs[channel] = _GpioInput(channel, ch_config, driver)
else: # output: else: # output:
self.__outputs[channel] = _GpioOutput(channel, ch_config, driver, self.__state_notifier) self.__outputs[channel] = _GpioOutput(channel, ch_config, driver, self.__notifier)
async def get_model(self) -> Dict: async def get_model(self) -> Dict:
return { return {
@ -260,7 +260,7 @@ class UserGpio:
if state != prev_state: if state != prev_state:
yield state yield state
prev_state = state prev_state = state
await self.__state_notifier.wait() await self.__notifier.wait()
def sysprep(self) -> None: def sysprep(self) -> None:
get_logger().info("Preparing User-GPIO drivers ...") get_logger().info("Preparing User-GPIO drivers ...")

View File

@ -71,13 +71,13 @@ class Plugin(BaseAtx): # pylint: disable=too-many-instance-attributes
self.__click_delay = click_delay self.__click_delay = click_delay
self.__long_click_delay = long_click_delay self.__long_click_delay = long_click_delay
self.__state_notifier = aiotools.AioNotifier() self.__notifier = aiotools.AioNotifier()
self.__region = aiotools.AioExclusiveRegion(AtxIsBusyError, self.__state_notifier) self.__region = aiotools.AioExclusiveRegion(AtxIsBusyError, self.__notifier)
self.__reader = gpio.BatchReader( self.__reader = gpio.BatchReader(
pins=set([self.__power_led_pin, self.__hdd_led_pin]), pins=set([self.__power_led_pin, self.__hdd_led_pin]),
interval=state_poll, interval=state_poll,
notifier=self.__state_notifier, notifier=self.__notifier,
) )
@classmethod @classmethod
@ -113,7 +113,7 @@ class Plugin(BaseAtx): # pylint: disable=too-many-instance-attributes
if state != prev_state: if state != prev_state:
yield state yield state
prev_state = state prev_state = state
await self.__state_notifier.wait() await self.__notifier.wait()
async def systask(self) -> None: async def systask(self) -> None:
await self.__reader.poll() await self.__reader.poll()

View File

@ -51,10 +51,10 @@ class Plugin(BaseHid):
noop: bool, noop: bool,
) -> None: ) -> None:
self.__state_notifier = aiomulti.AioProcessNotifier() self.__notifier = aiomulti.AioProcessNotifier()
self.__keyboard_proc = KeyboardProcess(noop=noop, state_notifier=self.__state_notifier, **keyboard) self.__keyboard_proc = KeyboardProcess(noop=noop, notifier=self.__notifier, **keyboard)
self.__mouse_proc = MouseProcess(noop=noop, state_notifier=self.__state_notifier, **mouse) self.__mouse_proc = MouseProcess(noop=noop, notifier=self.__notifier, **mouse)
@classmethod @classmethod
def get_plugin_options(cls) -> Dict: def get_plugin_options(cls) -> Dict:
@ -101,7 +101,7 @@ class Plugin(BaseHid):
if state != prev_state: if state != prev_state:
yield state yield state
prev_state = state prev_state = state
await self.__state_notifier.wait() await self.__notifier.wait()
async def reset(self) -> None: async def reset(self) -> None:
self.__keyboard_proc.send_reset_event() self.__keyboard_proc.send_reset_event()

View File

@ -47,7 +47,7 @@ class BaseDeviceProcess(multiprocessing.Process): # pylint: disable=too-many-in
name: str, name: str,
read_size: int, read_size: int,
initial_state: Dict, initial_state: Dict,
state_notifier: aiomulti.AioProcessNotifier, notifier: aiomulti.AioProcessNotifier,
device_path: str, device_path: str,
select_timeout: float, select_timeout: float,
@ -69,7 +69,7 @@ class BaseDeviceProcess(multiprocessing.Process): # pylint: disable=too-many-in
self.__fd = -1 self.__fd = -1
self.__events_queue: multiprocessing.queues.Queue = multiprocessing.Queue() self.__events_queue: multiprocessing.queues.Queue = multiprocessing.Queue()
self.__state_flags = aiomulti.AioSharedFlags({"online": True, **initial_state}, state_notifier) self.__state_flags = aiomulti.AioSharedFlags({"online": True, **initial_state}, notifier)
self.__stop_event = multiprocessing.Event() self.__stop_event = multiprocessing.Event()
def run(self) -> None: def run(self) -> None:

View File

@ -191,13 +191,13 @@ class Plugin(BaseHid, multiprocessing.Process): # pylint: disable=too-many-inst
self.__events_queue: multiprocessing.queues.Queue = multiprocessing.Queue() self.__events_queue: multiprocessing.queues.Queue = multiprocessing.Queue()
self.__state_notifier = aiomulti.AioProcessNotifier() self.__notifier = aiomulti.AioProcessNotifier()
self.__state_flags = aiomulti.AioSharedFlags({ self.__state_flags = aiomulti.AioSharedFlags({
"online": True, "online": True,
"caps": False, "caps": False,
"scroll": False, "scroll": False,
"num": False, "num": False,
}, self.__state_notifier) }, self.__notifier)
self.__stop_event = multiprocessing.Event() self.__stop_event = multiprocessing.Event()
@ -243,7 +243,7 @@ class Plugin(BaseHid, multiprocessing.Process): # pylint: disable=too-many-inst
if state != prev_state: if state != prev_state:
yield state yield state
prev_state = state prev_state = state
await self.__state_notifier.wait() await self.__notifier.wait()
@aiotools.atomic @aiotools.atomic
async def reset(self) -> None: async def reset(self) -> None:

View File

@ -155,8 +155,8 @@ class Plugin(BaseMsd): # pylint: disable=too-many-instance-attributes
self.__new_file_written = 0 self.__new_file_written = 0
self.__new_file_tick = 0.0 self.__new_file_tick = 0.0
self.__state_notifier = aiotools.AioNotifier() self.__notifier = aiotools.AioNotifier()
self.__state = _State(self.__state_notifier) self.__state = _State(self.__notifier)
logger = get_logger(0) logger = get_logger(0)
logger.info("Using OTG gadget %r as MSD", gadget) logger.info("Using OTG gadget %r as MSD", gadget)
@ -212,7 +212,7 @@ class Plugin(BaseMsd): # pylint: disable=too-many-instance-attributes
if state != prev_state: if state != prev_state:
yield state yield state
prev_state = state prev_state = state
await self.__state_notifier.wait() await self.__notifier.wait()
async def systask(self) -> None: async def systask(self) -> None:
await self.__watch_inotify() await self.__watch_inotify()
@ -294,7 +294,7 @@ class Plugin(BaseMsd): # pylint: disable=too-many-instance-attributes
async with self.__state._region: # pylint: disable=protected-access async with self.__state._region: # pylint: disable=protected-access
try: try:
async with self.__state._lock: # pylint: disable=protected-access async with self.__state._lock: # pylint: disable=protected-access
await self.__state_notifier.notify() await self.__notifier.notify()
assert self.__state.storage assert self.__state.storage
assert self.__state.vd assert self.__state.vd
@ -310,7 +310,7 @@ class Plugin(BaseMsd): # pylint: disable=too-many-instance-attributes
self.__new_file_written = 0 self.__new_file_written = 0
self.__new_file = await aiofiles.open(path, mode="w+b", buffering=0) self.__new_file = await aiofiles.open(path, mode="w+b", buffering=0)
await self.__state_notifier.notify() await self.__notifier.notify()
yield yield
self.__set_image_complete(name, True) self.__set_image_complete(name, True)
@ -324,7 +324,7 @@ class Plugin(BaseMsd): # pylint: disable=too-many-instance-attributes
# Между закрытием файла и эвентом айнотифи состояние может быть не обновлено, # Между закрытием файла и эвентом айнотифи состояние может быть не обновлено,
# так что форсим обновление вручную, чтобы получить актуальное состояние. # так что форсим обновление вручную, чтобы получить актуальное состояние.
await self.__reload_state() await self.__reload_state()
await self.__state_notifier.notify() await self.__notifier.notify()
async def write_image_chunk(self, chunk: bytes) -> int: async def write_image_chunk(self, chunk: bytes) -> int:
assert self.__new_file assert self.__new_file
@ -334,7 +334,7 @@ class Plugin(BaseMsd): # pylint: disable=too-many-instance-attributes
if self.__new_file_tick + 1 < now: if self.__new_file_tick + 1 < now:
# Это нужно для ручного оповещения о свободном пространстве на диске, см. get_state() # Это нужно для ручного оповещения о свободном пространстве на диске, см. get_state()
self.__new_file_tick = now self.__new_file_tick = now
await self.__state_notifier.notify() await self.__notifier.notify()
return self.__new_file_written return self.__new_file_written
@aiotools.atomic @aiotools.atomic
@ -382,7 +382,7 @@ class Plugin(BaseMsd): # pylint: disable=too-many-instance-attributes
while True: while True:
# Активно ждем, пока не будут на месте все каталоги. # Активно ждем, пока не будут на месте все каталоги.
await self.__reload_state() await self.__reload_state()
await self.__state_notifier.notify() await self.__notifier.notify()
if self.__state.vd: if self.__state.vd:
break break
await asyncio.sleep(5) await asyncio.sleep(5)
@ -394,7 +394,7 @@ class Plugin(BaseMsd): # pylint: disable=too-many-instance-attributes
# После установки вотчеров еще раз проверяем стейт, чтобы ничего не потерять # После установки вотчеров еще раз проверяем стейт, чтобы ничего не потерять
await self.__reload_state() await self.__reload_state()
await self.__state_notifier.notify() await self.__notifier.notify()
while self.__state.vd: # Если живы после предыдущей проверки while self.__state.vd: # Если живы после предыдущей проверки
need_restart = False need_restart = False
@ -410,7 +410,7 @@ class Plugin(BaseMsd): # pylint: disable=too-many-instance-attributes
break break
if need_reload_state: if need_reload_state:
await self.__reload_state() await self.__reload_state()
await self.__state_notifier.notify() await self.__notifier.notify()
except Exception: except Exception:
logger.exception("Unexpected MSD watcher error") logger.exception("Unexpected MSD watcher error")

View File

@ -179,8 +179,8 @@ class Plugin(BaseMsd): # pylint: disable=too-many-instance-attributes
self.__device_file: Optional[aiofiles.base.AiofilesContextManager] = None self.__device_file: Optional[aiofiles.base.AiofilesContextManager] = None
self.__written = 0 self.__written = 0
self.__state_notifier = aiotools.AioNotifier() self.__notifier = aiotools.AioNotifier()
self.__region = aiotools.AioExclusiveRegion(MsdIsBusyError, self.__state_notifier) self.__region = aiotools.AioExclusiveRegion(MsdIsBusyError, self.__notifier)
logger = get_logger(0) logger = get_logger(0)
logger.info("Using %r as MSD", self.__device_path) logger.info("Using %r as MSD", self.__device_path)
@ -234,7 +234,7 @@ class Plugin(BaseMsd): # pylint: disable=too-many-instance-attributes
if state != prev_state: if state != prev_state:
yield state yield state
prev_state = state prev_state = state
await self.__state_notifier.wait() await self.__notifier.wait()
@aiotools.atomic @aiotools.atomic
async def reset(self) -> None: async def reset(self) -> None:
@ -317,7 +317,7 @@ class Plugin(BaseMsd): # pylint: disable=too-many-instance-attributes
self.__written = 0 self.__written = 0
await self.__write_image_info(name, complete=False) await self.__write_image_info(name, complete=False)
await self.__state_notifier.notify() await self.__notifier.notify()
yield yield
await self.__write_image_info(name, complete=True) await self.__write_image_info(name, complete=True)
finally: finally: