def test_emit_return(): ee = EventEmitter() # make sure emission without callback retruns False nt.assert_false(ee.emit('data')) # add a callback ee.on('data')(lambda: None) # should return true now nt.assert_true(ee.emit('data'))
def __init__(self, endpoint=None, id=None, secret=None, debug=False, bot=SputnikSession, ca_certs_dir="/etc/ssl/certs", **kwargs): EventEmitter.__init__(self) self.debug = debug self.session_factory = BotFactory(username=id, password=secret, **kwargs) self.session_factory.on("connect", self.onConnect) self.session_factory.on("disconnect", self.onDisconnect) self.session_factory.on("join", self.onJoin) self.session_factory.session = bot self.base_uri = endpoint from urlparse import urlparse parse = urlparse(endpoint) if parse.scheme == 'wss': if parse.port is None: port = 8443 else: port = parse.port self.connection_string = "ssl:host=%s:port=%d:caCertsDir=%s" % (parse.hostname, port, ca_certs_dir) elif parse.scheme == 'ws': if parse.port is None: port = 8880 else: port = parse.port self.connection_string = "tcp:%s:%d" % (parse.hostname, port) else: raise NotImplementedError self.session = None self.transport_factory = websocket.WampWebSocketClientFactory(self.session_factory, url = self.base_uri, debug=self.debug, debug_wamp=self.debug)
def __init__(self, **kwargs): EventEmitter.__init__(self) for key, value in kwargs.iteritems(): setattr(self, key, value) component_config = types.ComponentConfig(realm = u"sputnik") wamp.ApplicationSessionFactory.__init__(self, config=component_config)
class PendingPacket(): def __init__(self, packet, packet_sender): print 'Init PendingPacket' self.ee = EventEmitter() self._packet_sender = packet_sender self._packet = packet def send(self): def packet_send(): self._packetSender.send(self._packet) self._intervalID = helpers.set_interval( packet_send, constants.TIMEOUT ) self._packet_sender.send(self._packet) def get_sequence_number(self): return self._packet.get_sequence_number() def acknowledge(self): self._intervalID.cancel() self.ee.emit('acknowledge')
def __init__(self, address): EventEmitter.__init__(self) threading.Thread.__init__(self) self.sp = serial.Serial(address, timeout=1) self.alive = True self.lock = threading.Lock()
def __init__(self, url, debug=False): WebSocketClient.__init__(self, url) EventEmitter.__init__(self) self.debug = debug self._session = None self._uniq_id = 0 self._callbacks = {}
def test_asyncio_error(): """Test that event_emitters can handle errors when wrapping coroutines as used with asyncio. """ loop = new_event_loop() ee = EventEmitter(loop=loop) should_call = Future(loop=loop) @ee.on('event') async def event_handler(): raise PyeeTestError() @ee.on('error') def handle_error(exc): should_call.set_result(exc) async def create_timeout(loop=loop): await sleep(0.1, loop=loop) if not should_call.done(): raise Exception('should_call timed out!') return should_call.cancel() timeout = create_timeout(loop=loop) @should_call.add_done_callback def _done(result): assert isinstance(result, PyeeTestError) ee.emit('event') loop.run_until_complete(gather(should_call, timeout, loop=loop)) loop.close()
class Runner(object): def __init__(self, client, make_request): self.client = client self.make_request = make_request self._pending = [] self.events = EventEmitter() def _on_request_finished(self, _): """ Start the next waiting request if possible. """ if len(self.client.active) < self.client.max_clients: self._start_request() def _start_request(self): """ Start a request and add callbacks to its future. Most notably, the completion of the requests's future will also trigger the completion of a future we had prepared earlier. """ request = self.make_request(streaming_callback=lambda c: None) future = concurrent.Future() self.events.emit("request_ready", future, request) self.client.fetch(request, callback=future.set_result) self.events.emit("request_started", future) self._pending.append(future) future.add_done_callback(lambda f: self.events.emit("request_finished", f)) future.add_done_callback(self._pending.remove) future.add_done_callback(self._on_request_finished)
def __init__(self, url, debug=False): self.debug = debug # by default socket connections don't timeout. this causes issues # where reconnects can get stuck # TODO: make this configurable? socket.setdefaulttimeout(10) WebSocketClient.__init__(self, url) EventEmitter.__init__(self)
def __init__(self, id=None, secret=None, endpoint="https://api.coinsetter.com/v1"): EventEmitter.__init__(self) self.username = id self.password = secret self.endpoint = endpoint self.session_id = None from urllib2 import urlopen self.ip = json.load(urlopen('http://jsonip.com'))['ip']
def __init__(self, log, clock, script_path, id, app, name, popen=subprocess.Popen): EventEmitter.__init__(self) self.log = log self.clock = clock self.script_path = script_path self.app = app self.name = name self.runner = None self._name = "%s-%s-%s" % (id, app, name) self._popen = popen
class IncomingMessage(object): def __init__(self, im_id, size): self.log = logging.getLogger( '%s' % self.__class__.__name__ ) self.log.debug('New IncomingMessage Created') self.im_id = im_id self.size = size self.ee = EventEmitter() self.synced = False self._next_sequence_number = 0 self._sync_sequence_number = None self._packets = SortedList() self.body = '' self.waiting = False def add_to_body(self, payload): if payload in self.body: self.log.debug('This content is already in the body.') return else: self.body += payload def reset(self): self.log.debug('IncomingMessage Reset') self.log.debug('Self Packets: %s', self._packets) self._packets.clear() self.synced = False self._next_sequence_number = 0 self._sync_sequence_number = None try: self.log.debug('Downloaded (%s) | Total Size (%s)', len(self.body), self.size) if len(self.body) >= int(self.size): self.log.debug('Download Complete') if len(self.body) > int(self.size): self.log.debug('Oversized Message') self.ee.emit('complete', {'body': self.body}) return else: # print self._message, self._message_size self.log.debug('Still downloading...') self.waiting = True except Exception as e: self.log.debug('Problem with resetting IncomingMessage: %s', e)
def __init__(self): """Constructor.""" # run the superclass constructor EventEmitter.__init__(self) self.type = None self.control_elements = [] self.data_conditions = [] # sensor_id should be unique rndnum = random.randint(0, 100000) self.sensor_id = "sensor" + str(rndnum)
class RegistrationOnlyEmitter(object): def __init__(self): self.emitter = EventEmitter() def on(self, event, f): if event in ['register_intent', 'register_vocab', 'recognizer_loop:utterance']: self.emitter.on(event, f) def emit(self, event, *args, **kwargs): event_name = event.message_type self.emitter.emit(event_name, event, *args, **kwargs)
def test_emit_error(): ee = EventEmitter() with nt.assert_raises(Exception): ee.emit('error') @ee.on('error') def onError(): pass # No longer raises and error instead return True indicating handled nt.assert_true(ee.emit('error'))
def __init__(self, clock, container, id, app, name, image, command, config, port_pool, port): EventEmitter.__init__(self) self.clock = clock self.id = id self.app = app self.name = name self.image = image self.command = command self.config = config self.port_pool = port_pool self.port = port self.state = 'init' self._container = container
class RegistrationOnlyEmitter(object): def __init__(self): self.emitter = EventEmitter() def on(self, event, f): allow_events_to_execute = True if allow_events_to_execute: # don't filter events, just run them all print "Event: "+str(event) self.emitter.on(event, f) else: # filter to just the registration events, # preventing them from actually executing if event in [ 'register_intent', 'register_vocab', 'recognizer_loop:utterance' ]: print "Event: " + str(event) self.emitter.on(event, f) def emit(self, event, *args, **kwargs): event_name = event.type self.emitter.emit(event_name, event, *args, **kwargs) def once(self, event, f): self.emitter.once(event, f) def remove(self, event_name, func): pass
def test_shorter_pattern(): """Tests correct behaviour with shorter patterns""" ee = EventEmitter() @ee.on('#') def event_handler(ev): raise ItWorkedException with nt.assert_raises(ItWorkedException) as it_worked: ee.emit('a/b/c') with nt.assert_raises(ItWorkedException) as it_worked: ee.emit('cool')
def __init__(self, url, auto_reconnect=True, auto_reconnect_timeout=0.5, debug=False): EventEmitter.__init__(self) self.collection_data = CollectionData() self.ddp_client = DDPClient(url, auto_reconnect=auto_reconnect, auto_reconnect_timeout=auto_reconnect_timeout, debug=debug) self.ddp_client.on('connected', self.connected) self.ddp_client.on('socket_closed', self.closed) self.ddp_client.on('failed', self.failed) self.ddp_client.on('added', self.added) self.ddp_client.on('changed', self.changed) self.ddp_client.on('removed', self.removed) self.ddp_client.on('reconnected', self._reconnected) self.connected = False self.subscriptions = {} self._login_data = None
def __init__(self, url, auto_reconnect=True, auto_reconnect_timeout=0.5, debug=False): EventEmitter.__init__(self) self.ddpsocket = None self._ddp_version_index = 0 self._retry_new_version = False self._is_closing = False self._is_reconnecting = False self.url = url self.auto_reconnect = auto_reconnect self.auto_reconnect_timeout = auto_reconnect_timeout self.debug = debug self._session = None self._uniq_id = 0 self._callbacks = {} self._init_socket()
def test_twisted_emit(): """Test that event_emitters can handle wrapping coroutines when using twisted and ensureDeferred. """ ee = EventEmitter(scheduler=ensureDeferred) should_call = Mock() @ee.on('event') async def event_handler(): should_call(True) ee.emit('event') should_call.assert_called_once()
def __init__( self, # type: Any addr, # type: str port, # type: int prot=default_protocol, # type: Protocol out_addr=None, # type: Union[None, Tuple[str, int]] debug_level=0 # type: int ): # type: (...) -> None """Initializes a peer to peer socket Args: addr: The address you wish to bind to (ie: "192.168.1.1") port: The port you wish to bind to (ie: 44565) prot: The protocol you wish to operate over, defined by a :py:class:`py2p.base.Protocol` object out_addr: Your outward facing address. Only needed if you're connecting over the internet. If you use '0.0.0.0' for the addr argument, this will automatically be set to your LAN address. debug_level: The verbosity you want this socket to use when printing event data Raises: socket.error: The address you wanted could not be bound, or is otherwise used """ object.__init__(self) EventEmitter.__init__(self) self.protocol = prot self.debug_level = debug_level self.routing_table = {} # type: Dict[bytes, BaseConnection] # In format {ID: handler} self.awaiting_ids = [] # type: List[BaseConnection] # Connected, but not handshook yet if out_addr: # Outward facing address, if you're port forwarding self.out_addr = out_addr elif addr == '0.0.0.0': self.out_addr = get_lan_ip(), port else: self.out_addr = addr, port info = (str(self.out_addr).encode(), prot.id.encode(), user_salt) h = sha384(b''.join(info)) self.id = b58encode_int(int(h.hexdigest(), 16)).encode() # type: bytes self._logger = getLogger('{}.{}.{}'.format( self.__class__.__module__, self.__class__.__name__, self.id)) self.__handlers = [ ] # type: List[Callable[[Message, BaseConnection], Union[bool, None]]] self.__closed = False
def __init__(self, packet_sender): # TODO: have this be a DuplexStream instead of an EventEmitter. # TODO: the Receiver should never send raw packets to the end host. It should # only be acknowledgement packets. Please see [1] self.ee = EventEmitter() self.incoming_messages = {} self._synced = False self._next_sequence_number = 0 self._sync_sequence_number = None self._packets = SortedList() self._packet_sender = packet_sender self._closed = False self._message = '' self._message_id = None self._fullmessage = '' self._message_size = 0 self._waiting = False self.log = logging.getLogger( '%s' % self.__class__.__name__ ) self.log.debug('Init Receiver')
def __init__(self, url, auto_reconnect=True, auto_reconnect_timeout=0.5, debug=False, headers=None): EventEmitter.__init__(self) self.ddpsocket = None self._ddp_version_index = 0 self._retry_new_version = False self._is_closing = False self._is_reconnecting = False self.url = url self.auto_reconnect = auto_reconnect self.auto_reconnect_timeout = auto_reconnect_timeout self.debug = debug self.headers = [('Host', self._get_domain_from_url(self.url))].append(headers) self._session = None self._uniq_id = 0 self._callbacks = {} self._init_socket()
def __init__(self, packet, packet_sender): print 'Init PendingPacket' self.ee = EventEmitter() self._packet_sender = packet_sender self._packet = packet
def test_longer_pattern(): """Tests correct behaviour with longer patterns""" ee = EventEmitter() @ee.on('a/b/#') def event_handler(ev): raise ItWorkedException ee.emit('c') @ee.on('+/a/b') def event_handler(ev): raise ItWorkedException('c and #/a/b') ee.emit('c')
def __init__(self, device=None, pin_a0=False, pin_a1=False, pin_a2=False, channel=microchip_pot_channel.NONE, non_vol_mode=microchip_pot_non_volatile_mode. VOLATILE_AND_NON_VOLATILE, init_non_vol_wiper_val=0): """Initialize a new instance of MicrochipPotentiometer. :param raspy.io.i2c.i2c_interface.I2CInterface device: The I2C bus device this instance is connected to. :param bool pin_a0: Set True if device's address pin A0 is high. :param bool pin_a1: Set True if device's address pin A1 is high. :param bool pin_a2: Set True if device's address pin A2 is high. :param int channel: The potentiometer channel. :param int non_vol_mode: The non-volatility mode. :param int init_non_vol_wiper_val: The initial value to set. :raises: raspy.argument_null_exception.ArgumentNullException if 'device' param is None. :raises: raspy.illegal_argument_exception.IllegalArgumentException if the specified channel is not supported by the device. :raises: raspy.io.io_exception.IOException if unable to open the I2C bus. """ Potentiometer.__init__(self) if device is None: msg = "Param 'device' cannot be None." raise ArgumentNullException(msg) if not self.is_channel_supported(channel): msg = "Specified channel not supported by device." raise IllegalArgumentException(msg) self.__emitter = EventEmitter() self.__channel = channel self.__currentValue = 0 self.__nonVolMode = non_vol_mode device_addr = MicrochipPotentiometer._build_i2c_address( pin_a0, pin_a1, pin_a2) self.__controller = mcp_device_controller.MCPDeviceController( device, device_addr) self.__emitter.on( EVENT_WIPER_ACTION, lambda wiper_evt: self._on_wiper_action_event(wiper_evt)) self._initialize(init_non_vol_wiper_val)
def __init__(self, ctx, **kwargs): self.ctx = ctx self.is_running = False # Provide an interface for event subscribers self.emitter = EventEmitter() # Prepare OSC message dispatcher and UDP server self.address = kwargs.get('osc_address', OSC_ADDRESS) self.port = kwargs.get('osc_port', OSC_PORT) bind = (self.address, self.port) disp = dispatcher.Dispatcher() disp.map('/leasebot/*', self._on_param) self._server = osc_server.ThreadingOSCUDPServer(bind, disp)
async def test_asyncio_once_emit(event_loop): """Test that event_emitters also wrap coroutines when using once """ ee = EventEmitter(loop=event_loop) should_call = Future(loop=event_loop) @ee.once('event') async def event_handler(): should_call.set_result(True) ee.emit('event') result = await wait_for(should_call, 0.1) assert result == True
def __init__(self, im_id, size): self.log = logging.getLogger('%s' % self.__class__.__name__) self.log.debug('New IncomingMessage Created') self.im_id = im_id self.size = size self.ee = EventEmitter() self.synced = False self._next_sequence_number = 0 self._sync_sequence_number = None self._packets = SortedList() self.body = '' self.waiting = False
def __init__(self, packets): self.log = logging.getLogger("%s" % self.__class__.__name__) self.log.info("Init Window") self.event_emitter = EventEmitter() self._packets = packets self._acknowledged = []
def test_pattern_matching(): """Test that patterns are correctly interpreted""" ee = EventEmitter() assert ee._matches('#', 'a/b/c') assert ee._matches('+/b/c', 'a/b/c') assert ee._matches('a/#', 'a/b/c') assert not ee._matches('a/#', 'c/a/b/c') with nt.assert_raises(PatternException) as e: ee._matches('#/b/c', 'c') assert not ee._matches('a/+/d/e', 'a/b/c/d/e')
def __init__(self, source=None, volume=None, aggressiveness=None, model_dir=None, lang=None, config=CONFIG): EventEmitter.__init__(self) self.config = config # ensure default values for k in CONFIG["listener"]: if k not in self.config["listener"]: self.config["listener"][k] = CONFIG["listener"][k] volume = volume or self.config["listener"]["default_volume"] aggressiveness = aggressiveness or self.config["listener"][ "default_aggressiveness"] model_dir = model_dir or self.config["listener"]["default_model_dir"] self.lang = lang or self.config["lang"] if "-" in self.lang: self.lang = self.lang.split("-")[0] if "{lang}" in model_dir: model_dir = model_dir.format(lang=self.lang) if not isdir(model_dir): if model_dir in self._default_models: logging.error( "you need to install the package: " "kaldi-chain-zamia-speech-{lang}".format(lang=self.lang)) raise ModelNotFound self.rec = PulseRecorder(source_name=source, volume=volume) self.vad = VAD(aggressiveness=aggressiveness) logging.info("Loading model from %s ..." % model_dir) self.asr = ASR(engine=ASR_ENGINE_NNET3, model_dir=model_dir, kaldi_beam=self.config["listener"]["default_beam"], kaldi_acoustic_scale=self.config["listener"] ["default_acoustic_scale"], kaldi_frame_subsampling_factor=self.config["listener"] ["default_frame_subsampling_factor"]) self._hotwords = dict(self.config["hotwords"])
class Server: def __init__(self, ctx, **kwargs): self.ctx = ctx self.is_running = False # Provide an interface for event subscribers self.emitter = EventEmitter() # Prepare OSC message dispatcher and UDP server self.address = kwargs.get('osc_address', OSC_ADDRESS) self.port = kwargs.get('osc_port', OSC_PORT) bind = (self.address, self.port) disp = dispatcher.Dispatcher() disp.map('/leasebot/*', self._on_param) self._server = osc_server.ThreadingOSCUDPServer(bind, disp) def start(self): thread = threading.Thread(target=self._start_server) thread.daemon = True thread.start() self.is_running = True def stop(self): self._server.shutdown() self.is_running = False def _start_server(self): self.ctx.log('OSC server @ {}:{}'.format(self.address, self.port)) self._server.serve_forever() def _on_param(self, address, *args): param = address.replace('/leasebot/', '') # Commands with no arguments if param == 'reset': self.emitter.emit('reset') return # We expect one float argument from now on if not len(args) == 1 or type(args[0]) is not float: return if param in ['temperature'] and 0 <= args[0] <= 1: self.emitter.emit('param', param, args[0]) if param in ['interval'] and 0 <= args[0] <= 5: self.emitter.emit('param', param, args[0]) if param in ['volume']: self.emitter.emit('param', param, args[0])
def __init__(self, host=None, port=None, route=None, ssl=None): config = Configuration.get().get("websocket") host = host or config.get("host") port = port or config.get("port") route = route or config.get("route") ssl = ssl or config.get("ssl") validate_param(host, "websocket.host") validate_param(port, "websocket.port") validate_param(route, "websocket.route") self.url = WebsocketClient.build_url(host, port, route, ssl) self.emitter = EventEmitter() self.client = self.create_client() self.pool = ThreadPool(10) self.retry = 5 self.connected_event = Event() self.started_running = False
async def test_asyncio_emit(event_loop): """Test that event_emitters can handle wrapping coroutines as used with asyncio. """ ee = EventEmitter(loop=event_loop) should_call = Future(loop=event_loop) @ee.on('event') async def event_handler(): should_call.set_result(True) ee.emit('event') result = await wait_for(should_call, 0.1) assert result == True
def __init__(self, username, password, **kwargs): if not username: raise UsernameMustExist('options.username must exist and may not be null') if not password: raise PasswordMustExist('options.password must exist and may not be null') self.user = SelfUser(username, password) self.ready = False self.servers = {} self._ws = None self.event = EventEmitter() self.message_cache = OrderedDict() self.cache_size = kwargs.get('cache_size') self.loop = kwargs.get('loop') if self.loop is None: self.loop = asyncio.get_event_loop() self.api = aiohttp.ClientSession(loop=self.loop) if self.cache_size is None or self.cache_size < 100: self.cache_size = 500
def test_emit_error(): """Errors raise with no event handler, otherwise emit on handler""" call_me = Mock() ee = EventEmitter() test_exception = PyeeTestException('lololol') with raises(PyeeTestException) as exc_info: ee.emit('error', test_exception) @ee.on('error') def on_error(exc): call_me() # No longer raises and error instead return True indicating handled assert ee.emit('error', test_exception) call_me.assert_called_once()
def __init__(self, symbol='BTC-USD', channels=[], shouldAuth=False, max_table_length=constants.MAX_TABLE_LEN, websocket=None): EventEmitter.__init__(self) self.channels = channels if max_table_length > 0: self.max_table_length = max_table_length else: self.max_table_length = constants.MAX_TABLE_LEN self.shouldAuth = shouldAuth self.symbol = symbol self.websocket = websocket self.data = { 'orderBookL2': [], 'instrument': [] } channels = self.channels symbol = self.symbol shouldAuth = self.shouldAuth websocket = self.websocket self.websocket = GdaxWebsocket() self.websocket.connect( shouldAuth=shouldAuth, websocket=websocket ) self.websocket.on('subscribe', self.on_subscribe) self.websocket.on('latency', self.on_latency) self.channels = [] self.subscribe_to_channels(channels) self.subscribe_to_instrument_channels(symbol, channels) self.secureChannels = [] if shouldAuth: self.subscribe_to_secure_instrument_channels(symbol, channels)
class PendingPacket(object): def __init__(self, packet, packet_sender): self.loop = ioloop.IOLoop.current() self.event_emitter = EventEmitter() self._packet_sender = packet_sender self._packet = packet self._interval_id = None self._sending = False self._sending_count = 0 self.log = logging.getLogger( '%s' % self.__class__.__name__ ) self.log.info('Init PendingPacket') def send(self): self._sending = True self.log.debug('Sending Packet #%s: %s', self._packet.get_sequence_number(), self._sending) self._packet_sender.send(self._packet) # self._interval_id = rudp.helpers.set_interval( # packet_send, # rudp.constants.TIMEOUT # ) # self.log.debug('Packet %s sent %d times', self._packet.get_sequence_number(), self._sending_count) def get_sequence_number(self): return self._packet.get_sequence_number() def acknowledge(self): self.log.debug('Pending Packet Acknowledged: %s', self._packet.get_sequence_number()) self._sending = None if self._interval_id: self._interval_id.cancel() self._interval_id = None self.event_emitter.emit('acknowledge')
def __init__(self, host, logLevel='INFO', loop=None, max_retries=5, create_event_emitter=_start_event_worker): self.host = host self.logger = CustomLogger('BfxWebsocket', logLevel=logLevel) self.loop = loop or asyncio.get_event_loop() # overide 'error' event to stop it raising an exception # self.events.on('error', self.on_error) self.ws = None self.max_retries = max_retries self.attempt_retry = True self.sockets = {} # start seperate process for the even emitter eventLoop = create_event_emitter() self.events = EventEmitter(scheduler=asyncio.ensure_future, loop=eventLoop)
def __init__(self, packet_sender): self.log = logging.getLogger('%s' % self.__class__.__name__) self.log.info('Init Sender') self._packet_sender = packet_sender self._windows = [] self._sending = None self._last_sent = 0 self.event_emitter = EventEmitter()
def __init__(self, packet_sender): print 'Init Receiver' # TODO: have this be a DuplexStream instead of an EventEmitter. # TODO: the Receiver should never send raw packets to the end host. It should # only be acknowledgement packets. Please see [1] self.ee = EventEmitter() self._synced = False self._next_sequence_number = 0 def sort_by_sequence(packet_a, packet_b): return packet_a.get_sequence_number( ) - packet_b.get_sequence_number() self._packets = LinkedList(sort_by_sequence) self._packet_sender = packet_sender self._closed = False
class PendingPacket(object): def __init__(self, packet, packet_sender): self.loop = ioloop.IOLoop.current() self.event_emitter = EventEmitter() self._packet_sender = packet_sender self._packet = packet self._interval_id = None self._sending = False self._sending_count = 0 self.log = logging.getLogger('%s' % self.__class__.__name__) self.log.info('Init PendingPacket') def send(self): self._sending = True self.log.debug('Sending Packet #%s: %s', self._packet.get_sequence_number(), self._sending) self._packet_sender.send(self._packet) # self._interval_id = rudp.helpers.set_interval( # packet_send, # rudp.constants.TIMEOUT # ) # self.log.debug('Packet %s sent %d times', self._packet.get_sequence_number(), self._sending_count) def get_sequence_number(self): return self._packet.get_sequence_number() def acknowledge(self): self.log.debug('Pending Packet Acknowledged: %s', self._packet.get_sequence_number()) self._sending = None if self._interval_id: self._interval_id.cancel() self._interval_id = None self.event_emitter.emit('acknowledge')
def __init__(self, topic, event_emitter=EventEmitter()): # self.graph = facebook.GraphAPI(Config.PAGE_ACCESS_TOKEN) logging.debug("initializing video Service!") event_emitter.on(topic, self.act) self.stream_url = '' self.proc = None logging.debug("creating cam file..") subprocess.Popen(shlex.split("modprobe bcm2835-v4l2"), stdout=subprocess.PIPE)
def __init__(self, initial_value, value_forwarder=None): """ Initialize the object. initial_value -- the initial value value_forwarder -- the method that updates the actual value on the thing """ EventEmitter.__init__(self) self.last_value = initial_value if value_forwarder is None: def fn(_): raise AttributeError('Read-only value') self.value_forwarder = fn else: self.value_forwarder = value_forwarder
def test_twisted_error(): """Test that event_emitters can handle wrapping coroutines when using twisted and ensureDeferred. """ ee = EventEmitter(scheduler=ensureDeferred) should_call = Mock() @ee.on('event') async def event_handler(): raise PyeeTestError() @ee.on('error') def handle_error(e): should_call(e) ee.emit('event') should_call.assert_called_once()
def __init__(self, runner=None): self.events = EventEmitter() self.started = None self.finished = None self.requests = 0 self._pending = {} self._records = [] if runner: self._attach_to(runner)
class InterceptEmitter(object): """ This class intercepts and allows emitting events between the skill_tester and the skill being tested. When a test is running emitted communication is intercepted for analysis """ def __init__(self): self.emitter = EventEmitter() self.q = None def on(self, event, f): # run all events print("Event: ", event) self.emitter.on(event, f) def emit(self, event, *args, **kwargs): event_name = event.msg_type if self.q: self.q.put(event) self.emitter.emit(event_name, event, *args, **kwargs) def wait_for_response(self, event, reply_type=None, *args, **kwargs): """Simple single thread implementation of wait_for_response.""" message_type = reply_type or event.msg_type + '.response' response = None def response_handler(msg): nonlocal response response = msg self.emitter.once(message_type, response_handler) self.emitter.emit(event.msg_type, event) return response def once(self, event, f): self.emitter.once(event, f) def remove(self, event_name, func): pass def remove_all_listeners(self, event_name): pass
class MessageBusEventHandler(WebSocketHandler): def __init__(self, application, request, **kwargs): super().__init__(application, request, **kwargs) self.emitter = EventEmitter() def on(self, event_name, handler): self.emitter.on(event_name, handler) def on_message(self, message): LOG.debug(message) try: deserialized_message = Message.deserialize(message) except Exception: return try: self.emitter.emit(deserialized_message.msg_type, deserialized_message) except Exception as e: LOG.exception(e) traceback.print_exc(file=sys.stdout) pass for client in client_connections: client.write_message(message) def open(self): self.write_message(Message("connected").serialize()) client_connections.append(self) def on_close(self): client_connections.remove(self) def emit(self, channel_message): if (hasattr(channel_message, 'serialize') and callable(getattr(channel_message, 'serialize'))): self.write_message(channel_message.serialize()) else: self.write_message(json.dumps(channel_message)) def check_origin(self, origin): return True
def __init__(self, packet_sender): self.log = logging.getLogger('%s' % self.__class__.__name__) self.log.info('Init Connection') self.event_emitter = EventEmitter() self._sender = Sender(packet_sender) self._receiver = Receiver(packet_sender) # pylint: disable=unused-variable @self._receiver.event_emitter.on('data') def on_data(data): self.log.debug('Received IncomingMessage: %s', data) self.event_emitter.emit('data', data) # pylint: disable=unused-variable @self._receiver.event_emitter.on('_reset') def on_reset(data): self.log.debug('Received reset message')
def test_listeners(): """`listeners()` gives you access to the listeners array.""" call_me = Mock() ee = EventEmitter() @ee.on('event') def event_handler(): pass listeners = ee.listeners('event') assert listeners[0] == event_handler # Overwrite listener listeners[0] = call_me ee.emit('event') call_me.assert_called_once()
def __init__(self, steamid, key=None, language='en', identity_secret='', poll_delay=30): EventEmitter.__init__(self) self.session = aiohttp.ClientSession() ConfManager.__init__(self, identity_secret, steamid, self.session) self.steamid = SteamID(steamid) if not self.steamid.isValid( ) or not self.steamid.type == SteamID.Type['INDIVIDUAL']: raise ValueError( f"Steam ID {self.steamid} is not valid, or is not a user ID") self.key = key self.language = language self.poll_delay = poll_delay self.logged_in = False self._trade_cache = {} self._conf_cache = {}
def __init__(self, host=client_config.get("host"), port=client_config.get("port"), path=client_config.get("route"), ssl=str2bool(client_config.get("ssl"))): validate_param(host, "host") validate_param(port, "port") validate_param(path, "route") # validate_param(ssl, "ssl") # ssl = str2bool(ssl) self.emitter = EventEmitter() self.scheme = "wss" if ssl else "ws" self.host = host self.port = port self.path = path self.exp_backoff_counter = 1 self.client = self._create_new_connection() self.pool = ThreadPool(10)
def __init__(self, backtesting=False, symbol='tBTCUSD', indicators={}, logLevel='INFO', exchange_type=ExchangeType.EXCHANGE): self.exchange_type = exchange_type self.marketData = {} self.positions = {} self.lastPrice = {} self.closedPositions = [] self.is_ready = False self.indicators = indicators self.candle_price_key = 'close' self.backtesting = backtesting self.symbol = symbol self.events = EventEmitter(scheduler=asyncio.ensure_future) # initialise custom logger self.logLevel = logLevel self.logger = CustomLogger('HFStrategy', logLevel=logLevel) super(Strategy, self).__init__()
class InterceptEmitter(object): """ This class intercepts and allows emitting events between the skill_tester and the skill being tested. When a test is running emitted communication is intercepted for analysis """ def __init__(self): self.emitter = EventEmitter() self.q = None def on(self, event, f): # run all events print("Event: ", event) self.emitter.on(event, f) def emit(self, event, *args, **kwargs): event_name = event.type if self.q: self.q.put(event) self.emitter.emit(event_name, event, *args, **kwargs) def once(self, event, f): self.emitter.once(event, f) def remove(self, event_name, func): pass def remove_all_listeners(self, event_name): pass
class Camera() running = True def __init__(self,fps=24): self.emitter = EventEmitter() self.fps = fps self.cap = cv2.VideoCapture(0) self.thread = threading.Thread(target=self.run) self.thread.daemon = True self.thread.start() def run(self): capturePeriodSecs = 1.0 / self.fps while self.Running == True: try: self.cap_frame() except Exception as error: print ("error with capturing frames: ", error) time.sleep(capturePeriodSecs) def onNewFrame(self,callback): self.emitter.on('frame', callback) def removeOnNewFrameListener(self,callback): self.emitter.remove_emitter_listener('frame', callback) def stop(self): self.running = False def cap_frame(self): f,img = self.cap.read() self.latest_frame = img self.emitter.emit('frame', img)
def __init__(self, clock, data, reset): """Initialize a new instance of TempSensor. :param raspy.io.gpio.Gpio clock: The GPIO pin used for the clock. :param raspy.io.gpio.Gpio data: The GPIO used for data. :param raspy.io.gpio.Gpio reset: The GPIO pin used to trigger reset. :raises: ArgumentNullException if any of the pins are None. """ Component.__init__(self) if clock is None: raise ArgumentNullException("'clock' cannot be None.") if data is None: raise ArgumentNullException("'data' cannot be None.") if reset is None: raise ArgumentNullException("'reset' cannot be None.") self.__emitter = EventEmitter() self.__rawTemp = 0.0 self.__scale = temp_scale.CELCIUS self.__tempSensor = DS1620(clock, data, reset)
async def test_asyncio_error(event_loop): """Test that event_emitters can handle errors when wrapping coroutines as used with asyncio. """ ee = EventEmitter(loop=event_loop) should_call = Future(loop=event_loop) @ee.on('event') async def event_handler(): raise PyeeTestError() @ee.on('error') def handle_error(exc): assert isinstance(exc, PyeeTestError) should_call.set_result(exc) ee.emit('event') result = await wait_for(should_call, 0.1) assert isinstance(result, PyeeTestError)