diff --git a/src/scripts/python/Handler.py b/src/scripts/python/Handler.py new file mode 100644 index 0000000..3aed6c8 --- /dev/null +++ b/src/scripts/python/Handler.py @@ -0,0 +1,46 @@ +from abc import ABC, abstractmethod +from pyudev import Context, Monitor, MonitorObserver + + +class Handler(ABC): + """Abstract Handler calss for device monitoring + + NOTE: No checking are done for overlaping filters and callback will be + even by multiple handlers. + + Args: + ABC: Abstract Base Class, provides abstract method functionality and + readability. + """ + + def __init__(self, filter) -> None: + """Initiate a monitor observer and applies `filter` if any provided + + Args: + filter (_type_): _description_ + """ + monitor = Monitor.from_netlink(Context()) + if filter: + monitor.filter_by(filter) + self.observer = MonitorObserver(monitor, callback=self.handler) + self.observer.start() + + @abstractmethod + def callback(self, device): + """Callback + + This method must be implemented by child calsses. This method is + responsible for further managments of the devices related to its filter. + + Args: + device (pyudev.Device): device passed by observer through handler + """ + raise NotImplemented("Callback MUST be implemented") + + def handler(self, device): + """wrapper around callback implemented + + Args: + device (pyudev.Device): modified device passed by self.observer + """ + self.callback(device) \ No newline at end of file