Ejemplo n.º 1
0
def test_open_close():
    print("Starting open/close test...")

    # Open non-existent GPIO (export should fail with EINVAL)
    with AssertRaises(periphery.GPIOError):
        periphery.GPIO(9999, "in")

    # Open legitimate GPIO
    gpio = periphery.GPIO(pin_output, "in")
    assert gpio.pin == pin_output
    assert gpio.fd > 0

    # Set direction out, check direction out, check value low
    gpio.direction = "out"
    assert gpio.direction == "out"
    assert gpio.read() == False
    # Set direction low, check direction out, check value low
    gpio.direction = "low"
    assert gpio.direction == "out"
    assert gpio.read() == False
    # Set direction high, check direction out, check value high
    gpio.direction = "high"
    assert gpio.direction == "out"
    assert gpio.read() == True
    # Set direction in, check direction in
    gpio.direction = "in"
    assert gpio.direction == "in"

    # Set invalid direction
    with AssertRaises(ValueError):
        gpio.direction = "blah"
    # Set invalid edge
    with AssertRaises(ValueError):
        gpio.edge = "blah"

    # Check interrupt edge support
    assert gpio.supports_interrupts == True

    # Set edge none, check edge none
    gpio.edge = "none"
    assert gpio.edge == "none"
    # Set edge rising, check edge rising
    gpio.edge = "rising"
    assert gpio.edge == "rising"
    # Set edge falling, check edge falling
    gpio.edge = "falling"
    assert gpio.edge == "falling"
    # Set edge both, check edge both
    gpio.edge = "both"
    assert gpio.edge == "both"
    # Set edge none, check edge none
    gpio.edge = "none"
    assert gpio.edge == "none"

    gpio.close()

    print("Open/close test passed.")
Ejemplo n.º 2
0
def test_arguments():
    ptest()

    # Invalid open types
    with AssertRaises("invalid open types", TypeError):
        periphery.GPIO("abc", "out")
    with AssertRaises("invalid open types", TypeError):
        periphery.GPIO(100, 100)
    # Invalid direction
    with AssertRaises("invalid direction", ValueError):
        periphery.GPIO(100, "blah")
Ejemplo n.º 3
0
def test_arguments():
    print("Starting arguments test...")

    # Invalid open types
    with AssertRaises(TypeError):
        periphery.GPIO("abc", "out")
    with AssertRaises(TypeError):
        periphery.GPIO(100, 100)
    # Invalid direction
    with AssertRaises(ValueError):
        periphery.GPIO(100, "blah")

    print("Arguments test passed.")
Ejemplo n.º 4
0
def host_connect(request, board):
    """
    Return board and host pins that are wired together
    """
    # FIXME: Make it possible to overrride these
    pin = 'D5'
    gpionr = 17

    gpio = None

    sh.sudo.tee(sh.echo(gpionr), '/sys/class/gpio/export')
    time.sleep(0.5)

    def teardown():
        if gpio:
            gpio.close()
        sh.sudo.tee(sh.echo(gpionr), '/sys/class/gpio/unexport')

    request.addfinalizer(teardown)

    gpio = periphery.GPIO(gpionr)
    gpio.direction = 'in'

    if check_host_connect(board, gpio, pin):
        return gpio, pin
    else:
        return None
Ejemplo n.º 5
0
 def configure_device(self, spi_mode, order, bits):
     """
     Configure the SPI device and GPIOs for communication with target
     """
     self.reset_pin = periphery.GPIO(self.gpio_reset, 'out')
     self.wake_pin = periphery.GPIO(self.gpio_wake, 'out')
     self.irq_pin = periphery.GPIO(self.gpio_irq, 'in')
     self.spi = periphery.SPI(self.spi_device, spi_mode,
                              self.spi_speed * 1e6)
     self.spi.bit_order = order
     self.spi.bits_per_word = bits
     print('Configured SPI %s for %s.' % (self.spi_device, self.name))
     print('Configured GPIO %d for %s Reset.' %
           (self.gpio_reset, self.name))
     print('Configured GPIO %d for %s Wake.' % (self.gpio_wake, self.name))
     print('Configured GPIO %d for %s IRQ.' % (self.gpio_irq, self.name))
Ejemplo n.º 6
0
def test_interactive():
    print("Starting interactive test...")

    gpio = periphery.GPIO(path, line_output, "out")

    print("Starting interactive test. Get out your multimeter, buddy!")
    raw_input("Press enter to continue...")

    # Check tostring
    print("GPIO description: {}".format(str(gpio)))
    passert("interactive success",
            raw_input("GPIO description looks ok? y/n ") == "y")

    # Drive GPIO out low
    gpio.write(False)
    passert("interactive success", raw_input("GPIO out is low? y/n ") == "y")

    # Drive GPIO out high
    gpio.write(True)
    passert("interactive success", raw_input("GPIO out is high? y/n ") == "y")

    # Drive GPIO out low
    gpio.write(False)
    passert("interactive success", raw_input("GPIO out is low? y/n ") == "y")

    gpio.close()
Ejemplo n.º 7
0
def main():
    parser = argparse.ArgumentParser(description="Raspberry Pi fan control")
    parser.add_argument("--gpio-pin",
                        dest="gpio_pin",
                        type=int,
                        default=GPIO_PIN,
                        help="GPIO pin to control the fan.")
    parser.add_argument("--on-threshold",
                        dest="on_threshold",
                        type=int,
                        default=ON_THRESHOLD,
                        help="Threshold temperature to turn on the fan.")
    parser.add_argument("--off-threshold",
                        dest="off_threshold",
                        type=int,
                        default=OFF_THRESHOLD,
                        help="Threshold temperature to turn off the fan.")
    parser.add_argument("--sleep-interval",
                        dest="sleep_interval",
                        type=int,
                        default=SLEEP_INTERVAL,
                        help="Check temperature every $x seconds.")
    args = parser.parse_args()

    try:
        fan = periphery.GPIO("/dev/gpiochip0", args.gpio_pin, "out")
    except Exception as e:
        logger.error(e)
        logger.error("Failed to open GPIO device. Exit.")
        return

    try:
        while True:
            temperature = get_temperature()
            logger.info(f"Temperature: {temperature}.")
            if temperature < args.off_threshold:
                if fan.read():
                    logger.info("Turning off Fan.")
                    fan.write(False)
            elif temperature > args.on_threshold:
                if not fan.read():
                    logger.info("Turning on Fan.")
                    fan.write(True)
            time.sleep(args.sleep_interval)
    except KeyboardInterrupt:
        pass
    except Exception as e:
        logger.error(e)
    finally:
        fan.close()
        logger.warning("Exit.")
Ejemplo n.º 8
0
def test_loopback():
    print("Starting loopback test...")

    # Open in and out pins
    gpio_in = periphery.GPIO(pin_input, "in")
    gpio_out = periphery.GPIO(pin_output, "out")

    # Drive out low, check in low
    print("Drive out low, check in low")
    gpio_out.write(False)
    assert gpio_in.read() == False

    # Drive out high, check in high
    print("Drive out high, check in high")
    gpio_out.write(True)
    assert gpio_in.read() == True

    # Check poll falling (1->0) interrupt
    print("Check poll faliing 1 -> 0 interrupt")
    gpio_in.edge = "falling"
    gpio_out.write(False)
    assert gpio_in.poll(0.1) == True
    assert gpio_in.read() == False

    # Check poll rising 0 -> 1 interrupt
    print("Check poll faliing 0 -> 1 interrupt")
    gpio_in.edge = "rising"
    gpio_out.write(True)
    assert gpio_in.poll(0.1) == True
    assert gpio_in.read() == True

    # Check poll timeout
    assert gpio_in.poll(1) == False

    gpio_in.close()
    gpio_out.close()

    print("Loopback test passed.")
Ejemplo n.º 9
0
def gpio_fixture_helper(request, gpionr):
    gpio = None
    sudo('sh -c "echo %d > /sys/class/gpio/export"' % (gpionr,))
    time.sleep(0.5)

    def teardown():
        if gpio:
            gpio.direction = 'in'
            gpio.close()
        sudo('sh -c "echo %d > /sys/class/gpio/unexport"' % (gpionr,))
    request.addfinalizer(teardown)

    gpio = periphery.GPIO(gpionr)
    return gpio
Ejemplo n.º 10
0
    def configure_gpio(self):
        if self.config['switchingMethod'] == 'GPIO':
            self._logger.info("Using GPIO for On/Off")
            self._logger.info("Configuring GPIO for pin {}".format(
                self.config['onoffGPIOPin']))

            if not self.config['invertonoffGPIOPin']:
                initial_output = 'low'
            else:
                initial_output = 'high'

            try:
                pin = periphery.GPIO(self.config['GPIODevice'],
                                     self.config['onoffGPIOPin'],
                                     initial_output)
                self._configuredGPIOPins['switch'] = pin
            except Exception as e:
                self._logger.error(e)

        if self.config['sensingMethod'] == 'GPIO':
            self._logger.info(
                "Using GPIO sensing to determine PSU on/off state.")
            self._logger.info("Configuring GPIO for pin {}".format(
                self.config['senseGPIOPin']))

            if self.config['senseGPIOPinPUD'] == '':
                bias = "disable"
            elif not self._SUPPORTS_LINE_BIAS:
                self._logger.warning(
                    "Kernel version 5.5 or greater required for GPIO bias. Using 'default' instead."
                )
                bias = "default"
            elif self.config['senseGPIOPinPUD'] == 'PULL_UP':
                bias = "pull_up"
            elif self.config['senseGPIOPinPUD'] == 'PULL_DOWN':
                bias = "pull_down"
            else:
                bias = "disable"

            try:
                pin = periphery.CdevGPIO(path=self.config['GPIODevice'],
                                         line=self.config['senseGPIOPin'],
                                         direction='in',
                                         bias=bias)
                self._configuredGPIOPins['sense'] = pin
            except Exception as e:
                self._logger.error(e)
Ejemplo n.º 11
0
    def configure_gpio(self):
        self.cleanup_gpio()

        if self.config['switchingMethod'] == 'GPIO':
            self._logger.info("Using GPIO for On/Off")
            self._logger.info("Configuring GPIO for pin {}".format(
                self.config['onoffGPIOPin']))

            if not self.config['invertonoffGPIOPin']:
                initial_output = 'low'
            else:
                initial_output = 'high'

            try:
                pin = periphery.GPIO(self.config['GPIODevice'],
                                     self.config['onoffGPIOPin'],
                                     initial_output)
                self._configuredGPIOPins['switch'] = pin
            except Exception as e:
                self._logger.error(e)

        if self.config['sensingMethod'] == 'GPIO':
            self._logger.info(
                "Using GPIO sensing to determine PSU on/off state.")
            self._logger.info("Configuring GPIO for pin {}".format(
                self.config['senseGPIOPin']))

            if self.config['senseGPIOPinPUD'] == 'PULL_UP':
                bias = "pull_up"
            elif self.config['senseGPIOPinPUD'] == 'PULL_DOWN':
                bias = "pull_down"
            else:
                bias = "disable"

            try:
                pin = periphery.CdevGPIO(path=self.config['GPIODevice'],
                                         line=self.config['senseGPIOPin'],
                                         direction='in',
                                         bias=bias)
                self._configuredGPIOPins['sense'] = pin
            except Exception as e:
                self._logger.error(e)
Ejemplo n.º 12
0
def test_interactive():
    print("Starting interactive test...")

    gpio = periphery.GPIO(pin_output, "out")

    print("Starting interactive test. Get out your multimeter, buddy!")
    raw_input("Press enter to continue...")

    # Drive GPIO out low
    gpio.write(False)
    assert raw_input("GPIO out is low? y/n ") == "y"

    # Drive GPIO out high
    gpio.write(True)
    assert raw_input("GPIO out is high? y/n ") == "y"

    # Drive GPIO out low
    gpio.write(False)
    assert raw_input("GPIO out is low? y/n ") == "y"

    gpio.close()

    print("Interactive test passed.")
def test_open_close():
    print("Starting open/close test...")

    # Open non-existent GPIO (export should fail with EINVAL)
    with AssertRaises(periphery.GPIOError):
        periphery.GPIO(9999, "in")

    # Open legitimate GPIO
    gpio = periphery.GPIO(line_output, "in")
    assert gpio.line == line_output
    assert gpio.direction == "in"
    assert gpio.fd >= 0

    # Set invalid direction
    with AssertRaises(ValueError):
        gpio.direction = "blah"
    # Set invalid edge
    with AssertRaises(ValueError):
        gpio.edge = "blah"
    # Unsupported proprety
    with AssertRaises(NotImplementedError):
        _ = gpio.chip_fd
    # Unsupported method
    with AssertRaises(NotImplementedError):
        gpio.read_event()

    # Set direction out, check direction out, check value low
    gpio.direction = "out"
    assert gpio.direction == "out"
    assert gpio.read() == False
    # Set direction low, check direction out, check value low
    gpio.direction = "low"
    assert gpio.direction == "out"
    assert gpio.read() == False
    # Set direction high, check direction out, check value high
    gpio.direction = "high"
    assert gpio.direction == "out"
    assert gpio.read() == True

    # Set direction in, check direction in
    gpio.direction = "in"
    assert gpio.direction == "in"

    # Set edge none, check edge none
    gpio.edge = "none"
    assert gpio.edge == "none"
    # Set edge rising, check edge rising
    gpio.edge = "rising"
    assert gpio.edge == "rising"
    # Set edge falling, check edge falling
    gpio.edge = "falling"
    assert gpio.edge == "falling"
    # Set edge both, check edge both
    gpio.edge = "both"
    assert gpio.edge == "both"
    # Set edge none, check edge none
    gpio.edge = "none"
    assert gpio.edge == "none"

    gpio.close()

    print("Open/close test passed.")
Ejemplo n.º 14
0
def main():
    subprocess.call(['umount', MOUNT_DEV])
    time.sleep(UNMOUNT_WAIT)
    gpio_mount = periphery.GPIO(GPIO, 'out')
    gpio_mount.write(False)

    while True:
        delay = 15
        try:
            print 'Start ...'
            config = load_config()

            slides = []
            for slide in config['slides']:
                if isinstance(slide, basestring):
                    slide = {'url': slide}
                if 'duration' in slide:
                    duration = int(slide['duration'])
                else:
                    duration = 1
                if 'wait' in slide:
                    wait = int(slide['wait'])
                else:
                    wait = 0

                try:
                    print 'Capture %s ...' % (slide['url'])
                    path = './tmp/slide-%05d.jpg' % len(slides)
                    capture(slide['url'], path, wait)
                    slides.append((path, duration))
                except subprocess.CalledProcessError, e:
                    print e

            print 'Mount USB flash ...'
            gpio_mount.write(True)
            while not os.path.exists(MOUNT_DEV):
                time.sleep(1)
            subprocess.check_call(['mount', MOUNT_DEV, MOUNT_ROOT])

            print 'Remove old frames ...'
            shutil.rmtree(MOUNT_PATH, True)
            os.mkdir(MOUNT_PATH)
            i = 0
            for slide in slides:
                for j in range(slide[1]):
                    filename = '%s/frame-%05d.jpg' % (MOUNT_PATH, i)
                    print 'Copy frame %s ...' % (filename)
                    shutil.copyfile(slide[0], filename)
                    i += 1

            print 'Unmount USB flash ...'
            subprocess.check_call(['umount', MOUNT_DEV])
            time.sleep(UNMOUNT_WAIT)
            gpio_mount.write(False)

            print 'Done.'

            if 'interval' in config:
                delay = int(config['interval'])
        except RuntimeError, e:
            print e
Ejemplo n.º 15
0
def test_loopback():
    print("Starting loopback test...")

    # Open in and out pins
    gpio_in = periphery.GPIO(pin_input, "in")
    gpio_out = periphery.GPIO(pin_output, "out")

    # Drive out low, check in low
    print("Drive out low, check in low")
    gpio_out.write(False)
    assert gpio_in.read() == False

    # Drive out high, check in high
    print("Drive out high, check in high")
    gpio_out.write(True)
    assert gpio_in.read() == True

    # Wrapper for running poll() in a thread
    def threaded_poll(gpio, timeout):
        ret = queue.Queue()

        def f():
            ret.put(gpio.poll(timeout))

        thread = threading.Thread(target=f)
        thread.start()
        return ret

    # Check poll falling 1 -> 0 interrupt
    print("Check poll falling 1 -> 0 interrupt")
    gpio_in.edge = "falling"
    poll_ret = threaded_poll(gpio_in, 5)
    time.sleep(1)
    gpio_out.write(False)
    assert poll_ret.get() == True
    assert gpio_in.read() == False

    # Check poll timeout on 0 -> 0
    print("Check poll falling timeout on 0 -> 0")
    poll_ret = threaded_poll(gpio_in, 2)
    time.sleep(1)
    gpio_out.write(False)
    assert poll_ret.get() == False
    assert gpio_in.read() == False

    # Check poll rising 0 -> 1 interrupt
    print("Check poll rising 0 -> 1 interrupt")
    gpio_in.edge = "rising"
    poll_ret = threaded_poll(gpio_in, 5)
    time.sleep(1)
    gpio_out.write(True)
    assert poll_ret.get() == True
    assert gpio_in.read() == True

    # Check poll timeout on 1 -> 1
    print("Check poll rising timeout on 1 -> 1")
    poll_ret = threaded_poll(gpio_in, 2)
    time.sleep(1)
    gpio_out.write(True)
    assert poll_ret.get() == False
    assert gpio_in.read() == True

    # Check poll rising+falling interrupts
    print("Check poll rising/falling interrupt")
    gpio_in.edge = "both"
    poll_ret = threaded_poll(gpio_in, 5)
    time.sleep(1)
    gpio_out.write(False)
    assert poll_ret.get() == True
    assert gpio_in.read() == False
    poll_ret = threaded_poll(gpio_in, 5)
    time.sleep(1)
    gpio_out.write(True)
    assert poll_ret.get() == True
    assert gpio_in.read() == True

    # Check poll timeout
    print("Check poll timeout")
    assert gpio_in.poll(1) == False

    gpio_in.close()
    gpio_out.close()

    print("Loopback test passed.")
Ejemplo n.º 16
0
def test_open_close():
    ptest()

    # Open non-existent GPIO (export should fail with EINVAL)
    with AssertRaises("non-existent GPIO", periphery.GPIOError):
        periphery.GPIO(path, 9999, "in")

    # Open legitimate GPIO
    gpio = periphery.GPIO(path, line_output, "in")
    passert("property line", gpio.line == line_output)
    passert("direction is in", gpio.direction == "in")
    passert("fd >= 0", gpio.fd >= 0)
    passert("chip_fd >= 0", gpio.chip_fd >= 0)

    # Check default label
    passert("property label", gpio.label == "periphery")

    # Set invalid direction
    with AssertRaises("set invalid direction", ValueError):
        gpio.direction = "blah"
    # Set invalid edge
    with AssertRaises("set invalid edge", ValueError):
        gpio.edge = "blah"
    # Set invalid bias
    with AssertRaises("set invalid bias", ValueError):
        gpio.bias = "blah"
    # Set invalid drive
    with AssertRaises("set invalid drive", ValueError):
        gpio.drive = "blah"

    # Set direction out, check direction out, check value low
    gpio.direction = "out"
    passert("direction is out", gpio.direction == "out")
    passert("value is low", gpio.read() == False)
    # Set direction low, check direction out, check value low
    gpio.direction = "low"
    passert("direction is out", gpio.direction == "out")
    passert("value is low", gpio.read() == False)
    # Set direction high, check direction out, check value high
    gpio.direction = "high"
    passert("direction is out", gpio.direction == "out")
    passert("value is high", gpio.read() == True)

    # Set drive open drain, check drive open drain
    gpio.drive = "open_drain"
    passert("drive is open drain", gpio.drive == "open_drain")
    # Set drive open source, check drive open source
    gpio.drive = "open_source"
    passert("drive is open drain", gpio.drive == "open_source")
    # Set drive default, check drive default
    gpio.drive = "default"
    passert("drive is default", gpio.drive == "default")

    # Set inverted true, check inverted true
    gpio.inverted = True
    passert("inverted is True", gpio.inverted == True)
    # Set inverted false, check inverted false
    gpio.inverted = False
    passert("inverted is False", gpio.inverted == False)

    # Attempt to set interrupt edge on output GPIO
    with AssertRaises("set interrupt edge on output GPIO",
                      periphery.GPIOError):
        gpio.edge = "rising"
    # Attempt to read event on output GPIO
    with AssertRaises("read event on output GPIO", periphery.GPIOError):
        gpio.read_event()

    # Set direction in, check direction in
    gpio.direction = "in"
    passert("direction is in", gpio.direction == "in")

    # Set edge none, check edge none
    gpio.edge = "none"
    passert("edge is none", gpio.edge == "none")
    # Set edge rising, check edge rising
    gpio.edge = "rising"
    passert("edge is rising", gpio.edge == "rising")
    # Set edge falling, check edge falling
    gpio.edge = "falling"
    passert("edge is falling", gpio.edge == "falling")
    # Set edge both, check edge both
    gpio.edge = "both"
    passert("edge is both", gpio.edge == "both")
    # Set edge none, check edge none
    gpio.edge = "none"
    passert("edge is none", gpio.edge == "none")

    # Set bias pull up, check bias pull up
    gpio.bias = "pull_up"
    passert("bias is pull up", gpio.bias == "pull_up")
    # Set bias pull down, check bias pull down
    gpio.bias = "pull_down"
    passert("bias is pull down", gpio.bias == "pull_down")
    # Set bias disable, check bias disable
    gpio.bias = "disable"
    passert("bias is disable", gpio.bias == "disable")
    # Set bias default, check bias default
    gpio.bias = "default"
    passert("bias is default", gpio.bias == "default")

    # Attempt to set drive on input GPIO
    with AssertRaises("set drive on input GPIO", periphery.GPIOError):
        gpio.drive = "open_drain"

    gpio.close()

    # Open with keyword arguments
    gpio = periphery.GPIO(path,
                          line_input,
                          "in",
                          edge="rising",
                          bias="default",
                          drive="default",
                          inverted=False,
                          label="test123")
    passert("property line", gpio.line == line_input)
    passert("direction is in", gpio.direction == "in")
    passert("fd >= 0", gpio.fd >= 0)
    passert("chip_fd >= 0", gpio.chip_fd >= 0)
    passert("edge is rising", gpio.edge == "rising")
    passert("bias is default", gpio.bias == "default")
    passert("drive is default", gpio.drive == "default")
    passert("inverted is False", gpio.inverted == False)
    passert("label is test123", gpio.label == "test123")

    gpio.close()
Ejemplo n.º 17
0
def test_loopback():
    ptest()

    # Open in and out lines
    gpio_in = periphery.GPIO(path, line_input, "in")
    gpio_out = periphery.GPIO(path, line_output, "out")

    # Drive out low, check in low
    print("Drive out low, check in low")
    gpio_out.write(False)
    passert("value is False", gpio_in.read() == False)

    # Drive out high, check in high
    print("Drive out high, check in high")
    gpio_out.write(True)
    passert("value is True", gpio_in.read() == True)

    # Wrapper for running poll() in a thread
    def threaded_poll(gpio, timeout):
        ret = queue.Queue()

        def f():
            ret.put(gpio.poll(timeout))

        thread = threading.Thread(target=f)
        thread.start()
        return ret

    # Check poll falling 1 -> 0 interrupt
    print("Check poll falling 1 -> 0 interrupt")
    gpio_in.edge = "falling"
    poll_ret = threaded_poll(gpio_in, 5)
    time.sleep(0.5)
    gpio_out.write(False)
    passert("gpio_in polled True", poll_ret.get() == True)
    passert("value is low", gpio_in.read() == False)
    event = gpio_in.read_event()
    passert("event edge is falling", event.edge == "falling")
    passert("event timestamp is non-zero", event.timestamp != 0)

    # Check poll rising 0 -> 1 interrupt
    print("Check poll rising 0 -> 1 interrupt")
    gpio_in.edge = "rising"
    poll_ret = threaded_poll(gpio_in, 5)
    time.sleep(0.5)
    gpio_out.write(True)
    passert("gpin_in polled True", poll_ret.get() == True)
    passert("value is high", gpio_in.read() == True)
    event = gpio_in.read_event()
    passert("event edge is rising", event.edge == "rising")
    passert("event timestamp is non-zero", event.timestamp != 0)

    # Set edge to both
    gpio_in.edge = "both"

    # Check poll falling 1 -> 0 interrupt
    print("Check poll falling 1 -> 0 interrupt")
    poll_ret = threaded_poll(gpio_in, 5)
    time.sleep(0.5)
    gpio_out.write(False)
    passert("gpio_in polled True", poll_ret.get() == True)
    passert("value is low", gpio_in.read() == False)
    event = gpio_in.read_event()
    passert("event edge is falling", event.edge == "falling")
    passert("event timestamp is non-zero", event.timestamp != 0)

    # Check poll rising 0 -> 1 interrupt
    print("Check poll rising 0 -> 1 interrupt")
    poll_ret = threaded_poll(gpio_in, 5)
    time.sleep(0.5)
    gpio_out.write(True)
    passert("gpio_in polled True", poll_ret.get() == True)
    passert("value is high", gpio_in.read() == True)
    event = gpio_in.read_event()
    passert("event edge is rising", event.edge == "rising")
    passert("event timestamp is non-zero", event.timestamp != 0)

    # Check poll timeout
    print("Check poll timeout")
    passert("gpio_in polled False", gpio_in.poll(1) == False)

    # Check poll falling 1 -> 0 interrupt with the poll_multiple() API
    print("Check poll falling 1 -> 0 interrupt with poll_multiple()")
    gpio_out.write(False)
    gpios_ready = periphery.GPIO.poll_multiple([gpio_in], 1)
    passert("gpios ready is gpio_in", gpios_ready == [gpio_in])
    passert("value is low", gpio_in.read() == False)
    event = gpio_in.read_event()
    passert("event edge is falling", event.edge == "falling")
    passert("event timestamp is non-zero", event.timestamp != 0)

    # Check poll rising 0 -> 1 interrupt with the poll_multiple() API
    print("Check poll rising 0 -> 1 interrupt with poll_multiple()")
    gpio_out.write(True)
    gpios_ready = periphery.GPIO.poll_multiple([gpio_in], 1)
    passert("gpios ready is gpio_in", gpios_ready == [gpio_in])
    passert("value is high", gpio_in.read() == True)
    event = gpio_in.read_event()
    passert("event edge is rising", event.edge == "rising")
    passert("event timestamp is non-zero", event.timestamp != 0)

    # Check poll timeout
    print("Check poll timeout with poll_multiple()")
    gpios_ready = periphery.GPIO.poll_multiple([gpio_in], 1)
    passert("gpios ready is empty", gpios_ready == [])

    gpio_in.close()
    gpio_out.close()

    # Open both GPIOs as inputs
    gpio_in = periphery.GPIO(path, line_input, "in")
    gpio_out = periphery.GPIO(path, line_output, "in")

    # Set bias pull-up, check value is high
    print("Check input GPIO reads high with pull-up bias")
    gpio_in.bias = "pull_up"
    time.sleep(0.1)
    passert("value is high", gpio_in.read() == True)

    # Set bias pull-down, check value is low
    print("Check input GPIO reads low with pull-down bias")
    gpio_in.bias = "pull_down"
    time.sleep(0.1)
    passert("value is low", gpio_in.read() == False)

    gpio_in.close()
    gpio_out.close()
Ejemplo n.º 18
0
def test_open_close():
    ptest()

    # Open non-existent GPIO (export should fail with EINVAL)
    with AssertRaises("non-existent GPIO", periphery.GPIOError):
        periphery.GPIO(9999, "in")

    # Open legitimate GPIO
    gpio = periphery.GPIO(line_output, "in")
    passert("property line", gpio.line == line_output)
    passert("direction is in", gpio.direction == "in")
    passert("fd >= 0", gpio.fd >= 0)

    # Set invalid direction
    with AssertRaises("set invalid direction", ValueError):
        gpio.direction = "blah"
    # Set invalid edge
    with AssertRaises("set invalid edge", ValueError):
        gpio.edge = "blah"
    # Unsupported property bias
    with AssertRaises("unsupported property bias", NotImplementedError):
        _ = gpio.bias
    with AssertRaises("unsupported property bias", NotImplementedError):
        gpio.bias = "pull_up"
    # Unsupported property drive
    with AssertRaises("unsupported property drive", NotImplementedError):
        _ = gpio.drive
    with AssertRaises("unsupported property drive", NotImplementedError):
        gpio.drive = "open_drain"
    # Unsupported proprety
    with AssertRaises("unsupported property chip_fd", NotImplementedError):
        _ = gpio.chip_fd
    # Unsupported method
    with AssertRaises("unsupported method", NotImplementedError):
        gpio.read_event()

    # Set direction out, check direction out, check value low
    gpio.direction = "out"
    passert("direction is out", gpio.direction == "out")
    passert("value is low", gpio.read() == False)
    # Set direction low, check direction out, check value low
    gpio.direction = "low"
    passert("direction is out", gpio.direction == "out")
    passert("value is low", gpio.read() == False)
    # Set direction high, check direction out, check value high
    gpio.direction = "high"
    passert("direction is out", gpio.direction == "out")
    passert("ivalue is high", gpio.read() == True)

    # Set inverted true, check inverted
    gpio.inverted = True
    passert("inverted is True", gpio.inverted == True)
    # Set inverted false, check inverted
    gpio.inverted = False
    passert("inverted is False", gpio.inverted == False)

    # Set direction in, check direction in
    gpio.direction = "in"
    passert("direction is in", gpio.direction == "in")

    # Set edge none, check edge none
    gpio.edge = "none"
    passert("edge is none", gpio.edge == "none")
    # Set edge rising, check edge rising
    gpio.edge = "rising"
    passert("edge is rising", gpio.edge == "rising")
    # Set edge falling, check edge falling
    gpio.edge = "falling"
    passert("edge is falling", gpio.edge == "falling")
    # Set edge both, check edge both
    gpio.edge = "both"
    passert("edge is both", gpio.edge == "both")
    # Set edge none, check edge none
    gpio.edge = "none"
    passert("edge is none", gpio.edge == "none")

    gpio.close()
Ejemplo n.º 19
0
def test_loopback():
    ptest()

    # Open in and out lines
    gpio_in = periphery.GPIO(line_input, "in")
    gpio_out = periphery.GPIO(line_output, "out")

    # Drive out low, check in low
    print("Drive out low, check in low")
    gpio_out.write(False)
    passert("value is low", gpio_in.read() == False)

    # Drive out high, check in high
    print("Drive out high, check in high")
    gpio_out.write(True)
    passert("value is high", gpio_in.read() == True)

    # Wrapper for running poll() in a thread
    def threaded_poll(gpio, timeout):
        ret = queue.Queue()

        def f():
            ret.put(gpio.poll(timeout))

        thread = threading.Thread(target=f)
        thread.start()
        return ret

    # Check poll falling 1 -> 0 interrupt
    print("Check poll falling 1 -> 0 interrupt")
    gpio_in.edge = "falling"
    poll_ret = threaded_poll(gpio_in, 5)
    time.sleep(0.5)
    gpio_out.write(False)
    passert("gpio_in polled True", poll_ret.get() == True)
    passert("value is low", gpio_in.read() == False)

    # Check poll rising 0 -> 1 interrupt
    print("Check poll rising 0 -> 1 interrupt")
    gpio_in.edge = "rising"
    poll_ret = threaded_poll(gpio_in, 5)
    time.sleep(0.5)
    gpio_out.write(True)
    passert("gpio_in polled True", poll_ret.get() == True)
    passert("value is high", gpio_in.read() == True)

    # Set edge to both
    gpio_in.edge = "both"

    # Check poll falling 1 -> 0 interrupt
    print("Check poll falling 1 -> 0 interrupt")
    poll_ret = threaded_poll(gpio_in, 5)
    time.sleep(0.5)
    gpio_out.write(False)
    passert("gpio_in polled True", poll_ret.get() == True)
    passert("value is low", gpio_in.read() == False)

    # Check poll rising 0 -> 1 interrupt
    print("Check poll rising 0 -> 1 interrupt")
    poll_ret = threaded_poll(gpio_in, 5)
    time.sleep(0.5)
    gpio_out.write(True)
    passert("gpio_in polled True", poll_ret.get() == True)
    passert("value is high", gpio_in.read() == True)

    # Check poll timeout
    print("Check poll timeout")
    passert("gpio_in polled False", gpio_in.poll(1) == False)

    # Check poll falling 1 -> 0 interrupt with the poll_multiple() API
    print("Check poll falling 1 -> 0 interrupt with poll_multiple()")
    gpio_out.write(False)
    gpios_ready = periphery.GPIO.poll_multiple([gpio_in], 1)
    passert("gpios ready is gpio_in", gpios_ready == [gpio_in])
    passert("value is low", gpio_in.read() == False)

    # Check poll rising 0 -> 1 interrupt with the poll_multiple() API
    print("Check poll rising 0 -> 1 interrupt with poll_multiple()")
    gpio_out.write(True)
    gpios_ready = periphery.GPIO.poll_multiple([gpio_in], 1)
    passert("gpios ready is gpio_in", gpios_ready == [gpio_in])
    passert("value is high", gpio_in.read() == True)

    # Check poll timeout
    print("Check poll timeout with poll_multiple()")
    gpios_ready = periphery.GPIO.poll_multiple([gpio_in], 1)
    passert("gpios ready is empty", gpios_ready == [])

    gpio_in.close()
    gpio_out.close()