def _tick(self): raw = '0,0,0,0,0' if (self._ser != None): try: raw = self._ser.readline() except SerialException as e: logging.error('Serial - unable to read data') pass parsed = raw.split(',') x, y, z = 0, 0, 0 if (self._config['sensor'] == 'phone'): x = self.x = float(parsed[2]) y = self.y = float(parsed[3]) z = self.z = float(parsed[4]) else: #shoe #YPRMfssT=,1.67,-53.00,12.33,1.08,0.01,0.11,-0.99,8.00,0,1, x = self.x = float(parsed[1]) y = self.y = float(parsed[2]) z = self.z = float(parsed[3]) # logging.info(x,y,z) self.intensity = (x**2 + y**2 + z**2)**0.5 smokesignal.emit('onData', self.x, self.y, self.z, self.intensity)
def test_instance_method(self): class Foo(object): def __init__(self): # Preferred way smokesignal.on('foo', self.foo) # Old way @smokesignal.on('foo') def _bar(): self.bar() self.foo_count = 0 self.bar_count = 0 def foo(self): self.foo_count += 1 def bar(self): self.bar_count += 1 foo = Foo() smokesignal.emit('foo') smokesignal.emit('bar') assert foo.foo_count == 1 assert foo.bar_count == 1
def test_EvaluatingListener(): @smokesignal.on("evaluation_finished") def t(evaluation, dataset, predictor): assert dataset == "dataset" assert isinstance(evaluation, EvaluationSheet) assert_array_equal(evaluation.tp, [1, 1, 2, 2]) assert_array_equal(evaluation.fp, [0, 1, 1, 2]) assert_array_equal(evaluation.fn, [1, 1, 0, 0]) assert_array_equal(evaluation.tn, [2, 1, 1, 0]) assert predictor == "predictor" t.called = True t.called = False relevant = {1, 2} universe = {1, 2, 3, 4} scoresheet = BaseScoresheet({1: 10, 3: 5, 2: 2, 4: 1}) EvaluatingListener(relevant=relevant, universe=universe) smokesignal.emit( "prediction_finished", scoresheet=scoresheet, dataset="dataset", predictor="predictor", ) assert t.called smokesignal.clear_all()
def userRenamed(self, oldname, newname): """ :param oldname: the nick of the user before the rename :param newname: the nick of the user after the rename """ smokesignal.emit('user_rename', self, oldname, newname)
def test_emit_with_callback_args(self): # Register first smokesignal.on('foo', self.mock_callback) assert smokesignal.responds_to(self.mock_callback, 'foo') smokesignal.emit('foo', 1, 2, 3, foo='bar') assert self.mock_callback.called_with(1, 2, 3, foo='bar')
def handlePrint(self, logDict): ''' All printing objects return their messages. These messages are routed to this method for handling. Send the messages to the printer. Optionally display the messages. Decorate the print messages with metadata. :param logDict: a dictionary representing this log item. Must contain keys message and type. :type logDict: dict. ''' # If the logger returns None, assume we dont want the output if logDict is None: return # write out the log message to file if self.queue is not None: self.queue.put(logDict) res = self.messageToString(logDict) # Write out the human-readable version to out if needed (but always print out # exceptions for testing purposes) if self.printLogs or logDict['type'] == 'ERR': self.redirectOut.trueWrite(res) # Broadcast the log to interested parties smokesignal.emit('logs', logDict)
def _tick(self): raw = '0,0,0,0,0' if (self._ser != None): try: raw = self._ser.readline() except SerialException as e: logging.error('Serial - unable to read data') pass parsed = raw.split(',') x,y,z = 0,0,0 if (self._config['sensor'] == 'phone'): x = self.x = float(parsed[2]) y = self.y = float(parsed[3]) z = self.z = float(parsed[4]) else: #shoe #YPRMfssT=,1.67,-53.00,12.33,1.08,0.01,0.11,-0.99,8.00,0,1, x = self.x = float(parsed[1]) y = self.y = float(parsed[2]) z = self.z = float(parsed[3]) # logging.info(x,y,z) self.intensity = (x**2 +y**2 + z**2)**0.5 smokesignal.emit('onData', self.x, self.y, self.z, self.intensity)
def tag_seen_callback(llrpMsg): """Function to run each time the reader reports seeing tags.""" tags = llrpMsg.msgdict['RO_ACCESS_REPORT']['TagReportData'] if tags: smokesignal.emit('rfid', { 'tags': tags, })
def test_once_decorator(self): # Register and call twice smokesignal.once('foo')(self.fn) smokesignal.emit('foo') smokesignal.emit('foo') assert self.fn.call_count == 1
def signedOn(self): for channel in settings.CHANNELS: if len(channel) > 1: self.join(channel[0], channel[1]) else: self.join(channel[0]) smokesignal.emit('signon', self)
def get_response(self, request: dict) -> dict: """ Return a response based on the input data. :param request: A dictionary with input data. :return: A response to the input data. """ self.response = self.bot.response self.request = request self.bot.reset() self.bot.user_id = request.get('user_id', '') self.bot.pub_id = request.get('pub_id', '') try: smokesignal.emit(BBotCore.SIGNAL_GET_RESPONSE_BEFORE, {}) self.bot.get_response(request) # get bot response self.process_pipeline() # run pipelin process: this proces changes bot output smokesignal.emit(BBotCore.SIGNAL_GET_RESPONSE_AFTER, {'bbot_response': self.response}) # triggers event: none of these should modify output except BBotCoreHalt as e: # this exception is used to do a soft halt self.logger.debug(e) #except BBotCoreError as e: # this exception sends exception msg to the bot output # self.bbot.text(e) self.logger.debug('Response from bbot metaengine: ' + str(self.response)) return self.response
def call_function(self, func_name: str, args: list, f_type: str='R'): """ Executes a BBot function or any bot engine function listed in functions_map attribute :param func_name: Name of the function :param args: List with arguments :param f_type: Function Type :return: """ self.core.logger.debug('Calling function "' + func_name + '" with args ' + str(args)) fmap = self.global_functions_map[func_name] start = datetime.datetime.now() response = None resp_code = BBotCore.FNC_RESPONSE_OK error_message = "" cost = fmap['cost'] exception = None try: smokesignal.emit(BBotCore.SIGNAL_CALL_BBOT_FUNCTION_BEFORE, {'name': func_name, 'args': args, 'register_enabled': fmap['register_enabled'], 'data': fmap}) response = getattr(fmap['object'], fmap['method'])(args, f_type) # convert dict into box to gain dotted notation access if isinstance(response, dict): response = Box(response) except BBotExtensionException as e: exception = e # do not remove >> https://stackoverflow.com/questions/29268892/python-3-exception-deletes-variable-in-enclosing-scope-for-unknown-reason resp_code = e.code error_message = str(e) cost = 0 response = '<error>' #@TODO customize and handle it by environment end = datetime.datetime.now() self.core.logger.debug('Function response: ' + str(response)) # Adds debug information about the executed function self.core.executed_functions.append({ 'function': func_name, 'args': args, 'return': response, 'responseTime': int((end - start).total_seconds() * 1000) }) smokesignal.emit(BBotCore.SIGNAL_CALL_BBOT_FUNCTION_AFTER, { 'name': func_name, 'response_code': resp_code, 'error_message': error_message, 'register_enabled': fmap['register_enabled'], 'data': fmap }) if resp_code == BBotCore.FNC_RESPONSE_OK: return response else: exception.args = (func_name + ' function error', ) + exception.args raise exception # propagate it to stop all functions execution
def slack_hello(self, data): """ Called when the client has successfully signed on to Slack. Sends the ``signon`` signal (see :ref:`plugins.signals`) :param data: dict from JSON received in WebSocket message """ smokesignal.emit('signon', self)
def test_once(self): # Register and call twice smokesignal.once('foo', self.fn) smokesignal.emit('foo') smokesignal.emit('foo') assert self.fn.call_count == 1 assert smokesignal.receivers['foo'] == set()
def on_prediction_finished(self, scoresheet, dataset, predictor): evaluation = EvaluationSheet(scoresheet, **self.params) smokesignal.emit( "evaluation_finished", evaluation=evaluation, dataset=dataset, predictor=predictor, )
def read(queue_object, key): ch, method, properties, body = yield queue_object.get() if body: logger.info('got a new incoming message from the bus, for key: %s' % key) smokesignal.emit(key, body) yield ch.basic_ack(delivery_tag=method.delivery_tag)
def signedOn(self): for channel in settings.CHANNELS: # If channel is more than one item tuple, second value is password if len(channel) > 1: self.join(encodings.from_unicode(channel[0]), encodings.from_unicode(channel[1])) else: self.join(encodings.from_unicode(channel[0])) smokesignal.emit('signon', self)
def test_on_decorator_max_calls_as_arg(self): # Register first - like a decorator smokesignal.on('foo', 3)(self.fn) # Call a bunch of times for x in range(10): smokesignal.emit('foo') assert self.fn.call_count == 3
def joined(self, channel): """ Called when the client successfully joins a new channel. Adds the channel to the known channel list and sends the ``join`` signal (see :ref:`plugins.signals`) :param channel: the channel that has been joined """ logger.info('Joined %s', channel) self.channels.add(channel) smokesignal.emit('join', self, channel)
def test_on_max_calls(self): # Register first smokesignal.on('foo', self.fn, max_calls=3) # Call a bunch of times for x in range(10): smokesignal.emit('foo') assert self.fn.call_count == 3 assert smokesignal.receivers['foo'] == set()
def joined(self, channel): """ Called when the client successfully joins a new channel. Adds the channel to the known channel list and sends the ``join`` signal (see :ref:`plugins.signals`) :param str channel: the channel that has been joined """ logger.info("Joined %s", channel) self.channels.add(channel) smokesignal.emit("join", self, channel)
def userLeft(self, user, channel): """ Called when a user leaves a channel in which the bot resides. Responsible for sending the ``user_left`` signal (see :ref:`plugins.signals`) :param user: IRC user string of the form ``{nick}!~{user}@{host}`` :param channel: the channel in which the event occurred """ nick = self.parse_nick(user) smokesignal.emit('user_left', self, nick, channel)
def left(self, channel): """ Called when the client successfully leaves a channel. Removes the channel from the known channel list and sends the ``left`` signal (see :ref:`plugins.signals`) :param channel: the channel that has been left """ logger.info('Left %s', channel) self.channels.discard(channel) smokesignal.emit('left', self, channel)
def test_CacheEvaluationListener(): l = CacheEvaluationListener() scores = BaseScoresheet({1: 10, 2: 5}) ev = EvaluationSheet(scores, {1}) smokesignal.emit("evaluation_finished", ev, "d", "p") ev2 = EvaluationSheet.from_file(l.fname) assert_array_equal(ev.data, ev2.data) smokesignal.clear_all() os.unlink(l.fname)
def test_CacheEvaluationListener(): l = CacheEvaluationListener() scores = BaseScoresheet({1: 10, 2: 5}) ev = EvaluationSheet(scores, {1}) smokesignal.emit('evaluation_finished', ev, 'd', 'p') ev2 = EvaluationSheet.from_file(l.fname) assert_array_equal(ev.data, ev2.data) smokesignal.clear_all() os.unlink(l.fname)
def adjust_relay(): global is_heating if should_heat() and not is_heating: print("Start heating (would change pin to HIGH)") is_heating = True smokesignal.emit('heating_updated', heating=is_heating) elif is_heating and not should_heat(): print("End heating (would change pin to LOW)") is_heating = False smokesignal.emit('heating_updated', heating=is_heating)
def test_CachePredictionListener(): l = CachePredictionListener() scoresheet = BaseScoresheet({1: 10, 2: 5, 3: 2, 4: 1}) smokesignal.emit("prediction_finished", scoresheet, "d", "p") with open(l.fname) as fh: # Line endings may be different across platforms assert fh.read().replace("\r\n", "\n") == "1\t10\n2\t5\n3\t2\n4\t1\n" smokesignal.clear_all() os.unlink(l.fname)
def joined(self, channel): """ Called when the client successfully joins a new channel. Adds the channel to the known channel list and sends the ``join`` signal (see :ref:`plugins.signals`) :param channel: the channel that has been joined """ logger.info('Joined %s', channel) self.channels.add(channel) self.sendLine("NAMES %s" % (channel,)) smokesignal.emit('join', self, channel)
def test_CachePredictionListener(): l = CachePredictionListener() scoresheet = BaseScoresheet({1: 10, 2: 5, 3: 2, 4: 1}) smokesignal.emit('prediction_finished', scoresheet, 'd', 'p') with open(l.fname) as fh: # Line endings may be different across platforms assert_equal(fh.read().replace("\r\n", "\n"), "1\t10\n2\t5\n3\t2\n4\t1\n") smokesignal.clear_all() os.unlink(l.fname)
def on_user_left(self, element): """ Handler called when a user leaves a public room. Responsible for sending the ``user_left`` signal (see :ref:`plugins.signals`) :param element: A <presence/> element, instance of `twisted.words.xish.domish.Element` """ nick = self.parse_nick(element) channel = self.parse_channel(element) logger.debug('User %s left channel %s', nick, channel) smokesignal.emit('user_left', self, nick, channel)
def test_instance_method_passes_args_kwargs(self): class Foo(object): def __init__(self): smokesignal.on('foo', self.foo) self.foo_count = 0 def foo(self, n, mult=1): self.foo_count += (n * mult) foo = Foo() smokesignal.emit('foo', 5, mult=6) assert foo.foo_count == 30
def attach(self, avatar, mind): ''' Completes the riffle association by attaching the avatar to its remote, adding it to the pool of connection stored here, and broadcasting the new connection. To listen for this ''' avatar.attached(mind) self.connections.add(avatar) out.info('Connected: ' + avatar.name) smokesignal.emit('%sConnected' % self.avatar.__name__, avatar, self)
def signedOn(self): """ Called when the client has successfully signed on to IRC. Establishes automatically joining channels. Sends the ``signon`` signal (see :ref:`plugins.signals`) """ for channel in settings.CHANNELS: # If channel is more than one item tuple, second value is password if isinstance(channel, (tuple, list)): self.join(*channel) else: self.join(channel) smokesignal.emit('signon', self)
def signedOn(self): """ Called when the client has successfully signed on to IRC. Establishes automatically joining channels. Sends the ``signon`` signal (see :ref:`plugins.signals`) """ for channel in settings.CHANNELS: # If channel is more than one item tuple, second value is password if len(channel) > 1: self.join(encodings.from_unicode(channel[0]), encodings.from_unicode(channel[1])) else: self.join(encodings.from_unicode(channel[0])) smokesignal.emit("signon", self)
def test_instance_method_max_calls(self): class Foo(object): def __init__(self): smokesignal.once('foo', self.foo) self.foo_count = 0 def foo(self): self.foo_count += 1 foo = Foo() for x in range(5): smokesignal.emit('foo') assert foo.foo_count == 1
def listen(self): """Listener for new socket mail from daemon. Do not call externally!! """ try: data = self._socketIn.recv(flags=zmq.NOBLOCK) if (data): logging.debug('I received data %s' % data) dataJson = json.loads(data) smokesignal.emit(dataJson.get('event'), dataJson) ## Socket is not ready except zmq.ZMQError as e: pass
def on_user_joined(self, element): """ Handler called when a user enters a public room. Responsible for sending the ``user_joined`` signal (see :ref:`plugins.signals`) :param element: A <presence/> element, instance of `twisted.words.xish.domish.Element` """ # NOTE: HipChat might send duplicates here. If this is a problem, ignore # presence stanzas that match /presence/x[@xmlns="http://hipchat.com/protocol/muc#room # or maybe more generally /presence/x/name nick = self.parse_nick(element) channel = self.parse_channel(element) logger.debug('User %s joined channel %s', nick, channel) smokesignal.emit('user_joined', self, nick, channel)
def background(): while True: # Get readings from sensor temperature = random.randint(79, 81) humidity = 45 store.temperature = temperature store.humidity = humidity print("Sensor reading: " + str(temperature) + "F, " + str(humidity) + "%") smokesignal.emit('sensor_reading', temperature=temperature, humidity=humidity) time.sleep(15)
def start(): smokesignal.emit('started') factory = comm.Factory() if settings.SERVER.get('SSL', False): reactor.connectSSL(settings.SERVER['HOST'], settings.SERVER['PORT'], factory, ssl.ClientContextFactory()) else: reactor.connectTCP(settings.SERVER['HOST'], settings.SERVER['PORT'], factory) reactor.run()
def test_once_decorator(self): # Make a method that has a call count def cb(): cb.call_count += 1 cb.call_count = 0 # Register first like a decorator smokesignal.once('foo')(cb) assert len(smokesignal._receivers['foo']) == 1 # Call twice smokesignal.emit('foo') smokesignal.emit('foo') assert cb.call_count == 1
def test_on_decorator_max_calls(self): # Make a method that has a call count def cb(): cb.call_count += 1 cb.call_count = 0 # Register first - like a cecorator smokesignal.on('foo', max_calls=3)(cb) assert len(smokesignal._receivers['foo']) == 1 # Call a bunch of times for x in range(10): smokesignal.emit('foo') assert cb.call_count == 3