def publish(self, topic, value, lock=True, binary=False): global _binpubs if Publisher.__enabled: try: if lock: _lock.acquire() if binary: if not isinstance(value, bytes): raise TypeError( "published binary value must be of type 'bytes'") logger.debug("sending binary value for topic %s" % topic) self._sender.send_multipart([topic.encode('utf-8'), value]) elif topic in _binpubs: # if a binary publisher exists for this topic, use that to # publish the value. It will call publish again (possibly multiple times) # with binary=True logger.debug("sending value via binpub for topic %s" % topic) try: _binpubs[topic][1].send(value) except Exception: logger.error("ERROR: %s" % traceback.format_exc()) else: msg = json.dumps([topic.encode('utf-8'), value], default=json_default) self._sender.send_multipart([msg]) if hasattr(self._sender, 'flush'): self._sender.flush() except Exception: print 'Publisher - Error publishing message %s: %s, %s' % \ (topic, value, traceback.format_exc()) finally: if lock: _lock.release()
def load_macro(self, macro_name): fpath = os.path.join(self.macrodir, macro_name) self._recorded_cmds = [] with open(fpath, 'rU') as f: content = f.read() # fix missing newline at end of file to avoid issues later when # we append to it if not content.endswith('\n'): with open(fpath, 'a') as f: f.write('\n') lines = content.split('\n') for i, line in enumerate(lines): logger.debug(line) try: self.command(line, save=False) except Exception as err: logger.error(''.join(traceback.format_tb(sys.exc_info()[2]))) msg = str(err) if self._gui: try: publish('console_errors', msg) except: logger.error("publishing of error failed") else: raise RuntimeError(msg)
def register(topic, obj): """Associates a given topic with a binary publisher based on the corresponding object type. If no binpub type exists for that object type, nothing happens. """ global _binpubs, _binpub_types sender = None if _binpub_types is None: load_binpubs() with _lock: if topic in _binpubs: logger.debug("found topic %s in _binpubs" % topic) _binpubs[topic][0] += 1 else: # see if a sender is registered for this object type for sender_type in _binpub_types: if sender_type.supports(obj): logger.debug("creating a sender for topic: %s" % topic) try: sender = sender_type(Pub_WV_Wrapper(topic)) except Exception: logger.error(traceback.format_exc()) _binpubs[topic] = [1, sender] break if sender is not None: sender.send(obj, first=True)
def register(topic, obj): """Associates a given topic with a binary publisher based on the corresponding object type. If no binpub type exists for that object type, nothing happens. """ sender = None if _binpub_types is None: load_binpubs() with _lock: if topic in _binpubs: logger.debug("found topic %s in _binpubs", topic) _binpubs[topic][0] += 1 else: # see if a sender is registered for this object type for sender_type in _binpub_types: if sender_type.supports(obj): logger.debug("creating a sender for topic: %s", topic) try: sender = sender_type(Pub_WV_Wrapper(topic)) except Exception: logger.error(traceback.format_exc()) _binpubs[topic] = [1, sender] break if sender is not None: sender.send(obj, first=True)
def publish(self, topic, value, lock=True, binary=False): if Publisher.__enabled: try: if lock: _lock.acquire() if binary: if not isinstance(value, bytes): raise TypeError("published binary value must be of type 'bytes'") logger.debug("sending binary value for topic %s", topic) self._sender.send_multipart([topic.encode('utf-8'), value]) elif topic in _binpubs: # if a binary publisher exists for this topic, use that # to publish the value. It will call publish again # (possibly multiple times) with binary=True logger.debug("sending value via binpub for topic %s", topic) try: _binpubs[topic][1].send(value) except Exception: logger.error("ERROR: %s", traceback.format_exc()) else: msg = json.dumps([topic.encode('utf-8'), value], default=json_default) self._sender.send_multipart([msg]) if hasattr(self._sender, 'flush'): self._sender.flush() except Exception: print 'Publisher - Error publishing message %s: %s, %s' % \ (topic, value, traceback.format_exc()) finally: if lock: _lock.release()
def create(self, typ, version=None, server=None, res_desc=None, **ctor_args): """Tries to import the given named module and return a factory function from it. The factory function or constructor must have the same name as the module. The module must be importable in the current Python environment. """ if server is not None or version is not None: return None if res_desc is not None and len(res_desc) > 0: return None if typ not in self._ctors: parts = typ.split('.') cname = parts[-1] modname = '.'.join(parts[:-1]) try: __import__(modname, globals(), locals(), [cname]) mod = sys.modules[modname] except (ImportError, KeyError), err: logger.debug(str(err)) return None try: self._ctors[typ] = getattr(mod, cname) except AttributeError, err: logger.debug(str(err)) return None
def create(self, typ, version=None, server=None, res_desc=None, **ctor_args): """Tries to import the given named module and return a factory function from it. The factory function or constructor must have the same name as the module. The module must be importable in the current Python environment. """ if server is not None or version is not None: return None if res_desc is not None and len(res_desc)>0: return None if typ not in self._ctors: parts = typ.split('.') cname = parts[-1] modname = '.'.join(parts[:-1]) try: mod = __import__(modname, globals(), locals(), [cname]) except ImportError, err: logger.debug(str(err)) return None try: self._ctors[typ] = getattr(mod, cname) except AttributeError, err: logger.debug(str(err)) return None
def unregister(topic): """Removes an association between a 'sender' and a topic.""" with _lock: if topic in _binpubs: logger.debug("Publisher unregistering topic %s", topic) if _binpubs[topic][0] <= 1: del _binpubs[topic] else: _binpubs[topic][0] -= 1
def load_binpubs(): """Loads all binpubs entry points.""" global _binpub_types logger.debug("loading binpubs") if _binpub_types is None: _binpub_types = [] # find all of the installed binpubs for ep in working_set.iter_entry_points('openmdao.binpub'): try: klass = ep.load() except Exception as err: logger.error("Entry point %s failed to load: %s" % (str(ep).split()[0], err)) else: logger.debug("adding binpub entry point: %s" % str(ep).split()[0]) with _lock: _binpub_types.append(klass)