54 lines
No EOL
1.6 KiB
Python
54 lines
No EOL
1.6 KiB
Python
import logging
|
|
from multiprocessing.synchronize import Event as BaseEvent
|
|
from argparse import Namespace
|
|
from typing import Optional
|
|
|
|
import zmq
|
|
|
|
from trap.timer import Timer
|
|
|
|
|
|
class Node():
|
|
def __init__(self, config: Namespace, is_running: BaseEvent, timer_counter: Timer):
|
|
self.config = config
|
|
self.is_running = is_running
|
|
self.timer_counter = timer_counter
|
|
self.zmq_context = zmq.Context()
|
|
self.logger = self._logger()
|
|
|
|
self.setup()
|
|
|
|
@classmethod
|
|
def _logger(cls):
|
|
return logging.getLogger(f"trap.{cls.__name__}")
|
|
|
|
def tick(self):
|
|
with self.timer_counter.get_lock():
|
|
self.timer_counter.value+=1
|
|
|
|
def setup(self):
|
|
raise RuntimeError("Not implemented setup()")
|
|
|
|
def run(self):
|
|
raise RuntimeError("Not implemented run()")
|
|
|
|
def sub(self, addr: str):
|
|
"Default zmq sub configuration"
|
|
sock = self.zmq_context.socket(zmq.SUB)
|
|
sock.setsockopt(zmq.CONFLATE, 1) # only keep latest frame. NB. make sure this comes BEFORE connect, otherwise it's ignored!!
|
|
sock.setsockopt(zmq.SUBSCRIBE, b'')
|
|
sock.connect(addr)
|
|
return sock
|
|
|
|
def pub(self, addr: str):
|
|
"Default zmq pub configuration"
|
|
sock = self.zmq_context.socket(zmq.PUB)
|
|
sock.setsockopt(zmq.CONFLATE, 1) # only keep latest frame
|
|
sock.bind(addr)
|
|
return sock
|
|
|
|
@classmethod
|
|
def start(cls, config: Namespace, is_running: BaseEvent, timer_counter: Optional[Timer]):
|
|
instance = cls(config, is_running, timer_counter)
|
|
instance.run()
|
|
instance.logger.info("Stopping") |