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 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 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 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)
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 send(self, message): self.lock.acquire() self.serial.write(message.package()) self.serial.flush() response = Message.read(self.serial) self.lock.release() return response.params
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 save(self, messages: List[Message]): """ Save the messages to the data store. The messages must all be of the same message type. :param List[Message] messages: a list of Message objects :return: None """ if messages: statement = Message.insert_statement() try: with self.connection as conn: with conn.cursor() as cursor: all_messages = [{ **vars(message) } for message in messages] try: logger.info( f"Inserting {len(all_messages)} messages. " f"(from: {all_messages[0]['device_timestamp'].isoformat()} " f"to: {all_messages[-1]['device_timestamp'].isoformat()})" ) logger.debug(pformat(all_messages)) execute_batch(cursor, statement, all_messages) except Exception as e: logger.warning( "Unable to insert row, checking to ensure table exists." ) if not self.table_exists(): self.create_table() execute_batch(cursor, statement, all_messages) except Exception as e: raise StorageError( f"Unable to store messages [{messages}]") from e
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 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 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
def test_create_channel(self): message = self.sample_message message.type = "create_channel" message.receiver_guid = "" message.data = {"name": "new_channel"} # Mock the webocket methods self.sender_mock_socket.send = unittest.mock.AsyncMock() dispatcher = Dispatcher({}) self.mock_receive_message(message, dispatcher) # It adds a new channel found = False new_channel = "" for channel in dispatcher.channels.values(): found = channel.name == "new_channel" if found: new_channel = channel break self.assertTrue(found) # It sends an 'ack' with the channel id self.sender_mock_socket.send.assert_called() sent_message = Message.from_json( self.sender_mock_socket.send.call_args_list[0][0][0]) self.assertEqual(sent_message.type, "ack") self.assertEqual(sent_message.data["channel_id"], new_channel.id)
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
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 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 evict(self, older_than: datetime): statement = Message.delete_statement() try: with self.connection as conn: with conn.cursor() as cursor: cursor.execute(statement, {'device_timestamp': older_than}) except Exception: logger.exception( f"Unable to delete messages prior to [{older_than}]")
def table_exists(self): """Determine if the table exists in the configured database.""" with self.connection as conn: with conn.cursor() as cursor: cursor.execute( "SELECT * FROM information_schema.tables " "WHERE table_schema = 'public' " "AND table_name = %(table_name)s", {'table_name': Message.table_name()}) return cursor.rowcount > 0
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 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 _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_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 setupMessage(self): self.Message = Message(self) def sizeHint(): sidebarWidth = self.Sidebar.width() windowWidth = self.MainWidget.width() return QSize(windowWidth - sidebarWidth, self.Message.height) def resizeEvent(event): self.NotificationArea.adjustSize() self.NotificationArea.move(0, self.MainWidget.height() - self.NotificationArea.height()) self.NotificationArea.sizeHint = sizeHint self.NotificationArea.resizeEvent = resizeEvent self.NotificationArea.adjustSize()
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, "")
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 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. ")
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 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 poll(self): '''Polls the IMAP server. For each new (UNSEEN) message, builds a list of DTO message objects and sends said list to the callback function.''' interval = self.my_config['interval'] if 'interval' in self.my_config else 60 while(1): print "Polling the IMAP server... " (retcode, messages) = self.conn.search(None, '(UNSEEN)') if retcode == 'OK': messages = [] if messages[0] == '' else messages n_messages = str(len(messages)) print "OK! Found " + n_messages + " messages.\n" if len(messages) > 0: for message in messages[0].split(' '): (ret, message_info) = self.conn.fetch(message, '(BODY[HEADER.FIELDS (SUBJECT)])') if(ret == 'OK'): subject = message_info[0][1].replace('Subject: ', '').rstrip() parts = subject.split('|') message_list = [] if len(parts) == 5: # Build the message object message = Message() message.type = parts[0] message.published = parts[1] message.story_id = parts[2] message.owner = parts[3] message.site = parts[4] message_list.append(message) if len(message_list) > 0: self.callback(message_list) else: print "Something went wrong...n" # Humm, that's nasty... sleep(interval)
class MainWindow(W.QMainWindow, Ui_MainWindow): def __init__(self, app): super(MainWindow, self).__init__() self.App = app self.setupUi(self) self.show() self.setupDragHint() self.setupSidebar() self.setupFileListArea() self.setupStartButton() self.setAcceptDrops(True) self.configSelector = PresetFile(self, self.configSelector) # self.setWindowFlags(Qt.FramelessWindowHint) self.setupMessage() UpdateChecker(self) def resizeEvent(self, event): # event.ignore() self.NotificationArea.resizeEvent(event) self.CenterWidgetUpper.resizeEvent(event) def dragEnterEvent(self, event): event.accept() def dropEvent(self, event): event.accept() for url in event.mimeData().urls(): if os.name == "nt": self.filelist.addFile(url.url().replace("file:///", "", 1)) elif os.name == "posix": self.filelist.addFile(url.url().replace("file:///", "/", 1)) def setupDragHint(self): opacity(self.dragHint, 0.2) def setupSidebar(self): pass def setupMessage(self): self.Message = Message(self) def sizeHint(): sidebarWidth = self.Sidebar.width() windowWidth = self.MainWidget.width() return QSize(windowWidth - sidebarWidth, self.Message.height) def resizeEvent(event): self.NotificationArea.adjustSize() self.NotificationArea.move(0, self.MainWidget.height() - self.NotificationArea.height()) self.NotificationArea.sizeHint = sizeHint self.NotificationArea.resizeEvent = resizeEvent self.NotificationArea.adjustSize() def setupStartButton(self): def on(): self.startButton.setChecked(True) self.startButton.setText("终止") self.Message.show("任务开始") def off(): self.startButton.setChecked(False) self.startButton.setText("开始") self.Message.show("任务结束") def onClick(): if self.startButton.isChecked() and self.filelist.children: self.filelist.startAll() elif (not self.startButton.isChecked()) and self.filelist.children: self.filelist.killAll() else: self.Message.show("当前没有任务") self.startButton.setChecked(False) self.filelist.startSignal.connect(on) self.filelist.doneSignal.connect(off) self.startButton.clicked.connect(onClick) def setupFileListArea(self): def sizeHint(): sidebarWidth = self.Sidebar.width() windowWidth = self.MainWidget.width() windowHeight = self.MainWidget.height() return QSize(windowWidth - sidebarWidth, windowHeight) def resizeEvent(event): self.CenterWidgetUpper.adjustSize() self.CenterWidgetUpper.sizeHint = sizeHint self.CenterWidgetUpper.resizeEvent = resizeEvent self.CenterWidgetUpper.adjustSize() self.filelist = F.FileList(self, self.hasfile) def closeEvent(self, event): event.accept() self.filelist.killAll() log("[Application Closed]")