def unregister(self): """Remove the current callback function from listening to the topic, and from the rosbridge client subscription list """ if callable(self._cb): dispatcher.disconnect(self._cb, signal=self._topic_name) self._rosbridge.unsubscribe(self)
def test_estimator_wholesale_integration(self): # the integration actually requires a proper Model self.wem.agent = BaselineTrader() #listen for predictions calculated predictions_received: List[List[CustomerPredictions]] = [] def listen_pred_ev(signal, sender, msg): predictions_received.append(msg) dispatcher.connect(listen_pred_ev, signals.COMP_USAGE_EST) #listen for wholesale orders orders_received = [] def listen_orders_ev(signal, sender, msg): orders_received.append(msg) dispatcher.connect(listen_orders_ev, signals.OUT_PB_ORDER) # 1. send some market messages that get picked up by wholesale dispatcher.send(signal=signals.PB_TIMESLOT_UPDATE, msg=PBTimeslotUpdate(firstEnabled=TIMESLOT_NOW, lastEnabled=TIMESLOT_NOW+24)) # no cleared trades or market transactions necessary for core test assert len(orders_received) == 0 # 2. send pubsub messages that trigger prediction dispatcher.send(signal=signals.PB_TIMESLOT_COMPLETE, msg=PBTimeslotComplete(timeslotIndex=TIMESLOT_NOW-1)) assert len(predictions_received) == 1 #predictions are lists of predictions for each customer assert len(predictions_received[0][0].predictions) == 24 # 3.5 meanwhile the wholesale agent reacted to the predictions and sent its orders # 3. expect wholesale market to react to prediction assert len(orders_received) == 24 # clean up listeners dispatcher.disconnect(listen_pred_ev, signals.COMP_USAGE_EST) dispatcher.disconnect(listen_orders_ev, signals.OUT_PB_ORDER)
def unsubscribe(self, stream, update_handler=None): """Generic method to unsubscribe from the channel. :param stream: a name of the channel :param update_handler: arbitrary keyword arguments. Depend on the specific exchange. The method first removes the listener from a dispatcher and then sends an unsubscribe message to a websocket if there are no more listeners on a stream. """ if update_handler: try: self.logger.info(f'Removing listener for {stream} ...') dispatcher.disconnect(update_handler, signal=stream, sender='binance') except dispatcher.errors.DispatcherKeyError as e: self.logger.error(e) # unsubscribe if no one is listening if not dispatcher.getReceivers(sender='binance', signal=stream): self.logger.info(f'Unsubscribing from {stream} ...') try: self._data.pop(stream) # remove data object self._subscriptions.pop(stream) # remove subscription socket = self._connections.pop(stream) # remove connection socket.close() # this will terminate the thread self.logger.info(f'Unsubscribed from {stream}') # parent thread does not call join here to avoid blocking except KeyError: self.logger.error(f'No subscription for stream {stream}')
def stop(self): if self.client: self.state = IO_DISCONNECTING dispatcher.disconnect(self._send, signal=m_common.IO_SEND) self.client.disconnect() self.client.loop_stop() self.state = IO_READY
def _removeCurrentCallbacks( cls, key, node = None, capture = 0, ): """De-register current callbacks, return previous callback Note: There should only ever be one receiver registered this way, so should always be either None or the previous callback. """ metaKey = (cls.type,capture,key) # remove all current watchers... receivers = dispatcher.liveReceivers( dispatcher.getReceivers( sender=node, signal=metaKey, ) ) receiver = None for receiver in receivers: if __debug__: log.info( """Disconnecting receiver for key %(metaKey)r for node %(node)r -> %(receiver)s"""%locals()) dispatcher.disconnect( receiver, signal = metaKey, sender=node, ) assert len(dispatcher.getReceivers( sender=node, signal=metaKey, )) == 0, """Event callback de-registration failed: %(cls)s %(key)s %(node)r"""%locals() return receiver
def onClose(self, event): doClose = True if self._modified: if platform.system() != 'Darwin': message = gettext('Your changes will be lost if you don\'t save them.') + '\n\n' + gettext('Do you want to save the changes you made to "%s"?') % (self.display.network.name()) caption = gettext('Neuroptikon') else: message = gettext('Your changes will be lost if you don\'t save them.') caption = gettext('Do you want to save the changes you made to "%s"?') % (self.display.network.name()) result = wx.MessageBox( message, caption, parent = self, style = wx.ICON_QUESTION | wx.YES_NO | wx.CANCEL) if result == wx.YES: doClose = self.onSaveNetwork() elif result == wx.CANCEL: doClose = False if doClose: self.display.selectObjects([]) wx.GetApp().inspector.inspectDisplay(None) network = self.display.network dispatcher.disconnect(self.networkDidChangeSavePath, ('set', 'savePath'), network) self.display.close() self.display = None self.Destroy() wx.GetApp().displayWasClosed(self) if not any(network.displays): wx.GetApp().releaseNetwork(network) elif event.GetEventType() == wx.wxEVT_CLOSE_WINDOW: event.Veto()
def stop(self): dispatcher.disconnect(self.send, signal=m_common.IO_SEND) self.thread_running = False self.thread.join() self.client.close() self.state = IO_DISCONNECTED return self.status()
def unsubscribe(self, channel_name, update_handler=None): """Generic method to unsubscribe from the channel. :param channel_name: a name of the channel :param update_handler: Arbitrary keyword arguments. Depend on the specific exchange. The method first removes the listener from a dispatcher and then sends an unsubscribe message to a websocket. """ # remove listener if update_handler is not None: try: self.logger.info('Removing listener for %s ...' % channel_name) dispatcher.disconnect(update_handler, signal=channel_name, sender='bitfinex') except dispatcher.errors.DispatcherKeyError: exc_msg = 'Tried to remove unrecognized listener while unsubscribing ' + \ 'from a channel {}'.format(channel_name) self.logger.info(exc_msg) # authenticated channels all have channel_id 0 and are automatically subscribed if channel_name in ['orders', 'user_trades', 'balances']: return # get the channel_id of public channels channel_id = self._get_channel_id(channel_name) if channel_id is None: self.logger.info('Not subscribed to %s' % channel_name) return # unsubscribe if no one is listening if not dispatcher.getReceivers(sender='bitfinex', signal=channel_name): self.logger.info('Unsubscribing from %s ...' % channel_name) self._ws.send(json.dumps({"event": "unsubscribe", "chanId": channel_id}))
def unsubscribe(self): """ Unsubscribe from the signal. """ dispatcher.disconnect(receiver=self.receiver, signal=self.signal, sender=self.sender)
def wait_for(self, signal, sender='pyvent', timeout=0, send=None): ret_val = None, None def fn(*args, **kargs): nonlocal ret_val ret_val = (args, kargs) dispatcher.connect(receiver=fn, signal=signal, sender=sender, weak=False) self.subscribe(signal) if send: self.send(**send) time_started = time.time() while not ret_val[0] and self.is_alive(): if timeout and time.time() - time_started > timeout: log.info(f'Wait for {signal} timed out') break dispatcher.disconnect(receiver=fn, signal=signal, sender=sender, weak=False) return ret_val
def unsubscribe(self): ''' unsubscribe me ''' if self.dispatch: dispatcher.disconnect(self.receive, signal=self.channel) pass
def unregister_subscriber(self, subscriber): """Remove a callback subscriber from its topic subscription list. If there is no callback subscribers in the subscription list. It will unsubscribe the topic. Args: subscriber (Subscriber): A subscriber with callback function that listen to the topic. """ topic = subscriber.topic if topic not in self._subscribers: return # subscribe_id = self._subscribers.get(topic).get('subscribe_id') subscribers = self._subscribers.get(topic).get('subscribers') if subscriber in subscribers: dispatcher.disconnect(subscriber.callback, signal=topic) subscribers.remove(subscriber) if len(subscribers) == 0: logger.info( 'Sending request to unsubscribe topic {}'.format(topic)) del subscribers[:] self.send( json.dumps({ 'op': 'unsubscribe', 'id': subscriber.subscribe_id, 'topic': topic })) del self._subscribers[topic]
def unload(): thread_pool.remove_callable(thread_run) if P.serial is not None and P.serial.isOpen(): P.serial.close() P.initialised = False dispatcher.disconnect(_init_recovery, signal=Constant.SIGNAL_USB_DEVICE_CHANGE)
def unload(): L.l.info('Unloading RFXCom') thread_pool.remove_callable(thread_run) if P.initialised: P.transport.close() P.initialised = False dispatcher.disconnect(_init_recovery, signal=Constant.SIGNAL_USB_DEVICE_CHANGE)
def leave_room_controller(self): """Leave room controller """ dispatcher.disconnect(self._louie_controller, ZWaveController.SIGNAL_CTRL_WAITING) dispatcher.disconnect(self._louie_controller, ZWaveController.SIGNAL_CONTROLLER) return True
def inspectDisplay(self, display): if display != self.display: if self.display is not None: dispatcher.disconnect(self.onDisplaySelectionChanged, ('set', 'selection'), self.display) self.display = display if self.display is not None: dispatcher.connect(self.onDisplaySelectionChanged, ('set', 'selection'), self.display) self.updateInspectors()
def willBeClosed(self): for visible in self.visibles: for attributeName in [ 'color', 'opacity', 'shape', 'texture', 'weight' ]: dispatcher.disconnect(self.refreshGUI, ('set', attributeName), visible) self.visibles = ObjectList()
def disconnect_from_measurement_events(self, arg_subscriptions): if isinstance(arg_subscriptions, list): for subscription in arg_subscriptions: dispatcher.disconnect(self.create_location_measurement, dispatcher.Any, subscription) else: dispatcher.disconnect(self.create_location_measurement, dispatcher.Any, arg_subscriptions)
def _cleanup(self): # disconnect extra events dispatcher.disconnect( self.getStatus, signal='xivelystatus', weak=False, )
def disconnect(self, receiver, signal, **kwargs): """ This is pretty self-explanatory :param kwargs: Passed to `pydispatch.dispatcher.disconnect` """ kwargs.setdefault('sender', self.sender) dispatcher.disconnect(receiver, signal, **kwargs)
def _cleanup(self): # disconnect extra events dispatcher.disconnect( self.getStatus, signal = 'xivelystatus', weak = False, )
def stop(self): ''' Stop handler ''' self.stopped = True self.logger.info("Stop handler") dispatcher.disconnect(self.__handler, signal=self.params.get( "listensignals", dispatcher.Any))
def unload(): L.l.info('Heat module unloading') global initialised initialised = False thread_pool.remove_callable(heat_loop.thread_run) dispatcher.disconnect(handle_event_heat, signal=Constant.SIGNAL_HEAT, sender=dispatcher.Any)
def willBeClosed(self): # Make sure any active edit gets committed. if self.grid.IsCellEditControlEnabled(): self.grid.DisableCellEditControl() self.label.SetLabel(gettext('Attributes:')) object = self.attributesTable.object if object: dispatcher.disconnect(self.attributesDidChange, ('set', 'attributes'), object) self.attributesTable.setObject(None)
def leave_room_network(self): """Leave room network """ dispatcher.disconnect(self._louie_network, ZWaveNetwork.SIGNAL_NETWORK_STARTED) dispatcher.disconnect(self._louie_network, ZWaveNetwork.SIGNAL_NETWORK_RESETTED) dispatcher.disconnect(self._louie_network, ZWaveNetwork.SIGNAL_NETWORK_AWAKED) dispatcher.disconnect(self._louie_network, ZWaveNetwork.SIGNAL_NETWORK_READY) dispatcher.disconnect(self._louie_network, ZWaveNetwork.SIGNAL_NETWORK_STOPPED) return True
def test_error_logged_if_deferred_not_supported(self): test_signal = object() test_handler = lambda: defer.Deferred() dispatcher.connect(test_handler, test_signal) with LogCapture() as l: send_catch_log(test_signal) self.assertEqual(len(l.records), 1) self.assertIn("Cannot return deferreds from signal handler", str(l)) dispatcher.disconnect(test_handler, test_signal)
def reset(self): if self.state == IO_CONNECTED: self.stop() self.state = IO_DISCONNECTED self.broker_address = None self.broker_port = None self.keepalive_period = None self.client = None dispatcher.disconnect(self._send, signal=m_common.IO_SEND)
def Destroy(self): dispatcher.disconnect(self.AddNewBuffer, signals.buffer_created, self.dlg.session) buffers = [] buffers.extend(self.empty_buffers) buffers.extend([self.get_buffer(i) for i in range(self.buffer.GetCount())]) buffers = set(buffers) for buffer in buffers: self.remove_buffer(buffer, fromUI = True, fromList = True) super(ItemsPanel, self).Destroy()
def disconnect_signals(self): """ Disable the signals within the work. This function reverses the process of `connect_signals` """ for task in self: try: dispatcher.disconnect(self.on_ok, signal=task.S_OK, sender=task) except dispatcher.errors.DispatcherKeyError as exc: logger.debug(str(exc))
def stopPubSub(self): ''' Stopping the PubSub system ''' if self.userId != 'None': _debug('stop pubsub for user #%s (%s)' % (self.userId, self.login)) dispatcher.disconnect( self.pubsub, signal='user-%s' % self.userId )
def dm_teardown(self): """ Disconnect the method from the signal. It's done to avoid conflicts when many instances of the mixin are being executed. """ try: dispatcher.disconnect(self.dequeue_next_page_requests, signal=signals.spider_idle) except DispatcherKeyError: pass
def __del__(self): dispatcher.disconnect(self.start_hot_word_detection) dispatcher.disconnect(self.play_file) self._exit_flag.set() sleep(5) if self._hot_word_detection_active.isSet(): self._logger.error('Fail to stop recognition process') if self._io_system_busy.isSet(): self._logger.error('Fail to stop playback process') self._logger.debug('Audio module release')
def unload_all(): dispatcher.send(UNLOAD_EVENT) # note, a copy of the _event_handlers[event] list is made here with the [:] # syntax as we are going to be removing event handlers from the list and # we can't do this while iterating over the same list. for event, handlers in _event_handlers.iteritems(): for handler in handlers[:]: dispatcher.disconnect(handler, signal=event) _event_handlers[event].remove(handler)
def disconnect_all(self, signal, **kwargs) -> None: """ 将所有接收器断开给定信号的连接 :param signal: :param kwargs: :return: """ for receiver in dispatcher.liveReceivers( dispatcher.getAllReceivers(self.send, signal)): dispatcher.disconnect(receiver, signal, self.sender, **kwargs)
def close(self): # disconnect from dispatcher dispatcher.disconnect( receiver = self._messageNotification, signal = (self.ipAddress,self.udpPort), ) # stop self.goOn = False self.gotMsgSem.release()
def close(self): # disconnect from dispatcher dispatcher.disconnect(receiver=self._messageNotification, ) # close pcap file self.pcapFile.close() # stop self.goOn = False self.gotMsgSem.release()
def tearDown(self): self.wait_for_queue() try: dispatcher.disconnect(self.ctrl_message) except : pass try: dispatcher.disconnect(self.ctrl_waiting) except : pass self.network.controller.cancel_command() self.ctrl_state_result = None
def dm_teardown(self): """ Disconnect the method from the signal. It's done to avoid conflicts when many instances of the mixin are being executed. """ try: dispatcher.disconnect( self.dequeue_next_page_requests, signal=signals.spider_idle ) except DispatcherKeyError: pass
def close(self): # disconnect from dispatcher dispatcher.disconnect( receiver = self._messageNotification, ) # close pcap file self.pcapFile.close() # stop self.goOn = False self.gotMsgSem.release()
def removeProperty(self, propertyname): ''' Remove one property in the model :param propertyname: :return: ''' prop = self._propertyDictionary.get(propertyname) if not prop == None: self._propertyDictionary.pop(propertyname) dispatcher.disconnect(self.onValueChangedHandler, signal=dataclass.DataClass.SIGNAL_VALUECHANGED, sender=prop) dispatcher.send( signal=GenericModel.SIGNAL_MODELCHANGED, sender=self ) else: raise model.PropertyNotPresentError('Property {} it isn\'t present in the model already present'.format(propertyname))
def disconnect(receiver, sender=Any, weak=True): """ Disconnects given receiver from sender for this signal. Wrapper for :func:`disconnect`. Usage:: from xyz import post_save # do not trigger log_saving_event when a Note is saved post_save.disconnect(log_saving_event, sender=Note) Publishes a debug log message via Python's `logging` module. """ disconnect(receiver, signal=self, sender=sender, weak=weak) logger.debug('{receiver} unsubscribed from {self}'.format(**locals()))
def run(self): try: # log log.info('thread started') while True: # kill thread if not self.goOn: break # wait for syncLock to be released self.syncLock.acquire() # kill thread if not self.goOn: break # sync mirror data to Google, if necessary self._syncToGoogle() # disconnect from dispatcher dispatcher.disconnect( self.indicateNewData, signal = 'newDataMirrored', weak = False, ) dispatcher.disconnect( self.getStatus, signal = "googlestatus", weak = False, ) # log log.info('thread ended') except Exception as err: output = [] output += ['===== crash in thread {0} ====='.format(self.name)] output += ['\nerror:\n'] output += [str(err)] output += ['\ncall stack:\n'] output += [traceback.format_exc()] output = '\n'.join(output) print output # critical error log.critical(output) raise
def _handle_admin(self): """ Manage pub settings of the ZMQ PUB socket. :return: the current list of signal triggering the PUB socket """ context = zmq.Context() admin = context.socket(zmq.REP) admin.setsockopt(zmq.IPV6, 1) admin.setsockopt(zmq.IPV4ONLY, 0) admin.bind("tcp://*:%s" % self.zmq_admin_port) def _handle_pub_all_callback(**kwargs): # Assume here that we got a JSON cleaned_event = self.clean_event(kwargs) self.queue.put(cleaned_event) subscriptions = set() while True: # Wait for next request from client message = admin.recv() log.info("Received request: %s" % message) try: message = json.loads(message) except Exception as e: print("That was not a JSON") log.error(e) continue if not set(message.keys()).issubset({"sub", "unsub"}): admin.send_json({"error": "Incorrect format use a JSON with sub, unsub"}) continue count = 0 if "sub" in message.keys(): for sub in message["sub"]: if sub not in subscriptions: dispatcher.connect(_handle_pub_all_callback, signal=sub) count += 1 subscriptions.add(sub) if "unsub" in message.keys(): for unsub in message["unsub"]: if unsub in subscriptions: dispatcher.disconnect(_handle_pub_all_callback, signal=unsub) count += 1 subscriptions.remove(unsub) admin.send_json({"subscriptions": list(subscriptions)})
def run(self): dld = DustLinkData.DustLinkData() try: # log log.info("thread started") while self.goOn: # log if log.isEnabledFor(logging.DEBUG): log.debug("updating DustLink modules") authCache = dld.authCache log.debug("Authentication cache hits={0}, misses={1}, size={2}".format(authCache.getHit(), authCache.getMiss(), authCache.getSize())) # update modules self._updateGateway() self._updateLbr() self._updateDataConnector() self._updatePersistence() # sleep a bit time.sleep(self.refresh_period) # disconnect from dispatcher dispatcher.disconnect( self.tearDown, signal = 'tearDown', weak = False, ) # log log.info('thread ended') except Exception as err: output = [] output += ['===== crash in thread {0} ====='.format(self.name)] output += ['\nerror:\n'] output += [str(err)] output += ['\ncall stack:\n'] output += [traceback.format_exc()] output = '\n'.join(output) print output # critical error log.critical(output) raise
def disconnect(self, receiver, signal, **kwargs): """ Disconnect a receiver function from a signal. This has the opposite effect of the :meth:`connect` method, and the arguments are the same. """ kwargs.setdefault('sender', self.sender) return dispatcher.disconnect(receiver, signal, **kwargs)
def node_stop(self): self._io_debug('stop') if self.node_state == NODE_RUNNING: self.node_controller.stop() self.node_serial.stop() dispatcher.disconnect(self.node_send, m_common.IO_RECV) elif self.node_state == NODE_READY: self.node_init() self.node_state = NODE_HALTED data = struct.pack("<BB", m_sensorlab.EVENT_NODE_PROPERTY_UPDATE, 1) data += m_sensorlab.property_reference_payload(m_sensorlab.STATE_PROPERTY_ID, m_sensorlab.TYPE_ASCII_ARRAY, len('halted'), 'halted') # send it timestamp = time.time() self._io_log(timestamp, data)
def _cleanup(self): # kill associated threads with self.dataLock: for connectParam in self.apiconnectors.keys(): self._deleteManagerConnection(connectParam) # disconnect from dispatcher dispatcher.disconnect( self.tearDown, signal = 'tearDown', weak = False, ) dispatcher.disconnect( self._ebHandler_deviceCommunicationError, signal = 'deviceCommunicationError', weak = False, )
def shutdown(self, *args, **kwargs): logging.debug("%s: Disconnecting filter %s from all source signals." % (self.session, self)) try: dispatcher.disconnect(self.remove_self, signals.dismiss_buffer, self.source) dispatcher.disconnect(self.remove_source_item, signals.remove_item, self.source) if hasattr(self, "clear"): dispatcher.disconnect(self.clear, signals.clear_buffer, self.source) dispatcher.disconnect(self.extend, signals.buffer_updated, self.source) except: logging.exception("%s: There was an error disconnecting filter %s from source signals." % (self.session, self)) return super(Filtered, self).shutdown(*args, **kwargs)
def _on_parent_changed( self, old_parent, new_parent ): # mark ourself as dirty self.set_dirty() # unregister from our old parent's events if old_parent != None: dispatcher.disconnect( self._on_transform_changed, Transform.on_transform_changed, old_parent ) # register to our new parent's events if new_parent != None: dispatcher.connect( self._on_transform_changed, Transform.on_transform_changed, new_parent )
def _get_color_values(self): """Search for color values available on this node.""" from openzwave.network import ZWaveNetwork from pydispatch import dispatcher _LOGGER.debug("Searching for zwave color values") # Currently zwave nodes only exist with one color element per node. if self._value_color is None: for value_color in self._value.node.get_rgbbulbs().values(): self._value_color = value_color if self._value_color_channels is None: self._value_color_channels = self.get_value( class_id=zwave.const.COMMAND_CLASS_SWITCH_COLOR, genre=zwave.const.GENRE_SYSTEM, type=zwave.const.TYPE_INT) if self._value_color and self._value_color_channels: _LOGGER.debug("Zwave node color values found.") dispatcher.disconnect( self._value_added, ZWaveNetwork.SIGNAL_VALUE_ADDED) self.update_properties()
def remove_buffer(self, buffer, fromList = False, fromUI = False): if fromUI and fromList: dispatcher.disconnect(self.HandleDismissBuffer, signals.dismiss_buffer, buffer) dispatcher.disconnect(self.HandleNewPosts, signals.buffer_updated, buffer) dispatcher.disconnect(self.HandleClearBuffer, signals.clear_buffer, buffer) dispatcher.disconnect(self.Handleremove_item, signals.remove_item, buffer) if fromUI: index = self.get_buffer_index(buffer) if index != wx.NOT_FOUND: self.buffer.Delete(index) self.dlg.CallHandlers('buffer', self.get_buffer()) if fromList: if buffer in self.empty_buffers: self.empty_buffers.remove(buffer)
def initRoverConn(self, newroverdict): # clear history dispatcher.disconnect(self._sendToRemote_handler) while len(self.roverdict) > 0: for oldIP in self.roverdict.keys(): self.subscriber.disconnect("tcp://%s:%s" % (oldIP, self.zmq_pub_port)) self.roverdict.pop(oldIP) # add new configuration self.roverdict = newroverdict.copy() log.info('Rover connection:', str(self.roverdict)) for roverIP, value in self.roverdict.items(): if not isinstance(value, str): self.subscriber.connect("tcp://%s:%s" % (roverIP, self.zmq_pub_port)) for serial in self.roverdict[roverIP]: signal = 'fromMoteConnector@' + serial dispatcher.connect( self._sendToRemote_handler, signal=signal.encode('utf8') ) else: self.roverdict.pop(roverIP)