def bind(self, resource): while self.bound is None and self.owner.process(1): pass resource = Node('resource', payload=[resource]) res = self.owner.Dispatcher.send_and_wait_for_response( Protocol('iq', tye='set', payload=[ Node('bind', attrs={'xmlns': NS_BIND}, payload=[resource]) ])) if is_result_node(res): self.bound.append(res.get_tag('bind').get_tag_data('jid')) jid = JID(res.get_tag('bind').get_tag_data('jid')) self.owner.user = jid.get_node() self.owner.resource = jid.get_resource() self.enable() res = self.owner.Dispatcher.send_and_wait_for_response( Protocol( 'iq', tye='set', payload=[Node('session', attrs={'xmlns': NS_SESSION})])) if is_result_node(res): self.session = 1 return 'ok' else: self.session = 0 else: return ''
def end(self): self.cancel() self.kill() self.running = False Protocol().print(self.result) time = self.get_current_time() Protocol().print(time + ': End\n') Log().print(time + ': Measurement ended ')
def handle_client_handshake(self, protocol, addr): identification = protocol.identification if not self.profile.is_id_exist(identification): return name = self.profile.get_name_by_id(identification) traffic_remain = self.profile.get_traffic_remain_by_id(identification) if traffic_remain <= 0: LOGGER.info( "Controller recv client but traffic <= 0, name: %s, traffic_remain: %s" % (name, traffic_remain)) return LOGGER.info("Controller recv client, name: %s, traffic_remain: %s" % (name, traffic_remain)) server = self.id_to_server.get(identification) if server: LOGGER.info( "Controller get registered client with tun_name: %s, tun_ip: %s, dst_ip: %s" % (server.tun.name, server.tun.tun_ip, server.tun.dst_ip)) server.client_addr = addr protocol = Protocol() protocol.cmd = CMD_SERVER_HANDSHAKE protocol.tun_ip_raw = self.ip_str_to_raw(server.tun.tun_ip) protocol.dst_ip_raw = self.ip_str_to_raw(server.tun.dst_ip) self.sock.sendto(self.wrap_data(protocol.get_bytes()), addr) else: tun_ip = self.alloc_ip() dst_ip = self.alloc_ip() tun_name = self.alloc_tun_name() if not tun_ip or not dst_ip or not tun_name: LOGGER.error( "Controller tun_ip or dst_ip or tun_name cannot be alloced" ) self.free_ip(tun_ip) self.free_ip(dst_ip) self.free_tun_name(tun_name) return server = Server(tun_name, tun_ip, dst_ip, addr, traffic_remain, self.client_send_data_callback) server.run() LOGGER.info( "controller get unregistered client with tun_name: %s, tun_ip: %s, dst_ip: %s" % (tun_name, tun_ip, dst_ip)) self.id_to_server[identification] = server protocol = Protocol() protocol.cmd = CMD_SERVER_HANDSHAKE protocol.tun_ip_raw = self.ip_str_to_raw(tun_ip) protocol.dst_ip_raw = self.ip_str_to_raw(dst_ip) self.sock.sendto(self.wrap_data(protocol.get_bytes()), addr)
def handleMessage(self, message, addr): if self.clients.get(addr, None) is None: try: if message.DataType != DataType.Handshake: return name = message.data.decode(encoding='UTF-8') room = message.room self.clients[addr] = name self.clientCharId[addr] = len(self.clients) self.rooms[room].append(addr) self.client_room[addr] = room update_message = self.get_update_message(addr, room, "joined") users_message = self.get_online_users(room) notification = "".join(update_message + users_message) print(notification) ret = Protocol( dataType=DataType.Handshake, room=message.room, data="".join(users_message).encode(encoding='UTF-8')) ret_b = Protocol(dataType=DataType.Handshake, room=message.room, data=notification.encode(encoding='UTF-8')) self.s.sendto(ret.out(), addr) self.broadcast(addr, room, ret_b) except Exception as err: print(err) return elif message.DataType == DataType.ClientData: self.broadcast(addr, message.room, message) elif message.DataType == DataType.Terminate: room = message.room update_message = self.get_update_message(addr, room, "left") self.clients.pop(addr) self.clientCharId.pop(addr) self.rooms[room].remove(addr) self.client_room.pop(addr) users_message = self.get_online_users(room) notification = "".join(update_message + users_message) print(notification) message_ter = Protocol(dataType=DataType.Terminate, room=room, data=notification.encode("utf-8")) self.broadcast(addr, message.room, message_ter)
def generate(a, c, m): def var(i): return "x{}".format(i) numeric = range(m) boolean = ["t", "f"] Q = set(numeric) | set(boolean) S = {var(i) for i in range(len(a))} I = {var(i): a[i] % m for i in range(len(a))} O = {q: 1 if (q == c or q == "t") else 0 for q in Q} T = set() for n in numeric: for n_ in numeric: pre = (n, n_) post = ((n + n_) % m, "t" if ((n + n_) % m) == c else "f") T.add(Transition(pre, post)) for b in boolean: pre = (n, b) post = (n, "t" if n == c else "f") T.add(Transition(pre, post)) return Protocol(Q, T, S, I, O)
def run(self): (host, port, team) = self._getopts() try: self.protocol = Protocol(host, port, team) self.protocol.run() except (socket.error, socket.gaierror), (value, message): print('Connection error: %s (%d)' % (message, value))
def piskvork_game(): """ play gomoku game using trained model and piskvork interface """ board = np.zeros((19, 19, 3), np.int8) running = [1] protocol = Protocol(board, running) thread = Thread(protocol) network = Network(-1) player = 0 thread.start() while running[0]: args = protocol.pullCmd() cmd = args[0].lower() del args[0] if cmd == "none": pass elif cmd == "start": print("OK") elif cmd == "turn": try: pos = args[0].split(',') x = int(pos[0]) y = int(pos[1]) mc_tree_search.put_on_board(board, (x, y), player ^ 1, 0) except: print("ERROR") play_turn(board, player, network) elif cmd == "begin": play_turn(board, player, network) pass else: print("ERROR") thread.join()
def select_user_stats(id_user: int, limit) -> Stats: query = "SELECT Stats.id_user, Stats.successful, Ports.* " \ "FROM Stats INNER JOIN Ports ON Stats.id_port = Ports.port " \ "WHERE Stats.id_user=?" \ "LIMIT ?;" total_fail: int = 0 total_success: int = 0 protocols: List[Protocol] = list() response_query: List[Dict[str, Any]] = conection_sqlite(DB, query, query_params=(id_user, limit), is_dict=True) for i in response_query: success: bool = False if i['successful'] == 'True': success = True total_success += 1 else: total_fail += 1 protocol: Protocol = Protocol(i['name'], i['port'], i['protocol'], i['description'], successful=success) protocols.append(protocol) stats: Stats = Stats(id_user, total_fail, total_success, protocols) return stats
def start_measurement(self, form): self.cancel() p = Protocol() l = Log() s = Settings() self.running = True time = self.get_current_time() self.start_time = default_timer() l.print('Starting Measurement ' + time) self.result += 'Begin: ' + time + '\n' self.result = ('Age: ' + form['age'] + '\n' + 'Sex: ' + form['sex'] + '\n' + 'Weight: ' + form['weight'] + '\n' + 'Height: ' + form['height'] + '\n' + 'Start time: ' + str(time) + '\n') PRE_WAIT_TIME = convert_time_to_seconds(s.get('pre_wait_time')) POST_WAIT_TIME = convert_time_to_seconds(s.get('post_wait_time')) RADIATION_TIME = convert_time_to_seconds(s.get('radiation_time')) TOTAL_TIME = convert_time_to_seconds(s.get('total_time')) window = TOTAL_TIME - PRE_WAIT_TIME - POST_WAIT_TIME - RADIATION_TIME start = PRE_WAIT_TIME + randint(0, window) end = start + RADIATION_TIME self.turn_on = Timer(float(start), self.on, [start]) self.turn_off = Timer(float(end), self.off, [end]) self.final = Timer(float(TOTAL_TIME), self.end) self.start()
def __init__(self, serial_dev): self.protocol = Protocol(self.TYPE, self.pack_pmt) self.serial_dev = serial_dev ChassisDev.__init__(self, "Servo", sub_topic = "/robot_chassis/Servo", sub_msg_class = Byte)
def abort(self): self.running = False self.cancel() self.kill() sleep(3) message = self.get_current_time() + ': Aborted\n' Protocol().print(message) Log().print(message)
def send_data_to_server(self): while self.connected: try: data = self.recording_stream.read(512) message = Protocol(dataType=DataType.ClientData, data=data) self.s.sendto(message.out(), self.server) except: self._disconnect()
def connectToServer(self): if self.connected: return True message = Protocol(dataType=DataType.Handshake, data=self.name.encode(encoding='UTF-8')) self.s.sendto(message.out(), self.server) data, addr = self.s.recvfrom(1025) datapack = Protocol(datapacket=data) if (addr == self.server and datapack.DataType == DataType.Handshake and datapack.data.decode('UTF-8') == 'ok'): print('Connected to server successfully!') print('Press Control + C to disconnect') self.connected = True return self.connected
def __init__(self): self.model = ma2.model.TCPClient() self.view = ma2.view.ClientWindow(self) self.protocol = Protocol() self.keywords = self.protocol.getKeywords() self.listener = Thread(target=self.recieve) self.listener.start() self.view.top.mainloop()
def scenario_connect_disconnect(): clients = [] next_spawn = tick() while True: current_tick = tick() if len(clients) < NUM_CLIENTS and current_tick >= next_spawn: # Spawn new player client = Client() client.disconnect = current_tick + random.randint(500, 4000) protocol = Protocol(client) clients.append((client, protocol)) print( "Spawning new client which will disconnect in {}ms. Number of clients: {}" .format(client.disconnect - current_tick, len(clients))) if not protocol.login("Alice", "1"): sys.exit(0) next_spawn = current_tick + 100 # Handle each client for client, protocol in clients: while protocol.handle_packet(): pass if current_tick >= client.disconnect: if random.randint(0, 1) == 0: # Gracefully logout protocol.logout() else: # Just disconnect protocol.disconnect() # Remove clients that are disconnected tmp = len(clients) clients = [(client, protocol) for client, protocol in clients if protocol.connected()] if len(clients) != tmp: print("Removed disconnected players. Number of clients: {}".format( len(clients))) # Figure out how long to sleep if clients: next_event = min( [client.disconnect for client, protocol in clients]) if len(clients) < NUM_CLIENTS: next_event = min([next_event, next_spawn]) else: next_event = next_spawn if next_event - current_tick > 0: print("Sleeping {}ms".format(next_event - current_tick)) time.sleep((next_event - current_tick) / 1000.0) else: print("No sleep: current_tick: {} next_event {}".format( current_tick, next_event))
def __init__(self, device='/dev/ttyUSB0', baud=115200): self.__hw = Protocol(device, baud) self.hid = self.get_id() self.calib = self.__get_calib() self.__pm = PointingModel(z1=self.calib[0], z2=self.calib[1], z3=self.calib[2]) self.target = EqCoords(0, 0) self.home()
def __init__(self): self.protocol = Protocol(self.TYPE, self.pack_pmt) ChassisDev.__init__(self, "smart_battery", pub_topic = "smart_battery", pub_msg_class = SmartBatteryStatus) self.battery_status = SmartBatteryStatus() ChassisDev.start_pub(self)
def receive_server_data(self): while self.connected: try: data, addr = self.s.recvfrom(1025) message = Protocol(datapacket=data) if message.DataType == DataType.ClientData: self.playing_stream.write(message.data) except: pass
def __init__(self, serial_dev): self.protocol = Protocol(self.TYPE, self.pack_pmt) self.serial_dev = serial_dev ChassisDev.__init__(self, "move_ctrl", sub_topic="cmd_vel", sub_msg_class=Twist)
def ejecutar(): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((_HOST, _PORT)) client = Protocol((_HOST, _PORT), sock, _REQUEST) client.execute() except KeyboardInterrupt: print("\n--> [Client End] Caught Keyboard Interrupt.\n--> Exiting\n ")