Exemplo n.º 1
0
def main():

    # Set up a simple argument parser.
    parser = binhoArgumentParser(
        description="Utility for SPI communication via Binho host adapter")
    parser.add_argument(
        "-r",
        "--read",
        default=0,
        help="Number of bytes expecting to receive from the SPI Bus",
    )
    parser.add_argument(
        "-w",
        "--write",
        nargs="*",
        type=ast.literal_eval,
        default=[],
        help="Bytes to send over the SPI Bus",
    )
    parser.add_argument("-f",
                        "--frequency",
                        default=None,
                        help="Set clock frequency")
    parser.add_argument("-c",
                        "--chipselect",
                        default=0,
                        help="Set CS signal IO pin")
    parser.add_argument(
        "-n",
        "--invertCS",
        action="store_true",
        help="Set CS signal as inverted (Active High)",
    )
    parser.add_argument("-m", "--mode", default=0, help="Set SPI mode")
    args = parser.parse_args()

    log_function = log_verbose if args.verbose else log_silent

    try:
        log_function("Trying to find a Binho host adapter...")
        device = parser.find_specified_device()

        if device.inBootloaderMode:
            print(
                "{} found on {}, but it cannot be used now because it's in DFU mode"
                .format(device.productName, device.commPort))
            sys.exit(errno.ENODEV)

        elif device.inDAPLinkMode:
            print(
                "{} found on {}, but it cannot be used now because it's in DAPlink mode"
                .format(device.productName, device.commPort))
            print("Tip: Exit DAPLink mode using 'binho daplink -q' command")
            sys.exit(errno.ENODEV)

        else:
            log_function("{} found on {}. (Device ID: {})".format(
                device.productName, device.commPort, device.deviceID))

    except DeviceNotFoundError:
        if args.serial:
            print(
                "No Binho host adapter found matching Device ID '{}'.".format(
                    args.serial),
                file=sys.stderr,
            )
        else:
            print("No Binho host adapter found!", file=sys.stderr)
        sys.exit(errno.ENODEV)

    # if we fail before here, no connection to the device was opened yet.
    # however, if we fail after this point, we need to make sure we don't
    # leave the serial port open.

    try:

        if args.write or int(args.read) > 0:

            if args.frequency:
                log_function("SPI clock set to {}Hz".format(args.frequency))

            if args.mode:

                if int(args.mode) < 0 or int(args.mode) > 3:
                    print(
                        "SPI mode must be 0, 1, 2, or 3. mode = {} is not a valid setting."
                        .format(args.mode))
                    device.close()
                    sys.exit(errno.EINVAL)
                else:
                    log_function("SPI mode set to mode {}".format(args.mode))

            csPin = {}

            if args.chipselect:
                if args.chipselect.isnumeric():
                    chipSelectStr = "IO" + str(args.chipselect)
                else:
                    chipSelectStr = args.chipselect

                csPin = device.gpio.getPin(chipSelectStr)
            else:
                csPin = None

            if csPin:
                if args.invertCS:
                    log_function(
                        "Using IO{} as an Active-High (inverted) ChipSelect signal"
                        .format(csPin.pinNumber))
                else:
                    log_function(
                        "Using IO{} as an Active-Low (standard) ChipSelect signal"
                        .format(csPin.pinNumber))
            else:
                log_function(
                    "No ChipSelect signal specified, will not be used for this transaction. Use -c to specify IO pin to\
                     use for ChipSelect if desired.")

            transmit(
                device,
                args.write,
                int(args.read),
                csPin,
                args.invertCS,
                args.mode,
                log_function,
            )

        else:
            log_function(
                "No transaction performed. Please specify data to write with '-w' or a number of bytes to read using \
                 '-r'.")
            log_function(
                "You can type 'binho spi --help' for more information.")

            # close the connection to the host adapter
            device.close()

    except Exception:  # pylint: disable=broad-except

        # Catch any exception that was raised and display it
        binho_error_hander()

    finally:

        # close the connection to the host adapter
        device.close()
Exemplo n.º 2
0
def main():

    # Set up a simple argument parser.
    parser = binhoArgumentParser(description="Utility for I2C communication via Binho host adapter")
    parser.add_argument(
        "-u", "--pullup", action="store_true", help="Enable 2.2k pullup resistors (3.3V)",
    )
    parser.add_argument("-f", "--frequency", default=None, help="Set clock frequency")
    parser.add_argument(
        "-a", "--address", nargs=1, type=ast.literal_eval, help="7-bit address for communication over the I2C Bus",
    )
    parser.add_argument(
        "-r", "--read", default=0, help="Number of bytes expecting to receive from the I2C Bus",
    )
    parser.add_argument(
        "-w", "--write", nargs="*", type=ast.literal_eval, default=[], help="Bytes to send over the I2C Bus",
    )
    parser.add_argument("-z", "--scan", action="store_true", help="Scan all possible i2c addresses")
    args = parser.parse_args()

    log_function = log_verbose if args.verbose else log_silent

    try:
        log_function("Trying to find a Binho host adapter...")
        device = parser.find_specified_device()

        if device.inBootloaderMode:
            print(
                "{} found on {}, but it cannot be used now because it's in DFU mode".format(
                    device.productName, device.commPort
                )
            )
            sys.exit(errno.ENODEV)

        elif device.inDAPLinkMode:
            print(
                "{} found on {}, but it cannot be used now because it's in DAPlink mode".format(
                    device.productName, device.commPort
                )
            )
            print("Tip: Exit DAPLink mode using 'binho daplink -q' command")
            sys.exit(errno.ENODEV)

        else:
            log_function("{} found on {}. (Device ID: {})".format(device.productName, device.commPort, device.deviceID))

    except DeviceNotFoundError:
        if args.serial:
            print(
                "No Binho host adapter found matching Device ID '{}'.".format(args.serial), file=sys.stderr,
            )
        else:
            print("No Binho host adapter found!", file=sys.stderr)
        sys.exit(errno.ENODEV)

    # if we fail before here, no connection to the device was opened yet.
    # however, if we fail after this point, we need to make sure we don't
    # leave the serial port open.

    try:

        device.operationMode = "I2C"

        if args.frequency:
            log_function("Setting I2C clock frequency to {}Hz".format(args.frequency))
            device.i2c.frequency = int(args.frequency)

        if args.pullup:
            log_function(
                "Engaging the internal 2.2kOhm PullUp resistors. (Pulled to 3.3V). Remove the '-u' flag to rely on "
                + "external resistors."
            )
            device.i2c.useInternalPullUps = True
        else:
            log_function(
                "Internal 2.2kOhm PullUp resistors are disengaged. Add the '-u' flag to engage the internal resistors."
            )
            device.i2c.useInternalPullUps = False

        if args.scan:
            if args.frequency:
                scan(device, args.pullup, [int(args.frequency)])
            else:
                scan(device, args.pullup, [100000, 400000, 1000000, 3200000])

        if args.write and args.read:
            transmit(device, args.address[0], args.write, int(args.read), log_function)
        elif args.write:
            write(device, args.address[0], args.write, log_function)
        elif args.read:
            read(device, args.address[0], int(args.read), log_function)
        else:
            if not args.scan:
                log_function(
                    "No transaction performed. Please specify data to write with '-w' or a number of bytes to read "
                    + "using '-r'."
                )
                log_function("You can type 'binho i2c --help' for more information.")

        # close the connection to the host adapter
        device.close()

    except Exception:  # pylint: disable=broad-except
        # Catch any exception that was raised and display it
        binho_error_hander()

        # close the connection to the host adapter
        device.close()
Exemplo n.º 3
0
def main():

    # Set up a simple argument parser.
    parser = binhoArgumentParser(description="Utility for experimenting with Binho host adapters on-board DAC")
    parser.add_argument(
        "-f",
        "--format",
        dest="format",
        type=str,
        default="voltage",
        choices=["voltage", "raw"],
        help="Format for the input.\nVoltage string, or binary value to be loaded into the DAC.",
    )
    parser.add_argument(
        "value",
        metavar="[value]",
        type=float,
        help="The desired voltage (default) or raw value to load into DAC (with -f raw).",
    )

    args = parser.parse_args()

    log_function = log_verbose if args.verbose else log_silent

    try:
        log_function("Trying to find a Binho host adapter...")
        device = parser.find_specified_device()

        if device.inBootloaderMode:
            print(
                "{} found on {}, but it cannot be used now because it's in DFU mode".format(
                    device.productName, device.commPort
                )
            )
            sys.exit(errno.ENODEV)

        elif device.inDAPLinkMode:
            print(
                "{} found on {}, but it cannot be used now because it's in DAPlink mode".format(
                    device.productName, device.commPort
                )
            )
            print("Tip: Exit DAPLink mode using 'binho daplink -q' command")
            sys.exit(errno.ENODEV)

        else:
            log_function("{} found on {}. (Device ID: {})".format(device.productName, device.commPort, device.deviceID))

    except DeviceNotFoundError:
        if args.serial:
            print(
                "No Binho host adapter found matching Device ID '{}'.".format(args.serial), file=sys.stderr,
            )
        else:
            print("No Binho host adapter found!", file=sys.stderr)
        sys.exit(errno.ENODEV)

    # if we fail before here, no connection to the device was opened yet.
    # however, if we fail after this point, we need to make sure we don't
    # leave the serial port open.

    try:

        pinNumber = device.dac.getDefaultDACPin()

        if args.format == "voltage":

            device.dac.setOutputVoltage(args.value)
            log_function("DAC channel {} set to {} Volts".format(pinNumber, args.value))

        else:
            device.dac.setOutputRaw(int(args.value))
            log_function("DAC channel {} set to {}".format(pinNumber, int(args.value)))

    finally:
        # close the connection to the host adapter
        device.close()
Exemplo n.º 4
0
def main():  # pylint: disable=too-many-locals

    # Set up a simple argument parser.
    parser = binhoArgumentParser(
        description="Utility for working with SPI FLASH memory devices")

    parser.add_argument("-c",
                        "--chipselect",
                        default=0,
                        help="Set CS signal IO pin")

    parser.add_argument(
        "-n",
        "--invertCS",
        action="store_true",
        help="Set CS signal as inverted (Active High)",
    )
    parser.add_argument("-m", "--mode", default=0, help="Set SPI mode")

    parser.add_argument(
        "-f",
        "--frequency",
        default=12000000,
        help="Specifies the frequency for the SPI Clock",
    )

    args = parser.parse_args()

    log_function = log_verbose if args.verbose else log_silent

    try:
        log_function("Trying to find a Binho host adapter...")
        device = parser.find_specified_device()

        if device.inBootloaderMode:
            print(
                "{} found on {}, but it cannot be used now because it's in DFU mode"
                .format(device.productName, device.commPort))
            sys.exit(errno.ENODEV)

        elif device.inDAPLinkMode:
            print(
                "{} found on {}, but it cannot be used now because it's in DAPlink mode"
                .format(device.productName, device.commPort))
            print("Tip: Exit DAPLink mode using 'binho daplink -q' command")
            sys.exit(errno.ENODEV)

        else:
            log_function("{} found on {}. (Device ID: {})".format(
                device.productName, device.commPort, device.deviceID))

    except DeviceNotFoundError:
        if args.serial:
            print(
                "No Binho host adapter found matching Device ID '{}'.".format(
                    args.serial),
                file=sys.stderr,
            )
        else:
            print("No Binho host adapter found!", file=sys.stderr)
        sys.exit(errno.ENODEV)

    # if we fail before here, no connection to the device was opened yet.
    # however, if we fail after this point, we need to make sure we don't
    # leave the serial port open.

    try:

        # set the host adapter operationMode to 'SPI'
        device.operationMode = "SPI"

        if args.frequency:
            log_function("SPI clock set to {}Hz".format(args.frequency))

        if args.mode:

            if int(args.mode) < 0 or int(args.mode) > 3:
                print(
                    "SPI mode must be 0, 1, 2, or 3. mode = {} is not a valid setting."
                    .format(args.mode))
                device.close()
                sys.exit(errno.EINVAL)
            else:
                log_function("SPI mode set to mode {}".format(args.mode))

        csPin = {}

        if args.chipselect:
            if args.chipselect.isnumeric():
                chipSelectStr = "IO" + str(args.chipselect)
            else:
                chipSelectStr = args.chipselect

            csPin = device.gpio_pins[chipSelectStr]
        else:
            csPin = None

        if csPin:
            if args.invertCS:
                log_function(
                    "Using IO{} as an Active-High (inverted) ChipSelect signal"
                    .format(csPin.pinNumber))
            else:
                log_function(
                    "Using IO{} as an Active-Low (standard) ChipSelect signal".
                    format(csPin.pinNumber))
        else:
            log_function(
                "No ChipSelect signal specified, will not be used for this transaction. Use -c to specify IO pin to\
                 use for ChipSelect if desired.")

        # Now that we've got the SPI CS pin configuration, let's go ahead and create the programmer object
        # This function accepts a number of parameters, not all shown or demo'd here
        # spiFlash = device.create_programmer(
        #    "spiFlash", chip_select_pin=csPin, autodetect=True, mode=args.mode,
        #    clocK_frequency=args.frequency
        # )

        print(
            "This command is still under construction. Please come back again later!"
        )
        sys.exit(1)

    finally:

        # close the connection to the host adapter
        device.close()
Exemplo n.º 5
0
def main():  # pylint: disable=too-many-statements

    # Set up a simple argument parser.
    parser = binhoArgumentParser(
        description="Convenience shell for working with Binho host adapters.")
    parser.add_argument(
        "-e",
        "--exec",
        metavar="code",
        type=str,
        help="Executes the provided code as though it were passed " +
        "to a Binho host adapter shell, and then terminates.",
        dest="code",
    )
    parser.add_argument(
        "-E",
        "--pre-exec",
        metavar="code",
        type=str,
        help="Executes the provided code as though it were passed " +
        "to a Binho host adapter shell, but does not explicitly terminate.",
        dest="prelude",
    )
    parser.add_argument(
        "-f",
        "--file",
        metavar="file",
        type=str,
        help="Executes the relevant file before starting the given shell.",
    )
    parser.add_argument(
        "-M",
        "--automagic",
        dest="automagic",
        action="store_true",
        help="Enable automagic, so lazy developers don't have to type %%.",
    )
    parser.add_argument(
        "-P",
        "--avoid-parens",
        dest="avoidparens",
        action="store_true",
        help=
        "Enable full autocall, so bare methods are executed, rather than printed.",
    )
    parser.add_argument(
        "-A",
        "--autoreload",
        dest="autoreload",
        action="store_true",
        help=
        "Attempts to reload python modules automatically as they change; so current objects import new \
              functionality. This may sometimes break your shell.",
    )
    parser.add_argument(
        "-S",
        "--singleton",
        dest="singleton",
        action="store_true",
        help=
        "Connect via a singleton that persists across device reconnects. Note: device state is not preserved.",
    )

    args = parser.parse_args()

    if args.singleton:
        connect_function = parser.get_singleton_for_specified_device
    else:
        connect_function = parser.find_specified_device

    binho = connect_function()

    if binho.inBootloaderMode:
        print(
            "{} found on {}, but it cannot be used now because it's in DFU mode"
            .format(binho.productName, binho.commPort))
        sys.exit(errno.ENODEV)

    elif binho.inDAPLinkMode:
        print(
            "{} found on {}, but it cannot be used now because it's in DAPlink mode"
            .format(binho.productName, binho.commPort))
        print("Tip: Exit DAPLink mode using 'binho daplink -q' command")
        sys.exit(errno.ENODEV)

    # Break into IPython for the shell.
    if not args.code:
        print(
            "Spawning an IPython shell for easy access to your Binho host adapter."
        )
        print(
            "Like normal python, you can use help(object) to get help for that object.\n"
        )

        print(
            "Try help(binho.gpio) to see the documentation for the Binho host adapter GPIO;"
        )
        print(
            "try dir(binho) to see a list of properties on the Binho Host Adapter object, and"
        )
        print(
            "try binho.available_interfaces() and binho.available_programmers() to see"
        )
        print(
            "the interfaces you can work with, and the programmers you can create.\n"
        )

        singleton_text = "singleton " if args.singleton else ""
        print(
            "A Binho host adapter {}object has been created for you as 'binho'. Have fun!\n"
            .format(singleton_text))

    # Create a new shell, and give it access to our created Binho object.
    shell = TerminalInteractiveShell()
    shell.push("binho")

    # Create nice aliases for our primary interfaces.
    # pylint: disable=unused-variable
    i2c = binho.i2c
    spi = binho.spi
    dac = binho.dac
    adc = binho.adc
    oneWire = binho.oneWire
    # uart = binho.uart
    gpio = binho.gpio
    # shell.push(('i2c', 'spi', 'adc', 'uart', 'gpio',))
    shell.push(("i2c", "spi", "gpio", "dac", "adc", "oneWire"))
    # pylint: enable=unused-variable

    # Make the autoreload extension available.
    shell.extension_manager.load_extension("autoreload")

    # Add our magic commands, to make execution more 'fun'.
    shell.register_magics(binhoShellMagics)

    # If the user has requested automagic, let them have their automagic.
    if args.automagic:
        shell.automagic = True

    # If we're in avoid parenthesis mode
    if args.avoidparens:
        shell.autocall = 2

    # If we're using autoreload, enable that.
    if args.autoreload:
        shell.run_cell("%autoreload 2")
        print(
            "Heads up: you've enabled autoreload. Things make break in unexpected ways as your code changes."
        )
        print(
            "You can fix this by adjusting your expectations regarding breakage.\n"
        )

    # Handle any inline execution requested.
    if args.code or args.prelude:

        # Replace any ;'s with newlines, so we can execute more than one
        # statement.
        code = args.code or args.prelude
        code = re.sub(r";\s*", "\n", code)
        lines = code.split("\n")

        # If we're in execute-and-quit mode, do so.

        for line in lines:
            shell.run_cell(line, shell_futures=True)

        # If we're to exit after running the relevant code, do so.
        if args.code:
            sys.exit(0)

    # If we have a file to execute, execute it.
    if args.file:
        shell.safe_execfile_ipy(args.file,
                                shell_futures=True,
                                raise_exceptions=True)

    # Run the shell itself.
    shell.connect_function = connect_function
    shell.mainloop()

    # close the connection to the device
    binho.close()
Exemplo n.º 6
0
def main():

    # Set up a simple argument parser.
    parser = binhoArgumentParser(
        description="Utility for 1-Wire communication via Binho host adapter")
    parser.add_argument("-n",
                        "--iopin",
                        default=0,
                        help="Use the given IO pin number for the 1Wire bus")
    parser.add_argument("-u",
                        "--pullup",
                        action="store_true",
                        help="Enable 2.2k pullup resistor (3.3V)")
    parser.add_argument(
        "-r",
        "--read",
        default=0,
        help="Number of bytes expecting to receive from the 1Wire Bus",
    )
    parser.add_argument(
        "-w",
        "--write",
        nargs="*",
        type=ast.literal_eval,
        default=[],
        help="Bytes to send over the 1Wire Bus",
    )
    parser.add_argument("-k",
                        "--skip",
                        action="store_true",
                        help="SKIP device selection")
    parser.add_argument("-z", "--search", action="store_true", help="Search")
    args = parser.parse_args()

    log_function = log_verbose if args.verbose else log_silent

    try:
        log_function("Trying to find a Binho host adapter...")
        device = parser.find_specified_device()

        if device.inBootloaderMode:
            print(
                "{} found on {}, but it cannot be used now because it's in DFU mode"
                .format(device.productName, device.commPort))
            sys.exit(errno.ENODEV)

        elif device.inDAPLinkMode:
            print(
                "{} found on {}, but it cannot be used now because it's in DAPlink mode"
                .format(device.productName, device.commPort))
            print("Tip: Exit DAPLink mode using 'binho daplink -q' command")
            sys.exit(errno.ENODEV)

        else:
            log_function("{} found on {}. (Device ID: {})".format(
                device.productName, device.commPort, device.deviceID))

    except DeviceNotFoundError:
        if args.serial:
            print(
                "No Binho host adapter found matching Device ID '{}'.".format(
                    args.serial),
                file=sys.stderr,
            )
        else:
            print("No Binho host adapter found!", file=sys.stderr)
        sys.exit(errno.ENODEV)

    # if we fail before here, no connection to the device was opened yet.
    # however, if we fail after this point, we need to make sure we don't
    # leave the serial port open.

    try:

        device.oneWire.begin(args.iopin, args.pullup)

        if args.search:
            address = device.oneWire.search()

            full_addr = "0x"
            for byte in address:
                full_addr += "{:02x}".format(byte)

            log_function(
                "Search discovered device with address = {}".format(full_addr))

        if args.write and args.read:
            transfer(device, args.skip, args.write, int(args.read),
                     log_function)
        elif args.write:
            write(device, args.skip, args.write, log_function)
        elif args.read:
            read(device, args.skip, int(args.read), log_function)

    finally:
        # close the connection to the host adapter
        device.close()
Exemplo n.º 7
0
def main():

    # Set up a simple argument parser.
    parser = binhoArgumentParser(description="utility for updating firmware on Binho host adapters")

    parser.add_argument(
        "-q", "--quit", action="store_true", help="Exit DFU mode, return to normal operation.",
    )

    parser.add_argument(
        "-b",
        "--btldr",
        action="store_true",
        help="Enter DFU mode. Note that this will be done automatically during firmware upgrade commands.",
    )

    parser.add_argument(
        "-l",
        "--latest",
        action="store_true",
        help="Update the firmware of the target device to the latest release available",
    )

    parser.add_argument(
        "-r", "--release", default=None, help="Update the firmware of the desired device to a specific release version",
    )

    args = parser.parse_args()

    log_function = log_verbose if args.verbose else log_silent

    try:

        log_function("Trying to find a Binho host adapter...")
        device = parser.find_specified_device()

        log_function("{} found on {}. (Device ID: {})".format(device.productName, device.commPort, device.deviceID))

    except DeviceNotFoundError:
        if args.serial:
            print(
                "No Binho host adapter found matching Device ID '{}'.".format(args.serial), file=sys.stderr,
            )
        else:
            print("No Binho host adapter found!", file=sys.stderr)
        sys.exit(errno.ENODEV)

    # if we fail before here, no connection to the device was opened yet.
    # however, if we fail after this point, we need to make sure we don't
    # leave the serial port open.

    try:

        if args.quit:

            if device.inBootloaderMode:

                log_function("Exiting bootloader...")
                device.exit_bootloader()
                log_function("Completed!")

            elif device.inDAPLinkMode:

                log_function("{} is not in bootloader, cannot exit!".format(device.productName))
                log_function("Note: You can exit DAPLink mode using the 'binho daplink -q' command.")

            else:

                log_function("{} is not in bootloader, cannot exit!".format(device.productName))
                log_function("Note: You can enter bootloader mode using the 'binho dfu' command.")

        elif args.btldr:

            if device.inBootloaderMode:

                log_function(
                    "{}:{} on {} is already in it's bootloader".format(
                        device.productName, device.deviceID, device.commPort
                    )
                )

            else:
                log_function("Resetting {} into it's bootloader".format(device.productName))
                binhoDFUManager.switchToBootloader(device)
                log_function("Bootloader Details:")
                log_function("Version: {}".format(binhoDFUManager.bootloaderInfo["version"]))
                log_function("Model: {}".format(binhoDFUManager.bootloaderInfo["model"]))
                log_function("BoardID: {}".format(binhoDFUManager.bootloaderInfo["boardID"]))
                log_function("Completed!")

        else:

            if args.latest and args.release:
                print("Invalid arguments. -l/--latest cannot be used with -r/--release")
                sys.exit(1)

            if args.latest:

                log_function("Getting latest firmware release...")
                latestVersion = binhoDFUManager.getLatestFirmwareVersion(device.FIRMWARE_UPDATE_URL)
                log_function("Latest Version: {}".format(latestVersion))

                if device.firmwareVersion == latestVersion:

                    print("This {} is already running the latest firmware.".format(device.productName))

                else:

                    log_function("Updating device...")
                    binhoDFUManager.switchToNormal(device)
                    log_function("Firmware Update Complete!")

            elif args.release:

                if device.firmwareVersion == args.release:
                    print(
                        "This {} is already running firmware version {}.".format(
                            device.productName, device.firmwareVersion
                        )
                    )

                else:

                    log_function("Looking for {} Release...".format(args.release))
                    is_available = binhoDFUManager.isFirmwareVersionAvailable(device.FIRMWARE_UPDATE_URL, args.release)

                    if not is_available:
                        print("{} is not available.".format(args.release))
                        sys.exit(1)

                    log_function("Found it. Preparing to update device.")

                    binhoDFUManager.switchToNormal(device, args.release)
                    log_function("Firmware Update Complete!")

            device.close()

    except Exception:  # pylint: disable=broad-except
        # Catch any exception that was raised and display it
        binho_error_hander()

        # close the connection to the host adapter
        device.close()
def main():  # pylint: disable=too-many-locals

    # Set up a simple argument parser.
    parser = binhoArgumentParser(description="Utility for working with I2C EEPROMs")
    parser.add_argument(
        "-u", "--pullup", action="store_true", help="Enable 2.2k pullup resistors (3.3V)",
    )

    parser.add_argument(
        "-n",
        "--partnumber",
        default=None,
        help="Look up device parameters based on EEPROM manufacturer part number. These parameters can be provided \
              individually.",
    )

    parser.add_argument(
        "-f", "--frequency", default=400000, help="Max supported clock frequency of the EEPROM",
    )
    parser.add_argument(
        "-a",
        "--address",
        default=0,
        help="Offset from base address set on pins A0-A2, if present on package. Defaults to 0b000",
    )
    parser.add_argument("-c", "--capacity", default=None, type=int, help="EEPROM capacity in bytes")
    parser.add_argument("-t", "--writetime", default=0.005, type=float, help="EEPROM write cycle time")
    parser.add_argument(
        "-m",
        "--bitmask",
        default="AAA",
        help="Bitmask to determine how to use lowest three bits of EEPROM I2C Address",
    )
    parser.add_argument("-g", "--pagesize", default=None, type=int, help="EEPROM page size in bytes")

    parser.add_argument(
        "-b",
        "--blank",
        action="store_true",
        help="Check if the EEPROM is blank. No other operation will be performed.",
    )
    parser.add_argument("-e", "--erase", action="store_true", help="Erase the EEPROM before writing")
    parser.add_argument(
        "-y", "--verify", action="store_true", help="Verify the EEPROM contents after writing",
    )

    parser.add_argument(
        "-r", "--read", default=None, type=str, help="Read EEPROM data and save it to the provided file",
    )
    parser.add_argument(
        "-w", "--write", default=None, type=str, help="Write the data from the provided file to the EEPROM",
    )

    args = parser.parse_args()

    log_function = log_verbose if args.verbose else log_silent

    try:
        log_function("Trying to find a Binho host adapter...")
        device = parser.find_specified_device()

        if device.inBootloaderMode:
            print(
                "{} found on {}, but it cannot be used now because it's in DFU mode".format(
                    device.productName, device.commPort
                )
            )
            sys.exit(errno.ENODEV)

        elif device.inDAPLinkMode:
            print(
                "{} found on {}, but it cannot be used now because it's in DAPlink mode".format(
                    device.productName, device.commPort
                )
            )
            print("Tip: Exit DAPLink mode using 'binho daplink -q' command")
            sys.exit(errno.ENODEV)

        else:
            log_function("{} found on {}. (Device ID: {})".format(device.productName, device.commPort, device.deviceID))

    except DeviceNotFoundError:
        if args.serial:
            print(
                "No Binho host adapter found matching Device ID '{}'.".format(args.serial), file=sys.stderr,
            )
        else:
            print("No Binho host adapter found!", file=sys.stderr)
        sys.exit(errno.ENODEV)

    # if we fail before here, no connection to the device was opened yet.
    # however, if we fail after this point, we need to make sure we don't
    # leave the serial port open.

    try:

        t0 = time.time()  # pylint: disable=unused-variable

        ih = IntelHex()  # pylint: disable=unused-variable
        programmer = []  # pylint: disable=unused-variable
        device.operationMode = "I2C"

        if args.partnumber:
            # programmer = device.create_programmer('eeprom', device='24FC512')
            log_function("Using predefined parameters for EEPROM part number {}".format(args.partnumber.upper()))
            programmer = device.create_programmer("eeprom", device=args.partnumber.upper())

        elif args.frequency and args.capacity and args.writetime and args.bitmask and args.pagesize:
            log_function("EEPROM manually defined:")
            log_function(
                "Max Clock Frequency: {}, Base Address Offset: {}, Bitmask: {}".format(
                    args.frequency, args.address, args.bitmask
                )
            )
            log_function(
                "Capacity: {} bytes, Page Size: {} bytes, Write Cycle Time: {} s".format(
                    args.capacity, args.pagesize, args.writetime
                )
            )

            programmer = device.create_programmer(
                "eeprom",
                args.capacity,
                args.pagesize,
                bitmask=str(args.bitmask),
                slave_address=args.address,
                write_cycle_length=args.writetime,
            )

        else:
            log_function("EEPROM part number not provided, parameters must be manually supplied.")
            log_function("Flags -f, -a, -c, -t, -m, -g should be used to supply the device parameters")
            log_function("when the device part number cannot be used.")
            device.close()
            sys.exit(1)

        log_function("")

        if args.pullup:
            log_function(
                "Engaging the internal 2.2kOhm PullUp resistors. (Pulled to 3.3V). Remove the '-u' flag to rely on "
                "external resistors."
            )
            device.i2c.useInternalPullUps = True
        else:
            log_function(
                "Internal 2.2kOhm PullUp resistors are disengaged. Add the '-u' flag to engage the internal resistors."
            )
            device.i2c.useInternalPullUps = False

        log_function("")

        if args.read and args.write:
            log_function(
                "Cannot perform read and write in the same operation! Please perform these operations separately"
            )
            device.close()
            sys.exit(1)

        if args.verify and not args.write:
            log_function("Cannot perform verify without writing a file at this time.")
            device.close()
            sys.exit(1)

        if args.blank:
            log_function("Checking if the EEPROM is blank...")
            t_start = time.time()
            isBlank = programmer.blankCheck()
            t_stop = time.time()
            elapsedTime = "%.3f" % (t_stop - t_start)

            if isBlank:
                log_function("EEPROM is blank! Elapsed time: {} seconds".format(elapsedTime))
                device.close()
                sys.exit(0)
            else:
                log_function("EEPROM is NOT blank! Elapsed time: {} seconds".format(elapsedTime))
                device.close()
                sys.exit(1)

        if args.erase:
            log_function("Erasing the EEPROM...")
            te_start = time.time()
            programmer.erase()
            te_stop = time.time()
            elapsedTime = "%.3f" % (te_stop - te_start)
            log_function("EEPROM Erase completed! Elapsed time: {} seconds".format(elapsedTime))

        if args.read:
            filename, file_extension = os.path.splitext(args.read)  # pylint: disable=unused-variable

            fileFormat = "bin"
            if file_extension == ".hex":
                fileFormat = "hex"

            log_function("Reading from the EEPROM...")
            tr_start = time.time()
            programmer.readToFile(args.read, format=fileFormat)
            tr_stop = time.time()
            elapsedTime = "%.3f" % (tr_stop - tr_start)
            log_function("EEPROM Read completed! Elapsed time: {} seconds".format(elapsedTime))
            log_function("EEPROM Data saved as {} file to : {}".format(fileFormat, args.read))

        if args.write:

            filename, file_extension = os.path.splitext(args.write)

            fileFormat = "bin"
            if file_extension == ".hex":
                fileFormat = "hex"

            log_function("Writing Data to EEPROM from {} file: {}".format(fileFormat, args.write))
            tw_start = time.time()
            programmer.writeFromFile(args.write, format=fileFormat)
            tw_stop = time.time()
            elapsedTime = "%.3f" % (tw_stop - tw_start)
            log_function("EEPROM Write completed! Elapsed time: {} seconds".format(elapsedTime))

        if args.verify:

            log_function("Verifying Data written to EEPROM from {} file: {}".format(fileFormat, args.write))
            ty_start = time.time()
            programmer.verifyFile(args.write, format=fileFormat)
            ty_stop = time.time()
            elapsedTime = "%.3f" % (ty_stop - ty_start)
            log_function("EEPROM Verify completed! Elapsed time: {} seconds".format(elapsedTime))

        # close the connection to the host adapter
        device.close()

    except Exception:  # pylint: disable=broad-except
        # Catch any exception that was raised and display it
        binho_error_hander()

        # close the connection to the host adapter
        device.close()
Exemplo n.º 9
0
def main():

    # Set up a simple argument parser.
    parser = binhoArgumentParser(
        description="utility for reading from Binho host adapter's ADC")
    parser.add_argument(
        "-f",
        "--format",
        dest="format",
        type=str,
        default="voltage",
        choices=["voltage", "raw"],
        help=
        "Format to output in.\nVoltage string, or raw fraction returned by the ADC.",
    )
    parser.add_argument(
        "-s",
        "--samples",
        dest="sample_count",
        type=int,
        default=1,
        help="The number of samples to read. (default: 1)",
    )
    parser.add_argument("-n",
                        "--iopin",
                        default=0,
                        help="Use the given IO pin number for the ADC input")

    args = parser.parse_args()

    log_function = log_verbose if args.verbose else log_silent

    try:
        log_function("Trying to find a Binho host adapter...")
        device = parser.find_specified_device()

        if device.inBootloaderMode:
            print(
                "{} found on {}, but it cannot be used now because it's in DFU mode"
                .format(device.productName, device.commPort))
            sys.exit(errno.ENODEV)

        elif device.inDAPLinkMode:
            print(
                "{} found on {}, but it cannot be used now because it's in DAPlink mode"
                .format(device.productName, device.commPort))
            print("Tip: Exit DAPLink mode using 'binho daplink -q' command")
            sys.exit(errno.ENODEV)

        else:
            log_function("{} found on {}. (Device ID: {})".format(
                device.productName, device.commPort, device.deviceID))

    except serial.SerialException:
        print(
            "The target Binho host adapter was found, but failed to connect because another application already has an\
             open connection to it.")
        print(
            "Please close the connection in the other application and try again."
        )
        sys.exit(errno.ENODEV)

    except DeviceNotFoundError:
        if args.serial:
            print(
                "No Binho host adapter found matching Device ID '{}'.".format(
                    args.serial),
                file=sys.stderr,
            )
        else:
            print("No Binho host adapter found!", file=sys.stderr)
        sys.exit(errno.ENODEV)

    # if we fail before here, no connection to the device was opened yet.
    # however, if we fail after this point, we need to make sure we don't
    # leave the serial port open.

    try:
        adcPin = {}

        if args.iopin:
            if args.iopin.isnumeric():
                adcPin = "IO" + str(args.iopin)
            else:
                adcPin = args.iopin.upper()
        else:
            adcPin = device.adc.getDefaultADCPin()

        if args.sample_count == 0:
            raise CapabilityError(
                "Cannot take 0 samples! Samples must be >= 1.")
        if args.sample_count > 1:
            log_function("Taking {} samples...".format(args.sample_count))
        else:
            log_function("Taking {} sample...".format(args.sample_count))

        log_function("")

        samples = []

        for x in range(args.sample_count):

            if args.format == "voltage":

                sample = device.adc.readInputVoltage(adcPin)
                log_function("[{}] ADC channel {} reads {} Volts".format(
                    x + 1, adcPin, sample))

            else:
                sample = device.adc.readInputRaw(adcPin)
                log_function("[{}] ADC channel {} reads {}".format(
                    x + 1, adcPin, sample))

            samples.append(sample)

        log_function("")

        if args.format == "voltage":
            log_function(
                "Stats: Min = {} V, Mean = {} V, Max = {} V, Range = {} V (n = {})"
                .format(
                    min(samples),
                    statistics.mean(samples),
                    max(samples),
                    "%.3f" % (max(samples) - min(samples)),
                    len(samples),
                ))
        else:
            log_function(
                "Stats: Min = {}, Mean = {}, Max = {}, Range = {} (n = {})".
                format(
                    min(samples),
                    statistics.mean(samples),
                    max(samples),
                    "%.3f" % (max(samples) - min(samples)),
                    len(samples),
                ))

    finally:
        # close the connection to the host adapter
        device.close()
Exemplo n.º 10
0
def main():

    # Set up a simple argument parser.
    parser = binhoArgumentParser(
        description="utility for reading from Binho host adapter's ADC")
    parser.add_argument(
        "-f",
        "--frequency",
        default=None,
        help="Set PWM frequency from 750Hz to 80000Hz",
    )
    parser.add_argument("-n",
                        "--iopin",
                        default=0,
                        help="Provide the IO pin to use for the pwm output")
    parser.add_argument(
        "value",
        metavar="[value]",
        help=
        "The desired duty cycle or raw value to load into the pwm generator.",
    )

    args = parser.parse_args()

    log_function = log_verbose if args.verbose else log_silent

    try:
        log_function("Trying to find a Binho host adapter...")
        device = parser.find_specified_device()

        if device.inBootloaderMode:
            print(
                "{} found on {}, but it cannot be used now because it's in DFU mode"
                .format(device.productName, device.commPort))
            sys.exit(errno.ENODEV)

        elif device.inDAPLinkMode:
            print(
                "{} found on {}, but it cannot be used now because it's in DAPlink mode"
                .format(device.productName, device.commPort))
            print("Tip: Exit DAPLink mode using 'binho daplink -q' command")
            sys.exit(errno.ENODEV)

        else:
            log_function("{} found on {}. (Device ID: {})".format(
                device.productName, device.commPort, device.deviceID))

    except serial.SerialException:
        print(
            "The target Binho host adapter was found, but failed to connect because another application already has an \
             open connection to it.")
        print(
            "Please close the connection in the other application and try again."
        )
        sys.exit(errno.ENODEV)

    except DeviceNotFoundError:
        if args.serial:
            print(
                "No Binho host adapter found matching Device ID '{}'.".format(
                    args.serial),
                file=sys.stderr,
            )
        else:
            print("No Binho host adapter found!", file=sys.stderr)
        sys.exit(errno.ENODEV)

    # if we fail before here, no connection to the device was opened yet.
    # however, if we fail after this point, we need to make sure we don't
    # leave the serial port open.

    try:

        device.operationMode = "IO"

        pin = {}

        if args.iopin:
            if args.iopin.isnumeric():
                pinStr = "IO" + str(args.iopin)
            else:
                pinStr = args.iopin.upper()
        else:
            pinStr = "IO0"

        # Will need to clean this up later to support other products
        # however, will need to do some plumbing to make that work, don't want it to delay the
        # initial release of this library
        if pinStr == "IO1":
            raise CapabilityError(
                "PWM Functionality is not supported on IO1 - please choose another pin!"
            )

        # get the desired pin
        pin = device.gpio_pins[pinStr]

        # set the pin mode
        pin.mode = "PWM"
        log_function("Configuring {} for PWM output".format(pinStr))

        if args.frequency:
            if args.frequency.isnumeric():

                targetFreq = int(args.frequency)
                if targetFreq < 750 or targetFreq > 80000:
                    raise CapabilityError(
                        "PWM Frequency must be a number from 750 to 80000 (Hz), not {}"
                        .format(args.frequency))

                pin.pwmFreq = targetFreq
                log_function("Setting PWM Frequency to {} Hz".format(
                    args.frequency))
            else:
                raise CapabilityError(
                    "PWM Frequency must be a number from 750 to 80000 (Hz), not {}"
                    .format(args.frequency))

        if args.value.isnumeric():

            if 0 <= int(args.value) <= 1024:

                pin.value = args.value
                log_function(
                    "Setting PWM output to {} (~{}% duty cycle)".format(
                        args.value, "%.1f" % (int(args.value) / 1024 * 100.0)))

            else:
                raise CapabilityError(
                    "PWM value must be a number from 0 to 1023 (or 0% to 100%), not {}"
                    .format(args.value))

        elif "%" in args.value:

            dutyCycle = args.value.strip("%")

            if dutyCycle.isnumeric():

                convValue = float(dutyCycle) / 100.0 * 1024

                if 0 <= int(convValue) <= 1024:

                    pin.value = int(convValue)
                    log_function(
                        "Setting PWM output to {} (~{}% duty cycle)".format(
                            int(convValue),
                            "%.1f" % (int(convValue) / 1024 * 100.0)))

                else:
                    raise CapabilityError(
                        "PWM value must be a number from 0 to 1023 (or 0% to 100%), not {}%"
                        .format(dutyCycle))

            else:
                raise CapabilityError(
                    "PWM value must be a number from 0 to 1023 (or 0% to 100%), not {}"
                    .format(args.value))

        else:
            raise CapabilityError(
                "PWM value must be a number from 0 to 1023 (or 0% to 100%), not {}"
                .format(args.value))

    finally:
        # close the connection to the host adapter
        device.close()
Exemplo n.º 11
0
def main():

    # Set up a simple argument parser.
    parser = binhoArgumentParser(
        description=
        "utility for using supported Binho host adapters in DAPLink mode to flash code to MCUs"
    )

    parser.add_argument("-t",
                        "--target",
                        default=None,
                        help="Manufacturer part number of target device")

    parser.add_argument("-f",
                        "--file",
                        default=None,
                        help="Path to binary file to program")

    parser.add_argument(
        "-e",
        "--erase",
        action="store_true",
        help="Perform chip-erase before programming",
    )

    parser.add_argument(
        "-r",
        "--reset",
        action="store_true",
        help="Reset the device after programming completes",
    )

    args = parser.parse_args()

    log_function = log_verbose if args.verbose else log_silent

    log_function("Checking for pyOCD...")

    try:
        import pyocd  # pylint: disable=import-outside-toplevel

    except ModuleNotFoundError:

        print(
            "PyOCD must be installed for this to work. Use 'pip install pyocd' to install the module."
        )
        sys.exit(1)

    log_function("pyOCD installation confirmed!")

    try:

        log_function("Trying to find a Binho host adapter...")
        device = parser.find_specified_device()

        if device.inDAPLinkMode:
            log_function(
                "{} found on {} in DAPLink mode (Device ID: {})".format(
                    device.productName, device.commPort, device.deviceID))

        else:
            log_function("{} found on {}. (Device ID: {})".format(
                device.productName, device.commPort, device.deviceID))

            print(
                "The {} is not in DAPLink mode. Please use the 'binho daplink' command "
            )
            sys.exit(errno.ENODEV)

    except DeviceNotFoundError:
        if args.serial:
            print(
                "No Binho host adapter found matching Device ID '{}'.".format(
                    args.serial),
                file=sys.stderr,
            )
        else:
            print("No Binho host adapter found!", file=sys.stderr)
        sys.exit(errno.ENODEV)

    # if we fail before here, no connection to the device was opened yet.
    # however, if we fail after this point, we need to make sure we don't
    # leave the serial port open.

    try:

        if not args.file and not (args.erase or args.reset):
            print("No binary file to program was supplied.")
            sys.exit(1)

        erase_setting = "auto"
        target_override = "cortex_m"

        if args.erase:
            erase_setting = "chip"

        if args.target:
            target_override = args.target

        if args.verbose:
            logging.basicConfig(level=logging.INFO)
        else:
            logging.basicConfig(level=logging.WARNING)

        with ConnectHelper.session_with_chosen_probe(
                target_override=target_override,
                chip_erase=erase_setting,
                smart_flash="false",
        ) as session:

            board = session.board
            target = board.target

            print("Vendor: {}\tPart Number: {}".format(target.vendor,
                                                       target.part_number))

            if args.erase:
                eraser = FlashEraser(session, FlashEraser.Mode.CHIP)
                eraser.erase()
                print("{} erased".format(target.part_number))

            if args.file:
                FileProgrammer(session).program(args.file)
                log_function("Target {} programmed with {}".format(
                    target.part_number, args.file))

            if args.reset:
                target.reset()
                print("Target {} reset".format(target.part_number))

    except pyocd.core.exceptions.TransferError:

        print(
            "Problem communicating with the target MCU. Please make sure SWDIO, SWCLK, and GND are properly "
            " connected and the MCU is powered up.")

    finally:

        # close the connection to the host adapter
        device.close()
Exemplo n.º 12
0
def main():

    # Set up a simple argument parser.
    parser = binhoArgumentParser(
        description="Sample template for creating custom Binho commands")
    parser.add_argument("-n",
                        "--iopin",
                        default=0,
                        help="Get an IO pin from the command arguments")

    # run the argument parser
    args = parser.parse_args()

    # setup logging - this will be printed to the consoled if the '-v' flag
    # was passed as an argument
    log_function = log_verbose if args.verbose else log_silent

    # Now try to find the desired device based on the arguments
    # wrap this in a try/except trap to handle failures gracefully
    try:
        log_function("Trying to find a Binho host adapter...")
        device = parser.find_specified_device()

        if device.inBootloaderMode:
            print(
                "{} found on {}, but it cannot be used now because it's in DFU mode"
                .format(device.productName, device.commPort))
            sys.exit(errno.ENODEV)

        elif device.inDAPLinkMode:
            print(
                "{} found on {}, but it cannot be used now because it's in DAPlink mode"
                .format(device.productName, device.commPort))
            print("Tip: Exit DAPLink mode using 'binho daplink -q' command")
            sys.exit(errno.ENODEV)

        else:
            log_function("{} found on {}. (Device ID: {})".format(
                device.productName, device.commPort, device.deviceID))

    except DeviceNotFoundError:
        if args.serial:
            print(
                "No Binho host adapter found matching Device ID '{}'.".format(
                    args.serial),
                file=sys.stderr,
            )
        else:
            print("No Binho host adapter found!", file=sys.stderr)
        sys.exit(errno.ENODEV)

    # if we fail before here, no connection to the device was opened yet.
    # however, if we fail after this point, we need to make sure we don't
    # leave the serial port open.

    # use another try/except to elegantly deal with any errors in the custom
    # command logic, making sure the connection to the device is cleaned up
    try:

        # implement your custom command logic here
        # pylint: disable=unused-variable
        pin = {}

        if args.iopin:
            if args.iopin.isnumeric():
                pin = "IO" + str(args.iopin)
            else:
                pin = args.iopin.upper()
        else:
            pin = "IO0"
        # pylint: enable=unused-variable

        log_function("Taking {} samples...".format(args.sample_count))

    finally:
        # close the connection to the host adapter
        device.close()
def main():

    # Set up a simple argument parser.
    parser = binhoArgumentParser(description="utility for using supported Binho host adapters in DAPLink mode")

    parser.add_argument(
        "-q", "--quit", action="store_true", help="Quit DAPlink mode, return to host adapter mode",
    )

    args = parser.parse_args()

    log_function = log_verbose if args.verbose else log_silent

    try:

        log_function("Trying to find a Binho host adapter...")
        device = parser.find_specified_device()

        if device.inDAPLinkMode:
            log_function("{} found on {} in DAPLink mode".format(device.productName, device.commPort))

        else:
            log_function("{} found on {}. (Device ID: {})".format(device.productName, device.commPort, device.deviceID))

    except DeviceNotFoundError:
        if args.serial:
            print(
                "No Binho host adapter found matching Device ID '{}'.".format(args.serial), file=sys.stderr,
            )
        else:
            print("No Binho host adapter found!", file=sys.stderr)
        sys.exit(errno.ENODEV)

    # if we fail before here, no connection to the device was opened yet.
    # however, if we fail after this point, we need to make sure we don't
    # leave the serial port open.

    try:

        if device.inBootloaderMode:
            log_function(
                "{} is in DFU mode, exiting to application mode before continuing...".format(device.productName)
            )
            device.exit_bootloader()
            time.sleep(5)
            device = parser.find_specified_device()

        if args.quit:

            if device.inDAPLinkMode:

                log_function("Returning to host adapter mode... This will cause the device to reset.")
                binhoDFUManager.switchToNormal(device)
                log_function("Completed!")

            else:

                log_function("{} is not in DAPLink mode.".format(device.productName))

        else:

            if device.inDAPLinkMode:

                log_function("{} is already in DAPLink mode.".format(device.productName))

            else:

                log_function("Switching to DAPLink mode... This will cause the device to reset.")
                binhoDFUManager.switchToDAPLink(device)
                log_function("Completed!")

        device.close()

    except Exception:  # pylint: disable=broad-except
        # Catch any exception that was raised and display it
        binho_error_hander()

        # close the connection to the host adapter
        device.close()
Exemplo n.º 14
0
def main():

    # Set up a simple argument parser.
    parser = binhoArgumentParser(
        description="utility for controller Binho host adapter's GPIO pins")
    parser.add_argument(
        "-m",
        "--mode",
        dest="mode",
        type=str,
        default="DIN",
        choices=["DIN", "DOUT"],
        help="Set the mode of the IO pin",
    )
    parser.add_argument("-n",
                        "--iopin",
                        default=0,
                        help="Provide the IO pin to use for this operation")
    parser.add_argument("-o",
                        "--output",
                        default=None,
                        help="Set the output value")

    args = parser.parse_args()

    log_function = log_verbose if args.verbose else log_silent

    try:
        log_function("Trying to find a Binho host adapter...")
        device = parser.find_specified_device()

        if device.inBootloaderMode:
            print(
                "{} found on {}, but it cannot be used now because it's in DFU mode"
                .format(device.productName, device.commPort))
            sys.exit(errno.ENODEV)

        elif device.inDAPLinkMode:
            print(
                "{} found on {}, but it cannot be used now because it's in DAPlink mode"
                .format(device.productName, device.commPort))
            print("Tip: Exit DAPLink mode using 'binho daplink -q' command")
            sys.exit(errno.ENODEV)

        else:
            log_function("{} found on {}. (Device ID: {})".format(
                device.productName, device.commPort, device.deviceID))

    except DeviceNotFoundError:
        if args.serial:
            print(
                "No Binho host adapter found matching Device ID '{}'.".format(
                    args.serial),
                file=sys.stderr,
            )
        else:
            print("No Binho host adapter found!", file=sys.stderr)
        sys.exit(errno.ENODEV)

    # if we fail before here, no connection to the device was opened yet.
    # however, if we fail after this point, we need to make sure we don't
    # leave the serial port open.

    try:

        device.operationMode = "IO"

        pin = {}

        if args.iopin:
            if args.iopin.isnumeric():
                pinStr = "IO" + str(args.iopin)
            else:
                pinStr = args.iopin.upper()
        else:
            pinStr = "IO0"

        # get the desired pin
        pin = device.gpio.getPin(pinStr)

        # set the pin mode
        if args.output:
            pin.mode = "DOUT"

            if args.output.isnumeric():

                if int(args.output) == 0:
                    pin.value = 0
                elif int(args.output) == 1:
                    pin.value = 1
                else:
                    raise ValueError(
                        "Output can only be set to 0 or 1, not {}".format(
                            args.output))

                log_function("Configured {} as a digital output = {} ".format(
                    pinStr, int(args.output)))

            elif args.output.upper() == "HIGH":
                pin.value = 1
                log_function(
                    "Configured {} as a digital output and drove the signal {} "
                    .format(pinStr, args.output.upper()))
            elif args.output.upper() == "LOW":
                pin.value = 0
                log_function(
                    "Configured {} as a digital output and drove the signal {} "
                    .format(pinStr, args.output.upper()))
            else:
                raise ValueError(
                    "Output can only be set to LOW or HIGH, not {}".format(
                        args.output))

        else:

            pin.mode = "DIN"
            value = pin.value
            if value == 0:
                log_function("{} is 0 (LOW)".format(pinStr))
            elif value == 1:
                log_function("{} is 1 (HIGH)".format(pinStr))

        # close the connection to the host adapter
        device.close()

    except Exception:  # pylint: disable=broad-except
        # Catch any exception that was raised and display it
        binho_error_hander()

        # close the connection to the host adapter
        device.close()