需要有关解耦脚本中使用的类的建议

时间:2017-12-13 21:17:27

标签: python design-patterns pyserial organization

我有一个python程序,其主要用例是通过CLI与它交互,以指示它通过串行发送字节数据包。串行目标遵循某个命令协议。 python程序根据CLI上的用户输入(发送的特定命令,命令的参数等)构建符合此协议的数据包。

此功能的模块由三个类组成:一个用于枚举enum以为每个可能的命令创建唯一标识符,一个用于将cmd模块子类化以实现用户的CLI接口(此类还执行参数输入清理)和最后一个类接收所需的命令和参数,并构建数据包以通过串行发送

我遇到的问题是这些课程变得非常紧密。理想情况下,我希望Master_Comm类是独立的,因此可以从其他模块访问它以发送来自不同源的数据包(比如脚本文件解析器)。因为Serial_Interface有一个Master_Comm的实例来访问sendcommand方法,以及实施输入卫生(可能需要在多个位置完成。

有关更好地组织此事的任何建议吗?特别是随着程序的增长(可能实现数百个命令)。

import serial
from cmd import Cmd
from enum import Enum, unique

@unique
class Command_Names(Enum):
    CMD1 = 1
    CMD2 = 2

class Serial_Interface(Cmd):
    def __init__(self, port, baud,):
        Cmd.__init__(self)
        self.slave_comm = Master_Comm(port=port, baud=baud)
        # setup stuff

    def do_cmd1(self, args):
        try:
            assert 0 <= int(args) <= 25, "Argument out of 0-25 range"
            self.slave_comm.sendcommand(Command_Names.CMD1, args)
        except (AssertionError) as e:
            print(e)

    def do_cmd2(self, args):
        try:
            # No args for cmd2, so don't check anything
            self.slave_comm.sendcommand(Command_Names.CMD2, args)
        except (AssertionError) as e:
            print(e)


class Master_Comm(object):
    _SLAVE_COMMANDS = {Command_Names.CMD1:           (b'\x10', b'\x06', b'\x06'),
                       Command_Names.CMD2:           (b'\x10', b'\x07', b'\x07')}

    _SOURCE_ID = b'\xF0'
    _SEQ_NUM = b'\x00'

    def __init__(self, port, baud):
        self.ser = serial.Serial(port=None,
                                 baudrate=int(baud)
                                 )
        self.ser.port = port

    def open_serial(self):
        # do stuff

    def close_serial(self):
        # do stuff

    def sendcommand(self, command, args):
        try:
            txpacket = bytearray()
            txpacket.extend(self._SOURCE_ID)
            txpacket.extend(self._SEQ_NUM)
            txpacket.extend(self._SLAVE_COMMANDS[command][0])
            txpacket.extend(self._SLAVE_COMMANDS[command][1])
            txpacket.extend(self._SLAVE_COMMANDS[command][2])
            self.ser.write(tx_bytes)
        except Exception as e:
            print(e)

1 个答案:

答案 0 :(得分:1)

您可以将Master_Comm类中的硬编码命令通过将它们作为参数传递给其__init__()构造函数来解耦。下面是这个的简单实现,它创建并使用一个名为CMDS的新词典,它是单独定义的。

当创建它的一个实例时,该表作为参数传递给Master_Comm类,然后将其作为参数传递给SerialInterface类(而不是创建它的#39;自己的。)

可以通过更改CMDS表格的格式进一步采取同样的想法,使其包含有关该命令的更多信息,然后在SerialInterface类中使用该表格。实现,而不是它仍然存在的硬编码的东西(例如与每个相关的字节元组的长度)。

注意我还更改了您的课程名称,使其遵循PEP 8 - Style Guide for Python Code命名建议。

import serial
from cmd import Cmd
from enum import Enum, unique

class SerialInterface(Cmd):
    def __init__(self, mastercomm):
        Cmd.__init__(self)
        self.slave_comm = mastercomm
        # setup stuff

    def do_cmd1(self, args):
        try:
            assert 0 <= int(args) <= 25, "Argument out of 0-25 range"
            self.slave_comm.sendcommand(CommandNames.CMD1, args)
        except (AssertionError) as e:
            print(e)

    def do_cmd2(self, args):
        try:
            # No args for cmd2, so don't check anything
            self.slave_comm.sendcommand(CommandNames.CMD2, args)
        except (AssertionError) as e:
            print(e)


class MasterComm:
    """ Customized serial communications class for communicating with serial
        port using the serial module and commands defined by the table "cmds".
    """
    def __init__(self, port, baud, cmds):
        self.ser = serial.Serial(port=None,
                                 baudrate=int(baud),)
        self.ser.port = port
        self.source_id = cmds['source_id']
        self.seq_num = cmds['seq_num']
        self.slave_commands = cmds['slave_commands']

    def sendcommand(self, command, args):
        try:
            txpacket = bytearray()
            txpacket.extend(self.source_id)
            txpacket.extend(self.seq_num)
            txpacket.extend(self.slave_commands[command][0])
            txpacket.extend(self.slave_commands[command][1])
            txpacket.extend(self.slave_commands[command][2])
            self.ser.write(txpacket)
        except Exception as e:
            print(e)


@unique
class CommandNames(Enum):
    CMD1 = 1
    CMD2 = 2

CMDS = {
    'source_id': b'\xF0',
    'seq_num': b'\x00',
    'slave_commands' : {CommandNames.CMD1: (b'\x10', b'\x06', b'\x06'),
                        CommandNames.CMD2: (b'\x10', b'\x07', b'\x07')}
}

mastercomm = MasterComm(0x03b2, 8192, CMDS)
serialinterface = SerialInterface(mastercomm)
serialinterface.cmdloop()