"""Muting the TV while the box listens: the button service's side. For the whole of a conversation, the button service holds a connection to the ir service's conversation socket (../ir-server.js); if the brain has turned muting on, the ir service mutes the TV when the connection opens and unmutes it when it closes. This side can't send any code, nor tell whether muting is on: the connection says only that a conversation is going on. """ import logging from contextlib import asynccontextmanager class Muting: """during(): for the length of a conversation, the ir service may mute the TV. open_unix_connection is asyncio's, bound to the ir service's conversation socket; log, logging.info. >>> import asyncio >>> class Writer: ... def close(self): print("hang up") ... async def wait_closed(self): pass >>> async def connect(): return print("connect") or (None, Writer()) >>> async def talk(muting): ... async with muting.during(): ... print("conversation") >>> asyncio.run(talk(Muting(connect))) connect conversation hang up Without the ir service, the conversation goes on, unmuted: >>> async def refused(): raise ConnectionRefusedError("no ir service") >>> asyncio.run(talk(Muting(refused, log=print))) mute: can't reach the ir service: no ir service conversation """ def __init__(self, open_unix_connection, log=logging.info): self.__connect, self.__log = open_unix_connection, log @asynccontextmanager async def during(self): writer = None try: _, writer = await self.__connect() except OSError as err: self.__log(f"mute: can't reach the ir service: {err}") try: yield finally: if writer: try: writer.close() await writer.wait_closed() except OSError as err: self.__log(f"mute: hanging up: {err}")