示例#1
0
def process_cmdline(_available_ports: List[str], _testcmdline=None):
    """process_cmdline(_available_ports, _testcmdline="")

    _available_ports is a list? of port names
    _testcmdline can be list of strings that can be used to fake a command line.
    If None, the default
    command line processing is performed, otherwise,
    the list of strings in the argument is used.

    processes the command line arguments
    returns a tuple of (ui, verbose, cmdl_debug) if arguments are ok, Otherwise raises an exception
    """
    msg: str = ''
    _tcl = []
    if _testcmdline:
        _tcl = _testcmdline
    tempargs = sys.argv[1:] + _tcl
    help_processing(_available_ports, tempargs)

    if _testcmdline:
        args = _PARSER.parse_args(_testcmdline)
    else:
        args = _PARSER.parse_args()

    if args.logdebug:
        LOGGER.setLevel(logging.DEBUG)
    elif args.loginfo:
        LOGGER.setLevel(logging.INFO)

    possible_port: str = args.Port
    if args.Controller:
        possible_ctrl = args.Controller
    else:
        possible_ctrl = 'dlxii'

    if len(_available_ports) != 1:
        if not args.Port.upper() in _available_ports:
            msg = f'Port {args.Port} not available: available ports are: {_available_ports}, aborting'

            raise Exception(msg)
    else:
        possible_port = _available_ports[0]

    ctrl: Tuple[str, Any] = knowncontrollers.select_controller(possible_ctrl)
    if not ctrl:
        msg = f'Controller {args.Controller} not available: available controlers are: {knowncontrollers.get_controller_ids()}, aborting'

        raise Exception(msg)

    verbose: bool = args.verbose
    cmdl_debug = args.cldebug
    _ui = userinput.UserInput(ctrl[1])
    _ui.comm_port = possible_port
    if verbose:
        msg = f'[verbose] ctrl:{ctrl}, port:{_ui.comm_port}, dbg:{cmdl_debug}, verbose: True'

    return (_ui, verbose, cmdl_debug)
示例#2
0
    def request(self):
        """request()

        Request comm port id, repeater controller type, and filename containing controller commands
        """
        CtrlStrings = namedtuple('CtrlStrings', ['org', 'lc'])
        while True:
            #tups: List[Tuple[str, str]] = []
            tups: List[CtrlStrings] = []
            available_p: List[str] = GetPorts().get()
            if available_p and len(available_p) > 1:
                print(f'Available comport(s) are: {available_p}')
                tups = [CtrlStrings(org=_.strip(), lc=_.strip().lower())
                        for _ in available_p]
                useri = self._inputa("Comm Port for repeater?>").strip()
            elif available_p:
                tups = [CtrlStrings(org=_.strip(), lc=_.strip().lower())
                        for _ in available_p]
                useri = tups[0].lc
            else:
                print('No available ports')
                self.close()
                raise Exception(" no available ports")

            hits: List[Any] = [t for t in tups if useri.lower() in t]
            if hits:
                #[_port] = hits
                self.comm_port = hits[0].org
                print(f'Using serial port: {self.comm_port}')
                break

        print('Known controllers: \n\t' +
              '\n\t'.join(knowncontrollers.get_controller_ids()))

        _msg = f'Controller options: {str(knowncontrollers.get_known())}'
        while True:
            print(_msg)
            useri = self._inputa("Controller type?>")
            ctrl = knowncontrollers.select_controller(useri)
            if ctrl:
                self.controller_type = ctrl[1]
                self.serial_port = myserial.MySerial(self.controller_type)
                break

        self.inputfn = self._inputa(
            "file name to send to repeater or blank?>")
示例#3
0
def process_cmdline(_available_ports: List[str],
                    _testcmdline: List[str] = None) -> Tuple[Any, Any, Any]:
    """process_cmdline(_available_ports, _testcmdline="")

    _available_ports is a list? of port names
    _testcmdline can be list of strings that can be used to fake a command line.
    If None, the default
    command line processing is performed, otherwise,
    the list of strings in the argument is used.

    processes the command line arguments
    returns a tuple of (ui, verbose, cmdl_debug) if arguments are ok, Otherwise raises an exception
    """
    _tcl = []
    if _testcmdline:
        _tcl = _testcmdline
    tempargs = sys.argv[1:] + _tcl
    proc1(tempargs, _available_ports)
    # if not ('-h' in tempargs or '--help' in tempargs):
    # if _available_ports.isEmpty():
    #msg = 'no available communication port: aborting'
    #raise SystemExit(msg)
    # if '-h' in tempargs or '--help' in tempargs:
    # _PARSER.print_help()
    #raise SystemExit()

    if _testcmdline:
        args = _PARSER.parse_args(_testcmdline)
    else:
        args = _PARSER.parse_args()

    _aa = proc2(args, )
    possible_port = _aa[0]
    possible_ctrl = _aa[1]
    # if args.logdebug:
    # LOGGER.setLevel(logging.DEBUG)
    # elif args.loginfo:
    # LOGGER.setLevel(logging.INFO)

    #possible_port = args.Port
    # if args.Controller:
    #possible_ctrl = args.Controller
    # else:
    #possible_ctrl = 'dlxii'

    if len(_available_ports) != 1:
        if not args.Port.upper() in _available_ports:
            msg = 'Port {} not available: available ports are: {}, aborting' \
                .format(args.Port, _available_ports)
            raise Exception(msg)
    else:
        possible_port = _available_ports[0]

    ctrl = knowncontrollers.select_controller(possible_ctrl)
    if not ctrl:
        msg = 'Controller {} not available: available controlers are: {}, aborting' \
            .format(args.Controller, knowncontrollers.get_controller_ids())
        raise Exception(msg)

    verbose = args.verbose
    cmdl_debug = args.cldebug
    _ui = userinput.UserInput(ctrl[1])
    _ui.comm_port = possible_port
    if verbose:
        msg = '[verbose] ctrl:{}, port:{}, dbg:{}, verbose: True'\
            .format(ctrl, _ui.comm_port, cmdl_debug)
    return (_ui, verbose, cmdl_debug)
class TestCommandreader(unittest.TestCase):
    """command reader test"""
    ctrl = knowncontrollers.select_controller('dlxii')[1]
    ui = userinput.UserInput(ctrl)

    def setUp(self):
        pass

    def tearDown(self):
        pass

    @classmethod
    def setUpClass(cls):
        TestCommandreader.ui.inputfn = "cmdreadertest.txt"

    @classmethod
    def tearDownClass(cls):
        pass

    def test0_inst(self):
        _cr = CommandReader(TestCommandreader.ui)
        eres = '[CommandReader closed: True, [UserInput: , cmdreadertest.txt]]'
        self.assertEqual(eres, str(_cr))
        self.assertEqual(eres, repr(_cr))

    def test1_open(self):
        """testopen()

        """
        _cr = CommandReader(TestCommandreader.ui)
        _fcr = None
        try:
            self.assertTrue(_cr.atts['is_closed'])
            self.assertEqual("", _cr.get())
            _cr.close()
            self.assertTrue(_cr.open())

            eres = '[CommandReader closed: False, [UserInput: , cmdreadertest.txt]]'
            self.assertEqual(eres, str(_cr))
            self.assertEqual(eres, repr(_cr))

            self.assertFalse(_cr.atts['is_closed'])
            try:
                _cr.open()
                assert "did not detect multiple attempts to open"
            except AssertionError:
                pass

            _cr.close()
            self.assertTrue(_cr.atts['is_closed'])
            fakeui = userinput.UserInput(dlxii.Device())
            fakeui.inputfn = 'totaljunk.txt'
            _fcr = CommandReader(fakeui)
            self.assertFalse(_fcr.open())
            self.assertEqual(
                "[Errno 2] No such file or directory: 'totaljunk.txt'",
                str(_fcr.atts['lasterror']))
            self.assertTrue(_fcr.atts['is_closed'])
        finally:
            if _fcr:
                _fcr.close()

            _cr.close()

    def test0_close(self):
        """"check for close working"""
        _cr = CommandReader(TestCommandreader.ui)
        if (_cr.atts['is_closed']):
            _cr.open()
        self.assertFalse(_cr.atts['is_closed'])
        _cr.close()
        self.assertTrue(_cr.atts['is_closed'])

    def test3_get(self):
        """testget

        """
        _cr = CommandReader(TestCommandreader.ui)
        try:
            _cr.open()
            lines = []

            while True:
                line = _cr.get()
                if line == "":
                    break
                lines.append(line)

            # should have read all lines from a stream so the stream should automatically
            # close
            self.assertTrue(_cr.atts['is_closed'])
            self.assertEqual(7, len(lines))
            lastline = lines[6]
            self.assertFalse(lastline.endswith("\n"))
            emptyline = lines[5]
            self.assertEqual("\n", emptyline)
            self.assertEqual("line 4\n", lines[3])

        finally:
            _cr.close()
            self.assertTrue(_cr.atts['is_closed'])
 def test_select_controller(self):
     self.assertFalse(knowncontrollers.select_controller(''))
     self.assertFalse(knowncontrollers.select_controller('junk'))
     ctrltup = knowncontrollers.select_controller('dlx2')
     self.assertEqual('dlxii', ctrltup[0])
     self.assertTrue(isinstance(ctrltup[1], dlxii.Device))