__init__.py 11.1 KB
Newer Older
Daniel Hoffend's avatar
Daniel Hoffend committed
1
2
import os
import display
Yuval Adam's avatar
Yuval Adam committed
3
import leds
Daniel Hoffend's avatar
Daniel Hoffend committed
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
import utime
import buttons
import max30001
import math
import struct

WIDTH = 160
HEIGHT = 80
OFFSET_Y = 49
ECG_RATE = 128
HISTORY_MAX = ECG_RATE * 4
DRAW_AFTER_SAMPLES = 5
SCALE_FACTOR = 30
MODE_USB = "USB"
MODE_FINGER = "Finger"
FILEBUFFERBLOCK = 4096
COLOR_BACKGROUND = [0, 0, 0]
COLOR_LINE = [255, 255, 255]
COLOR_TEXT = [255, 255, 255]
COLOR_MODE_FINGER = [0, 255, 0]
COLOR_MODE_USB = [0, 0, 255]
COLOR_WRITE_FG = [255, 255, 255]
COLOR_WRITE_BG = [255, 0, 0]

current_mode = MODE_FINGER
history = []
filebuffer = bytearray()
write = 0
bias = True
update_screen = 0
pause_screen = 0
pause_histogram = False
histogram_offset = 0
sensor = 0
disp = display.open()

Yuval Adam's avatar
Yuval Adam committed
40
41
42
leds.dim_top(1)
COLORS = [((23 + (15 * i)) % 360, 1.0, 1.0) for i in range(11)]

Daniel Hoffend's avatar
Daniel Hoffend committed
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# variables for high-pass filter
moving_average = 0
alpha = 2
beta = 3


def update_history(datasets):
    global history, moving_average, alpha, beta
    for val in datasets:
        history.append(val - moving_average)
        moving_average = (alpha * moving_average + beta * val) / (alpha + beta)

    # trim old elements
    history = history[-HISTORY_MAX:]


# variables for pulse detection
pulse = -1
samples_since_last_pulse = 0
q_threshold = -1
r_threshold = 1
q_spike = -ECG_RATE


def neighbours(n, lst):
    """
    neighbours(2, "ABCDE") = ("AB", "BC", "CD", "DE")
    neighbours(3, "ABCDE") = ("ABC", "BCD", "CDE")
    """

    for i in range(len(lst) - (n - 1)):
        yield lst[i : i + n]


def detect_pulse(num_new_samples):
    global history, pulse, samples_since_last_pulse, q_threshold, r_threshold, q_spike

    # look at 3 consecutive samples, starting 2 samples before the samples that were just added, e.g.:
    # existing samples: "ABCD"
    # new samples: "EF" => "ABCDEF"
    # consider ["CDE", "DEF"]
    # new samples: "GHI" => "ABCDEFGHI"
    # consider ["EFG", "FGH", "GHI"]
    for [prev, cur, next_] in neighbours(3, history[-(num_new_samples + 2) :]):
        samples_since_last_pulse += 1

        if prev > cur < next_ and cur < q_threshold:
            q_spike = samples_since_last_pulse
            # we expect the next q-spike to be at least 60% as high as this one
            q_threshold = (cur * 3) // 5
        elif (
            prev < cur > next_
            and cur > r_threshold
            and samples_since_last_pulse - q_spike < ECG_RATE // 10
        ):
            # the full QRS complex is < 0.1s long, so the q and r spike in particular cannot be more than ECG_RATE//10 samples apart
            pulse = 60 * ECG_RATE // samples_since_last_pulse
            samples_since_last_pulse = 0
            q_spike = -ECG_RATE
            if pulse < 30 or pulse > 210:
                pulse = -1
            # we expect the next r-spike to be at least 60% as high as this one
            r_threshold = (cur * 3) // 5
        elif samples_since_last_pulse > 2 * ECG_RATE:
            q_threshold = -1
            r_threshold = 1
            pulse = -1


Daniel Hoffend's avatar
Daniel Hoffend committed
113
114
115
116
117
def callback_ecg(datasets):
    global update_screen, history, filebuffer, write
    update_screen += len(datasets)

    # update histogram datalist
118
    if not pause_histogram:
119
120
        update_history(datasets)
        detect_pulse(len(datasets))
Daniel Hoffend's avatar
Daniel Hoffend committed
121
122
123

    # buffer for writes
    if write > 0:
124
125
126
127
        for value in datasets:
            filebuffer.extend(struct.pack("h", value))
            if len(filebuffer) >= FILEBUFFERBLOCK:
                write_filebuffer()
Daniel Hoffend's avatar
Daniel Hoffend committed
128
129
130
131
132
133
134
135
136
137
138

    # don't update on every callback
    if update_screen >= DRAW_AFTER_SAMPLES:
        draw_histogram()


def write_filebuffer():
    global write, filebuffer
    # write to file
    chars = ""
    lt = utime.localtime(write)
139
    filename = "/ecg-{:04d}-{:02d}-{:02d}_{:02d}{:02d}{:02d}.log".format(*lt)
Daniel Hoffend's avatar
Daniel Hoffend committed
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166

    # write stuff to disk
    try:
        f = open(filename, "ab")
        f.write(filebuffer)
        f.close()
    except OSError as e:
        print("Please check the file or filesystem", e)
        write = 0
        pause_screen = -1
        disp.clear(COLOR_BACKGROUND)
        disp.print("IO Error", posy=0, fg=COLOR_TEXT)
        disp.print("Please check", posy=20, fg=COLOR_TEXT)
        disp.print("your", posy=40, fg=COLOR_TEXT)
        disp.print("filesystem", posy=60, fg=COLOR_TEXT)
        disp.update()
        close_sensor()
    except:
        print("Unexpected error, stop writeing logfile")
        write = 0

    filebuffer = bytearray()


def open_sensor():
    global sensor
    sensor = max30001.MAX30001(
167
        usb=(current_mode == MODE_USB),
Daniel Hoffend's avatar
Daniel Hoffend committed
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
        bias=bias,
        sample_rate=ECG_RATE,
        callback=callback_ecg,
    )


def close_sensor():
    global sensor
    sensor.close()


def toggle_mode():
    global current_mode
    close_sensor()
    current_mode = MODE_USB if current_mode == MODE_FINGER else MODE_FINGER
    open_sensor()


def toggle_bias():
    global bias
    close_sensor()
189
    bias = not bias
Daniel Hoffend's avatar
Daniel Hoffend committed
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
    open_sensor()


def toggle_write():
    global write, disp, pause_screen
    pause_screen = utime.time_ms() + 1000
    disp.clear(COLOR_BACKGROUND)
    if write > 0:
        write_filebuffer()
        write = 0
        disp.print("Stop", posx=50, posy=20, fg=COLOR_TEXT)
        disp.print("logging", posx=30, posy=40, fg=COLOR_TEXT)
    else:
        filebuffer = bytearray()
        write = utime.time()
        disp.print("Start", posx=45, posy=20, fg=COLOR_TEXT)
        disp.print("logging", posx=30, posy=40, fg=COLOR_TEXT)

    disp.update()


def toggle_pause():
    global pause_histogram, histogram_offset, history
213
    if pause_histogram:
Daniel Hoffend's avatar
Daniel Hoffend committed
214
215
216
217
218
219
220
        pause_histogram = False
        history = []
    else:
        pause_histogram = True
    histogram_offset = 0


Yuval Adam's avatar
Yuval Adam committed
221
222
223
224
225
226
227
def draw_leds(val):
    # val should be in [0, 11]
    for i in range(11):
        leds.prep_hsv(10 - i, COLORS[10 - i] if i < val else (0, 0, 0))
    leds.update()


Daniel Hoffend's avatar
Daniel Hoffend committed
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
def draw_histogram():
    global disp, history, current_mode, bias, write, pause_screen, update_screen

    # skip rendering due to message beeing shown
    if pause_screen == -1:
        return
    elif pause_screen > 0:
        t = utime.time_ms()
        if t > pause_screen:
            pause_screen = 0
        else:
            return

    disp.clear(COLOR_BACKGROUND)

    # offset in pause_histogram mode
244
245
246
247
    window_end = int(len(history) - histogram_offset)
    s_start = max(0, window_end - (ECG_RATE * 2))
    s_end = max(0, window_end)
    s_draw = max(0, s_end - WIDTH)
Daniel Hoffend's avatar
Daniel Hoffend committed
248
249

    # get max value and calc scale
250
    value_max = max(abs(x) for x in history[s_start:s_end])
Daniel Hoffend's avatar
Daniel Hoffend committed
251
252
253
    scale = SCALE_FACTOR / (value_max if value_max > 0 else 1)

    # draw histogram
254
255
256
257
258
259
260
    # values need to be inverted so high values are drawn with low pixel coordinates (at the top of the screen)
    draw_points = (int(-x * scale + OFFSET_Y) for x in history[s_draw:s_end])

    prev = next(draw_points)
    for x, value in enumerate(draw_points):
        disp.line(x, prev, x + 1, value, col=COLOR_LINE)
        prev = value
Daniel Hoffend's avatar
Daniel Hoffend committed
261
262

    # draw text: mode/bias/write
263
    if pause_histogram:
Daniel Hoffend's avatar
Daniel Hoffend committed
264
265
266
        disp.print(
            "Pause"
            + (
267
                " -{:0.1f}s".format(histogram_offset / ECG_RATE)
Daniel Hoffend's avatar
Daniel Hoffend committed
268
269
270
271
272
273
274
275
                if histogram_offset > 0
                else ""
            ),
            posx=0,
            posy=0,
            fg=COLOR_TEXT,
        )
    else:
276
        draw_leds((max(history[-5:]) * scale + SCALE_FACTOR) * 11 / (SCALE_FACTOR * 2))
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
        if pulse < 0:
            disp.print(
                current_mode + ("+Bias" if bias else ""),
                posx=0,
                posy=0,
                fg=(
                    COLOR_MODE_FINGER if current_mode == MODE_FINGER else COLOR_MODE_USB
                ),
            )
        else:
            disp.print(
                "BPM: {}".format(pulse),
                posx=0,
                posy=0,
                fg=(
                    COLOR_MODE_FINGER if current_mode == MODE_FINGER else COLOR_MODE_USB
                ),
            )
Daniel Hoffend's avatar
Daniel Hoffend committed
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326

    # announce writing ecg log
    if write > 0:
        t = utime.time()
        if write > 0 and t % 2 == 0:
            disp.print("LOG", posx=0, posy=60, fg=COLOR_WRITE_FG, bg=COLOR_WRITE_BG)

    disp.update()
    update_screen = 0


def main():
    global pause_histogram, histogram_offset

    # show button layout
    disp.clear(COLOR_BACKGROUND)
    disp.print("  BUTTONS  ", posx=0, posy=0, fg=COLOR_TEXT)
    disp.print("Finger/USB>", posx=0, posy=20, fg=COLOR_MODE_FINGER)
    disp.print("     Bias >", posx=0, posy=40, fg=COLOR_MODE_USB)
    disp.print("< Write Log", posx=0, posy=60, fg=COLOR_WRITE_BG)
    disp.update()
    utime.sleep(3)

    # start ecg
    open_sensor()
    while True:
        button_pressed = {"BOTTOM_LEFT": 0, "BOTTOM_RIGHT": 0, "TOP_RIGHT": 0}
        while True:
            v = buttons.read(
                buttons.BOTTOM_LEFT | buttons.BOTTOM_RIGHT | buttons.TOP_RIGHT
            )

327
            # BOTTOM LEFT
Daniel Hoffend's avatar
Daniel Hoffend committed
328
329
330

            if button_pressed["BOTTOM_LEFT"] == 0 and v & buttons.BOTTOM_LEFT != 0:
                button_pressed["BOTTOM_LEFT"] = utime.time_ms()
331
                if not pause_histogram:
Daniel Hoffend's avatar
Daniel Hoffend committed
332
333
334
335
336
337
338
339
340
341
342
                    toggle_write()
                else:
                    l = len(history)
                    histogram_offset += ECG_RATE / 2
                    if l - histogram_offset < WIDTH:
                        histogram_offset = l - WIDTH

            if button_pressed["BOTTOM_LEFT"] > 0 and v & buttons.BOTTOM_LEFT == 0:
                duration = utime.time_ms() - button_pressed["BOTTOM_LEFT"]
                button_pressed["BOTTOM_LEFT"] = 0

343
            # BOTTOM RIGHT
Daniel Hoffend's avatar
Daniel Hoffend committed
344
345
346

            if button_pressed["BOTTOM_RIGHT"] == 0 and v & buttons.BOTTOM_RIGHT != 0:
                button_pressed["BOTTOM_RIGHT"] = utime.time_ms()
347
                if not pause_histogram:
Daniel Hoffend's avatar
Daniel Hoffend committed
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
                    toggle_bias()
                else:
                    histogram_offset -= ECG_RATE / 2
                    histogram_offset -= histogram_offset % (ECG_RATE / 2)
                    if histogram_offset < 0:
                        histogram_offset = 0

            if button_pressed["BOTTOM_RIGHT"] > 0 and v & buttons.BOTTOM_RIGHT == 0:
                duration = utime.time_ms() - button_pressed["BOTTOM_RIGHT"]
                button_pressed["BOTTOM_RIGHT"] = 0

            # TOP RIGHT

            # down, and still pressed
            if button_pressed["TOP_RIGHT"] > 0 and v & buttons.TOP_RIGHT != 0:
                duration = utime.time_ms() - button_pressed["TOP_RIGHT"]
                if duration > 1000:
                    button_pressed["TOP_RIGHT"] = -1
                    toggle_pause()

            # register down event
            elif button_pressed["TOP_RIGHT"] == 0 and v & buttons.TOP_RIGHT != 0:
                button_pressed["TOP_RIGHT"] = utime.time_ms()

            # register up event but event already called
            if button_pressed["TOP_RIGHT"] == -1 and v & buttons.TOP_RIGHT == 0:
                button_pressed["TOP_RIGHT"] = 0

            # register normal up event
            elif button_pressed["TOP_RIGHT"] > 0 and v & buttons.TOP_RIGHT == 0:
                duration = utime.time_ms() - button_pressed["TOP_RIGHT"]
                button_pressed["TOP_RIGHT"] = 0
380
                if pause_histogram:
Daniel Hoffend's avatar
Daniel Hoffend committed
381
382
383
384
385
386
387
                    toggle_pause()
                else:
                    toggle_mode()


if __name__ == "__main__":
    main()