Source code for caspia.gateway.network

import hashlib
from copy import deepcopy

import caspia.meadow
import caspia.node
from caspia.gateway.cidmanagement import CidManagement


[docs]class Network: """ Manages Caspia CAN Network """ def __init__(self, pollen_client, cidmng: CidManagement): self.pollen_client = pollen_client self.cidmng = cidmng self.nodes = dict() self._component_cache = dict()
[docs] def get_node(self, name): """ Return node for a given name. Create a new one, if it does not exist yet. """ if name in self.nodes: return self.nodes[name] cid = self.cidmng.lease(name) node = caspia.node.Node(self.pollen_client, cid) self.nodes[name] = node return node
[docs] def reset_configuration(self): self._component_cache = dict()
[docs] def get_configured_component(self, node, comp_cls, comp_cfg): """ Return existing or a new Component instance configured based on given config """ # We have to make a deep copy of the config, because it will contain # rules-specific configuration, which has to be cleared on reset_configuration(). comp_cfg = deepcopy(comp_cfg) cfg_hash = self._get_config_hash(node, comp_cfg) if cfg_hash in self._component_cache: return self._component_cache[cfg_hash] else: _, comp = node.register_component(comp_cls) comp.config = comp_cfg self._component_cache[cfg_hash] = comp return comp
def _get_config_hash(self, node, comp_cfg): hsh = hashlib.sha1(comp_cfg.get_bytes()) hsh.update(int.to_bytes(node.can_id, 3, 'little')) return hsh.hexdigest()