def mqtt_is_run(mosquito_uri): P_Log("[FY] Finding BROKER MQTT on {}".format(mosquito_uri)) if mqtt_alive(mosquito_uri): P_Log("\t[[FG]OK[FW]] BROKER MQTT Located on {}".format(mosquito_uri)) P_Log("") else: P_Log("\t[[FR]ERROR[FW]] BROKER MQTT NOT Located") exit()
def init_ttys(): ttydef, ttyout, ttyerr = utils.assing_ttys() P_Log("[FY]Availables TTYs:") P_Log("\t Terminal: {}".format(ttydef)) P_Log("\t Components: {}".format(ttyout)) P_Log("\t Components errors: {}".format(ttyerr)) P_Log("") return ttydef, ttyout, ttyerr
def find_MQTT(mosquito_uri): if utils.mqtt_alive(mosquito_uri): P_Log("[FY] BROKER MQTT Located on {} [[FG]OK[FY]]".format(mosquito_uri)) else: P_Log("[FY] BROKER MQTT local NOT Located [[FY]ERROR[FW]]") mosquito_uri="0.0.0.0:0" return mosquito_uri
def Get_BB_Robot(self): if self.BB(): general=self.BB.Get_Robot(self.robot) if general!={}: P_Log("[FY] Robot [FG]{} is online[FY] getting conf".format(self.robot)) self.general=general else: P_Log("[FR] [ERROR][FY] Bigbrother not found") exit()
def stop(self): component="{}/{}".format(self.robot_dir,self.component) uri_comp = self.BB.Control_Service(component) proxy=Proxy(uri_comp) if proxy(): P_Log("[FR][DOWN][FY] Component {}".format(component)) proxy.shutdown() else: P_Log("[FR][ERROR][FY] Connecting to Component {} seems Stopped".format(component))
def Get_BB_Comp(self,component): if self.BB(): comp=self.BB.Get_Comp(component) if comp!={}: P_Log("[FR] [ERROR][FY] {} is online on host:{}".format(component,comp["host"])) exit() else: P_Log("[FR] [ERROR][FY] Bigbrother not found") exit()
def call(self, fn, *args): try: return self._link_.call(fn, *args) except Exception as ex: #raise P_Log("[[FR]ERROR[FW]] Running call on Proxy {}".format( self.get_uri())) P_Log(str(ex)) return None
def check_comp_files(dir_comp, cls): files = ["conf_" + cls, "__init__"] Files_available = [ x.split(".py")[0] for x in os.listdir(robots_dir + dir_comp) ] for f in files: if f not in Files_available: P_Log("[FR]ERROR:[FY] File {} not found in {}".format(f, dir_comp)) exit() P_Log("[FY] Files on {} [[FG]OK[FY]]".format(dir_comp))
def init_ethernet(): eths = utils.get_all_ip_eths() P_Log("[FY]Availables Interfaces:") ethernet = "" for ips, interface in eths: P_Log("\t {}: {}".format(interface, ips)) if interface == id: ethernet = id ip = ips if len(eths) == 0: P_Log("[FR][ERROR][FW] No interface finded") exit() return eths
def Get_BigBrother_comp(proxy,robot,comp): if proxy is not None: mycomp=proxy.Get_Comp(comp) else: P_Log("[FR] [ERROR][FW] Comunicating with BIGBROTHER") exit() return mycomp
def Get_BigBrother_config(proxy,robot): if proxy is not None: default=proxy.Get_Robot(robot) else: P_Log("[FR] [ERROR][FW] Comunicating with BIGBROTHER") exit() return default
def load_json(self, filename): self.filename = filename if (".json" in filename) else (filename + ".json") try: data = open(filename).read() data = self.del_coments(data) data = self.substitute_params(data) data_json = json.loads(data) except ValueError as e: P_Log("[FR]ERROR:[FS] JSON incorrectly described: {}".format( str(e))) exit() except Exception: P_Log("[FR]ERROR:[FS] file not found loading {}".format(filename)) return {} return data_json
def Pub(self): if not self.sync: for n in self.topics: self.Pub_single(n) self.Pub_events() else: P_Log("start active")
def Get_Instance(robot_dir,component): dir_etc=robots_dir+robot_dir+"/etc/" instances=conf.get_conf(dir_etc+"instances.json") try: return instances[component] except: P_Log("[FR] [ERROR][FW] {} Not found in {}/instances".format(component,robot_dir)) exit()
def start(self): if self.sync: self.work = True self.thread = Thread(target=self._Do_Pub, name=self._comp + ":PUB") self.thread.setDaemon(True) self.thread.start() else: P_Log("Mode asyncronous activate")
def Get_MQTT(self): MQTT="{}:{}".format(self.component["_etc"]["ip"], self.component["_etc"]["MQTT_port"]) MQTT_uri=find_MQTT(MQTT) if MQTT_uri!="0.0.0.0:0": self.component["_etc"]["MQTT_uri"]=MQTT_uri else: P_Log("[ERROR] Broker {} not available".format(MQTT)) exit()
def __init__(self,robot_dir,component,general={},instance={}): self.robot_dir=robot_dir self.component=component dir_etc=robots_dir+robot_dir+"/etc/" if general=={}: general=Get_General(robot_dir) self.general=general if instance=={}: instance=Get_Instance(robot_dir,component) self.instance,errors=parser.instance_check(instance) if len(errors)==0: P_Log("[FY] component syntactic checking [FG] [OK]") else: for err in errors: P_Log("[FR] [ERROR][FY] Syntactic in {}-->{}".format(err[0],err[1])) exit() broadcast_port=general["broadcast_port"] self.uri_BB,self.BB=Get_BigBrother_proxy()
def add_event(self, entity, event): try: name, fn = event.split("::") self.events.setdefault(entity, []) fn = fn.replace("self.", "self.obj.") self.events[entity].append((name, fn)) #print("Pub events",self.events) except: P_Log("error loading {}".format(event))
def get_cls_comp(dir_comp, cls): base_module = dir_comp.replace("/", ".") module, errors = get_module_class(dir_comp, cls) if module == "": P_Log("[FR]ERROR:[FW] class {} not found in component".format(cls)) for e, error in errors: P_Log("\t[FR]{}[FW] on {}".format(e, error)) exit() try: #module=importlib.import_module(module) comp_cls = getattr(module, cls) P_Log("[FY] Module:{}, Class:{} [FG][OK][FW]".format( module.__name__, cls)) return comp_cls except Exception as ex: P_Log("[FR]ERROR:[FW] Module {} --> {}".format(base_module, str(ex))) raise exit()
def params(cad): component = parser.get_COMPONENT(cad) if component != "": robot, comp = component.split("://") node, comp = comp.split("/") return robot, node, comp else: P_Log( "{} not valid sintax robot://node/component or robot://component". format(cad)) exit()
def run_component(*args, run="start"): try: args = list(args) args.insert(0, "python3") args[1] = args[1] + ".py" if run in ["start", "stop", "kill", "status"]: args.append(run) args.append("&") p = Popen(args) time.sleep(1) except: raise P_Log("[FR][ERROR][FY] Running Component {}".format(args[2]))
def connect(self): try: if not self.OK: self._link_ = RPCClient(self.host, int(self.port), timeout=20) if self._link_.is_connected(): self.OK = self.__create_hooks() else: self.OK = False except: self.OK = False if self.showerr: P_Log("[FR]ERROR [FW] No Connect to {}".format(uri)) finally: return self.OK
def __init__(self, uri, show=False): self.showerr = show try: self.host, self.port = uri.split(":") except: self.host = "0.0.0.0" self.port = 0 self.OK = False self.__linked = False try: self._link_ = RPCClient(self.host, int(self.port), timeout=10) self.__linked = True except: self.__linked = False if show: P_Log("[FR]ERROR [FW] No Link to {}".format(uri))
def locate_BB(port=9999): P_Log("[FY]Finding BigBrother on ethernet segment") uri_BB=BB.Get_BigBrother(port) if uri_BB!="0.0.0.0:0": P_Log("[FY]Located on {}".format(uri_BB)) return uri_BB
def add_topics(self, *topics): for n in topics: if hasattr(self.obj, n): self.topics.add(n) else: P_Log("{} not registered".format(n))
def Set_BigBrother_config(proxy,robot,conf): if proxy is not None: proxy.Register_Robot_Conf(robot,conf) else: P_Log("[FR] [ERROR][FW] Comunicating with BIGBROTHER") exit()
sys.path.append(robots_dir) def params(cad): component = parser.get_COMPONENT(cad) if component != "": robot, comp = component.split("://") node, comp = comp.split("/") return robot, node, comp else: P_Log( "{} not valid sintax robot://node/component or robot://component". format(cad)) exit() if __name__ == '__main__': if len(sys.argv) == 2: P_Log("please print start/stop/kill/status") exit() if len(sys.argv) == 3: robot = sys.argv[1] dir_etc = robots_dir + robot + "/etc/" init = conf.get_conf(dir_etc + "init.json") init = [robot + "://" + x for x in init] if sys.argv[2] == "start": conf.init_ttys() conf.init_ethernet() for c in init: run_component("component", c, run=sys.argv[2])
from PYRobot.libs.starter import Comp_Starter import PYRobot.libs.utils as utils import PYRobot.libs.utils_BB as BB from PYRobot.libs.botlogging.coloramadefs import P_Log robots_dir = utils.get_PYRobots_dir() sys.path.append(robots_dir) if __name__ == '__main__': if len(sys.argv) >= 2: if sys.argv[1] == "start": server = Comp_Starter("bin", "bigbrother") if server.uri_BB == "0.0.0.0:0": server.Create("PYRobot") server.start() if sys.argv[1] == "stop": server = Comp_Starter("bin", "bigbrother") if server.uri_BB != "0.0.0.0:0": print(server.uri_BB) server.stop() if sys.argv[1] == "kill": pids = utils.findProcessIdByName("PYRobot/bigbrother") for p, n in pids: utils.kill_process(p) P_Log("killing {} PID:{}".format(n, p)) if sys.argv[1] == "status": st = Comp_Starter("bin", "bigbrother") if st.uri_BB != "0.0.0.0:0": st.status()
def Start_Server(config): servers = [] warnings = {} info = [] status = False interfaces = config["_etc"]["_INTERFACES"] if type(interfaces) not in [tuple, list]: interfaces = [ interfaces, ] host = config["_etc"]["ip"] port = config["_etc"]["port"] name = config["_etc"]["name"] cls = config["_etc"]["obj_cls"] register = not config["_etc"]["sys"] try: class_comp = Loader_Config(cls, **config) obj = class_comp() utils.change_process_name(name) obj._PROC["PID"] = os.getpid() obj._PROC["status"] = (obj.hello() == "hi") if obj._PROC["status"]: interfaces.append(Control_Interface) for inter in interfaces: interface = Interface(inter, obj) warnings[interface.__name__] = interface.Not_Implemented port = utils.get_free_port(port, host) info.append((interface.__name__, "{}:{}".format(host, port))) servers.append(StreamServer((host, port), interface())) port = port + 1 obj._PROC["info"] = info obj._PROC["warnings"] = warnings for s in servers[:-1]: s.start() #obj.set_PROC(status,info,warnings) time.sleep(0.3) if register: obj._Register_Component() obj._PROC["SERVER"] = servers[-1] obj.show_PROC() print("\n\n") try: #obj.L_info("Starting __Run__ ") obj.__Run__() except: pass servers[-1].serve_forever() try: obj.__Close__() #obj.L_info("__Close__ Component") except: pass except KeyboardInterrupt: for s in servers: s.close() try: obj.__Close__() except: pass utils.set_tty_out(config["_etc"]["ttydef"]) P_Log("[FR][DOWN][FY] Starded Component {}".format(name)) except Exception as ex: if status: utils.set_tty_out(config["_etc"]["ttydef"]) P_Log("[FR][DOWN][FY] Starded Component {}".format(name)) raise else: utils.set_tty_out(config["_etc"]["ttydef"]) raise P_Log("[FR][ERROR][FY] Starded Component {}".format(name)) P_Log(str(ex))
format(cad)) exit() def get_node(host): uri, bb = Get_BigBrother_proxy() if bb(): return bb.Get_Node(host) else: return "0.0.0.0:0" if __name__ == '__main__': myhost = utils.get_host_name() if len(sys.argv) <= 2: P_Log("[ERROR] USE robot://node/component (start/stop/kill/status)") exit() if len(sys.argv) > 2: robot, node, comp = params(sys.argv[1]) P_Log("[FY]COMPONENT:[FW]{}://{}/{}".format(robot, node, comp)) if sys.argv[2] == "start": if node in [myhost, "LOCAL"]: st = Comp_Starter(robot, comp) st.Create() #print(st.component) if st.uri_BB != "0.0.0.0:0": st.Get_BB_Robot() st.Get_MQTT() st.Get_BB_Comp("{}/{}".format(robot, comp)) st.start() else: