summaryrefslogtreecommitdiff
path: root/test-cli/test/helpers/gpio.py
blob: f127f2b1da3cedf405a01e2b029e75a188a32668 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import os

class gpio (object):
    gpioNum = None

    def __init__(self, gpioNum, dir, val):
        self.gpioNum = gpioNum
        self.__export(gpioNum)
        self.__set_dir(gpioNum, dir)
        if dir == 'out':
            self.__set_value(gpioNum, val)

    def set_val(self, value):
        self.__set_value( self.gpioNum, value)


    def __export(self, gpio_number):
        if not os.path.isfile("/sys/class/gpio/gpio{}/value".format(gpio_number)):
            try:
                f = open("/sys/class/gpio/export", "w", newline="\n")
                f.write(str(gpio_number))
                f.close()
            except IOError:
                return False, '{}'.format(IOError.errno)
        return True

    def __unexport(self, gpio_number):
        if os.path.isfile("/sys/class/gpio/gpio{}/value".format(gpio_number)):
            try:
                f = open("/sys/class/gpio/unexport", "w", newline="\n")
                f.write(str(gpio_number))
                f.close()
            except IOError:
                return False, '{}'.format(IOError.errno)
        return True

    def __set_dir(self, gpio_number, dir):
        try:
            f = open("/sys/class/gpio/gpio{}/direction".format(gpio_number), "r+", newline="\n")
            val = f.readline()
            if val != dir:
                f.write(dir)
            f.close()
        except IOError:
            return False, '{}'.format(IOError.errno)
        return True

    def __set_value(self, gpio_number, value):
        try:
            f = open("/sys/class/gpio/gpio{}/value".format(gpio_number), "w", newline="\n")
            f.write(str(value))
            f.close()
        except IOError:
            return False, '{}'.format(IOError.errno)
        return True