def node_register(self, message): """ Module registration authority handling. Can be overriden by user""" try: # create an index pointer for each module name namel = {v["name"]: k for k, v in self._modules.iteritems()} if not self._modules.keys(): mod_id = 1 # If the name exists give module the same id elif message.device_name in namel: mod_id = namel[message.device_name] # TODO make it clean old keys based on last time else: mod_id = max(self._modules.keys()) + 1 log.debug("Handing out new module id %d" % mod_id) self._modules[mod_id] = {"name": message.device_name, "last": message.time} # prepare the payload for the acknowlegement pl = self.messenger.new_service(msg="%d" % mod_id) response = self.messenger.ack_msg(pl) # Repond to node with the module id return(response) except Exception as e: log.error("Exception %s" % e) pl = self.messenger.new_service(name="%s" % e) response = self.messenger.ack_msg(pl) # Repond to node with exception return(response)
def _respond(self, req): """ Reponse """ # Note: In production code this needs to be Async since tx over # the wire round trip time >= over the ram rtt. Alternatively it # should aknowledge the inproc message and then manage the remote # connection without time contrains # return (self.upload("Nodemodule: %s" % req).replace("Nodemodule", # store all incoming messages to the queue # in order to proccess in the node_main self.rx_q.put(req, block=False, timeout=self._rx_timeout) # Detect and handle registration message if req.msg_type == NodeMessenger.REG: return self.node_register(req) log.info("Forwarding message") print(req) # Wrap it around an uplink message uplink_msg = self.remote.messenger.preamble_msg([req]) # This is the part that uplink response message is stripped out # I am taking one wrong assumptions here, for demo purposes # That the message contains one peripheral peripheral[0] # TODO make it real code return (self.upload(uplink_msg).peripheral[0])
def run(cmd): """ Execute shell command in detached mdoe.""" proc = Popen([cmd], stdout=PIPE, stderr=PIPE, shell=True) ret, err = proc.communicate() if err: # ignore warnings in error stream if "Warning" in err: CLogger.warning(err.strip()) return err raise PiBlinkerError(err) else: return ret
def _respond(self, req): """ Method defines how the data should be proccessed and return a response to caller. Should be overridden by user """ # Note: Returning None will cancell server response but can block # Socket based on zmq configuration log.info("Server Received message") print(req) # Detect and handle registration message if req.msg_type == self.ul_messenger.REG: return self.network_register(req) return req
def node_main(self): """ User implemented main loop for node """ test_msg_pl = self.messenger.new_service("Hello %d" % self.counter) test_msg = self.messenger.solicited_msg(test_msg_pl) self.send_msg(test_msg) log.info("Nodemodule: Sending") print(test_msg) gevent.sleep(0.3) if self.has_msg(): log.info("Nodemodule: Received") rep = self.get_msg(blk=True) print("%s" % rep) self.counter += 1
def _respond(self, req): """ Method defines how the data should be proccessed and return a response to caller. Should be overridden by user """ log.info("Server Received message") print(req) # Detect and handle registration message if req.metadata.message_type == self.messenger.REG: return self.network_register(req) # I am taking two wrong assumptions here, for demo purposes # That the message contains one peripheral peripheral[0] # And that it contains one service payload[0] # TODO make it real code msg = req.peripheral[0].payload[0].msg req.peripheral[0].payload[0].msg = "%s to you too" % msg return req
def network_register(self, message): try: metadata = message.metadata loc = message.location # create an index pointer for each module name namel = {v["name"]: k for k, v in self._clients.iteritems()} if not self._clients.keys(): client_id = 1 # If the name exists give module the same id elif metadata.device_name in namel: client_id = namel[metadata.device_name] # TODO make it clean old keys based on last time else: client_id = max(self._clients.keys()) + 1 if loc: location = self.messenger._location_tpl(lat=loc.lat, long=loc.long, street=loc.street, building=loc.building, floor=loc.floor, room=loc.room, city=loc.city, country=loc.country, postcode=loc.postcode) self._clients[client_id] = {"name": metadata.device_name, "app_id": metadata.app_id, "network_id": metadata.network_id, "last": metadata.time, "location": location} # prepare the payload for the acknowlegement response = self.messenger.ack_msg(cmd="register", params=["%s" % client_id]) # Repond to node with the module id return(response) except Exception as e: log.error("Exception %s" % e) # prepare the payload for the acknowlegement response = self.messenger.nack_msg(cmd="register", params=["%s" % e]) # Repond to node with exception return(response)
def network_register(self): try: reg_msg = self.ul_messenger.register_msg() # Attempt to register and get the response reginfo = self.upload(reg_msg) # If server accepted registration continue if reginfo.metadata.message_type == self.ul_messenger.ACK: node_id = int([n for n in reginfo.control.params][0]) self.messenger.set_id(node_id) log.info("Registration Accepted, new id %d" % node_id) return else: raise Exception() except Exception as e: log.error("Failed to register to network %s" % e) sys.exit(1) print(reg_msg)
def setup(self, log_level="ver_debug", log_label="PiBlinker", log_path=None, log_colors=None): """ Module Init.""" # Map a color to GPIO.BCM PIN self.LEDS = {"RED": [17], "GREEN": [18], "BLUE": [27], "PURPLE": [17, 27], "YELLOW": [17, 18], "CYAN": [18, 27], "WHITE": [17, 18, 27]} self.last_mode = 0 # Configure the GPIO ports in hardware map(self.run, [(x % v) for n in self.LEDS.values() for v in n for x in ["gpio export %d out", "gpio -g mode %d out"]]) self.i2c_devices = {} # Assosiate log levels with colors if not log_colors: log_colors = {"base_color": "CYAN", "info": "HBLUE", "warning": "YELLOW", "error": "RED", "debug": "GREEN", "ver_debug": "GREEN"} # Initalise the logging module CLogger.setup(log_label, log_level, log_path, log_colors) return self
def node_register(self): """ User accessible method for handling registration message """ try: # Prepare and send the registration message init_msg = self.messenger.register_msg() self._send(msg=init_msg) # Accept the new module_id from server reginfo = self._recv() # If server accepted registration continue if reginfo.msg_type == NodeMessenger.ACK: node_id = [n for n in reginfo.payload][0].msg node_id = int(node_id) self.messenger.set_id(node_id) log.info("Registration Accepted, new id %d" % node_id) return else: raise Exception() except Exception as e: log.error("Failed to register module %s" % e) sys.exit(1)
import zmq.green as zmq import zmq.error import gevent from zclient import ZClient from abc import ABCMeta, abstractmethod from nodemessenger import NodeMessenger from colorlogger import CLogger as log __author__ = "Minos Galanakis" __license__ = "LGPL" __version__ = "0.0.1" __email__ = "*****@*****.**" __project__ = "ga" __date__ = "30-05-2017" log.setup(__file__, projectpath.log_level) class NodeModule(ZClient): """ Communications module that implemts a request/response logic """ __metaclass__ = ABCMeta def __init__(self, ipcfname="zmqnode", modulename="NodeModule"): """ Instantiate an client object that will accept """ super(NodeModule, self).__init__(ipcfname, None, "ipc",
def debug(self, *args): """ Print a debug message and notify the user with the LED.""" CLogger.debug(args[-1])
from __future__ import print_function import projectpath import sys import gevent import zmq.green as zmq from zgreenbase import zeroGreenBase from colorlogger import CLogger as log __author__ = "Minos Galanakis" __license__ = "LGPL" __version__ = "X.X.X" __email__ = "*****@*****.**" __project__ = "codename" __date__ = "26-05-2017" log.setup(__file__, "debug") class ZClient(zeroGreenBase): def __init__(self, hostname, port, transport, zmq_mode, max_workers=None): """ Instantiate an client object that will accept """ super(ZClient, self).__init__(hostname, port, transport, zmq_mode) def connect(self): self.socket.connect(self.binding) def disconnect(self): self.socket.disconnect(self.binding) def _send(self, **kwargs):