class Core: def _getopts(self): parser = optparse.OptionParser() parser.add_option('-a', '--host', dest='host', help='host to connect', default='localhost') parser.add_option('-p', '--port', dest='port', type='int', help='port to use') parser.add_option('-n', '--team', dest='team', help='the team name') parser.add_option('-t', '--term', dest='term', help='set a terminal path (will be open for each new drone)', default=False) opts, args = parser.parse_args() if not (opts.host and opts.port and opts.team): parser.print_help() print('\nError: missing options.') print sys.exit(0) utils.term = opts.term return (opts.host, opts.port, opts.team) 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)) except Exception, e: print('Error: %s' % e)
def download(self, code, start, end, downloadPath=None, source='morningstar'): self.source = source Protocol.sendStatus("Data source", source) if source == "Yahoo": result = self.downloadYahoo(code, start, end, downloadPath) if not result: return self.download(code, start, end, downloadPath) else: return result else: start = dt.datetime.fromtimestamp( int(start)) if type(start) == str else start if start != None: self.data = DataReader(code, data_source=source, start=start, end=dt.datetime.today()) else: self.data = DataReader(code, data_source=source, end=dt.datetime.today()) self.__loaded = True if downloadPath != None: filepath = os.path.join(downloadPath, code + str(int(end)) + '.csv') self.data.to_csv(filepath) return filepath return None
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 parse_args(): ''' Handles parsing arguments Reference: https://docs.python.org/3/library/argparse.h ''' usage = 'python3 server.py port key' parser = argparse.ArgumentParser(usage=usage) # arugments to be parsed parser.add_argument('port', type=int, help='port to listen on') parser.add_argument('key', type=str, help='The key parameter specifies a secret key \ that must match the server’s secret key. This key will be also used to derive both \ the session keys and the initialization vectors.') # parse arguments args = parser.parse_args() # error checking if int(args.port) not in range(0, 65536): Protocol.log( 'Error: wrong command line arguments.\n\t\tport must be 0-65535') parser.exit('Usage: ' + usage) # return arguments to main return args
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 processConn(address, data): protocol = Protocol() start = time.time() sock = protocol.createSocket() try: try: f = open(data, 'r') print(data) data = f.read() f.close() except: print("No such file found.") data = "NSF" ack = protocol.sendPacket(sock, data, address) print("Client informed. Removing Client.") sock.close() return #send data to client in packets of size MTU packets, retransmissions = protocol.sendPackets(sock, data, address) sock.close() print("\nTransfer done.") print(packets, " packets transmitted.") print(retransmissions, " retransmissions.") print("Time Elapsed: ", str(time.time() - start)) except Exception as e: print(e) print("Server Error")
class Client(threading.Thread): def __init__(self, server_socket,\ socket_fd,\ oper,\ username): threading.Thread.__init__(self) self.server_socket = server_socket self.socket_fd = socket_fd self.oper = oper self.username = username self.protocol = Protocol(oper) self.text_color = Utils.colors["white"] self.beep = "\a" def run(self): self.oper.user_join_msg(self.username) try: while True: rlist, wlist, xlist = select.select([self.socket_fd], [], [], 0) if rlist: # lets firsts send every message msg = self.socket_fd.recv(Utils.RECV_BUFFER).rstrip() if msg: self.protocol.process_message(msg, self) except socket.error, e: print "<{username}> Disconnected - Connection error: {msg}".format( username=self.username, msg=e) self.oper.remove_client(self)
def main(): ''' Main function ''' # parse args args = parse_args() # initilize socket & listen for connections s = socket.socket() # handles 'port in use' s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((HOST, args.port)) s.listen(5) Protocol.log('Listening on {}:{}'.format(str(HOST), str(args.port))) Protocol.log('Using secret key: {}'.format(args.key)) # while True: conn, addr = s.accept() addr = str(addr) Protocol.log('{}: New connection from: {}'.format( datetime.now().strftime('%H:%M:%S'), addr)) try: handle_client(conn, args.key) except BadKeyError: Protocol.log( 'Error: wrong key.\n\t\tInvalid encryption key used, closing connection' ) # close connection Protocol.log('closed connection!') conn.close()
def __init__(self, executor, browser): Protocol.__init__(self, executor, browser) self.webdriver_binary = executor.webdriver_binary self.webdriver_args = executor.webdriver_args self.capabilities = self.executor.capabilities self.session_config = None self.server = None
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 test_load_non_existant_protocol(): """ test loading protocol file that doesn't exist """ Protocol.load(path(__file__).parent / path('protocols') / path('no protocol'))
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 handler(signum, frame): print("\033[2KTerminating...") message = Protocol(dataType=DataType.Terminate, room=self.room, data=self.name.encode(encoding='UTF-8')) self.s.sendto(message.out(), self.server) if platform.system() == "Windows": os.kill(os.getpid(), signal.SIGBREAK) else: os.kill(os.getpid(), signal.SIGKILL)
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 __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 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 __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 __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 __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 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 ")
def __init__(self, conn): Protocol.__init__(self, conn) self.mapfn = self.reducefn = None self.register_command('mapfn', self.set_mapfn) self.register_command('reducefn', self.set_reducefn) self.register_command('map', self.call_mapfn) self.register_command('reduce', self.call_reducefn) self.send_command('ready')
def __init__(self): self.protocol = Protocol(self.TYPE, self.pack_pmt) ChassisDev.__init__(self, "chassis", pub_topic="imu/data_raw", pub_rate=10, pub_msg_class=Imu) self.imu = Imu() ChassisDev.start_pub(self)
def handle_client(sock, secret): ''' Handle new client ''' client_handler = ClientHandler(sock, secret) if not client_handler.handshake(): return 'Failed handshake' Protocol.log('Passed handshake') # hanle client task client_handler.handleTask() return
def __init__(self, worker, server): """Connect to the specified worker""" Protocol.__init__(self) self.server = server self.register_command('taskcomplete', self.complete_task) self.register_command('ready', lambda x, y: self.initialize_worker()) # Create connection logging.debug("Connecting to worker %s:%d..." % worker) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.connect(worker)
def __init__(self): Protocol.__init__(self) # Module-specific attributes self.attributes = { "NAME": 'http', "MODULE_SPEAKS_PROTOCOL": True, "PROTOCOL_DEFAULT_PORTS": [80, 1080, 8080], "PROTOCOL_SPEAKS_FIRST": False, "PATTERN": r"^HTTP.+?\s\d{3}\s.+?" } self.compile_pattern()
class Client(Protocol): def __init__(self): self.engine = Engine() self.engine.print_traceback = True self.proto = FitnesseProtocol(self) def ack(self): self.ack_received = True def connectionMade(self): self.socketToken = sys.argv[4] request = "GET /?responder=socketCatcher&ticket=%s HTTP/1.1\r\n\r\n" % self.socketToken bytes = request.encode("UTF-8") self.transport.write(bytes) def dataReceived(self, data): self.proto.dataReceived(data) def content(self, data): self.doc = Document(data) self.doc.visit_tables(self) def on_table(self, table): fixture = self.engine.process(table, throw=False) self.write_table(table) def on_comment(self, node): html = str(node.toxml()) self.transport.write(util.format_10_digit_number(len(html) + 1)) self.transport.write(html) self.transport.write('\n') def done(self): self.transport.loseConnection() def write_table(self, table): html = str(table.toxml()) # Fixme : str() workaround for 'Data must not be unicode' self.transport.write(util.format_10_digit_number(len(html) + 1)) self.transport.write(html) self.transport.write('\n') def write_number(self, number): self.transport.write(util.format_10_digit_number(number)) def report(self): summary = self.engine.summary # 0 right, 0 wrong, 0 ignored, 0 exceptions self.write_number(0) self.write_number(summary.right) self.write_number(summary.wrong) self.write_number(summary.ignored) self.write_number(summary.exceptions) summary.reset()
def __init__(self): self.protocol = Protocol(self.TYPE, self.pack_pmt) ChassisDev.__init__(self, "Chassis", pub_topic="/encoder_cnts", pub_msg_class=Float32MultiArray, pub_rate=20) self.counters = Float32MultiArray() ChassisDev.start_pub(self)
def __init__(self): Protocol.__init__(self) # Module-specific attributes self.attributes = { "NAME": 'ftp', "MODULE_SPEAKS_PROTOCOL": True, "PROTOCOL_DEFAULT_PORTS": [21], "PROTOCOL_SPEAKS_FIRST": True, "PATTERN": r"\d{3}(\s|-).*" } self.compile_pattern()
def __init__(self): super(BafanConfig, self).__init__() # uic.loadUi('BafangConfigTool.ui', self) # Load the .ui file, no code completion self.started = False self.setupUi(self) self.protocol = Protocol() self.get_ports() self.bafang = Bafang() self.connect_signals() self.connected = False self.started = True
def __init__(self): Protocol.__init__(self) # Module-specific attributes self.attributes = { "NAME": 'socks5', "MODULE_SPEAKS_PROTOCOL": True, "PROTOCOL_DEFAULT_PORTS": [1080, 8080], "PROTOCOL_SPEAKS_FIRST": False, "PATTERN": r"" } self.compile_pattern()
def __init__(self, server_socket,\ socket_fd,\ oper,\ username): threading.Thread.__init__(self) self.server_socket = server_socket self.socket_fd = socket_fd self.oper = oper self.username = username self.protocol = Protocol(oper) self.text_color = Utils.colors["white"] self.beep = "\a"
def _disconnect(self): print("Try to disconnect") self.playing_stream.stop_stream() self.playing_stream.close() self.recording_stream.stop_stream() self.recording_stream.close() self.p.terminate() message = Protocol(dataType=DataType.Disconnect, data=self.name.encode(encoding='UTF-8')) self.s.sendto(message.out(), self.server) self.connected = False
def __init__(self): self.protocol = Protocol(self.TYPE, self.pack_pmt) ChassisDev.__init__(self, "Speed", pub_topic="/speed_wheel", pub_msg_class=Float32MultiArray, pub_rate=20) self.speeds = Float32MultiArray() self.speeds.data = [0, 0, 0] ChassisDev.pub_data_update(self, self.speeds) ChassisDev.start_pub(self)
def __init__(self, part, io, sync=True): """part - Part object, io - *IO object. If sync is True do protocol synchronization (if supported by device.""" self._part = part self._io = io protocolPath = self._part.getProtocolFileName(self._io.getHardware()) protocolPath = os.path.join('ProtocolDescriptionFiles', protocolPath) self._protocol = Protocol(protocolPath) self._wdelay = 1 """Write delay hack""" if sync: self.opSync()
def load_abstract_protocol(filename, simp_level=1, output_file=None): # Load protocol with open(filename) as in_file: protocol = json.load(in_file) parse_protocol(protocol) states = make_states(protocol) simplify_states(protocol, states, simp_level) transitions = make_transitions(protocol, states) io_states = make_initial_output_states(protocol, states) initial_states, true_states, false_states = io_states problematic_heads = test_heads(protocol, states, transitions) if output_file is not None: with open(output_file, 'w') as out_file: print_abstract_protocol(out_file, protocol['title'], protocol['constraints'], states, transitions, initial_states, true_states, false_states, problematic_heads) # Construct Protocol(...) Q = {sn(abstract_state_name(states[i], i)) for i, q in enumerate(states)} T = set() for i, j, k, l in transitions: a = sn(abstract_state_name(states[i], i)) b = sn(abstract_state_name(states[j], j)) c = sn(abstract_state_name(states[k], k)) d = sn(abstract_state_name(states[l], l)) T.add(Transition((a, b), (c, d))) S = {sn(abstract_state_name(states[i], i)) for i in initial_states} I = {q: q for q in S} Q1 = {sn(abstract_state_name(states[i], i)) for i in true_states} Q0 = {sn(abstract_state_name(states[i], i)) for i in false_states} O = {**{q: 1 for q in Q1}, **{q: 0 for q in Q0}} H = { upair(sn(abstract_state_name(states[i], i)), sn(abstract_state_name(states[j], j))) for i, j in problematic_heads } P = Protocol(Q, T, S, I, O, H) P.name = lambda: name return P
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): Protocol.__init__(self) # Module-specific attributes self.attributes = { "NAME": 'irc', "MODULE_SPEAKS_PROTOCOL": True, "PROTOCOL_DEFAULT_PORTS": [6660, 6661, 6662, 6663, 6664, 6665, 6666, 6667, 6668, 6669, 7000], "PROTOCOL_SPEAKS_FIRST": True, "PATTERN": r"[0-9A-Z:a-z-\s*._]+?:[0-9A-Z:a-z-\s*._]+?" } self.compile_pattern() self.unprocessed = '' self.registered = False
def get_metadata(self): meta_cmds = [ ("interface", Protocol.FE_CMD_INTERFACE), ("firmware", Protocol.FE_CMD_FIRMWARE), ("decoder", Protocol.FE_CMD_DECODER), ("build_date", Protocol.FE_CMD_BUILDDATE), ("compiler", Protocol.FE_CMD_COMPILER), ("os", Protocol.FE_CMD_OSNAME), ("build_by", Protocol.FE_CMD_USER), ("email", Protocol.FE_CMD_EMAIL) ] meta = {} location_ids = None for _, cmd in meta_cmds: self.queue_out.put(Protocol.create_packet(cmd)) self.queue_out.put(Protocol.create_packet(Protocol.FE_CMD_LOCATION_ID_LIST, data=bytearray(b'\x00\x00\x00'), use_length=True)) while True: if all(name in meta for name, _ in meta_cmds) and location_ids is not None: break try: if not self.queue_out.empty(): packet = self.queue_out.get(False) LOG.debug("--> %s" % binascii.hexlify(packet[1:-2])) self.ser.write(packet) self.ser.flush() resp = self.queue_in.get() LOG.debug("<-- %s" % binascii.hexlify(resp)) data = Protocol.decode_packet(resp) # FIXME: hax, make more elegant meta_info = [(name, data[1].decode("ascii").rstrip('\0')) for name, cmd_id in meta_cmds if cmd_id + 1 == data[0]] if meta_info: m = meta_info[0] LOG.debug("Received meta: %s" % m[0]) meta[m[0]] = m[1] elif data[0] == Protocol.FE_CMD_LOCATION_ID_LIST + 1: ids = len(data[1]) / 2 LOG.debug("Received %d location IDs" % ids) location_ids = struct.unpack_from(">%dH" % ids, buffer(data[1])) # TODO: error message handling except Queue.Empty: pass return meta, location_ids
def handle(self): proto = Protocol(self.rfile.read, self.wfile.write) command, args = proto.read_cmd() # switch case to handle the specific git command if command == 'git-upload-pack': cls = UploadPackHandler elif command == 'git-receive-pack': cls = ReceivePackHandler else: return h = cls(self.server.backend, self.rfile.read, self.wfile.write) h.handle()
def __init__(self, **args): # Here we are going to intercept the original _defineParams function # and replace by an empty one, this is to postpone the definition of # params until the protocol is set and then self.protocol can be used # for a more dynamic definition object.__setattr__(self, '_defineParamsBackup', self._defineParams) object.__setattr__(self, '_defineParams', self._defineParamsEmpty) Protocol.__init__(self, **args) Viewer.__init__(self, **args) self.allowHeader.set(False) self.showPlot = True # This flag will be used to display a plot or return the plotter self._tkRoot = None self.formWindow = None self.setWorkingDir(self.getProject().getTmpPath())
def get_ram_data(self, location, size): LOG.debug("Get RAM location: 0x%02x, offset: %d, size: %d" % (location[0], location[1], size)) packet = Protocol.create_packet(Protocol.FE_CMD_RAM_READ, location, size) LOG.debug("--> %s" % binascii.hexlify(packet[1:-2])) self.ser.write(packet) self.ser.flush() resp = self.queue_in.get(5) if resp: LOG.debug("<-- %s" % binascii.hexlify(resp)) data = Protocol.decode_packet(resp) if data[0] == Protocol.FE_CMD_RAM_READ + 1: return data[1] else: LOG.warn("Failed to load location...")
def add(self, data): #组包 if len(self.datas) == 0: self.datas = data else: self.datas = "%s%s" % (self.datas, data) #拆包 length = -1 length_index = self.datas.find('length\" :') if length_index != -1: length_end = self.datas.find(',', length_index + 9, length_index + 9 + 10) if length_end == -1: length_end = self.datas.find('}', length_index + 9, length_index + 9 + 10) if length_end != -1: length = self.datas[length_index + 9:length_end] if length != -1: length = int(length.strip()) if length != -1 and length <= len(self.datas): package = self.datas[0:length] package = Protocol.checkPackage(package) if self._package_decode_callback: self._package_decode_callback(package) if len(self.datas) == length: self.datas = '' else: self.datas = self.datas[length]
class Battery(ChassisDev): TYPE = 0x03 # 12 bytes data package format in struct pack_pmt = "2f2H" 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 data_handler(self, bin_data_pack): try: voltage, rate, _,_ = \ self.protocol.decode(bin_data_pack) except e: print e return self.battery_status.voltage = voltage self.battery_status.rate = rate self.battery_status.charge_state = 0 if voltage > 2000: self.battery_status.percentage = 100 - (2520 - voltage)/4 else: self.battery_status.percentage = 100 - (1260 - voltage)/1.6 ChassisDev.pub_data_update(self, self.battery_status)
def _build_result(cls, code, data): """ 构造客户端返回包 """ body = Protocol.build_int(code) if data is not None: if code > 0 and len(str(data)) > 0: if isinstance(data, types.DictType) or isinstance(data, types.ListType): body += dumps(data) else: body += str(data) pack = Protocol.build_int(len(body)) pack += body # print len(pack) return pack
class ServoCtrl(ChassisDev): TYPE = 0x82 # 12 bytes data package format in struct, only first byte valid pack_pmt = "4B2f" 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 start_subscribe(self): def cb_func(pwm_data): self.dev_write(self.pwm_to_encoder(pwm_data.data)) ChassisDev.start_sub(self, cb_func) def pwm_to_encoder(self, pwm): """ construct the payload """ return [pwm, 0,0,0,0,0] def dev_write(self, data): """ write data to serial """ self.serial_dev.write(self.protocol.encode(data)) print "Servo: Write to serial", data
class Odom(ChassisDev): TYPE = 0x01 # 12 bytes data package format in struct pack_pmt = "3i" def __init__(self): self.protocol = Protocol(self.TYPE, self.pack_pmt) ChassisDev.__init__(self, "Chassis", pub_topic = "/encoder_cnts", pub_msg_class = Float32MultiArray, pub_rate = 20) self.counters = Float32MultiArray() ChassisDev.start_pub(self) def data_handler(self, bin_data_pack): counter0, counter1, counter2 = \ self.protocol.decode(bin_data_pack) self.counters.data = [counter0, counter1, counter2] ChassisDev.pub_data_update(self, self.counters)
class Speed(ChassisDev): TYPE = 0x02 # 12 bytes data package format in struct pack_pmt = "3f" def __init__(self): self.protocol = Protocol(self.TYPE, self.pack_pmt) ChassisDev.__init__(self, "Speed", pub_topic = "/speed_wheel", pub_msg_class = Float32MultiArray, pub_rate = 20) self.speeds = Float32MultiArray() self.speeds.data = [0,0,0] ChassisDev.pub_data_update(self, self.speeds) ChassisDev.start_pub(self) def data_handler(self, bin_data_pack): wheel0, wheel1, wheel2 = \ self.protocol.decode(bin_data_pack) self.speeds.data = [wheel0, wheel1, wheel2] ChassisDev.pub_data_update(self, self.speeds)
def get_location_info(self, location_id): LOG.debug("Get location info: 0x%02x" % location_id) packet = Protocol.create_packet(Protocol.FE_CMD_LOCATION_ID_INFO, data=struct.pack(">H", location_id)) LOG.debug("--> %s" % binascii.hexlify(packet[1:-2])) self.ser.write(packet) self.ser.flush() locinfo = namedtuple('LocationInfo', ['flags', 'parent', 'ram_page', 'flash_page', 'ram_addr', 'flash_addr', 'size']) resp = self.queue_in.get(5) if resp: LOG.debug("<-- %s" % binascii.hexlify(resp)) data = Protocol.decode_packet(resp) if data[0] == Protocol.FE_CMD_LOCATION_ID_INFO + 1: return locinfo(*struct.unpack_from(">HHBBHHH", buffer(data[1]))) else: LOG.warn("Failed to load location...")
def _read_header_callback(self, buf): """ 读取数据包 """ self._server.status.inc(CacheServer.status_fields[3], len(buf)) body_length = Protocol.parse_int(buf) logger.debug("header size: %d" % body_length) self._stream.read_bytes(body_length, self._read_body_callback)
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 get_top_level_domain(self): ##check for http/https://www string = String(self.domain) strVar = string.formatter() if strVar == False: check = Protocol(self.domain) checkDM = check.check_protocol() if checkDM == False: print('Invalid Domain') else: get = TopDomain(self.domain) srch = get.extractor() if srch == False: print ('Could not get domain') else: return srch else: return strVar
class CgiFactory(object): """cgi 工厂,用于生成各种cgi""" def __init__(self, field): self._field = field self._proto = Protocol() def gen_error_cgi(self, errno, errmsg): """产生一个错误处理的cgi""" cgi = CgiBase(self._proto) cgi.gen_json_reply(errno, errmsg) return cgi def gen_cgi(self): try: self._proto.unpackReq(self._field) interfaceName = self._proto.req["interfaceName"] intent = interfaceName.split("."); if len(intent) != 2: raise InterErr(InterErr.E_INVALID_PARA, "interfaceName[%s] is invalid" % interfaceName) intent[0] = intent[0].strip() intent[1] = intent[1].strip() str_module = "worker.%s.%s" % (intent[0], intent[1]) module = __import__(str_module, fromlist=[""]) if not hasattr(module, intent[1]): raise InterErr(InterErr.E_NO_INTERFACE, "no that interfaceName[%s]" % intent[1]) inter_obj = getattr(module, intent[1])(self._proto) return inter_obj except ImportError, e: Log.error(traceback.format_exc()) e = InterErr(InterErr.E_INVALID_PARA, "invalid interfaceName") return CgiBase(self._proto, exception=e) except Exception, e: Log.error(traceback.format_exc()) return CgiBase(self._proto, exception=e)
def __init__(self): self.protocol = Protocol(self.TYPE, self.pack_pmt) ChassisDev.__init__(self, "Chassis", pub_topic = "/encoder_cnts", pub_msg_class = Float32MultiArray, pub_rate = 20) self.counters = Float32MultiArray() ChassisDev.start_pub(self)
def dumpProtocols(self, results): """docstring for dumpProtocols""" pass i = 0 for result in results: if i < 10: protocol = Protocol(result['href']) protocolId = result['href'].replace("http://www.nature.com/protocolexchange/protocols/","") f = open("files/"+protocolId+'.txt','w') f.write(protocol.toJSON()) f.close() else: break i += 1 #m = ExchangeSearch(["pcr"], 500, "community") #m.dumpProtocols(m.results) #p = Protocol("http://www.nature.com/protocolexchange/protocols/3077")
def __init__(self): self.protocol = Protocol(self.TYPE, self.pack_pmt) ChassisDev.__init__(self, "Speed", pub_topic = "/speed_wheel", pub_msg_class = Float32MultiArray, pub_rate = 20) self.speeds = Float32MultiArray() self.speeds.data = [0,0,0] ChassisDev.pub_data_update(self, self.speeds) ChassisDev.start_pub(self)