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

Need suggestions for decoupling classes used in a script

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

此功能的模块由三个 classes 组成:一个子classes enum 为每个可能的命令创建唯一标识符,一个子classes cmd为用户实现 CLI 接口的模块(这个 class 也进行参数输入清理),最后一个 class 接收所需的命令和参数并构建数据包以通过 serial[=16] 发送出去=]

我遇到的问题是这些 classes 变得非常耦合。理想情况下,我希望 Master_Comm class 是独立的,以便可以从其他模块访问它以发送来自不同来源的数据包(比如脚本文件解析器)。因为它 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)

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

这个 table 在创建它的实例时作为参数传递给 Master_Comm class,然后作为参数传递给 SerialInterface class(而不是创建它自己的)。

同样的想法可以通过更改 CMDS table 的格式来进一步实现,因此它包含有关命令的更多信息,然后在 SerialInterface [=29] 中使用它=]' 实现而不是它仍然包含的硬编码内容(例如与每个字节相关联的字节元组的长度)。

请注意,我还更改了您 class 的名称,使它们遵循 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()