class TestCommandParser(UnitTest): def setUp(self): self.parser = CommandParser() def test_command_parser_returns_a_command_create_class(self): class_name = "class_name" arguments = ["create", "class", "--name", class_name] self.assert_equals( class_name, str(self.parser.parse(arguments).class_creator.class_name)) def test_command_parser_returns_a_command_create_interface(self): class_name = "class_name" arguments = ["create", "interface", "--name", class_name] self.assert_equals( class_name, str(self.parser.parse(arguments).interface_creator.class_name)) def test_command_parser_returns_a_command_create_project(self): project_name = "arbitrary_project_name" author_name = "author_name" arguments = [ "create", "project", "--name", project_name, "--author", author_name ] self.assert_equals(project_name, str(self.parser.parse(arguments).project.name))
def test_robot_movement(self): command = CommandParser( 'PLACE 0,0,NORTH MOVE REPORT').get_validated_command() self.robot.robot_movemant(command) self.assertEqual('Output: 0,1,NORTH', self.robot.get_report_state()) command = CommandParser( 'PLACE 0,0,NORTH LEFT REPORT').get_validated_command() self.robot.robot_movemant(command) self.assertEqual('Output: 0,0,WEST', self.robot.get_report_state()) command = CommandParser('PLACE 1,2,EAST MOVE MOVE LEFT MOVE REPORT' ).get_validated_command() self.robot.robot_movemant(command) self.assertEqual('Output: 3,3,NORTH', self.robot.get_report_state()) command = CommandParser('PLACE 0,0,EAST MOVE MOVE LEFT MOVE REPORT' ).get_validated_command() self.robot.robot_movemant(command) self.assertEqual('Output: 2,1,NORTH', self.robot.get_report_state()) command = CommandParser( 'PLACE 0,0,EAST MOVE MOVE LEFT MOVE PLACE 3,3,SOUTH MOVE REPORT' ).get_validated_command() self.robot.robot_movemant(command) self.assertEqual('Output: 3,2,SOUTH', self.robot.get_report_state())
def main(): parser = CommandParser() try: command_list = parser.parse() except CommandParser.ParserException as e: sys.exit(e) router = Router(command_list) runner_class = router.get_runner() timeline = Timeline() runner_class(timeline).run(command_list)
def __init__(self, test_name): # Only argument stuff self.running = False self.bt_receiver = btReceiver(debug = True) self.file_manager = fileManager(test_name, debug = True) self.command_parser = CommandParser() self.rotation = Rotation() self.mode = "manual" self.control_mode = "torque" self.attitude = [0,0,0] #[ypr] [DEG] self.speed = [HDD_ZERO_SPEED,HDD_ZERO_SPEED,HDD_ZERO_SPEED] #[xyz] [RPM] self.torque = [0,0,0] #[xyz] [Nm] self.voltage = [0,0,0] #[xyz] [V] self.iGains = [5, 10, 0] #[PID] self.wGains = [15, 25, 0] #[PID]
def create_book(self, command, counter): Path.reset_path() Debug.logger.info(u"开始制作第 {} 本电子书".format(counter)) Debug.logger.info(u"对记录 {} 进行分析".format(command)) task_list = CommandParser.get_task_list(command) # 分析命令 if len(task_list) == 0: return for task in task_list: if Config.debug_for_create_book: pass else: Worker.distribute(task) Debug.logger.info(u"网页信息抓取完毕") task_result_list = [] for task in task_list: task_result = TaskResult(task) task_result.extract_data() task_result_list.append(task_result) Debug.logger.info(u"数据库信息获取完毕") # 下载图片 for task_result in task_result_list: task_result.download_img() Debug.logger.info(u"所有任务图片获取完毕") # 按体积自动分卷 # 渲染html && 压缩为电子书 book = Book(task_result_list) book_list = book.auto_split(Config.max_book_size_mb * 1024) for chapter in book_list: chapter.create_book() return
def __init__(self, queue_read: Queue, queue_sent: Queue): super().__init__() self.queue_read = queue_read self.queue_sent = queue_sent # queue_read Timer initialization self.queue_timer = QTimer(self) self.queue_timer.timeout.connect(self.queueChecker) # Better to use gui/qt for timer functionality to operate with qt inside qt self.queue_timer.setInterval( 10) # each 10ms call func to check queue messages from websocket self.queue_timer.start() # Init command parse self.cmd_parser = CommandParser() # Create communication protocol self.protocol = ClientProtocol()
def __init__(self): self.commandparser = CommandParser() self.adapter = SQLAdapter() self.movies = {} self.actors = {} self.initialize_functions() self.load_initial_state() self.program_loop()
def __init__(self, args): self.no_colors = False def parse_args_and_opts(args): optionParser = OptionParser() for opt in Todo.opts: optionParser.add_option(*opt[4:], help=opt[0], action=opt[1], dest=opt[2], default=opt[3]) return optionParser.parse_args() if not os.path.exists(os.path.dirname(_todo_file)): os.mkdir(os.path.dirname(_todo_file)) if not os.path.exists(_todo_file): with file(_todo_file, 'w') as f: pass try: opts, args = parse_args_and_opts(args) setattr(Todo, 'no_colors', opts.no_colors) parserGenerator = TaskParserGenerator(_todo_file) tasks, last_index = parserGenerator.parse() commandParser = CommandParser([cmd[1] for cmd in Todo.cmds]) command, args_left = commandParser.parse(args) changes = getattr(Todo.TodoCommands(tasks, last_index), command)(args_left) if changes: parserGenerator.generate(tasks) except (TodoError, IOError, ValueError) as err: print('error: {0}'.format(err))
def Initialize(port, functionMap={}, asyncHandler=None): ''' Initializes BlackBoard with the corresponding parameters. :param int port: The port through which BlackBoard will communicate with this module. :param dictionary functionMap: A dictionary containing **key:value** pairs, where the *key* is the name of a command received (a string), and the *value* is either a tuple containing a function as a first element and a boolean as a second element, or a function. The function in both cases is the function that is going to execute the specified command and receives on object of type :class:`Command` (See :ref:`Creating a command handler <creating_a_command_handler>`). The boolean value indicates whether the execution of that command should be synchronous (on the same thread) or asynchronous, usually synchronous execution is preferred for fast commands that can answer almost immediately and asynchronous for commands that might take a little time. When the value is only a function, by default the execution is synchronous. *functionMap* can also contain an entry with a string containing only an asterisk, meaning that would be the handler in case no other handler is found for a specific command. .. note:: Notice that although functionMap can include a wildcard handler and this might seem like the module could answer anything, BlackBoard will only send commands that are registered under this module's configuration. :param function asyncHandler: A function that would handle the response of commands when sent with the method :func:`Send` instead of using :func:`SendAndWait`. This means the execution of a program that sends a command could continue and an asynchronous handler would handle the response when one is received. .. note:: Notice that the asyncHandler functionality could also be achieved using a :class:`ParallelSender` object, but it has other implications. ''' global _executors, _connMan, _parser, _p, _initialized, _ready _executors = { 'busy': (lambda x: Response('busy'), False), 'ready': (_isReady, False), 'alive': (lambda x: Response('alive', True), False) } for m in functionMap: if isinstance(functionMap[m], types.FunctionType): _executors[m] = (functionMap[m], False) elif isinstance(functionMap[m], tuple): _executors[m] = functionMap[m] else: print 'Element in function map is not a function nor a correct tuple: ' + repr( functionMap[m]) _connMan = ConnectionManager(port) _parser = CommandParser(asyncHandler) _p = threading.Thread(target=_MainThread) _p.daemon = True _initialized = True
class CLI: def __init__(self): self.game = Game() self.command_parser = CommandParser() self.init_command_parser() print('Welcome to the "Do you even math?" game!') def init_command_parser(self): self.command_parser.add_command('start', self.start) self.command_parser.add_command('highscores', self.print_highscores) self.command_parser.add_command('exit', self.exit) def start_menu(self): print(''' Here are your options: - start - highscores - exit''') command = input('?> ') self.command_parser.execute(command) def start(self): username = input('Enter your playername>') print('Welcome {}! Let the game begin!'.format(username)) self.game.register(username) while not self.game.is_over: self.game.generate_new_question() print('Question #{}:'.format(self.game.level)) print(self.game.get_expression_string()) try: answer = int(input('?> ')) except ValueError: print('Answer must be an integer!') if self.game.give_answer(answer): print('Correct') else: print('''Incorrect! Answer was {}. Ending game. You score is: {}'''.format( self.game.get_answer(), self.game.get_score())) self.game.restart() self.start_menu() def print_highscores(self): print(self.game.get_highscores_string()) self.start_menu() def exit(self): import sys sys.exit()
class CLI: def __init__(self): self.game = Game() self.command_parser = CommandParser() self.init_command_parser() print('Welcome to the "Do you even math?" game!') def init_command_parser(self): self.command_parser.add_command('start', self.start) self.command_parser.add_command('highscores', self.print_highscores) self.command_parser.add_command('exit', self.exit) def start_menu(self): print(''' Here are your options: - start - highscores - exit''') command = input('?> ') self.command_parser.execute(command) def start(self): username = input('Enter your playername>') print('Welcome {}! Let the game begin!'.format(username)) self.game.register(username) while not self.game.is_over: self.game.generate_new_question() print('Question #{}:'.format(self.game.level)) print(self.game.get_expression_string()) try: answer = int(input('?> ')) except ValueError: print('Answer must be an integer!') if self.game.give_answer(answer): print('Correct') else: print( '''Incorrect! Answer was {}. Ending game. You score is: {}''' .format(self.game.get_answer(), self.game.get_score())) self.game.restart() self.start_menu() def print_highscores(self): print(self.game.get_highscores_string()) self.start_menu() def exit(self): import sys sys.exit()
def start(self): """ Makes all required initializations and starts the server. """ print "Starting AWG server..." print "Listening on %s" % (self.host) print "RPCBIND on port %s" % (self.rpcbind_port) print "VXI-11 on port %s" % (self.vxi11_port) print "Creating sockets..." # Create RPCBIND socket self.rpcbind_socket = self.create_socket(self.host, self.rpcbind_port) # Create VXI-11 socket self.lxi_socket = self.create_socket(self.host, self.vxi11_port) # Initialize SCPI command parser self.parser = CommandParser(self.awg) # Connect to the external AWG #self.awg.initialize() # Run the server self.main_loop()
def __init__(self, args): self.no_colors = False def parse_args_and_opts(args): optionParser = OptionParser() for opt in Todo.opts: optionParser.add_option(*opt[4:], help=opt[0], action=opt[1], dest=opt[2], default=opt[3]) return optionParser.parse_args() if not os.path.exists(os.path.dirname(_todo_file)): os.mkdir(os.path.dirname(_todo_file)) if not os.path.exists(_todo_file): with file(_todo_file, "w") as f: pass try: opts, args = parse_args_and_opts(args) setattr(Todo, "no_colors", opts.no_colors) parserGenerator = TaskParserGenerator(_todo_file) tasks, last_index = parserGenerator.parse() commandParser = CommandParser([cmd[1] for cmd in Todo.cmds]) command, args_left = commandParser.parse(args) changes = getattr(Todo.TodoCommands(tasks, last_index), command)(args_left) if changes: parserGenerator.generate(tasks) except (TodoError, IOError, ValueError) as err: print ("error: {0}".format(err))
def main(): engine = create_engine("sqlite:///cinema.db") Base.metadata.create_all(engine) session = Session(bind=engine) cinema_city = Cinema(session) new_movies_and_projections_in_cinema(cinema_city) command_parser = CommandParser() command_parser.add_command("show_movies", cinema_city.show_movies) cinema_city.show_movies(session) command = input(">>>") command_parser.run_command(command)
class Simulation(object): def __init__(self): self.command_parser = CommandParser() self.reset() def reset(self): self.board = Board(5, 5) self.robot = Robot(self.board) def run(self, line): command = self.command_parser.parse(line) try: command.invoke(target=self.robot) except MoveOutOfBoundsError as e: print 'Skip %s:' % command.identifier, e except MissingPlaceError as e: print 'Skip %s:' % command.identifier, e
def create_book(self, command, counter): Path.reset_path() Debug.logger.info(u"开始制作第 {} 本电子书".format(counter)) Debug.logger.info(u"对记录 {} 进行分析".format(command)) task_list = CommandParser.get_task_list(command) # 分析命令 if len(task_list) == 0: return for task in task_list: if Config.debug_for_create_book: pass else: Worker.distribute(task) Debug.logger.info(u"网页信息抓取完毕") task_result_list = [] toTo_list = [ Type.wechat, Type.huxiu, Type.huawei, Type.xueqiu, Type.sina, Type.zhengshitang, Type.jinwankansa, Type.wuxia, Type.doc360, Type.todo, Type.todo1, Type.todo2, Type.fiel, Type.taoguba_article ] for task in task_list: if task.get_task_type() in toTo_list: task = ColumnTask(task.account_id) task_result = TaskResult(task) task_result.extract_data() task_result_list.append(task_result) Debug.logger.info(u"数据库信息获取完毕") # 下载图片 for task_result in task_result_list: task_result.download_img() # print '所有任务图片获取完毕' Debug.logger.info(u"所有任务图片获取完毕") # 按体积自动分卷 # 渲染html && 压缩为电子书 book = Book(task_result_list) book_list = book.auto_split(Config.max_book_size_mb * 1024) for chapter in book_list: chapter.create_book() return
def main(): fill_with_questions(session) command_parser = CommandParser() command_parser.add_command("begin", begin_interaction_with_user) command_parser.add_command("start", start_game) command_parser.add_command("highscores", show_highscores) command_parser.add_command("finish", finish) command_parser.run_command("begin") command = prompt_for_input() command_parser.run_command(command) while command != "finish": command = prompt_for_input() command_parser.run_command(command)
class Game: def __init__(self): self.parser = CommandParser() self.load_functions() self.run() def initialize_game(self): name = input("Character Name> ") health = 100 nickname = input("Character Nickname> ") self.hero = Hero(name, health, nickname) self.level = 1 self.map = Dungeon() self.map.spawn(self.hero) def run(self): running = True system('clear') print("Welcome to Dungeons & Pythons!") print("What are you waiting for? Create your character and start slaying...") self.initialize_game() print("Loading Level " + str(self.level) + '...') sleep(3) while running: system('clear') if not self.hero.is_alive(): print("\n\nGAME OVER!") sleep(3) self.run() print("Character: {0}".format(str(self.hero))) print("Health: {0}".format(str(self.hero.get_health()))) print("Weapon: {0}".format(str(self.hero.weapon))) print("Level: {0}".format(str(self.level))) print("\n") self.map.print_map() command = input("\nEnter direction <u, d, r, l>: ") self.parser.take_command(command) self.hero = self.map.hero if self.map.game_ended: system('clear') self.level += 1 self.map = Dungeon(self.level) if not self.map.map: print("YOU WON!!! Congratulations, Dungeon Master! ;)") self.map.spawn(self.hero) print("Loading Level " + str(self.level) + '...') sleep(3) def move_up(self, arguments): self.map.move('up') def move_down(self, arguments): self.map.move('down') def move_right(self, arguments): self.map.move('right') def move_left(self, arguments): self.map.move('left') def load_functions(self): self.parser.add_function('u', self.move_up) self.parser.add_function('d', self.move_down) self.parser.add_function('r', self.move_right) self.parser.add_function('l', self.move_left)
from command_parser import CommandParser from guilds import guilds_instance import guilds import discord """ Commands that can be used by anyone """ parser = CommandParser("!") @parser.command(help_text="pings the bot") async def ping(ctx): await ctx.send("pong!") on_message = parser.on_message """ Commands for server owners only """ owner_parser = CommandParser("!") @owner_parser.command(help_text="makes a guild object for this server") async def registerserver(ctx): if (guilds_instance.fetch_guild(ctx.message.guild.id) == None): presrole = await ctx.message.guild.create_role( name="President", color=discord.Color.gold(), hoist=True) guilds_instance.guilds.append( guilds.Guild(ctx.message.guild.id, electionChannel=ctx.message.channel.id, presidentRole=presrole.id))
def test_unknown_command(): parser = CommandParser(cmds) cmd, _ = parser.parse(['greet'] + args)
def __init__(self): self.game = Game() self.command_parser = CommandParser() self.init_command_parser() print('Welcome to the "Do you even math?" game!')
def create_command_parser(): command_parser = CommandParser() command_parser.add_command('show_movies', show_movies) command_parser.add_command( 'show_movie_projections', show_movie_projections) command_parser.add_command('make_reservation', make_reservation) command_parser.add_command('cancel_reservation', cancel_reservation) command_parser.add_command('exit', exit) command_parser.add_command('help', show_help) return command_parser
class MovieCatalog: def __init__(self): self.commandparser = CommandParser() self.adapter = SQLAdapter() self.movies = {} self.actors = {} self.initialize_functions() self.load_initial_state() self.program_loop() def add_movie(self, arguments): title = input("title> ") year = input("year> ") rating = input("rating> ") movie = Movie(title, year, rating) #add movie only if it's not already in the catalog for movie_in_catalog in self.movies.values(): if movie_in_catalog == movie: print("{0} is already in your catalog!".format(movie)) return False #when a movie is saved in the database, the adapter returns its id movie_id = self.adapter.save_movie(movie) self.movies[movie_id] = movie print("{0} was added to your catalog!".format(movie)) return True def remove_movie(self, arguments): movie_id = int(arguments[0]) del self.movies[movie_id] self.adapter.remove_movie(movie_id) def add_actor(self, arguments): movie_id = int(arguments[0]) #if no actor id is given then the actor hasn't been added to the db #in which case we need to add him/her and get the actor_id if len(arguments) == 1: name = input("name> ") actor = Actor(name) actor_id = self.adapter.save_actor(actor) self.actors[actor_id] = actor else: actor_id = int(arguments[1]) actor = self.adapter.get_actor(actor_id) #add the movie_id<->actor_id relation to the relation table self.adapter.add_actor_to_movie(movie_id, actor_id) #add the actor to the cast in the movie dictionary of the catalog self.movies[movie_id].cast[actor_id] = actor print("{0} was added to the list of actors of {1}".format( actor, self.movies[movie_id])) def list_movies(self, arguments): for movie_id, movie in self.movies.items(): print("[{0}] {1}".format(movie_id, movie)) def list_actors(self, arguments): for actor_id, actor in self.actors.items(): print("[{0}] {1}".format(actor_id, actor)) def movie_info(self, arguments): movie_id = int(arguments[0]) movie = self.movies[movie_id] print("Title: {0}".format(movie.get_title())) print("Year: {0}".format(movie.get_year())) cast = [actor.get_name() for actor in movie.cast.values()] print("Cast: {0}".format(', '.join(cast).rstrip(', '))) print("Rating: {0}".format(movie.get_rating())) def actor_info(self, arguments): actor_id = int(arguments[0]) actor = self.actors[actor_id] print("{0} stars in:".format(actor,)) for movie_id, movie in self.movies.items(): if actor_id in movie.cast: print("[{0}] {1}".format(movie_id, movie)) def find_movies(self, arguments): rating = int(arguments[0]) found_movies = False print("Movies with {0} stars:".format(str(rating))) for movie_id, movie in self.movies.items(): if movie.get_rating() == rating: found_movies = True print("[{0}] {1}".format(movie_id, movie)) if not found_movies: print("-- there are no movies with {0} stars --".format(str(rating))) def rate_movie(self, arguments): movie_id = int(arguments[0]) rating = input("rating> ") self.movies[movie_id].change_rating(rating) self.adapter.update_rating(movie_id, rating) def exit(self, arguments): sys.exit(0) def load_initial_state(self): self.movies = self.adapter.load_movies() self.actors = self.adapter.load_actors() def initialize_functions(self): #add functions to the dictionary of functions the parser recognizes self.commandparser.on("add_movie", self.add_movie) self.commandparser.on("add_actor", self.add_actor) self.commandparser.on("list_movies", self.list_movies) self.commandparser.on("list_actors", self.list_actors) self.commandparser.on("rate_movie", self.rate_movie) self.commandparser.on("find_movies", self.find_movies) self.commandparser.on("movie_info", self.movie_info) self.commandparser.on("actor_info", self.actor_info) self.commandparser.on("remove_movie", self.remove_movie) self.commandparser.on("exit", self.exit) def program_loop(self): while True: command = input("> ") self.commandparser.take_command(command)
def test_known_command(): parser = CommandParser(cmds) result_cmd, result_args = parser.parse([cmds[0]] + args) assert result_cmd == cmds[0] assert result_args == args
""" Handlers for the RPG commands. """ import guilds from guilds import guilds_instance from . import rpg_instance from command_parser import CommandParser import time parser = CommandParser("?") parser.add_custom_context( "player", lambda ctx: rpg_instance.fetchplayer(ctx.user.id, ctx.user.name)) @parser.command(aliases="h", help_text="show this help message") async def help(ctx): response = "**Commands:**\n" for command in parser.commands: help_text = parser.get_command_help(command) if help_text is not None: response += "\n" + help_text await ctx.send(response) """ SPAM COOLDOWN TRACKER - user id keys, time.time() values """ cooldowns = {}
from robot import Robot from table import Table from command_parser import CommandParser if __name__ == '__main__': table = Table() robot = Robot(table) input_command = 'init' os.system('cls') print("Toy Robot Simulation\n") input_choice = str( input( 'CHOOSE 1 AUTOMATE TESTING (with ready files) or 2 FOR MANUAL TESTING (input via console) ' )) if input_choice == '1': with open('example_files/commands1.txt') as fp: lines = fp.read().split("\n") for input_command in lines: print("Input: " + input_command) command_parser = CommandParser( input_command).get_validated_command() robot.robot_movemant(command_parser) print("\n") elif input_choice == '2': while input_command: input_command = str(input('Input: ')) command_parser = CommandParser( input_command).get_validated_command() robot.robot_movemant(command_parser)
class AwgServer(object): def __init__(self, awg, host=None, rpcbind_port=None, vxi11_port=None): if host is not None: self.host = host else: self.host = HOST if not isinstance(rpcbind_port, (int, type(None))): raise TypeError("rpcbind_port must be an integer.") if rpcbind_port is not None: self.rpcbind_port = rpcbind_port else: self.rpcbind_port = RPCBIND_PORT if not isinstance(vxi11_port, (int, type(None))): raise TypeError("vxi11_port must be an integer.") if vxi11_port is not None: self.vxi11_port = vxi11_port else: self.vxi11_port = VXI11_PORT if awg is None or not isinstance(awg, BaseAWG): raise TypeError("awg variable must be of AWG class.") self.awg = awg def create_socket(self, host, port): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Disable the TIME_WAIT state of connected sockets. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((host, port)) sock.listen(1) # Become a server socket, maximum 1 connection return sock def start(self): """ Makes all required initializations and starts the server. """ print "Starting AWG server..." print "Listening on %s" % (self.host) print "RPCBIND on port %s" % (self.rpcbind_port) print "VXI-11 on port %s" % (self.vxi11_port) print "Creating sockets..." # Create RPCBIND socket self.rpcbind_socket = self.create_socket(self.host, self.rpcbind_port) # Create VXI-11 socket self.lxi_socket = self.create_socket(self.host, self.vxi11_port) # Initialize SCPI command parser self.parser = CommandParser(self.awg) # Connect to the external AWG #self.awg.initialize() # Run the server self.main_loop() def main_loop(self): """ The main loop of the server. """ # Run the VXI-11 server while True: # VXI-11 requests are processed after receiving a valid RPCBIND request. print "\nWaiting for connection request..." res = self.process_rpcbind_request() if res != OK: print "Incompatible RPCBIND request." continue self.process_lxi_requests() self.close_lxi_sockets() # Disconnect from the external AWG self.signal_gen.connect() def process_rpcbind_request(self): """Replies to RPCBIND/Portmap request and sends VXI-11 port number to the oscilloscope.""" #while True: connection, address = self.rpcbind_socket.accept() rx_data = connection.recv(128) if len(rx_data) > 0: print "\nIncoming connection from %s:%s." % (address[0], address[1]) # Validate the request. ## If the request is not GETPORT or does not come from VXI-11 Core (395183), ## we have nothing to do wit it procedure = self.bytes_to_uint(rx_data[0x18:0x1c]) if procedure != GET_PORT: return NOT_GET_PORT_ERROR program_id = self.bytes_to_uint(rx_data[0x2C:0x30]) if program_id != VXI11_CORE_ID: return NOT_VXI11_ERROR # Generate and send response resp = self.generate_rpcbind_response() resp_data = self.generate_resp_data(rx_data, resp) connection.send(resp_data) # Close connection and RPCBIND socket. connection.close() return OK def process_lxi_requests(self): connection, address = self.lxi_socket.accept() while True: rx_buf = connection.recv(255) if len(rx_buf) > 0: # Parse incoming VXI-11 command status, vxi11_procedure, scpi_command = self.parse_lxi_request(rx_buf) if status == NOT_VXI11_ERROR: print "Received VXI-11 request from an unknown source." break elif status == UNKNOWN_COMMAND_ERROR: print "Unknown VXI-11 request received. Procedure id %s" % (vxi11_procedure) break print "VXI-11 %s, SCPI command: %s" % (LXI_PROCEDURES[vxi11_procedure], scpi_command) # Process the received VXI-11 request if vxi11_procedure == CREATE_LINK: resp = self.generate_lxi_create_link_response() elif vxi11_procedure == DEVICE_WRITE: """ The parser parses and executes the received SCPI command. VXI-11 DEVICE_WRITE function requires an empty reply. """ self.parser.parse_scpi_command(scpi_command) elif vxi11_procedure == DEVICE_READ: """ DEVICE_READ request is sent to a device when an answer after command execution is expected. SDG1000X-E sends this request in two cases: a. It requests the ID of the AWG (*IDN? command). In this case we MUST supply a valid ID to make the scope think that it is working with a genuine Siglent AWG. b. After setting all the parameters of the AWG and before starting frequency sweep (C1:BSWV? command). It looks like the scope is supposed to verify that all the required AWG settings were set correctly. In the real life it seems that in the second case the scope totally ignores the response and will accept any garbage. It makes our life easy and we send AWG ID as reply to any DEVICE_READ request. """ resp = self.generate_lxi_idn_response(AWG_ID_STRING) elif vxi11_procedure == DESTROY_LINK: """ If DESTROY_LINK is received, the oscilloscope ends the session opened by CREATE_LINK request and won't send any commands before issuing a new CREATE_LINK request. All we have to do is to exit the loop and continue listening to RPCBIND requests. """ break else: """ If the received command is none of the above, something went wrong and we should exit the loop and continue listening to RPCBIND requests. """ break # Generate and send response resp_data = self.generate_resp_data(rx_buf, resp) connection.send(resp_data) # Close connection connection.close() def parse_lxi_request(self, rx_data): """Parses VXI-11 request. Returns VXI-11 command code and SCPI command if it exists. @param rx_data: bytes array containing the source packet. @return: a tuple with 3 values: 1. status - is 0 if the request could be processed, error code otherwise. 2. VXI-11 procedure id if it is known, None otherwise. 3. string containing SCPI command if it exists in the request.""" # Validate source program id. ## If the request doesn't come from VXI-11 Core (395183), it is ignored. program_id = self.bytes_to_uint(rx_data[0x10:0x14]) if program_id != VXI11_CORE_ID: return (NOT_VXI11_ERROR, None, None) # Procedure: CREATE_LINK (10), DESTROY_LINK (23), DEVICE_WRITE (11), DEVICE_READ (12) vxi11_procedure = self.bytes_to_uint(rx_data[0x18:0x1c]) scpi_command = None status = OK # Process the remaining data according to the received VXI-11 request if vxi11_procedure == CREATE_LINK: cmd_length = self.bytes_to_uint(rx_data[0x38:0x3C]) scpi_command = rx_data[0x3C:0x3C+cmd_length] elif vxi11_procedure == DEVICE_WRITE: cmd_length = self.bytes_to_uint(rx_data[0x3C:0x40]) scpi_command = rx_data[0x40:0x40+cmd_length] elif vxi11_procedure == DEVICE_READ: pass elif vxi11_procedure == DESTROY_LINK: pass else: status = UNKNOWN_COMMAND_ERROR print "Unknown VXI-11 command received. Code %s" % (vxi11_procedure) return (status, vxi11_procedure, str(scpi_command).strip()) def get_xid(self, rx_packet): """ Extracts XID from the incoming RPC packet. """ xid = rx_packet[0x04:0x08] return xid def generate_resp_data(self, rx_buf, resp): """ Generates the response data to be sent to the oscilloscope. """ # Generate RPC header xid = self.get_xid(rx_buf) rpc_hdr = self.generate_rpc_header(xid) # Generate packet size header data_size = len(rpc_hdr) + len(resp) size_hdr = self.generate_packet_size_header(data_size) # Merge all the headers resp_data = size_hdr + rpc_hdr + resp return resp_data def generate_packet_size_header(self, size): """ Generates the header containing reply packet size. """ # 1... .... .... .... .... .... .... .... = Last Fragment: Yes size = size | 0x80000000 # .000 0000 0000 0000 0000 0000 0001 1100 = Fragment Length: 28 res = self.uint_to_bytes(size) return res def generate_rpc_header(self, xid): """ Generates RPC header for replying to oscilloscope's requests. @param xid: XID from the request packet as bytes sequence. """ hdr = "" # XID: 0xXXXXXXXX (4 bytes) hdr += xid # Message Type: Reply (1) hdr += "\x00\x00\x00\x01" # Reply State: accepted (0) hdr += "\x00\x00\x00\x00" # Verifier ## Flavor: AUTH_NULL (0) hdr += "\x00\x00\x00\x00" ## Length: 0 hdr += "\x00\x00\x00\x00" # Accept State: RPC executed successfully (0) hdr += "\x00\x00\x00\x00" return hdr # ========================================================================= # Response data generators # ========================================================================= def generate_rpcbind_response(self): """Returns VXI-11 port number as response to RPCBIND request.""" resp = self.uint_to_bytes(self.vxi11_port) return resp def generate_lxi_create_link_response(self): """Generates reply to VXI-11 CREATE_LINK request.""" # VXI-11 response ## Error Code: No Error (0) resp = "\x00\x00\x00\x00" ## Link ID: 0 resp += "\x00\x00\x00\x00" ## Abort Port: 0 resp += "\x00\x00\x00\x00" ## Maximum Receive Size: 8388608=0x00800000 #resp += self.uint_to_bytes(8388608) resp += "\x00\x80\x00\x00" return resp def generate_lxi_idn_response(self, id_string): ## Error Code: No Error (0) resp = "\x00\x00\x00\x00" # Reason: 0x00000004 (END) resp += "\x00\x00\x00\x04" # Add the AWG id string id_length = len(id_string) + 3 resp += self.uint_to_bytes(id_length) resp += id_string # The sequence ends with \n and two \0 termination bytes. resp += "\x0A\x00\x00" return resp # ========================================================================= # Helper functions # ========================================================================= def bytes_to_uint(self, bytes_seq): """ Converts a sequence of 4 bytes to 32-bit integer. Byte 0 is MSB. """ num = ord(bytes_seq[0]) num = num * 0x100 + ord(bytes_seq[1]) num = num * 0x100 + ord(bytes_seq[2]) num = num * 0x100 + ord(bytes_seq[3]) return num def uint_to_bytes(self, num): """ Converts a 32-bit integer to a sequence of 4 bytes. Byte 0 is MSB. """ byte3 = (num / 0x1000000) & 0xFF byte2 = (num / 0x10000) & 0xFF byte1 = (num / 0x100) & 0xFF byte0 = num & 0xFF bytes_seq = bytearray((byte3, byte2, byte1, byte0)) return bytes_seq def print_as_hex(self, buf): """ Prints a buffer as a set of hexadecimal numbers. Created for debug purposes. """ buf_str = "" for b in buf: buf_str += "0x%X " % ord(b) print buf_str def close_rpcbind_sockets(self): """ Closes RPCBIND socket. """ try: self.rpcbind_socket.close() except: pass def close_lxi_sockets(self): """ Closes VXI-11 socket. """ try: self.lxi_socket.close() except: pass def close_sockets(self): self.close_rpcbind_sockets() self.close_lxi_sockets() def __del__(self): self.close_sockets()
try: color = webcolors.name_to_hex(color_string, spec='css3')[1:] return color except: try: color = color_string[1:] test = webcolors.hex_to_rgb("#" + color) return color except: return False """ GUILD MODULE COMMANDS """ parser = CommandParser("!") parser.add_custom_context( "guild", lambda ctx: guilds_instance.fetch_guild(ctx.message.guild.id)) @parser.command(aliases="h", help_text="show this help message") async def help(ctx): response = "**Commands:**\n" for command in parser.commands: help_text = parser.get_command_help(command) if help_text is not None: response += "\n" + help_text await ctx.send(response) @parser.command(help_text="shows the guild's parties")
def __init__(self): self.parser = CommandParser() self.load_functions() self.run()
def __init__(self): self.command_parser = CommandParser() self.reset()
def setUp(self): self.parser = CommandParser()
class NoNickname(Exception): pass def read_token(): token_file_name = os.path.join(WORKDIR, 'fmf_bot_token') if not os.path.isfile(token_file_name): token_file_name = '/root/fmf_bot_token' with open(token_file_name, 'r') as f: return f.read().strip() bot = Bot(token=read_token()) dp = Dispatcher(bot) command_parser = CommandParser(dp) def member_in_db(connection, member_id): cur = connection.cursor() cur.execute('SELECT COUNT(*) FROM members WHERE id=?', (member_id, )) return cur.fetchone()[0] > 0 def add_member_to_db(connection, member_id, member_name, chat_id): cur = connection.cursor() # member_id and chat_id are the same, so it's just a historical issue. cur.execute('INSERT INTO members (id, name, chat) VALUES (?, ?, ?)', (member_id, member_name, chat_id)) connection.commit()
class ClientQObject(QObject): # Flag of login state is_logged = False def __init__(self, queue_read: Queue, queue_sent: Queue): super().__init__() self.queue_read = queue_read self.queue_sent = queue_sent # queue_read Timer initialization self.queue_timer = QTimer(self) self.queue_timer.timeout.connect(self.queueChecker) # Better to use gui/qt for timer functionality to operate with qt inside qt self.queue_timer.setInterval( 10) # each 10ms call func to check queue messages from websocket self.queue_timer.start() # Init command parse self.cmd_parser = CommandParser() # Create communication protocol self.protocol = ClientProtocol() # Signals login_received = pyqtSignal(bool) # when received login result companies_list_received = pyqtSignal(list) # received list of companies cliend_data_received = pyqtSignal( dict) # recived data with client information # Check reading queue def queueChecker(self): if self.queue_read.qsize() > 0: # get message from websocket and parse it msg = self.queue_read.get() self.parse_server_message(msg) # Parse everything, that is not related to communication def not_connection_messages(self, msg): if self.is_logged is False: return res = self.cmd_parser.parse(msg) return res def parse_server_message(self, msg): # message should be json msg = self.protocol.verify_msg(msg) if msg is None: return switcher = { MessageType.LOGIN.value: self.on_login_request_answer, MessageType.KEEP_ALIVE.value: self.on_keep_alive_request } func = switcher.get(int(msg["type"]), self.not_connection_messages) res = func(msg) # After parsing need to make some stuff with received and parsed information # TODO : make it more clearly and optimized if res is not None: if int(msg["type"]) == MessageType.COMPANIES_OPEN_LIST.value: self.companies_list_received.emit(res) elif int(msg["type"]) == MessageType.CLIENT_DATA.value: self.cliend_data_received.emit(res) def on_keep_alive_request(self, msg): # server wants keep alive. Just send him to inform, that client is alive msg_json = self.protocol.create_keep_alive_msg() # put to sent queue self.queue_sent.put(msg_json) def on_login_request_answer(self, msg): if self.is_logged: # This functionality can be used only player is not logged into system return body = msg["body"] self.is_logged = body["result"] self.protocol.uuid = body[ "uuid"] # Store uuid. Client will use it in communication with server for better indentification self.login_received.emit(self.is_logged) def transfer_login_auth(self, login, password): # prepare message msg = self.protocol.create_login_msg(login, password) # sent message to websocket queue self.queue_sent.put(msg) def send_companies_list_request(self): msg_json = self.protocol.request_companies_list() self.queue_sent.put(msg_json) def send_client_data_request(self): msg_json = self.protocol.request_client_data() self.queue_sent.put(msg_json)
#!/usr/bin/env python3 # `cpp_tools` is a set of lightweight python scripts used to facilitate and speed up development in C++. # Copyright (C) 2018 Guillaume Duclos-Cianci # This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later # version. # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # You should have received a copy of the GNU General Public License along with this program. # If not, see <http://www.gnu.org/licenses/>. from command_create_project import CommandCreateProject from command_parser import CommandParser if __name__ == '__main__': command = CommandParser().parse() command.execute()
from command_parser import CommandParser cp = CommandParser() while True: try: command = input(cp.get_prompt()) cp.breakout(command) except StopIteration: break
def create_command_parser(): command_parser = CommandParser() command_parser.add_command('show_movies', show_movies) command_parser.add_command('show_movie_projections', show_movie_projections) command_parser.add_command('make_reservation', make_reservation) command_parser.add_command('cancel_reservation', cancel_reservation) command_parser.add_command('exit', exit) command_parser.add_command('help', show_help) return command_parser
class BTRosInterface: def __init__(self, test_name): # Only argument stuff self.running = False self.bt_receiver = btReceiver(debug = True) self.file_manager = fileManager(test_name, debug = True) self.command_parser = CommandParser() self.rotation = Rotation() self.mode = "manual" self.control_mode = "torque" self.attitude = [0,0,0] #[ypr] [DEG] self.speed = [HDD_ZERO_SPEED,HDD_ZERO_SPEED,HDD_ZERO_SPEED] #[xyz] [RPM] self.torque = [0,0,0] #[xyz] [Nm] self.voltage = [0,0,0] #[xyz] [V] self.iGains = [5, 10, 0] #[PID] self.wGains = [15, 25, 0] #[PID] def initialize(self): # Get params and allocate msgs self.state_update_rate = rospy.get_param('/rate', 5000) #Buetooth self.bt_receiver.initialize() def start(self): # Create subs, services, publishers, threads self.running = True #subscribers self.command_sub = rospy.Subscriber('/controller_command', String, self.process_command) self.mode_sub = rospy.Subscriber('/mode', String, self.set_mode) self.control_mode_sub = rospy.Subscriber('/control_mode', String, self.set_control_mode) self.attitude_sub = rospy.Subscriber('/attitude', Float32MultiArray, self.set_attitude) self.speedX_sub = rospy.Subscriber('/speed_x', Float32, self.set_speed_x) self.speedY_sub = rospy.Subscriber('/speed_y', Float32, self.set_speed_y) self.speedZ_sub = rospy.Subscriber('/speed_z', Float32, self.set_speed_z) self.torqueX_sub = rospy.Subscriber('/torque_x', Float32, self.set_torque_x) self.torqueY_sub = rospy.Subscriber('/torque_y', Float32, self.set_torque_y) self.torqueZ_sub = rospy.Subscriber('/torque_z', Float32, self.set_torque_z) self.voltageX_sub = rospy.Subscriber('/voltage_x', Float32, self.set_voltage_x) self.voltageY_sub = rospy.Subscriber('/voltage_y', Float32, self.set_voltage_y) self.voltageZ_sub = rospy.Subscriber('/voltage_z', Float32, self.set_voltage_z) self.iGains_sub = rospy.Subscriber('/iGains', Float32MultiArray, self.set_iGains) self.wGains_sub = rospy.Subscriber('/wGains', Float32MultiArray, self.set_wGains) #publishers self.data1_pub = rospy.Publisher('/time1', Float32, queue_size=70) self.data2_pub = rospy.Publisher('/wx', Float32, queue_size=70) self.data3_pub = rospy.Publisher('/wy', Float32, queue_size=70) self.data4_pub = rospy.Publisher('/wz', Float32, queue_size=70) self.data5_pub = rospy.Publisher('/time2', Float32, queue_size=70) self.data6_pub = rospy.Publisher('/wx_raw', Float32, queue_size=70) self.data7_pub = rospy.Publisher('/wy_raw', Float32, queue_size=70) self.data8_pub = rospy.Publisher('/wz_raw', Float32, queue_size=70) self.cmd_yaw_pub = rospy.Publisher('/cmd_yaw', Float32, queue_size=70) self.cmd_speedX_pub = rospy.Publisher('/cmd_speedX', Float32, queue_size=70) self.cmd_torqueX_pub = rospy.Publisher('/cmd_torqueX', Float32, queue_size=70) self.cmd_voltageX_pub = rospy.Publisher('/cmd_voltageX', Float32, queue_size=70) self.qE4_pub = rospy.Publisher('/qE4', Float32, queue_size=70) self.qE1_pub = rospy.Publisher('/qE1', Float32, queue_size=70) self.qE2_pub = rospy.Publisher('/qE2', Float32, queue_size=70) self.qE3_pub = rospy.Publisher('/qE3', Float32, queue_size=70) self.qDE1_pub = rospy.Publisher('/qDE1', Float32, queue_size=70) self.qDE2_pub = rospy.Publisher('/qDE2', Float32, queue_size=70) self.qDE3_pub = rospy.Publisher('/qDE3', Float32, queue_size=70) Thread(target=self.update_state).start() def stop(self): self.running = False self.command_sub.unregister() self.mode_sub.unregister() self.control_mode_sub.unregister() self.attitude_sub.unregister() self.speedX_sub.unregister() self.speedY_sub.unregister() self.speedZ_sub.unregister() self.torqueX_sub.unregister() self.torqueY_sub.unregister() self.torqueZ_sub.unregister() self.voltageX_sub.unregister() self.voltageY_sub.unregister() self.voltageZ_sub.unregister() self.iGains_sub.unregister() self.wGains_sub.unregister() self.data1_pub.unregister() self.data2_pub.unregister() self.data3_pub.unregister() self.data4_pub.unregister() self.data5_pub.unregister() self.data6_pub.unregister() self.data7_pub.unregister() self.data8_pub.unregister() self.cmd_yaw_pub.unregister() self.cmd_speedX_pub.unregister() self.cmd_torqueX_pub.unregister() self.cmd_voltageX_pub.unregister() self.qE4_pub.unregister() self.qE1_pub.unregister() self.qE2_pub.unregister() self.qE3_pub.unregister() self.qDE1_pub.unregister() self.qDE2_pub.unregister() self.qDE3_pub.unregister() self.bt_receiver.stop() self.file_manager.stop() def set_mode(self, msg): self.mode = msg.data def set_control_mode(self, msg): self.control_mode = msg.data def set_attitude(self, msg): self.attitude = msg.data def set_speed_x(self, msg): self.speed[0] = msg.data def set_speed_y(self, msg): self.speed[1] = msg.data def set_speed_z(self, msg): self.speed[2] = msg.data def set_torque_x(self, msg): self.torque[0] = msg.data def set_torque_y(self, msg): self.torque[1] = msg.data def set_torque_z(self, msg): self.torque[2] = msg.data def set_voltage_x(self, msg): self.voltage[0] = msg.data def set_voltage_y(self, msg): self.voltage[1] = msg.data def set_voltage_z(self, msg): self.voltage[2] = msg.data def set_iGains(self, msg): self.iGains = msg.data def set_wGains(self, msg): self.wGains = msg.data def process_command(self, msg): print "msg to send:"+msg.data if (msg.data == "end") : self.running = False return else: args = [self.mode, self.control_mode, self.attitude, self.speed, self.torque, self.voltage] command_code = self.command_parser.parse_command(msg.data, args, self.iGains, self.wGains) if (command_code!=[-1,-1,-1,-1]): frame = self.file_manager.encode(command_code) self.bt_receiver.write(frame) else: rospy.logwarn("Unknown command") print "Unknown command" def update_state(self): rate = rospy.Rate(self.state_update_rate) while self.running and not rospy.is_shutdown(): # Receive data if(self.bt_receiver.read()): packet = self.bt_receiver.packet if (packet[0]==1 or packet[0]==2): self.bt_receiver.reset() #write data to file self.file_manager.save_data(packet, self.speed, self.torque, self.voltage, self.attitude) #publish data data = self.file_manager.decode(packet) if (packet[0]==1): self.data1_pub.publish(data[0])#*57.2958 self.data2_pub.publish(data[1]) self.data3_pub.publish(data[2]) self.data4_pub.publish(data[3])#*9.5493 qE = self.rotation.get_qE(self.attitude[0]*0.0174, [data[0], data[1], data[2], data[3]]) self.qE4_pub.publish(qE[0]) self.qE1_pub.publish(qE[1]) self.qE2_pub.publish(qE[2]) self.qE3_pub.publish(qE[3]) self.qDE1_pub.publish(qE[1]*qE[0]) self.qDE2_pub.publish(qE[2]*qE[0]) self.qDE3_pub.publish(qE[3]*qE[0]) elif (packet[0]==2): self.data5_pub.publish(data[0]) self.data6_pub.publish(data[1]) self.data7_pub.publish(data[2]) self.data8_pub.publish(data[3]) self.cmd_yaw_pub.publish(self.attitude[0]) self.cmd_speedX_pub.publish(self.speed[0]) self.cmd_torqueX_pub.publish(self.torque[0]) self.cmd_voltageX_pub.publish(self.voltage[0]) rate.sleep()