-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIOToolbox.py
executable file
·3614 lines (2713 loc) · 122 KB
/
IOToolbox.py
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Universiteit Antwerpen
# Functional Morphology
# Falk Mielke
# 2019/06/06
# contains parts as ADAPTATION of https://github.com/adafruit/Adafruit_Python_GPIO
# used to connect I2C via the FT232H interface
################################################################################
### Libraries ###
################################################################################
import os as OS
import sys as SYS
import select as SEL # for timed user input
import re as RE # regular expressions
import time as TI # time, for process pause and date
import atexit as EXIT # commands to shut down processes
import subprocess as SP
import threading as TH # threading for trigger
import queue as QU # data buffer
from collections import deque as DEQue # double ended queue
import numpy as NP # numerics
import pandas as PD # data storage
import scipy.signal as SIG
import math as MATH
import matplotlib as MP # plotting
MP.use('TkAgg')
import matplotlib.pyplot as MPP # plot control
# import ftdi1 as FTDI
# import pyftdi as FTDI
import ftdi1 as FTDI
uldaq_skip_import = False
if not uldaq_skip_import:
import uldaq as UL # MCC DAQ negotiation
import logging
logger = logging.getLogger(__name__)
### MCC DAQ drivers and library
# follow readme in https://github.com/mccdaq/uldaq
# download $ wget -N https://github.com/mccdaq/uldaq/releases/download/v1.2.0/libuldaq-1.2.0.tar.bz2
# extract $ tar -xvjf libuldaq-1.2.0.tar.bz2 && cd libuldaq-1.2.0
# build $ ./configure && make -j2 && sudo make install -j2
# if "make" fails, you might need to do: ln -s /usr/bin/autom-1.16 /usr/bin/aclocal-1.14 && ln -s /usr/bin/automake-1.16 /usr/bin/automake-1.14
# pip install uldaq
### FTDI FT232H breakout drivers and library
## driver
# see https://www.ftdichip.com/Drivers/D2XX.htm
# wget https://www.ftdichip.com/Drivers/D2XX/Linux/libftd2xx-x86_64-1.4.8.gz
# tar -xvzf libftd2xx-x86_64-1.4.8.gz
# mv release ftd2xx
# cd ftd2xx/build/
# cp libftd2xx.* /usr/local/lib
# chmod 0755 /usr/local/lib/libftd2xx.so.1.4.8
# ln -sf /usr/local/lib/libftd2xx.so.1.4.8 /usr/local/lib/libftd2xx.so
## software
# wget https://www.intra2net.com/en/developer/libftdi/download/libftdi1-1.5.tar.bz2
# tar -xvf libftdi1-1.5.tar.bz2
# cd libftdi1-1.5
# mkdir build && cd build
# cmake -DCMAKE_INSTALL_PREFIX="/usr" ../
# make
# make install
#
## also:
# pip install pyftdi pylibftdi
################################################################################
### Global Specifications ###
################################################################################
coordinates = ['x', 'y', 'z']
FT232H_VID = 0x0403 # Default FTDI FT232H vendor ID
FT232H_PID = 0x6014 # Default FTDI FT232H product ID
_REPEAT_DELAY = 4
################################################################################
### Plotting ###
################################################################################
the_font = { \
# It's really sans-serif, but using it doesn't override \sffamily, so we tell Matplotlib
# to use the "serif" font because then Matplotlib won't ask for any special families.
# 'family': 'serif' \
# , 'serif': 'Iwona' \
'family': 'sans-serif'
, 'sans-serif': 'DejaVu Sans'
, 'size': 10#*1.27 \
}
def PreparePlot():
# select some default rc parameters
MP.rcParams['text.usetex'] = True
MPP.rc('font',**the_font)
# Tell Matplotlib how to ask TeX for this font.
# MP.texmanager.TexManager.font_info['iwona'] = ('iwona', r'\usepackage[light,math]{iwona}')
MP.rcParams['text.latex.preamble'] = [\
r'\usepackage{upgreek}'
, r'\usepackage{cmbright}'
, r'\usepackage{sansmath}'
]
MP.rcParams['pdf.fonttype'] = 42 # will make output TrueType (whatever that means)
def PolishAx(ax):
# axis cosmetics
ax.get_xaxis().set_tick_params(which='both', direction='out')
ax.get_yaxis().set_tick_params(which='both', direction='out')
ax.tick_params(top = False)
ax.tick_params(right = False)
# ax.tick_params(left=False)
ax.spines['top'].set_visible(False)
ax.spines['bottom'].set_visible(True)
ax.spines['left'].set_visible(True)
ax.spines['right'].set_visible(False)
################################################################################
### Base GPIO Functionality ###
################################################################################
RISING = 1
FALLING = 2
BOTH = 3
PUD_OFF = 0
PUD_DOWN = 1
PUD_UP = 2
class BaseGPIO(object):
"""Base class for implementing simple digital IO for a platform.
Implementors are expected to subclass from this and provide an implementation
of the setup, output, and input functions."""
def setup(self, pin, mode, pull_up_down=PUD_OFF):
"""Set the input or output mode for a specified pin. Mode should be
either OUT or IN."""
raise NotImplementedError
def output(self, pin, value):
"""Set the specified pin the provided high/low value. Value should be
either HIGH/LOW or a boolean (true = high)."""
raise NotImplementedError
def input(self, pin):
"""Read the specified pin and return HIGH/true if the pin is pulled high,
or LOW/false if pulled low."""
raise NotImplementedError
def set_high(self, pin):
"""Set the specified pin HIGH."""
self.output(pin, HIGH)
def set_low(self, pin):
"""Set the specified pin LOW."""
self.output(pin, LOW)
def is_high(self, pin):
"""Return true if the specified pin is pulled high."""
return self.input(pin) == HIGH
def is_low(self, pin):
"""Return true if the specified pin is pulled low."""
return self.input(pin) == LOW
# Basic implementation of multiple pin methods just loops through pins and
# processes each one individually. This is not optimal, but derived classes can
# provide a more optimal implementation that deals with groups of pins
# simultaneously.
# See MCP230xx or PCF8574 classes for examples of optimized implementations.
def output_pins(self, pins):
"""Set multiple pins high or low at once. Pins should be a dict of pin
name to pin value (HIGH/True for 1, LOW/False for 0). All provided pins
will be set to the given values.
"""
# General implementation just loops through pins and writes them out
# manually. This is not optimized, but subclasses can choose to implement
# a more optimal batch output implementation. See the MCP230xx class for
# example of optimized implementation.
for pin, value in iter(pins.items()):
self.output(pin, value)
def setup_pins(self, pins):
"""Setup multiple pins as inputs or outputs at once. Pins should be a
dict of pin name to pin type (IN or OUT).
"""
# General implementation that can be optimized by derived classes.
for pin, value in iter(pins.items()):
self.setup(pin, value)
def input_pins(self, pins):
"""Read multiple pins specified in the given list and return list of pin values
HIGH/True if the pin is pulled high, or LOW/False if pulled low.
"""
# General implementation that can be optimized by derived classes.
return [self.input(pin) for pin in pins]
def add_event_detect(self, pin, edge):
"""Enable edge detection events for a particular GPIO channel. Pin
should be type IN. Edge must be RISING, FALLING or BOTH.
"""
raise NotImplementedError
def remove_event_detect(self, pin):
"""Remove edge detection for a particular GPIO channel. Pin should be
type IN.
"""
raise NotImplementedError
def add_event_callback(self, pin, callback):
"""Add a callback for an event already defined using add_event_detect().
Pin should be type IN.
"""
raise NotImplementedError
def event_detected(self, pin):
"""Returns True if an edge has occured on a given You need to
enable edge detection using add_event_detect() first. Pin should be
type IN.
"""
raise NotImplementedError
def wait_for_edge(self, pin, edge):
"""Wait for an edge. Pin should be type IN. Edge must be RISING,
FALLING or BOTH."""
raise NotImplementedError
def cleanup(self, pin=None):
"""Clean up GPIO event detection for specific pin, or all pins if none
is specified.
"""
raise NotImplementedError
# helper functions useful to derived classes
def _validate_pin(self, pin):
# Raise an exception if pin is outside the range of allowed values.
if pin < 0 or pin >= self.NUM_GPIO:
raise ValueError('Invalid GPIO value, must be between 0 and {0}.'.format(self.NUM_GPIO))
def _bit2(self, src, bit, val):
bit = 1 << bit
return (src | bit) if val else (src & ~bit)
################################################################################
### FT232H Initialization ###
################################################################################
def _check_running_as_root():
# NOTE: Checking for root with user ID 0 isn't very portable, perhaps
# there's a better alternative?
if OS.geteuid() != 0:
raise RuntimeError('Expected to be run by root user! Try running with sudo.')
def disable_FTDI_driver():
"""Disable the FTDI drivers for the current platform. This is necessary
because they will conflict with libftdi and accessing the FT232H. Note you
can enable the FTDI drivers again by calling enable_FTDI_driver.
"""
SP.call('modprobe -r -q ftdi_sio', shell=True)
SP.call('modprobe -r -q usbserial', shell=True)
# Note there is no need to disable FTDI drivers on Windows!
def enable_FTDI_driver():
"""Re-enable the FTDI drivers for the current platform."""
# SP.check_call('modprobe -q ftdi_sio', shell=True)
# SP.check_call('modprobe -q usbserial', shell=True)
pass
def ManageDrivers():
disable_FTDI_driver()
EXIT.register(enable_FTDI_driver)
def FindDevices(vid = FT232H_VID, pid = FT232H_PID):
"""Return a list of all FT232H device serial numbers connected to the
machine. You can use these serial numbers to open a specific FT232H device
by passing it to the FT232H initializer's serial parameter.
"""
try:
# Create a libftdi context.
ctx = None
ctx = FTDI.new()
# Enumerate FTDI devices.
device_list = None
count, device_list = FTDI.usb_find_all(ctx, vid, pid)
if count < 0:
raise RuntimeError('ftdi_usb_find_all returned error {0}: {1}'.format(count, FTDI.get_error_string(self._ctx)))
# Walk through list of devices and assemble list of serial numbers.
devices = []
while device_list is not None:
# Get USB device strings and add serial to list of devices.
ret, manufacturer, description, serial = FTDI.usb_get_strings(ctx, device_list.dev, 256, 256, 256)
if serial is not None:
devices.append(serial)
device_list = device_list.next
return devices
finally:
# Make sure to clean up list and context when done.
if device_list is not None:
FTDI.list_free(device_list)
if ctx is not None:
FTDI.free(ctx)
def FindAllI2CSlaves(master):
print ('Scanning all I2C bus addresses...')
# Enumerate all I2C addresses.
for address in range(127):
# Skip I2C addresses which are reserved.
if address <= 7 or address >= 120:
continue
# Create I2C object.
i2c = I2CDevice(master, address)
# Check if a device responds to this address.
if i2c.ping():
print ('Found I2C device at address 0x{0:02X}'.format(address))
print ('Done!')
################################################################################
### FT232H Control ###
################################################################################
class FT232H(BaseGPIO):
def __init__(self, vid = FT232H_VID, pid = FT232H_PID, serial = None, multiplexer_address = None, clock_hz = 1e6):
"""Create a FT232H object. Will search for the first available FT232H
device with the specified USB vendor ID and product ID (defaults to
FT232H default VID & PID). Can also specify an optional serial number
string to open an explicit FT232H device given its serial number. See
the FT232H.enumerate_device_serials() function to see how to list all
connected device serial numbers.
"""
# Initialize FTDI device connection.
ManageDrivers()
self._ctx = FTDI.new()
if self._ctx == 0:
raise RuntimeError('ftdi_new failed! Is libftdi1 installed?')
# Register handler to close and cleanup FTDI context on program exit.
EXIT.register(self.close)
if serial is None:
# Open USB connection for specified VID and PID if no serial is specified.
self._check(FTDI.usb_open, vid, pid)
else:
# Open USB connection for VID, PID, serial.
self._check(FTDI.usb_open_string, 's:{0}:{1}:{2}'.format(vid, pid, serial))
# Reset device.
self._check(FTDI.usb_reset)
# Disable flow control. Commented out because it is unclear if this is necessary.
#self._check(FTDI.setflowctrl, FTDI.SIO_DISABLE_FLOW_CTRL)
# Change read & write buffers to maximum size, 65535 bytes.
self._check(FTDI.read_data_set_chunksize, 65535)
self._check(FTDI.write_data_set_chunksize, 65535)
# Clear pending read data & write buffers.
self._check(FTDI.usb_purge_buffers)
# Enable MPSSE and syncronize communication with device.
self._mpsse_enable()
self._mpsse_sync()
# Initialize all GPIO as inputs.
self._write(b'\x80\x00\x00\x82\x00\x00')
self._direction = 0x0000
self._level = 0x0000
# connecting a TCA9548A Multiplexer
self.pins_in_use = []
if multiplexer_address is not None:
self.multiplexer = TCA9548A(self, multiplexer_address, clock_hz = clock_hz)
def close(self):
"""Close the FTDI device. Will be automatically called when the program ends."""
if self._ctx is not None:
FTDI.free(self._ctx)
self._ctx = None
def _write(self, string):
"""Helper function to call write_data on the provided FTDI device and
verify it succeeds.
"""
# Get modem status. Useful to enable for debugging.
#ret, status = FTDI.poll_modem_status(self._ctx)
#if ret == 0:
# logger.debug('Modem status {0:02X}'.format(status))
#else:
# logger.debug('Modem status error {0}'.format(ret))
length = len(string)
# try:
# ret = FTDI.write_data(self._ctx, string, length)
# except TypeError:
# print (string)
ret = FTDI.write_data(self._ctx, string); #compatible with libFtdi 1.3
# Log the string that was written in a python hex string format using a very
# ugly one-liner list comprehension for brevity.
#logger.debug('Wrote {0}'.format(''.join(['\\x{0:02X}'.format(ord(x)) for x in string])))
if ret < 0:
raise RuntimeError('ftdi_write_data failed with error {0}: {1}'.format(ret, FTDI.get_error_string(self._ctx)))
if ret != length:
raise RuntimeError('ftdi_write_data expected to write {0} bytes but actually wrote {1}!'.format(length, ret))
def _check(self, command, *args):
"""Helper function to call the provided command on the FTDI device and
verify the response matches the expected value.
"""
ret = command(self._ctx, *args)
logger.debug('Called ftdi_{0} and got response {1}.'.format(command.__name__, ret))
if ret != 0:
raise RuntimeError('ftdi_{0} failed with error {1}: {2}'.format(command.__name__, ret, FTDI.get_error_string(self._ctx)))
def _poll_read(self, expected, timeout_s=5.0):
"""Helper function to continuously poll reads on the FTDI device until an
expected number of bytes are returned. Will throw a timeout error if no
data is received within the specified number of timeout seconds. Returns
the read data as a string if successful, otherwise raises an execption.
"""
start = TI.time()
# Start with an empty response buffer.
response = bytearray(expected)
# print ('response', response, expected)
index = 0
# Loop calling read until the response buffer is full or a timeout occurs.
while TI.time() - start <= timeout_s:
ret, data = FTDI.read_data(self._ctx, expected - index)
# print (ret, data)
# py2:
# ('response', bytearray(b'\x00\x00'), 2)
# (0, '\x00\xd7')
# (0, '\x00\xd7')
# (2, '\xfa\xab')
# py3:
# response bytearray(b'\x00\x00') 2
# 0 b'\x90='
# 0 b'\x90='
# 2 b'\xfa\xab'
# Fail if there was an error reading data.
if ret < 0:
raise RuntimeError('ftdi_read_data failed with error code {0}.'.format(ret))
# Add returned data to the buffer.
response[index:index+ret] = data[:ret]
# index += ret
# Buffer is full, return the result data.
# if index >= expected:
# return str(response)
## Py3: (FM)
if ret >= expected:
return response
TI.sleep(0.01)
raise RuntimeError('Timeout while polling ftdi_read_data for {0} bytes!'.format(expected))
def _mpsse_enable(self):
"""Enable MPSSE mode on the FTDI device."""
# Reset MPSSE by sending mask = 0 and mode = 0
self._check(FTDI.set_bitmode, 0, 0)
# Enable MPSSE by sending mask = 0 and mode = 2
self._check(FTDI.set_bitmode, 0, 2)
def _mpsse_sync(self, max_retries=10):
"""Synchronize buffers with MPSSE by sending bad opcode and reading expected
error response. Should be called once after enabling MPSSE."""
# Send a bad/unknown command (0xAB), then read buffer until bad command
# response is found.
self._write(b'\xAB')
# Keep reading until bad command response (0xFA 0xAB) is returned.
# Fail if too many read attempts are made to prevent sticking in a loop.
tries = 0
sync = False
while not sync:
data = self._poll_read(2)
if data == b'\xfa\xab':
sync = True
tries += 1
if tries >= max_retries:
raise RuntimeError('Could not synchronize with FT232H!')
def mpsse_set_clock(self, clock_hz, adaptive=False, three_phase=False):
"""Set the clock speed of the MPSSE engine. Can be any value from 450hz
to 30mhz and will pick that speed or the closest speed below it.
"""
# Disable clock divisor by 5 to enable faster speeds on FT232H.
self._write(b'\x8A')
# Turn on/off adaptive clocking.
if adaptive:
self._write(b'\x96')
else:
self._write(b'\x97')
# Turn on/off three phase clock (needed for I2C).
# Also adjust the frequency for three-phase clocking as specified in section 2.2.4
# of this document:
# http://www.ftdichip.com/Support/Documents/AppNotes/AN_255_USB%20to%20I2C%20Example%20using%20the%20FT232H%20and%20FT201X%20devices.pdf
if three_phase:
self._write(b'\x8C')
else:
self._write(b'\x8D')
# Compute divisor for requested clock.
# Use equation from section 3.8.1 of:
# http://www.ftdichip.com/Support/Documents/AppNotes/AN_108_Command_Processor_for_MPSSE_and_MCU_Host_Bus_Emulation_Modes.pdf
# Note equation is using 60mhz master clock instead of 12mhz.
divisor = int(MATH.ceil((30000000.0-float(clock_hz))/float(clock_hz))) & 0xFFFF
if three_phase:
divisor = int(divisor*(2.0/3.0))
logger.debug('Setting clockspeed with divisor value {0}'.format(divisor))
# Send command to set divisor from low and high byte values.
# my_str = "hello world"
# my_str_as_bytes = str.encode(my_str)
# print(my_str_as_bytes, type(my_str_as_bytes) )
# my_decoded_str = my_str_as_bytes.decode()
# print(my_decoded_str, type(my_decoded_str) )
# val = (0x86, divisor & 0xFF, (divisor >> 8) & 0xFF)
# ba = bytearray(val)
# help(ba)
# string = bytes(ba)
# print(val, ba, string)
# print (str(bytearray((0x86, divisor & 0xFF, (divisor >> 8) & 0xFF))))
# print (bytes(bytearray((0x86, divisor & 0xFF, (divisor >> 8) & 0xFF))))
self._write(bytes(bytearray((0x86, divisor & 0xFF, (divisor >> 8) & 0xFF))))
def mpsse_read_gpio(self):
"""Read both GPIO bus states and return a 16 bit value with their state.
D0-D7 are the lower 8 bits and C0-C7 are the upper 8 bits.
"""
# Send command to read low byte and high byte.
self._write(b'\x81\x83')
# Wait for 2 byte response.
data = self._poll_read(2)
# Assemble response into 16 bit value.
low_byte = data[0]
high_byte = data[1]
logger.debug('Read MPSSE GPIO low byte = {0:02X} and high byte = {1:02X}'.format(low_byte, high_byte))
return (high_byte << 8) | low_byte
def mpsse_gpio(self):
"""Return command to update the MPSSE GPIO state to the current direction
and level.
"""
level_low = (self._level & 0xFF)
level_high = ((self._level >> 8) & 0xFF)
dir_low = (self._direction & 0xFF)
dir_high = ((self._direction >> 8) & 0xFF)
return bytes(bytearray((0x80, level_low, dir_low, 0x82, level_high, dir_high)))
def mpsse_write_gpio(self):
"""Write the current MPSSE GPIO state to the FT232H chip."""
self._write(self.mpsse_gpio())
def get_i2c_device(self, address, **kwargs):
"""Return an I2CDevice instance using this FT232H object and the provided
I2C address. Meant to be passed as the i2c_provider parameter to objects
which use the Adafruit_Python_GPIO library for I2C.
"""
return I2CDevice(self, address, **kwargs)
# GPIO functions below:
def _setup_pin(self, pin, mode):
if pin < 0 or pin > 15:
raise ValueError('Pin must be between 0 and 15 (inclusive).')
if mode not in (IN, OUT):
raise ValueError('Mode must be IN or OUT.')
if mode == IN:
# Set the direction and level of the pin to 0.
self._direction &= ~(1 << pin) & 0xFFFF
self._level &= ~(1 << pin) & 0xFFFF
else:
# Set the direction of the pin to 1.
self._direction |= (1 << pin) & 0xFFFF
def setup(self, pin, mode):
"""Set the input or output mode for a specified pin. Mode should be
either OUT or IN."""
self._setup_pin(pin, mode)
self.mpsse_write_gpio()
def setup_pins(self, pins, values={}, write=True):
"""Setup multiple pins as inputs or outputs at once. Pins should be a
dict of pin name to pin mode (IN or OUT). Optional starting values of
pins can be provided in the values dict (with pin name to pin value).
"""
# General implementation that can be improved by subclasses.
for pin, mode in iter(pins.items()):
self._setup_pin(pin, mode)
for pin, value in iter(values.items()):
self._output_pin(pin, value)
if write:
self.mpsse_write_gpio()
def _output_pin(self, pin, value):
if value:
self._level |= (1 << pin) & 0xFFFF
else:
self._level &= ~(1 << pin) & 0xFFFF
def output(self, pin, value):
"""Set the specified pin the provided high/low value. Value should be
either HIGH/LOW or a boolean (true = high)."""
if pin < 0 or pin > 15:
raise ValueError('Pin must be between 0 and 15 (inclusive).')
self._output_pin(pin, value)
self.mpsse_write_gpio()
def output_pins(self, pins, write=True):
"""Set multiple pins high or low at once. Pins should be a dict of pin
name to pin value (HIGH/True for 1, LOW/False for 0). All provided pins
will be set to the given values.
"""
for pin, value in iter(pins.items()):
self._output_pin(pin, value)
if write:
self.mpsse_write_gpio()
def input(self, pin):
"""Read the specified pin and return HIGH/true if the pin is pulled high,
or LOW/false if pulled low."""
return self.input_pins([pin])[0]
def input_pins(self, pins):
"""Read multiple pins specified in the given list and return list of pin values
HIGH/True if the pin is pulled high, or LOW/False if pulled low."""
if [pin for pin in pins if pin < 0 or pin > 15]:
raise ValueError('Pin must be between 0 and 15 (inclusive).')
_pins = self.mpsse_read_gpio()
return [((_pins >> pin) & 0x0001) == 1 for pin in pins]
def LED(self, pin, turn_on = False):
# turn an LED on or off
if pin not in self.pins_in_use:
self.setup(pin, OUT)
self.output(pin, HIGH if turn_on else LOW)
################################################################################
### GPIO Function ###
################################################################################
OUT = 0
IN = 1
HIGH = True
LOW = False
def TestGPIO(pin_nr = 7):
ft1 = FT232H(serial = FindDevices()[0])
# pin_nr = 7 # D7
# pin_nr = 8 # C0
ft1.setup(pin_nr, OUT)
TI.sleep(1)
for _ in range(2):
ft1.output(pin_nr, HIGH)
# Sleep for 1 second.
TI.sleep(1)
# Set pin D7 to a low level so the LED turns off.
ft1.output(pin_nr, LOW)
TI.sleep(1)
ft1.close()
def TestGPIOInput(pin_nr = 3):
ft1 = FT232H(serial = FindDevices()[0])
ft1.setup(pin_nr, IN)
TI.sleep(0.01)
t0 = TI.time()
status = False
print (ft1.input(pin_nr))
while True:
new = ft1.input(pin_nr)
if status == new:
TI.sleep(0.000001)
if TI.time() - t0 > 10.:
break
else:
status = new
print (status, TI.time()-t0)
ft1.close()
################################################################################
### Trigger Logger = Trogger ###
################################################################################
class Ligger(TH.Thread):
# trigger listener
def __init__(self, output_file, header = None):
super(Ligger, self).__init__()
self.data_queue = QU.Queue()
self.led_queue = QU.Queue()
self.output_file = output_file
if header is not None:
self.PrintFiles(header)
# self.counter = 0
def PrintFiles(self, result):
# self.counter += 1
# print ("writing", self.counter)
# print (">", result)
print(result, file = self.output_file)
def run(self):
self.running = True
while self.running:
if not self.data_queue.empty():
data_str = self.data_queue.get()
self.PrintFiles(data_str)
split_data = data_str.split(';')
if (split_data[1] == 'False'):# and not (split_data[0] == '7'):
self.led_queue.put(True)
continue
TI.sleep(1e-8)
# print ("stopped ligger")
def Stop(self):
while not self.data_queue.empty():
self.PrintFiles(self.data_queue.get())
# print ("stopped.")
self.running = False
# def join(self, *args, **kwargs):
# # print (self.data_queue)
# # self.data_queue.join()
# super(Ligger, self).join(*args, **kwargs)
# # print ('all done')
class TroggerLED(TH.Thread):
# trigger listener
def __init__(self, pin, ft_breakout, led_queue, data_queue, duration = 10):
self.pin = pin
self.ft_breakout = ft_breakout
self.led_queue = led_queue
self.data_queue = data_queue
self.duration = duration
self.ft_breakout.setup(self.pin, OUT)
super(TroggerLED, self).__init__()
def run(self):
# blink if receiving a queue signal
self.running = True
while self.running:
if not self.led_queue.empty():
if self.led_queue.get():
self.Blink()
TI.sleep(1e-8)
# print ("stopped ligger")
def Blink(self):
dt = 1/self.duration
# initially switch LED for .5 secs
self.data_queue.put( "%i;%s;%f" % (7, 'on0', TI.time()) )
self.ft_breakout.output(self.pin, HIGH)
TI.sleep(.25)
self.data_queue.put( "%i;%s;%f" % (7, 'off0', TI.time()) )
# self.data_queue.put( "%i;%s;%f" % (7, False, TI.time()) )
# self.ft_breakout.output(self.pin, LOW)
# TI.sleep(.25)
for repeat in range(int(self.duration//1)):
# Set pin to a low level so the LED turns off.
# self.data_queue.put( "%i;%s;%f" % (7, False, TI.time()) )
self.ft_breakout.output(self.pin, LOW)
TI.sleep((repeat)*dt)
# Set pin to a high level so the LED turns on.
self.data_queue.put( "%i;%s;%f" % (7, 'on%i' % (repeat+1), TI.time()) )
self.ft_breakout.output(self.pin, HIGH)
TI.sleep(1.-(repeat)*dt)
self.data_queue.put( "%i;%s;%f" % (7, 'off%i' % (repeat+1), TI.time()) )
# self.data_queue.put( "%i;%s;%f" % (7, False, TI.time()) )
self.ft_breakout.output(self.pin, LOW)
def Stop(self):
self.running = False
class Shouter(TH.Thread):
# A Logged Producer Process
def __init__(self, label, data_queue, autostart = False):
super(Shouter, self).__init__()
# self.in_queue = in_queue
self.data_queue = data_queue
self.label = label
self.setDaemon(True)
if autostart:
self.start()
def run(self):
self.running = True
while self.running:
self.Process()
TI.sleep(1e-8)
# print ("stopped %s" % str(self.label))
def Stop(self):
self.running = False
def Process(self):
# Do the processing job here
dice = RND.uniform(0.,1.,1)
if dice > 0.999:
self.data_queue.put( "%i;%.3f;%f" % (self.label, dice, TI.time()) )
class LoggedPin(Shouter):
def __init__(self, ft_breakout, pin_nr, *args, **kwargs):
self.ft_breakout = ft_breakout
self.pin_nr = pin_nr
# kwargs['label'] = str(pin_nr)
self.ft_breakout.setup(self.pin_nr, IN)
self.status = self.ft_breakout.input(self.pin_nr)
super(LoggedPin, self).__init__(*args, **kwargs)
def Process(self):
# Do the processing job here
t = TI.time()
new_status = self.ft_breakout.input(self.pin_nr)
if new_status != self.status:
self.status = new_status
self.data_queue.put( "%i;%s;%f" % (self.pin_nr, str(self.status), t) )
class Trogger(object):
# A Trigger-Logger
def __init__(self, pins = [], serial = None, storage_file = None, led_duration = 10.):
if serial is None:
self.ft_breakout = FT232H(serial = FindDevices()[0])
else:
self.ft_breakout = FT232H(serial = serial)
if storage_file is None:
storage_file = "%s_log.txt" % (TI.strftime('%Y%m%d'))
# spawn threads to print
self.archivar = Ligger( open(storage_file, 'a') \
, header = '#________\npin;changes_to;time_%s' % (TI.strftime('%Y%m%d')) \
)
self.archivar.setDaemon(True)
self.archivar.start()
# spawn threads to process
self.logged_pins = [LoggedPin(self.ft_breakout, pin, data_queue = self.archivar.data_queue \
, autostart = True, label = str(pin) \
) for pin in pins]
for lpin in self.logged_pins:
lpin.data_queue.put( "%i;%s;%f" % (lpin.pin_nr, str(lpin.status), TI.time()) )
print ('trogger led')
self.indicator = TroggerLED( pin = 7, ft_breakout = self.ft_breakout \
, led_queue = self.archivar.led_queue, data_queue = self.archivar.data_queue \
, duration = led_duration \
)
self.indicator.setDaemon(True)
self.indicator.start()
EXIT.register(self.Quit)
def Log(self):
# TI.sleep(2)
while True:
TI.sleep(1e-2)
def Quit(self):
for lpin in self.logged_pins:
lpin.Stop()
lpin.join()
self.indicator.Stop()
self.indicator.join()
self.archivar.Stop()
self.archivar.join()
self.ft_breakout.close()
print ('safely exited.')
def __enter__(self):
# required for context management ("with")
return self
def __exit__(self, exc_type, exc_value, traceback):
# exiting when in context manager
self.Quit()
def TestTrogger(pins = []):
with Trogger(pins) as trog:
try:
trog.Log()
except KeyboardInterrupt as ki:
trog.Quit()
################################################################################
### MCC USB1608G DAQ ###
################################################################################
instrument_labels = { '01DF5B18': 'blue' \
, '01DF5AFB': 'green'
}
if not uldaq_skip_import:
status_dict = { \
UL.ScanStatus.IDLE: 'idle' \
, UL.ScanStatus.RUNNING: 'running' \
}
class MCCDAQ(object):
# generic device functions
# for output pin values
LOW = 0
HIGH = 255
# analog input recording mode
if not uldaq_skip_import:
recording_mode = UL.ScanOption.BLOCKIO