def toggle_state(self): self._value = not self._value self._log.info("button toggle: {}".format(self._value)) _message = Message(Event.BUTTON) _message.set_value(self._value) if self._queue: self._queue.add(_message)
def test_send(self, SenderMockWebSocket, ReceiverMockWebSocket): # Set up some clients sender = Client(SenderMockWebSocket) receiver = Client(ReceiverMockWebSocket) message_handler = MessageHandler() message_handler.add_client(sender) message_handler.add_client(receiver) self.assertTrue(len(message_handler.clients) == 2) # It sends a message to receiver sample_message = Message(receiver_guid=receiver.address, type="announce", data="data") asyncio.get_event_loop().run_until_complete( message_handler.send(sender, sample_message)) # It called send ReceiverMockWebSocket.send.assert_called() # It sent the right message sent_message = Message.from_json( ReceiverMockWebSocket.send.call_args[0][0]) sent_data = sent_message.data sent_type = sent_message.type self.assertEqual(sent_data, sample_message.data) self.assertEqual(sent_type, sample_message.type) # It set the "sender_guid" sent_from = sent_message.sender_guid self.assertEqual(sent_from, sender.address)
def _activated(self): ''' The default function called when the sensor is activated. ''' if self._enabled: if self._orientation is Orientation.PORT or self._orientation is Orientation.PORT_SIDE: self._log.info( Fore.RED + 'activated {} infrared:{} on pin {}...'.format( self._orientation.label, self._label, self._pin)) elif self._orientation is Orientation.STBD or self._orientation is Orientation.STBD_SIDE: self._log.info( Fore.GREEN + 'activated {} infrared:{} on pin {}...'.format( self._orientation.label, self._label, self._pin)) else: self._log.info( Fore.YELLOW + 'activated {} infrared:{} on pin {}...'.format( self._orientation.label, self._label, self._pin)) self._queue.add(Message(self._event)) if Infrared.ACTIVATE_TIMEOUT_SEC: self._sensor.wait_for_inactive( timeout=Infrared.ACTIVATE_TIMEOUT_SEC) else: self._log.info( '[DISABLED] activated infrared:{} on pin {}...'.format( self._label, self._pin))
def test_to_json(self): message = Message(sample_message["sender_guid"], sample_message["receiver_guid"], sample_message["channel_id"], sample_message["type"], sample_message["data"]) desired_json = json.dumps(sample_message) self.assertEqual(message.to_json(), desired_json)
def activated_port(self): if self._enabled: self._log.info(Style.BRIGHT + 'activated: ' + Style.NORMAL + Fore.RED + 'port bumper sensor.' + Style.RESET_ALL) self._queue.add(Message(Event.BUMPER_PORT)) else: self._log.info('[DISABLED] bumper activated port.') pass
def activated_center(self): if self._enabled: self._log.info(Style.BRIGHT + 'activated: ' + Style.NORMAL + Fore.BLUE + 'center bumper sensor.' + Style.RESET_ALL) self._queue.add(Message(Event.BUMPER_CNTR)) else: self._log.info('[DISABLED] bumper activated center.') pass
def subscribe(self): ''' DESCRIPTION. ''' self._log.debug('subscribe called.') # await asyncio.sleep(random.random() * 8) self._log.info(Fore.GREEN + 'Subscriber {} has subscribed.'.format(self._name)) _message_count = 0 _message = Message(-1, Event.NO_ACTION, None) # initial non-null message with Subscription(self._message_bus) as queue: while _message.event != Event.SHUTDOWN: _message = queue.get() # _message = await queue.get() # self._log.info(Fore.GREEN + '1. calling receive_message()...') # await self.receive_message(_message) self.receive_message(_message) # self._log.info(Fore.GREEN + '2. called receive_message(), awaiting..') _message_count += 1 self._log.info(Fore.GREEN + 'Subscriber {} rxd msg #{}: priority: {}; desc: "{}"; VALUE: '.format(\ self._name, _message.number, _message.priority, _message.description) + Fore.WHITE + Style.NORMAL + '{}'.format(_message.value)) if random.random() < 0.1: self._log.info(Fore.GREEN + 'Subscriber {} has received enough'.format(self._name)) break self._log.info(Fore.GREEN + 'Subscriber {} is shutting down after receiving {:d} messages.'.format(self._name, _message_count))
def test_text_message(self): parser = MessengerRequestParser() json = { "object": "page", "entry": [ { "id": "<PAGE_ID>", "time": 1458692752478, "messaging": [ { "sender": {"id": "<PSID>"}, "recipient": {"id": "<PAGE_ID>"}, "timestamp": 1458692752478, "message": { "mid": "mid.1457764197618:41d102a3e1ae206a38", "text": "hello, world!", "quick_reply": { "payload": "<DEVELOPER_DEFINED_PAYLOAD>" }, }, } ], } ], } message = Message( sender_id="<PSID>", recipient_id="<PAGE_ID>", message_type="text", text="hello, world!", ) self.assertEqual(parser.get_message(json), message)
def test_message_with_attachment(self): parser = MessengerRequestParser() json = { "object": "page", "entry": [ { "id": "<PAGE_ID>", "time": 1458692752478, "messaging": [ { "sender": {"id": "<PSID>"}, "recipient": {"id": "<PAGE_ID>"}, "timestamp": 1458692752478, "message": { "mid": "mid.1457764197618:41d102a3e1ae206a38", "seq": "52181", "attachments": [ { "type": "<image|video|audio|file>", "payload": {"url": "<ATTACHMENT_URL>"}, } ], }, } ], } ], } message = Message( sender_id="<PSID>", recipient_id="<PAGE_ID>", message_type="text", text="" ) self.assertEqual(parser.get_message(json), message)
def test_broadcast(self, SenderMockWebSocket, Receiver1MockWebSocket, Receiver2MockWebSocket): # Set up some clients sender = Client(SenderMockWebSocket) receiver1 = Client(Receiver1MockWebSocket) receiver2 = Client(Receiver2MockWebSocket) channel = Channel("test_channel") channel.add_client(sender) channel.add_client(receiver1) channel.add_client(receiver2) self.assertTrue(len(channel.clients) == 3) # It sends a message to each client sample_message = Message( type = "announce", data= "data" ) asyncio.get_event_loop().run_until_complete( channel.broadcast(sender, sample_message) ) # It called send Receiver1MockWebSocket.send.assert_called() Receiver2MockWebSocket.send.assert_called() # It sent the right message sent_message = Message.from_json(Receiver1MockWebSocket.send.call_args[0][0]) sent_data = sent_message.data sent_type = sent_message.type sent_channel_id = sent_message.channel_id self.assertEqual(sent_data, sample_message.data) self.assertEqual(sent_type, sample_message.type) self.assertEqual(sent_channel_id, channel.id) # It set the "sender_guid" sent_from = sent_message.sender_guid self.assertEqual(sent_from, sender.address)
def activated_stbd(self): if self._enabled: self._log.info(Style.BRIGHT + 'activated: ' + Style.NORMAL + Fore.GREEN + 'starboard bumper sensor.' + Style.RESET_ALL) self._queue.add(Message(Event.BUMPER_STBD)) else: self._log.info('[DISABLED] bumper activated starboard.') pass
async def received_event(self, partition_context, event): """ The callback function for handling a received event. The callback takes two parameters: partition_context which contains partition context and event which is the received event. For detailed partition context information, please refer to `PartitionContext <https://docs.microsoft.com/en-us/python/api/azure-eventhub/azure.eventhub.partitioncontext?view=azure-python>`_. For detailed event information, please refer to `EventData <https://docs.microsoft.com/en-us/python/api/azure-eventhub/azure.eventhub.eventdata?view=azure-python>`_. :param azure.eventhub.PartitionContext partition_context: The EventHub partition context. See :param Optional[azure.eventhub.EventData] event: The event data :return: None """ try: logger.debug(f"Received the event: '{event.body_as_str(encoding='UTF-8') if event else 'None'}'" f" from the partition with ID: '{partition_context.partition_id}'") logger.debug(partition_context) data = json.loads(event.body_as_str(encoding='UTF-8')) if 'messageType' in data and 'version' in data and 'data' in data: _data = data.get('data', {}) message = Message( message_type=data.get('messageType'), message_version=data.get('version'), device_id=_data.get('deviceSerialNumber', _data.get('deviceName', None)), source_id=MessageType.get_source_id(message_type=data.get('messageType'), message_version=data.get('version'), message_data=_data), device_time=_data.get('deviceTime', _data.get('eventTime', datetime.now().timestamp())), location=Location(longitude=_data.get('longitude', 0), latitude=_data.get('latitude', 0), altitude=_data.get('altitude', 0)), data=_data ) self.buffer.append(message) buffer_delta = datetime.now(timezone.utc) - self.last_buffer_flush if len(self.buffer) >= self.buffer_size or buffer_delta.total_seconds() > self.max_buffer_time_in_sec: self.checkpoint_count += len(self.buffer) self.flush_buffer() if self.checkpoint_count > self.checkpoint_after_messages: try: await partition_context.update_checkpoint(event) self.checkpoint_count = 0 logger.info("Checkpoint Updated.") except Exception as ue: logger.error(str(ue)) evict_delta = datetime.now(timezone.utc) - self.last_eviction_time if evict_delta.total_seconds() > self.data_eviction_interval_in_seconds: self.last_eviction_time = datetime.now(timezone.utc) eviction_cutoff = datetime.fromtimestamp( datetime.now(timezone.utc).timestamp() - self.max_time_to_keep_data_in_seconds, tz=timezone.utc ) self.storage_delegate.evict(eviction_cutoff) except Exception as e: logger.exception(e)
async def chattext(self, data: dict): message = Message(self.bot,data) for p in self.bot.settings['global_prefixes']: if message.content.startswith(p): data_split = str(message.content)[len(p):].split(" ", 1) command = data_split.pop(0) if command == "echo": await self.bot.send(data_split[0])
def add_message(self, message, sender, receiver, automated): # the message should be in the receiver's inbox now = datetime.datetime.now() time = now.strftime("%a %d/%m/%Y %I:%M%p") message = Message(sender, receiver, message, automated, time) message_dict = message.__dict__ with open(messagesDir) as f: messagesData = json.load(f) messagesData["allMessages"].append(message_dict) with open(messagesDir, "w") as file: json.dump(messagesData, file, indent=4)
def _activated(self): ''' The default function called when the sensor is activated. ''' if self._enabled and self._scan_enabled: self._log.info('cat sensed.') self._log.info(Fore.RED + Style.BRIGHT + 'detected CAT!') self._queue.add(Message(Event.CAT_SCAN)) self.set_mode(False) self._warning_display() else: self._log.info('[DISABLED] activated catscan.')
def test_doesnt_understands_message(self): specialist = WordsByAnjiSpecialist() self.assertEqual( specialist.understands( Message( sender_id="<SENDER_ID>", recipient_id="<RECIPIENT_ID>", message_type="text", text="are you a pepper?", )), False, )
def process_notification(event:Mapping[str,Any],_=None): """ Amazon Lambda Function entry point. """ print(dumps(event)) for record in event['Records']: message = Message(record) print('{} is {}'.format( message.face_id, ', '.join(message.filter_emotions()))) write_message(message)
async def handle_connection(self, websocket: iter, path: str): client = Client(websocket) print("New client: " + client.address, flush=True) channel = None try: async for json_message in websocket: message = Message.from_json(json_message) if message.type == "create_channel": new_channel = Channel(message.data["name"]) self.channels[new_channel.id] = new_channel ack = Message(type="ack", data={"channel_id": new_channel.id}) await websocket.send(ack.to_json()) continue channel_id = message.channel_id if channel_id in self.channels.keys(): channel = self.channels[channel_id] else: message = Message(type="error") await websocket.send(message.to_json()) await websocket.close() break if (message.type in ["announce"]): channel.add_client(client) await channel.broadcast(client, message) elif (message.type in ["offer", "answer", "ice"]): await channel.send(client, message) elif (message.type in ["name"]): await channel.broadcast(client, message) finally: if channel: channel.remove_client(client) # broadcast the departure message = Message(type="hangup") await channel.broadcast(client, message) print("Client " + client.address + " left", flush=True)
def test_understands_message(self): specialist = WordsByAnjiSpecialist() self.assertEqual( specialist.understands( Message( sender_id="<SENDER_ID>", recipient_id="<RECIPIENT_ID>", message_type="text", text="give me a word from anji", )), True, ) self.assertEqual( specialist.understands( Message( sender_id="<SENDER_ID>", recipient_id="<RECIPIENT_ID>", message_type="text", text="wise pepper", )), True, )
def setUp(self): self.target_channel = Channel("target_channel") self.target_channel.broadcast = unittest.mock.AsyncMock() self.target_channel.send = unittest.mock.AsyncMock() self.another_channel = Channel("another_channel") self.channels = { self.target_channel.id: self.target_channel, self.another_channel.id: self.another_channel } self.sender_mock_socket = MockAsyncIterator(iter([])) self.sender = Client(self.sender_mock_socket) self.receiver_mock_socket = MockAsyncIterator(iter([])) self.receiver = Client(self.receiver_mock_socket) self.sample_message = Message(self.sender.address, self.receiver.address, self.target_channel.id, "")
async def chattext(self, data): message = Message(self.bot, data) for p in self.bot.settings['global_prefixes']: if message.content.startswith(p): try: data_split = message.content[len(p):].split(" ", 1) command = data_split.pop() msg = '' if data_split: msg = data_split[0] await self.on_command(command, msg) except Exception as e: #catch a failed commmand self.logger.debug(e) print(e) await self.bot.send("Something went wrong with this command. contact dev. ")
def _callback(self, pin, pin_type, value): ''' This is the callback method from the I²C Master, whose events are being returned from the Arduino. The pin designations for each sensor are hard-coded to match the robot's hardware as well as the Arduino. There's little point in configuring this in the YAML since it's hard-coded in both hardware and software. The default pins A1-A5 are defined as IR analog sensors, 9-11 are digital bumper sensors. ''' if not self._enabled or self._suppressed: self._log.debug(Fore.BLACK + Style.DIM + 'SUPPRESSED callback: pin {:d}; type: {}; value: {:d}'.format(pin, pin_type, value)) return # self._log.debug(Fore.BLACK + Style.BRIGHT + 'callback: pin {:d}; type: {}; value: {:d}'.format(pin, pin_type, value)) _message = None # NOTE: the shorter range infrared triggers preclude the longer range triggers if pin == 1: if value > self._port_side_trigger_distance: _message = Message(Event.INFRARED_PORT_SIDE) elif pin == 2: if value > self._port_trigger_distance: _message = Message(Event.INFRARED_PORT) elif pin == 3: if value > self._center_trigger_distance: _message = Message(Event.INFRARED_CNTR) elif pin == 4: if value > self._stbd_trigger_distance: _message = Message(Event.INFRARED_STBD) elif pin == 5: if value > self._stbd_side_trigger_distance: _message = Message(Event.INFRARED_STBD_SIDE) elif pin == 9: if value == 1: _message = Message(Event.BUMPER_PORT) elif pin == 10: if value == 1: _message = Message(Event.BUMPER_CNTR) elif pin == 11: if value == 1: _message = Message(Event.BUMPER_STBD) if _message is not None: _message.set_value(value) self._queue.add(_message)
def get_message(self, json): if json["object"] == "page": for entry in json["entry"]: for messaging_event in entry["messaging"]: if messaging_event.get("message"): text = "" if "text" in messaging_event["message"]: text = messaging_event["message"]["text"] return Message( sender_id=messaging_event["sender"]["id"], recipient_id=messaging_event["recipient"]["id"], message_type="text", text=text, ) return None
async def dispatch(websocket, path): client = Client(websocket) print("New client: " + client.address, flush=True) try: async for json_message in websocket: message = Message.from_json(json_message) if (message.type == "announce"): message_handler.add_client(client) await message_handler.broadcast(client, message) elif (message.type in ["offer","answer","ice"]): await message_handler.send(client, message) finally: message_handler.remove_client(client) # broadcast the departure message = Message(type = "hangup") await message_handler.broadcast(client, message) print("Client " + client.address + " left", flush=True)
def _callback_front(self, pin, pin_type, value): ''' This is the callback method from the I2C Master, whose events are being returned from the Arduino. The pin designations for each sensor here mirror those in the YAML configuration. ''' self._log.debug(Fore.BLACK + Style.BRIGHT + 'callback: pin {:d}; type: {}; value: {:d}'.format( pin, pin_type, value)) _message = None if pin == 0: if value > self._trigger_distance: _message = Message(Event.INFRARED_STBD_SIDE) elif pin == 1: if value > self._trigger_distance: _message = Message(Event.INFRARED_STBD) elif pin == 2: if value > self._trigger_distance: _message = Message(Event.INFRARED_CENTER) elif pin == 3: if value > self._trigger_distance: _message = Message(Event.INFRARED_PORT) elif pin == 4: if value > self._trigger_distance: _message = Message(Event.INFRARED_PORT_SIDE) elif pin == 9: if value == 1: _message = Message(Event.BUMPER_STBD) elif pin == 10: if value == 1: _message = Message(Event.BUMPER_CENTER) elif pin == 11: if value == 1: _message = Message(Event.BUMPER_PORT) if _message is not None: _message.set_value(value) self._queue.add(_message)
def handle(self, message): ''' This receives a TOCK message every 1000ms (i.e., at 1Hz), obtaining the CPU temperature. Writes a pretty print message to the log. If the temperature exceeds the threshold and the message queue has been set, sends a HIGH TEMPERATURE message. ''' if self._enabled and ( message.event is Event.CLOCK_TOCK ) \ and (( next(self._counter) % self._sample_time_sec ) == 0 ): if self._fan: self._fan.react_to_temperature(self._cpu.temperature) self.display_temperature() if self.is_max_temperature(): self._log.warning('CPU HIGH TEMPERATURE!') if self._clock: _message = Message(Event.HIGH_TEMPERATURE) self._clock.message_bus.add(_message) return message
def test_message_with_fallback_attachment(self): parser = MessengerRequestParser() json = { "object": "page", "entry": [ { "id": "<PAGE_ID>", "time": 1458692752478, "messaging": [ { "sender": {"id": "<PSID>"}, "recipient": {"id": "<PAGE_ID>"}, "timestamp": 1458692752478, "message": { "mid": "mid.1458696618141:b4ef9d19ec21086067", "text": "<URL_SENT_BY_THE_USER>", "attachments": [ { "type": "fallback", "payload": None, "title": "<TITLE_OF_THE_URL_ATTACHMENT>", "URL": "<URL_OF_THE_ATTACHMENT>", } ], }, } ], } ], } message = Message( sender_id="<PSID>", recipient_id="<PAGE_ID>", message_type="text", text="<URL_SENT_BY_THE_USER>", ) self.assertEqual(parser.get_message(json), message)
def get_message(self, event, value): _message = Message(event=event, value=value) if self._message_bus != None: _message.set_subscribers(self._message_bus.subscribers) return _message
def get_auto_leveling(self): request = Message([0xAA, 0xAA], 2, 32, False, False, [], direction='out') return self.send(request)
def set_homing_command(self, command, queue=True): request = Message([0xAA, 0xAA], 2, 31, True, queue, [command], direction='out') return self.send(request)