class Account: def __init__(self, remote): self.remote = remote self.emitter = EventEmitter() self.accounts = {} self.account = {} self.emitter.on('newListener', self.new_listener) self.emitter.on('removeListener', self.remove_listener) self.emitter.on('transaction', self.info_affected_account) def new_listener(self, account, listener): if account == 'removeListener': return if not util.is_valid_address(account): self.account = Exception('invalid account') self.accounts[account] = listener def remove_listener(self, account): if not util.is_valid_address(account): raise Exception('invalid account') del self.accounts[account] def info_affected_account(self, data): # dispatch accounts = util.affected_accounts(data) for account in accounts: callback = self.accounts[account] tx = util.process_tx(data, account) if callback: callback(tx)
class Account: def __init__(self, remote): self.remote = remote self.emitter = EventEmitter() self.accounts = {} self.account = {} self.emitter.on('newListener', self.new_listener) self.emitter.on('removeListener', self.remove_listener) self.emitter.on('transaction', self.info_affected_account) def new_listener(self, account, listener): if account == 'removeListener': return if not Wallet.is_valid_address(account): self.account = Exception('invalid account') self.accounts[account] = listener def remove_listener(self, account): if not Wallet.is_valid_address(account): raise Exception('invalid account') del self.accounts[account] """
class WebSocketServer(Server): def __init__(self, remote): super(WebSocketServer, self).__init__(remote) self._shutdown = False self.emitter = EventEmitter() def connect(self, callback): if self.connected: return # if self.ws is None: # self.ws.close() try: self.ws = create_connection(self.ws_address) self.opened = True except Exception as e: logger.error(e) return e self.emitter.on("open", self.socket_open) self.emitter.on('message', self.remote.handle_message) self.emitter.on('close', self.handle_close) return def socket_open(self): """ socket打开的回调函数 :return: """ self.opened = True req = self.remote.subscribe(["ledger", "server"]) return req.submit() # 代码进行到此处,接下来需要构建 # 其他message、close和error的回调 def handle_close(self): """ handle close and error exception and should re-connect server after 3 seconds :return: """ if self.state == 'offline': return self.set_state('offline') if self.timer != 0: return self.remote.emitter.emit('disconnect') self.timer = 3 self.job = schedule.every(self.timer).seconds.do( self.connect_after_close) def connect_after_close(self, err): """ 当socket断掉之后的重连 :return: """ if not err: # 对应handle_close中的schedule.every方法 schedule.cancel_job(self.job) self.timer = 0 self.remote.emitter.emit('reconnect') def set_state(self, state): if state == self.state: return self.state = state self.connected = (state == 'online') if not self.connected: self.opened = False def send_message(self, command, data): """ refuse to send msg if connection blows out :param command: :param data: :return: backen 返回结果 """ if not self.opened: return req_id = (self.id + 1) msg = dict({'id': req_id, 'command': command}, **data) self.ws.send(json.dumps(msg)) callback = self.ws.recv() return {'req_id': req_id, 'callback': callback} def send(self, data): ret = None data = json.dumps(data).encode('utf-8') try: self.ws.send(data) except Exception as e: print("websocket send error"), e return ret def close(self): _data = { "command": "close", } self._shutdown = True return self.send(_data)
class World: """A world containg all traffic lights logic""" def __init__(self, websocket, traffic_light_data): self.websocket = websocket self.traffic_lights = OrderedDict() self.emitter = EventEmitter() self.active_roads = {'N': [], 'E': [], 'S': [], 'W': []} self.traffic_lights_to_move_to_end = [] self.start_time = time.time() self.clearance_time = 6 self.allow_green = True self.generate_traffic_lights(traffic_light_data) self.emitter.on('state-change', self.send_state) self.emitter.on('red-traffic-light', self.red_traffic_light_event) self.emitter.on('orange-traffic-light', self.orange_traffic_light_event) self.emitter.on('green-traffic-light', self.green_traffic_light_event) def generate_traffic_lights(self, traffic_light_data): for id, cardinal_direction in traffic_light_data.items(): traffic_light_type = id[1] if traffic_light_type == 'B': self.traffic_lights[id] = TrafficLight(id, cardinal_direction, self.emitter, self.active_roads) elif traffic_light_type == 'V': self.traffic_lights[id] = TrafficLight(id, cardinal_direction, self.emitter, self.active_roads) elif traffic_light_type == 'F': self.traffic_lights[id] = TrafficLight(id, cardinal_direction, self.emitter, self.active_roads) else: self.traffic_lights[id] = TrafficLight(id, cardinal_direction, self.emitter, self.active_roads) def process_simulation_state(self, simulation_state): for id, traffic_count in simulation_state.items(): self.traffic_lights[id.upper()].set_has_traffic(True if int(traffic_count) > 0 else False) async def update(self): while True: elapsed_time = time.time() - self.start_time for id, traffic_light in self.traffic_lights.items(): if elapsed_time > self.clearance_time and self.allow_green: asyncio.create_task(traffic_light.update()) for id in self.traffic_lights_to_move_to_end: self.traffic_lights.move_to_end(id) self.traffic_lights_to_move_to_end.remove(id) await asyncio.sleep(0.016) async def send_state(self): payload = json.dumps(self.get_state()) await self.websocket.send(payload) def red_traffic_light_event(self, id): self.start_time = time.time() if self.is_all_traffic_lights_red(): self.allow_green = True def orange_traffic_light_event(self, id): pass def green_traffic_light_event(self, id): self.traffic_lights_to_move_to_end.append(id); self.allow_green = False def is_all_traffic_lights_red(self): for id, traffic_light in self.traffic_lights.items(): if not traffic_light.is_red(): return False return True def get_state(self): state = {} for key, traffic_light in self.traffic_lights.items(): state[key] = traffic_light.state.value return state