vsergeev / python-periphery

A pure Python 2/3 library for peripheral I/O (GPIO, LED, PWM, SPI, I2C, MMIO, Serial) in Linux.
MIT License
529 stars 139 forks source link

gpio not unexported on close #11

Closed nicola-lunghi closed 6 years ago

nicola-lunghi commented 7 years ago

Hi periphery export the gpio correctly on open try: with open("/sys/class/gpio/export", "w") as f_export: f_export.write("%d\n" % pin) except IOError as e: raise GPIOError(e.errno, "Exporting GPIO: " + e.strerror)

but on close it didn't unexport the pin

nicola-lunghi commented 7 years ago
pin_no = 403
# FIX: periphery don't unexport the directory on closing
    gpio_path = "/sys/class/gpio/gpio%d" % pin_no

    if os.path.isdir(gpio_path):
        # Export the pin
        try:
            with open("/sys/class/gpio/unexport", "w") as f_export:
                f_export.write("%d\n" % pin_no)
        except IOError as e:
            raise periphery.GPIOError(e.errno, "Exporting GPIO: " + e.strerror)
vsergeev commented 6 years ago

python-periphery doesn't unexport the pin on close because unexporting has side effects, like resetting the pin direction to input. If you used python-periphery to drive a pin as an output, it wouldn't retain that state after you closed the pin if were automatically unexported.

Some might argue that this is more correct, and that the program should keep the pin open for as long as it's being used, but I think that the convenience of having one-off scripts that can drive outputs and expect them to remain driven is more valuable. Automatically unexporting would also be at odds with the "preserve" direction in the current GPIO API.

Closing the issue for now, but I'm open to hearing compelling arguments for unexporting on close.