def read_connect(self): buff = self.read_bin() if not buff: return msg = Message() r = msg.decode(buff) if r != 0: return if r < 0: self.close() return c = self.conn_proxy log.debug(0, '*%d read message: %s', c.index, msg) cmd = msg.get(0) if cmd != 'connect rsp': log.error(0, 'invalid command. msg:%s', msg) return err = msg.get(1) if err != 'ok': log.error(0, 'accept fail. msg:%s', msg) self.close() return Bridge(self.conn, self.conn_proxy) self.conn = None self.conn_proxy = None if self.timer: del_timer(self.timer) self.timer = None
def read(self): buff = self.read_bin() if not buff: return msg = Message() r = msg.decode(buff) if r != 0: return if r < 0: self.close() return c = self.conn_proxy log.debug(0, '*%d read message. msg:%s', c.index, msg) cmd = msg.get(0) if cmd != 'accept rsp': log.error(0, 'invalid message. msg:%s', msg) self.close() return err = msg.get(1) if err != 'ok': log.error(0, 'accept fail. msg:%s', msg) self.close() return self.ready_proxy = True del_conn(c, WRITE_EVENT) self.check_ready()
def on_message(self, message): """Handles messages from server""" message = Message.decode(message) if self.last_message == "JOIN": message = Message("BOARD", "") self.write_message(message.json()) self.last_message = "BOARD" elif self.last_message == "BOARD": board = message.body["board"] board = Board.from_json(board) x, y = make_move(board) message = Message("MOVE", {"x": x, "y": y}) self.write_message(message.json()) self.last_message = "MOVE" elif self.last_message == "MOVE": message = Message("BOARD", "") self.write_message(message.json()) self.last_message = "BOARD" elif message.header == "ERROR": print("ERROR") print(message.body) sys.exit(1) else: print("Unrecognized message header: {}".format(message.header))
def read(self): buff = self.read_bin() if not buff: return msg = Message() r = msg.decode(buff) if r != 0: return if r < 0: self.close() return self.process(msg)
def ready_connect_proxy(self): c = self.conn_proxy log.debug(0, '*%d connect: %s', c.index, c.addr.text) msg = Message(['accept req', self.key]) log.debug(0, '*%d send message: %s', c.index, msg) buff = msg.encode() if not buff: log.error(0, 'invalid message: %s', msg) return c.wev.buff = struct.pack('I', len(buff)) + buff c.wev.handler = lambda: self.send() self.send()
def send_msg(self, msg): c = self.conn if isinstance(msg, str) or isinstance(msg, list) or isinstance( msg, Message): msg = Message(msg) if msg.get(0) != 'heartbeat req': log.debug(0, '*%d send message: %s', c.index, msg) else: log.trace(0, '*%d send message: %s', c.index, msg) buff = msg.encode() if not buff: log.error(0, 'invalid message: %s', msg) return self.send_bin(buff)
async def login(message, client, broadcast): request = LoginRequest() request.ParseFromString(message.serialized_message) response = LoginResponse() with AccountService() as service: try: account = service.get(request.username, request.password) except (AccountNotFoundError, InvalidPasswordError): response.success = False response.error_message = 'Invalid credentials' else: response.success = True client.username = account.username account.logged_in = True if response.success: with PlayerService() as service: account = service.session.merge(account) for character in account.characters: service.remove(character.id) await client.send(Message( message_type=MessageType.login_response, message=response))
async def create_character(message, client, server): info = CreateCharacterRequest() info.ParseFromString(message.serialized_message) character = Character(account_username=client.username, name=info.name, body_color=info.body_color, shirt_color=info.shirt_color, legs_color=info.legs_color, last_x=300, last_y=300, velocity_x=0, velocity_y=0, last_position_update=datetime.now()) response = CreateCharacterResponse() with AccountService() as service: character_id = service.add_character(client.username, character) response.success = True response.character_id = character_id response.x = character.last_x response.y = character.last_y await client.send( Message(message_type=MessageType.create_character_response, message=response))
async def player_move(message, client, server): info = PlayerMove() info.ParseFromString(message.serialized_message) with PlayerService() as service: player = service.get(client.player_id) if not player: raise Exception('Received player_move event for invalid player!') character = player.character character.set_position_synchronized(server.map, Vector(info.x, info.y)) # We sometimes get numbers like 1e-5, so set them to zero to reduce # long running errors clean_velocity = Vector(info.velocity_x, info.velocity_y) clean_velocity.clear_zero_values() character.velocity_x = clean_velocity.x character.velocity_y = clean_velocity.y server.players.update_character(client, character) broadcast_message = OtherPlayerMove() broadcast_message.player_id = client.player_id broadcast_message.x = character.last_x broadcast_message.y = character.last_y broadcast_message.velocity_x = character.velocity_x broadcast_message.velocity_y = character.velocity_y await server.broadcast(Message(message_type=MessageType.other_player_move, message=broadcast_message), exclude=client)
async def players_state(message, client, broadcast): if not client.player_id: raise Exception('Received players_request event for invalid player!') players_response = PlayersResponse() with PlayerService() as service: players = service.get_all() for player in players: if player.id == client.player_id: continue character = player.character player_info = players_response.players.add() player_info.player_id = player.id x, y = character.get_position() player_info.x = x player_info.y = y player_info.velocity_x = character.velocity_x player_info.velocity_y = character.velocity_y await client.send( Message(message_type=MessageType.players_response, message=players_response))
async def player_move(message, client, broadcast): info = PlayerMove() info.ParseFromString(message.serialized_message) with PlayerService() as service: player = service.get(client.player_id) if not player: raise Exception('Received player_move event for invalid player!') character = player.character character.last_x = info.x character.last_y = info.y character.velocity_x = info.velocity_x character.velocity_y = info.velocity_y character.last_position_update = datetime.now() broadcast_message = OtherPlayerMove() broadcast_message.player_id = client.player_id broadcast_message.x = info.x broadcast_message.y = info.y broadcast_message.velocity_x = info.velocity_x broadcast_message.velocity_y = info.velocity_y await broadcast(Message(message_type=MessageType.other_player_move, message=broadcast_message), exclude=client)
async def player_join(message, client, server): info = JoinRequest() info.ParseFromString(message.serialized_message) with CharacterService() as service: character = service.get(info.character_id) with PlayerService() as service: character = service.session.merge(character) service.create(character) server.players.update_all_positions() players_response = PlayersResponse() for other_character in server.players.characters.values(): player_info = players_response.players.add() player_info.player_id = other_character.id player_info.character.x = other_character.last_x player_info.character.y = other_character.last_y player_info.velocity_x = other_character.velocity_x player_info.velocity_y = other_character.velocity_y player_info.character.body_color = other_character.body_color player_info.character.shirt_color = other_character.shirt_color player_info.character.legs_color = other_character.legs_color player_info.character.name = other_character.name client.player_id = info.character_id server.players.add(client, character) await client.send(Message( message_type=MessageType.players_response, message=players_response)) player_join = PlayerJoin() player_join.player_id = client.player_id player_join.character.x = character.last_x player_join.character.y = character.last_y player_join.character.body_color = character.body_color player_join.character.shirt_color = character.shirt_color player_join.character.legs_color = character.legs_color player_join.character.name = character.name await server.broadcast(Message( message_type=MessageType.player_join, message=player_join), exclude=client)
def send_connect(self): c = self.conn_proxy log.debug(0, '*%d connect: %s', c.index, c.addr.text) timestamp = int(time.time()) rand = '%x_%d' % (random.randint(0, 0xffffffff), get_sequence()) sign = auth.get_sign(self.secret, [timestamp, rand]) msg = Message(['connect req', self.key, timestamp, rand, sign]) log.debug(0, '*%d send message: %s', c.index, msg) buff = msg.encode() if not buff: log.error(0, 'invalid message: %s', msg) return c.wev.buff = struct.pack('I', len(buff)) + buff c.wev.handler = lambda: self.send() self.send()
async def player_join(message, client, broadcast): info = JoinRequest() info.ParseFromString(message.serialized_message) with CharacterService() as service: character = service.get(info.character_id) with PlayerService() as service: players = service.get_all() characters = [player.character for player in players] character = service.session.merge(character) service.create(character) client.player_id = info.character_id players_response = PlayersResponse() for other_character in characters: player_info = players_response.players.add() player_info.player_id = other_character.id x, y = other_character.get_position() player_info.x = x player_info.y = y player_info.velocity_x = other_character.velocity_x player_info.velocity_y = other_character.velocity_y player_info.color = other_character.color player_info.name = other_character.name await client.send( Message(message_type=MessageType.players_response, message=players_response)) player_join = PlayerJoin() player_join.player_id = client.player_id x, y = character.get_position() player_join.x = x player_join.y = y player_join.color = character.color player_join.name = character.name await broadcast(Message(message_type=MessageType.player_join, message=player_join), exclude=client)
def phy_event_handler( self, raw_data, event_type ): # this may be a asyn thread/process, need lock report pipe "simple usage control handler" #print("HID PHY EVENT:", event_type, raw_data) msg = PhyMessage(PhyMessage.MSG_HID_RAW_DATA, self.id(), Message.seq_root(), event=event_type, value=array.array('B', raw_data[1:])) self.handle_phy_message(msg)
def handle_attached_msg(self, seq, data): val = data.get('value', None) if val: kwargs = {'repeat': LogicDevice.INTERVAL_POLL_DEVICE} command = ServerMessage(Message.CMD_POLL_DEVICE, self.id(), self.next_seq(Message.seq_root()), **kwargs) self.prepare_command(command) else: message = ServerMessage(Message.MSG_DEVICE_ATTACH, self.id(), seq, value=None) self.prepare_message(message)
def handle_phy_interrupt_message(self, msg): type = Message.MSG_DEVICE_INTERRUPT_DATA seq = Message.seq_root() #print(self.__class__.__name__, "int", msg) value = msg.value() if value[0] == 0: return HidMessage(type, self.id(), seq, value=value[1:], pipe=self.logic_pipe()).send() else: print(self.__class__.__name__, "Invalid irq message:", value)
async def send_chat_message(message, client, server): info = SendChatMessage() info.ParseFromString(message.serialized_message) broadcast_message = ReceiveChatMessage() broadcast_message.player_id = client.player_id broadcast_message.msg = info.msg with PlayerService() as service: player = service.get(client.player_id) position = player.character.last_position await server.broadcast_in_range( Message(message_type=MessageType.receive_chat_message, message=broadcast_message), position, CHAT_RADIUS)
def handle_phy_interrupt_message(self, msg): type = Message.MSG_DEVICE_INTERRUPT_DATA seq = Message.seq_root() (RW_OK, NAK_W, NAK_ADDR, W_ONLY_OK) = range(4) #print(self.__class__.__name__, "int", msg) value = msg.value() if value[0] == 0x9A and value[1] == RW_OK: return HidMessage(type, self.id(), seq, value=value[2:], pipe=self.logic_pipe()).send() else: print(self.__class__.__name__, "Invalid irq message:", value)
async def characters_request(message, client, broadcast): response = CharactersResponse() with AccountService() as service: characters = service.get_characters(client.username) for character in characters: character_info = response.characters.add() character_info.character_id = character.id character_info.name = character.name character_info.color = character.color character_info.x = character.last_x character_info.y = character.last_y await client.send( Message(message_type=MessageType.characters_response, message=response))
async def register_account(message, client, broadcast): request = RegisterRequest() request.ParseFromString(message.serialized_message) response = RegisterResponse() with AccountService() as service: try: service.create(request.username, request.password) except AccountAlreadyExistsError: response.success = False response.error_message = 'Username already in use' else: response.success = True await client.send( Message(message_type=MessageType.register_response, message=response))
async def chunk_request(message, client, server): info = ChunkRequest() info.ParseFromString(message.serialized_message) chunk_id = (int(info.chunk_x), int(info.chunk_y)) chunk = server.map.chunks.get(chunk_id, []) response = ChunkResponse() response.chunk_x = info.chunk_x response.chunk_y = info.chunk_y for chunk_object in chunk: chunk_object_info = ChunkObject() chunk_object_info.object_id = chunk_object.object_id chunk_object_info.x = chunk_object.x chunk_object_info.y = chunk_object.y response.objects.append(chunk_object_info) await client.send( Message(message_type=MessageType.chunk_response, message=response))
async def players_state(message, client, server): if not client.player_id: raise Exception('Received players_request event for invalid player!') server.players.update_all_positions() players_response = PlayersResponse() for character in server.players.players.values(): if character.id == client.player_id: continue player_info = players_response.players.add() player_info.player_id = character.id player_info.x = character.last_x player_info.y = character.last_y player_info.velocity_x = character.velocity_x player_info.velocity_y = character.velocity_y await client.send(Message( message_type=MessageType.players_response, message=players_response))
async def player_stop(message, client, server): info = PlayerStop() info.ParseFromString(message.serialized_message) with PlayerService() as service: player = service.get(client.player_id) if not player: raise Exception('Received player_stop event for invalid player!') character = player.character character.set_position_synchronized(server.map, Vector(info.x, info.y)) character.velocity_x = 0 character.velocity_y = 0 server.players.update_character(client, character) broadcast_message = OtherPlayerStop() broadcast_message.player_id = client.player_id broadcast_message.x = character.last_x broadcast_message.y = character.last_y await server.broadcast(Message(message_type=MessageType.other_player_stop, message=broadcast_message), exclude=client)
def set_get_chip_info(self): kwargs = {'addr': 0, 'size': 7} command = ServerMessage(Message.CMD_DEVICE_PAGE_READ, self.id(), self.next_seq(Message.seq_root()), **kwargs) self.prepare_command(command)
def __init__(self, url, size): super().__init__(url) message = Message("JOIN", {"size": size}) self.write_message(message.json()) self.last_message = "JOIN"
def on_start(self): root = self.root KeyboardShotcut.keyboard_shortcut(root, 112, 19, 'p', ['ctrl']) msg_data = [ array.array('B', [49, 148, 111, 2, 78, 1, 122, 0, 0, 0, 0]), array.array('B', [49, 21, 97, 2, 54, 1, 78, 0, 0, 0, 0]), array.array('B', [49, 148, 58, 2, 141, 1, 131, 0, 0, 0, 0]), array.array('B', [49, 145, 58, 2, 129, 1, 169, 0, 0, 0, 0]), array.array('B', [49, 145, 66, 2, 119, 1, 121, 0, 0, 0, 0]), array.array('B', [49, 145, 69, 2, 104, 1, 154, 0, 0, 0, 0]), array.array('B', [49, 145, 72, 2, 86, 1, 118, 0, 0, 0, 0]), array.array('B', [49, 145, 73, 2, 62, 1, 157, 0, 0, 0, 0]), array.array('B', [49, 145, 73, 2, 39, 1, 110, 0, 0, 0, 0]), array.array('B', [49, 145, 68, 2, 19, 1, 97, 0, 0, 0, 0]), array.array('B', [49, 145, 62, 2, 2, 1, 148, 0, 0, 0, 0]), array.array('B', [49, 145, 54, 2, 241, 0, 139, 0, 0, 0, 0]), array.array('B', [49, 145, 44, 2, 227, 0, 82, 0, 0, 0, 0]), array.array('B', [49, 145, 34, 2, 216, 0, 107, 0, 0, 0, 0]), array.array('B', [49, 145, 22, 2, 206, 0, 91, 0, 0, 0, 0]), array.array('B', [49, 145, 8, 2, 199, 0, 69, 0, 0, 0, 0]), array.array('B', [49, 145, 251, 1, 193, 0, 103, 0, 0, 0, 0]), array.array('B', [49, 145, 236, 1, 189, 0, 100, 0, 0, 0, 0]), array.array('B', [49, 145, 221, 1, 187, 0, 97, 0, 0, 0, 0]), array.array('B', [49, 145, 206, 1, 187, 0, 127, 0, 0, 0, 0]), array.array('B', [49, 145, 191, 1, 194, 0, 101, 0, 0, 0, 0]), array.array('B', [49, 145, 177, 1, 201, 0, 138, 0, 0, 0, 0]), array.array('B', [49, 145, 165, 1, 212, 0, 82, 0, 0, 0, 0]), array.array('B', [49, 145, 153, 1, 226, 0, 115, 0, 0, 0, 0]), array.array('B', [49, 145, 143, 1, 246, 0, 77, 0, 0, 0, 0]), array.array('B', [49, 145, 136, 1, 12, 1, 129, 0, 0, 0, 0]), array.array('B', [49, 145, 131, 1, 34, 1, 92, 0, 0, 0, 0]), array.array('B', [49, 145, 129, 1, 55, 1, 157, 0, 0, 0, 0]), array.array('B', [49, 145, 129, 1, 74, 1, 128, 0, 0, 0, 0]), array.array('B', [49, 145, 135, 1, 94, 1, 95, 0, 0, 0, 0]), array.array('B', [49, 145, 143, 1, 111, 1, 149, 0, 0, 0, 0]), array.array('B', [49, 145, 152, 1, 125, 1, 159, 0, 0, 0, 0]), array.array('B', [49, 145, 163, 1, 138, 1, 129, 0, 0, 0, 0]), array.array('B', [49, 145, 176, 1, 146, 1, 168, 0, 0, 0, 0]), array.array('B', [49, 145, 190, 1, 153, 1, 106, 0, 0, 0, 0]), array.array('B', [49, 145, 207, 1, 155, 1, 121, 0, 0, 0, 0]), array.array('B', [49, 145, 225, 1, 155, 1, 145, 0, 0, 0, 0]), array.array('B', [49, 145, 246, 1, 144, 1, 84, 0, 0, 0, 0]), array.array('B', [49, 145, 10, 2, 129, 1, 121, 0, 0, 0, 0]), array.array('B', [49, 145, 26, 2, 112, 1, 129, 0, 0, 0, 0]), array.array('B', [49, 145, 37, 2, 92, 1, 67, 0, 0, 0, 0]), array.array('B', [49, 145, 43, 2, 65, 1, 122, 0, 0, 0, 0]), array.array('B', [49, 145, 43, 2, 34, 1, 108, 0, 0, 0, 0]), array.array('B', [49, 145, 32, 2, 6, 1, 77, 0, 0, 0, 0]), ] #array.array('B', [49, 21, 32, 2, 6, 1, 77, 0, 0, 0, 0]), ] # report_list = [ # Message('msg', Message.MSG_DEVICE_INTERRUPT_DATA, 'dev', root.next_seq(), # value=array.array('B', [36, 16, 2, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0,])), # Message('msg', Message.MSG_DEVICE_INTERRUPT_DATA, 'dev', root.next_seq(), # value=array.array('B', [50, 16, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ])), # Message('msg', Message.MSG_DEVICE_INTERRUPT_DATA, 'dev', root.next_seq(), # value=array.array('B', [49, 21, 230, 1, 40, 1, 129, 0, 0, 0])), # Message('msg', Message.MSG_DEVICE_INTERRUPT_DATA, 'dev', root.next_seq(), # value=array.array('B', [49, 145, 230, 1, 40, 1, 129, 0, 0, 0])), # Message('msg', Message.MSG_DEVICE_INTERRUPT_DATA, 'dev', root.next_seq(), # value=array.array('B', [12, 32, 26, 17, 53, 243, 179,1, 0, 0, 0]))] for data in msg_data: msg = Message('msg', Message.MSG_DEVICE_INTERRUPT_DATA, 'dev', root.next_seq(), value=data) root.handle_message(msg)
mm = MemMapStructure() #page 0 page_cache = mm.get_page(Page.ID_INFORMATION) page_cache.save_to_buffer(0, v_chip_id) mm.page_parse(page_cache.id()) #page 1 page_cache = mm.get_page(Page.OBJECT_TABLE) page_cache.save_to_buffer(0, v_block_info) mm.page_parse(page_cache.id()) msg_list = [ Message('local', Message.MSG_DEVICE_PAGE_READ, Page.ID_INFORMATION, root.next_seq(), value=mm.get_page(Page.ID_INFORMATION)), Message('local', Message.MSG_DEVICE_PAGE_READ, Page.OBJECT_TABLE, root.next_seq(), value=mm.get_page(Page.OBJECT_TABLE)) ] #page x page_id_list = [(7, 0), (6, 0), (37, 0), (38, 0), (8, 0), (15, 0), (15, 1), (100, 0)] #page_id_list = [] for page_id in page_id_list: page_cache = mm.get_page(page_id) if page_cache:
def set_raw_command(self, raw_data): kwargs = {'value': raw_data} command = ServerMessage(Message.CMD_DEVICE_RAW_DATA, self.id(), self.next_seq(Message.seq_root()), **kwargs) self.prepare_command(command)
def on_message(self, message): try: message = Message.decode(message) except Exception as e: # Replies with an error. message = Message("ERROR", str(e)) self.write_message(message.json()) # Logs the error to a file. with open("server.log", "a") as file: file.write("ERROR: " + str(e)) return if message.header == "JOIN": # Makes sure a user has not already joined. if self.board is not None: message = Message("ERROR", "A game is already in progress.") self.write_message(message.json()) return # Checks mandatory params. try: size = message.body["size"] except KeyError: message = Message("ERROR", "Bad join request.") self.write_message(message.json()) return # Checks optional params. if "seed" in message.body: seed = message.body["seed"] else: seed = time.time() # Generates the game board. self.board = Board(size, seed) # Replies when done. message = Message("DONE", {"success": True}) self.write_message(message.json()) elif message.header == "BOARD": # Ensures a user has already joined. if self.board is None: message = Message("ERROR", "Please join a game first.") self.write_message(message.json()) return # Replies with the current state of the board. message = Message("DONE", { "success": True, "board": self.board.serialize() }) self.write_message(message.json()) elif message.header == "MOVE": # Ensures a user has already joined. if self.board is None: message = Message("ERROR", "Please join a game first.") self.write_message(message.json()) return # Checks mandatory params. try: x = message.body["x"] y = message.body["y"] except KeyError: message = Message("ERROR", "Bad join request.") self.write_message(message.json()) return # Checks that x and y are in bounds. if x >= self.board.basin_count or y >= self.board.basin_count: message = Message("ERROR", "Selected coordinate is out of bounds.") self.write_message(message.json()) return # Updates the game board. self.board.check_node(x, y) # Replies when done. message = Message("DONE", {"success": True}) self.write_message(message.json()) else: message = Message("ERROR", "No request of that type exists.") self.write_message(message.json())