Esempio n. 1
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()
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()
Esempio 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)))

        # 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()
Esempio n. 4
0
    # Finally read back the newly written data from the EEPROM
    writeData = [0xF0, 0x00, 0x00]
    readCount = 4
    rxData, status = binho.oneWire.transfer(writeData, readCount, command="SKIP")

    if status:
        rcvdBytes = "Read from EEPROM - Resp: {} byte(s):\t".format(len(rxData))
        for byte in rxData:
            rcvdBytes += "\t " + "0x{:02x}".format(byte)

        print(rcvdBytes)
    else:
        print("5. Read Back From EEPROM Failed!")

    print()
    print("Finished!")


# It's generally bad practice to indiscriminately catch all exceptions, however the
# binho_error_handler() simply prints out all the debug info as the script terminates
# it does not try to continue execution under any circumstances
except Exception:

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

finally:

    # close the connection to the host adapter
    binho.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()
Esempio n. 6
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():

    # 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()
Esempio n. 8
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.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.")

        # 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)

    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()
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)

        # 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()
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()
Esempio n. 11
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 ValueError(
                "PWM Functionality is not supported on IO1 - please choose another pin!"
            )

        # get the desired pin
        pin = device.gpio.getPin(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 ValueError(
                        "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 ValueError(
                    "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 ValueError(
                    "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 ValueError(
                        "PWM value must be a number from 0 to 1023 (or 0% to 100%), not {}%"
                        .format(dutyCycle))

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

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

        # 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()