mirror of
https://github.com/mofeng-git/One-KVM.git
synced 2025-12-12 01:00:29 +08:00
using default logger
This commit is contained in:
parent
055f3a141a
commit
ab87784b75
@ -1,6 +1,5 @@
|
|||||||
git+git://github.com/willbuckner/rpi-gpio-development-mock@master#egg=rpi
|
git+git://github.com/willbuckner/rpi-gpio-development-mock@master#egg=rpi
|
||||||
aiohttp
|
aiohttp
|
||||||
contextlog
|
|
||||||
pyyaml
|
pyyaml
|
||||||
bumpversion
|
bumpversion
|
||||||
tox
|
tox
|
||||||
|
|||||||
@ -50,7 +50,7 @@ logging:
|
|||||||
(): contextlog.SmartFormatter
|
(): contextlog.SmartFormatter
|
||||||
style: "{"
|
style: "{"
|
||||||
datefmt: "%H:%M:%S"
|
datefmt: "%H:%M:%S"
|
||||||
format: "[{asctime}] {app:10.10} {fg_bold_purple}{name:20.20} {log_color}{levelname:>7}{reset} {message} -- {cyan}{_extra}{reset}"
|
format: "[{asctime}] {name:15.15} {levelname:>7} --- {message}"
|
||||||
|
|
||||||
handlers:
|
handlers:
|
||||||
console:
|
console:
|
||||||
|
|||||||
@ -10,10 +10,6 @@ from typing import Set
|
|||||||
from typing import Callable
|
from typing import Callable
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
from contextlog import get_logger
|
|
||||||
from contextlog import patch_logging
|
|
||||||
from contextlog import patch_threading
|
|
||||||
|
|
||||||
from RPi import GPIO
|
from RPi import GPIO
|
||||||
|
|
||||||
import aiohttp
|
import aiohttp
|
||||||
@ -25,6 +21,9 @@ from .streamer import Streamer
|
|||||||
|
|
||||||
|
|
||||||
# =====
|
# =====
|
||||||
|
_logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def _system_task(method: Callable) -> Callable:
|
def _system_task(method: Callable) -> Callable:
|
||||||
async def wrap(self: "_Application") -> None:
|
async def wrap(self: "_Application") -> None:
|
||||||
try:
|
try:
|
||||||
@ -32,7 +31,7 @@ def _system_task(method: Callable) -> Callable:
|
|||||||
except asyncio.CancelledError:
|
except asyncio.CancelledError:
|
||||||
pass
|
pass
|
||||||
except Exception:
|
except Exception:
|
||||||
get_logger().exception("Unhandled exception")
|
_logger.exception("Unhandled exception")
|
||||||
raise SystemExit(1)
|
raise SystemExit(1)
|
||||||
return wrap
|
return wrap
|
||||||
|
|
||||||
@ -83,7 +82,7 @@ class _Application:
|
|||||||
app=app,
|
app=app,
|
||||||
host=self.__config["server"]["host"],
|
host=self.__config["server"]["host"],
|
||||||
port=self.__config["server"]["port"],
|
port=self.__config["server"]["port"],
|
||||||
print=(lambda text: [get_logger().info(line.strip()) for line in text.strip().splitlines()]),
|
print=(lambda text: [_logger.info(line.strip()) for line in text.strip().splitlines()]), # type: ignore
|
||||||
)
|
)
|
||||||
|
|
||||||
async def __root_handler(self, _: aiohttp.web.Request) -> aiohttp.web.Response:
|
async def __root_handler(self, _: aiohttp.web.Request) -> aiohttp.web.Response:
|
||||||
@ -103,27 +102,23 @@ class _Application:
|
|||||||
return ws
|
return ws
|
||||||
|
|
||||||
async def __on_shutdown(self, _: aiohttp.web.Application) -> None:
|
async def __on_shutdown(self, _: aiohttp.web.Application) -> None:
|
||||||
logger = get_logger()
|
_logger.info("Cancelling system tasks ...")
|
||||||
|
|
||||||
logger.info("Cancelling system tasks ...")
|
|
||||||
for task in self.__system_tasks:
|
for task in self.__system_tasks:
|
||||||
task.cancel()
|
task.cancel()
|
||||||
await asyncio.gather(*self.__system_tasks)
|
await asyncio.gather(*self.__system_tasks)
|
||||||
|
|
||||||
logger.info("Disconnecting clients ...")
|
_logger.info("Disconnecting clients ...")
|
||||||
for ws in list(self.__sockets):
|
for ws in list(self.__sockets):
|
||||||
await self.__remove_socket(ws)
|
await self.__remove_socket(ws)
|
||||||
|
|
||||||
async def __on_cleanup(self, _: aiohttp.web.Application) -> None:
|
async def __on_cleanup(self, _: aiohttp.web.Application) -> None:
|
||||||
logger = get_logger()
|
|
||||||
|
|
||||||
if self.__streamer.is_running():
|
if self.__streamer.is_running():
|
||||||
await self.__streamer.stop()
|
await self.__streamer.stop()
|
||||||
|
|
||||||
logger.info("Cleaning up GPIO ...")
|
_logger.info("Cleaning up GPIO ...")
|
||||||
GPIO.cleanup()
|
GPIO.cleanup()
|
||||||
|
|
||||||
logger.info("Bye-bye")
|
_logger.info("Bye-bye")
|
||||||
|
|
||||||
@_system_task
|
@_system_task
|
||||||
async def __stream_controller(self) -> None:
|
async def __stream_controller(self) -> None:
|
||||||
@ -175,20 +170,20 @@ class _Application:
|
|||||||
if method:
|
if method:
|
||||||
await method()
|
await method()
|
||||||
return None
|
return None
|
||||||
get_logger().warning("Received incorrect command: %r", command)
|
_logger.warning("Received an incorrect command: %r", command)
|
||||||
return "ERROR incorrect command"
|
return "ERROR incorrect command"
|
||||||
|
|
||||||
async def __register_socket(self, ws: aiohttp.web.WebSocketResponse) -> None:
|
async def __register_socket(self, ws: aiohttp.web.WebSocketResponse) -> None:
|
||||||
async with self.__sockets_lock:
|
async with self.__sockets_lock:
|
||||||
self.__sockets.add(ws)
|
self.__sockets.add(ws)
|
||||||
get_logger().info("Registered new client socket: remote=%s; id=%d; active=%d",
|
_logger.info("Registered new client socket: remote=%s; id=%d; active=%d",
|
||||||
ws._req.remote, id(ws), len(self.__sockets)) # pylint: disable=protected-access
|
ws._req.remote, id(ws), len(self.__sockets)) # pylint: disable=protected-access
|
||||||
|
|
||||||
async def __remove_socket(self, ws: aiohttp.web.WebSocketResponse) -> None:
|
async def __remove_socket(self, ws: aiohttp.web.WebSocketResponse) -> None:
|
||||||
async with self.__sockets_lock:
|
async with self.__sockets_lock:
|
||||||
try:
|
try:
|
||||||
self.__sockets.remove(ws)
|
self.__sockets.remove(ws)
|
||||||
get_logger().info("Removed client socket: remote=%s; id=%d; active=%d",
|
_logger.info("Removed client socket: remote=%s; id=%d; active=%d",
|
||||||
ws._req.remote, id(ws), len(self.__sockets)) # pylint: disable=protected-access
|
ws._req.remote, id(ws), len(self.__sockets)) # pylint: disable=protected-access
|
||||||
await ws.close()
|
await ws.close()
|
||||||
except Exception:
|
except Exception:
|
||||||
@ -196,10 +191,6 @@ class _Application:
|
|||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
patch_logging()
|
|
||||||
patch_threading()
|
|
||||||
get_logger(app="kvmd")
|
|
||||||
|
|
||||||
parser = argparse.ArgumentParser()
|
parser = argparse.ArgumentParser()
|
||||||
parser.add_argument("-c", "--config", default="kvmd.yaml", metavar="<path>")
|
parser.add_argument("-c", "--config", default="kvmd.yaml", metavar="<path>")
|
||||||
options = parser.parse_args()
|
options = parser.parse_args()
|
||||||
|
|||||||
@ -1,13 +1,15 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
|
import logging
|
||||||
|
|
||||||
from typing import Tuple
|
from typing import Tuple
|
||||||
|
|
||||||
from contextlog import get_logger
|
|
||||||
|
|
||||||
from RPi import GPIO
|
from RPi import GPIO
|
||||||
|
|
||||||
|
|
||||||
# =====
|
# =====
|
||||||
|
_logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class Atx:
|
class Atx:
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
@ -42,15 +44,15 @@ class Atx:
|
|||||||
|
|
||||||
async def click_power(self) -> None:
|
async def click_power(self) -> None:
|
||||||
if (await self.__click(self.__power_switch, self.__click_delay)):
|
if (await self.__click(self.__power_switch, self.__click_delay)):
|
||||||
get_logger().info("Clicked power")
|
_logger.info("Clicked power")
|
||||||
|
|
||||||
async def click_power_long(self) -> None:
|
async def click_power_long(self) -> None:
|
||||||
if (await self.__click(self.__power_switch, self.__long_click_delay)):
|
if (await self.__click(self.__power_switch, self.__long_click_delay)):
|
||||||
get_logger().info("Clicked power (long press)")
|
_logger.info("Clicked power (long press)")
|
||||||
|
|
||||||
async def click_reset(self) -> None:
|
async def click_reset(self) -> None:
|
||||||
if (await self.__click(self.__reset_switch, self.__click_delay)):
|
if (await self.__click(self.__reset_switch, self.__click_delay)):
|
||||||
get_logger().info("Clicked reset")
|
_logger.info("Clicked reset")
|
||||||
|
|
||||||
async def __click(self, pin: int, delay: float) -> bool:
|
async def __click(self, pin: int, delay: float) -> bool:
|
||||||
if not self.__lock.locked():
|
if not self.__lock.locked():
|
||||||
|
|||||||
@ -1,15 +1,17 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
import asyncio.subprocess
|
import asyncio.subprocess
|
||||||
|
import logging
|
||||||
|
|
||||||
from typing import Dict
|
from typing import Dict
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
from contextlog import get_logger
|
|
||||||
|
|
||||||
from RPi import GPIO
|
from RPi import GPIO
|
||||||
|
|
||||||
|
|
||||||
# =====
|
# =====
|
||||||
|
_logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class Streamer: # pylint: disable=too-many-instance-attributes
|
class Streamer: # pylint: disable=too-many-instance-attributes
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
@ -41,13 +43,13 @@ class Streamer: # pylint: disable=too-many-instance-attributes
|
|||||||
|
|
||||||
async def start(self) -> None:
|
async def start(self) -> None:
|
||||||
assert not self.__proc_task
|
assert not self.__proc_task
|
||||||
get_logger().info("Starting mjpg_streamer ...")
|
_logger.info("Starting mjpg_streamer ...")
|
||||||
await self.__set_hw_enabled(True)
|
await self.__set_hw_enabled(True)
|
||||||
self.__proc_task = self.__loop.create_task(self.__process())
|
self.__proc_task = self.__loop.create_task(self.__process())
|
||||||
|
|
||||||
async def stop(self) -> None:
|
async def stop(self) -> None:
|
||||||
assert self.__proc_task
|
assert self.__proc_task
|
||||||
get_logger().info("Stopping mjpg_streamer ...")
|
_logger.info("Stopping mjpg_streamer ...")
|
||||||
self.__proc_task.cancel()
|
self.__proc_task.cancel()
|
||||||
await asyncio.gather(self.__proc_task, return_exceptions=True)
|
await asyncio.gather(self.__proc_task, return_exceptions=True)
|
||||||
await self.__set_hw_enabled(False)
|
await self.__set_hw_enabled(False)
|
||||||
@ -65,8 +67,6 @@ class Streamer: # pylint: disable=too-many-instance-attributes
|
|||||||
await asyncio.sleep(self.__sync_delay)
|
await asyncio.sleep(self.__sync_delay)
|
||||||
|
|
||||||
async def __process(self) -> None:
|
async def __process(self) -> None:
|
||||||
logger = get_logger()
|
|
||||||
|
|
||||||
proc: Optional[asyncio.subprocess.Process] = None # pylint: disable=no-member
|
proc: Optional[asyncio.subprocess.Process] = None # pylint: disable=no-member
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
@ -75,13 +75,13 @@ class Streamer: # pylint: disable=too-many-instance-attributes
|
|||||||
stdout=asyncio.subprocess.PIPE,
|
stdout=asyncio.subprocess.PIPE,
|
||||||
stderr=asyncio.subprocess.STDOUT,
|
stderr=asyncio.subprocess.STDOUT,
|
||||||
)
|
)
|
||||||
logger.info("Started mjpg_streamer pid=%d: %s", proc.pid, self.__cmd)
|
_logger.info("Started mjpg_streamer pid=%d: %s", proc.pid, self.__cmd)
|
||||||
|
|
||||||
empty = 0
|
empty = 0
|
||||||
while proc.returncode is None:
|
while proc.returncode is None:
|
||||||
line = (await proc.stdout.readline()).decode(errors="ignore").strip()
|
line = (await proc.stdout.readline()).decode(errors="ignore").strip()
|
||||||
if line:
|
if line:
|
||||||
logger.info("mjpg_streamer: %s", line)
|
_logger.info("mjpg_streamer: %s", line)
|
||||||
empty = 0
|
empty = 0
|
||||||
else:
|
else:
|
||||||
empty += 1
|
empty += 1
|
||||||
@ -95,9 +95,9 @@ class Streamer: # pylint: disable=too-many-instance-attributes
|
|||||||
break
|
break
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
if proc:
|
if proc:
|
||||||
logger.error("Unexpected finished mjpg_streamer pid=%d with retcode=%d", proc.pid, proc.returncode)
|
_logger.error("Unexpected finished mjpg_streamer pid=%d with retcode=%d", proc.pid, proc.returncode)
|
||||||
else:
|
else:
|
||||||
logger.error("Can't start mjpg_streamer: %s", err)
|
_logger.error("Can't start mjpg_streamer: %s", err)
|
||||||
await asyncio.sleep(1)
|
await asyncio.sleep(1)
|
||||||
|
|
||||||
if proc:
|
if proc:
|
||||||
|
|||||||
@ -1,4 +1,3 @@
|
|||||||
RPi.GPIO
|
RPi.GPIO
|
||||||
aiohttp
|
aiohttp
|
||||||
contextlog
|
|
||||||
pyyaml
|
pyyaml
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user