summaryrefslogtreecommitdiffstats
path: root/mdb/backend.py
blob: 8e40da5d1d4e33fb75f17d4ad846557d707bd28f (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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import time

try:
    import pigpio
except:
    pigpio = None

RX_PIN = 4
TX_PIN = 17


class Backend(object):
    def __init__(self):
        pass

    def open(self):
        pass

    def close(self):
        pass

    def read(self):
        return b''

    def write(self, data):
        pass


#
# Dummy backend driver, for testing purposes only
#
class DummyBackend(Backend):
    def read(self):
        time.sleep(0.005)
        return b''


#
# Backend driver for raspberry pi pigpio library
#
class RaspiBackend(Backend):
    def __init__(self, rx_pin=RX_PIN, tx_pin=TX_PIN):
        self.rx_pin = rx_pin
        self.tx_pin = tx_pin

    def open(self):
        self.pi = pigpio.pi()
        self.pi.wave_clear()
        self.pi.set_mode(self.tx_pin, pigpio.INPUT)

        try:
            self.pi.bb_serial_read_close(self.rx_pin)
        except:
            pass

        status = self.pi.bb_serial_read_open(self.rx_pin, 9600, 9)
        if status:
            raise Exception('Port open failed: %d', status)

    def read(self):
        while True:
            cnt, data = self.pi.bb_serial_read(self.rx_pin)
            if cnt <= 0:
                time.sleep(0.001)
            else:
                return data

    def write(self, data):
        self.pi.wave_add_serial(self.tx_pin, 9600, data, bb_bits=9, bb_stop=6)
        wid = self.pi.wave_create()

        self.pi.set_mode(self.tx_pin, pigpio.OUTPUT)
        self.pi.wave_send_once(wid)   # transmit serial data

        while self.pi.wave_tx_busy(): # wait until all data sent
            time.sleep(0.001)

        self.pi.wave_delete(wid)
        self.pi.set_mode(self.tx_pin, pigpio.INPUT)


#
# Backend device based on STM32F1 MDB-USB adapter (to be actually designed...)
#
class SerialBackend(Backend):
    def __init__(self, device='/dev/ttyACM0'):
        self.ser = serial.Serial(device)

    def read(self):
        return self.ser.read()

    def write(self, data):
        self.ser.write(data)