-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbiopac1k.py
executable file
·98 lines (77 loc) · 2.7 KB
/
biopac1k.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
#!/usr/bin/env python
import sys
import socket
from datetime import datetime
import subprocess
import signal
import os
import time
import serial
# Be sure to set this to the correct device! Under linux, it is something
# like /dev/ttyACM0. On OSX, it will be /dev/ttyUSBNNNN, where NNNN is
# some cryptic number. On windows, it will be a COM port (e.g., COM4).
TRIGGER_DEVICE = '/dev/ttyACM0'
LABJACK_HOSTNAME = '192.168.0.12'
class LabjackRunner:
"""
lj = LabjackRunner(outfilename)
lj.start() # returns immediately
# wait a while, then...
lj.stop() # halt recording and close the output file
"""
def __init__(self, outfilename, hostname=LABJACK_HOSTNAME, sampRate=100):
self.hostname = hostname
self.outfile_name = outfilename
self.outfile_desc = None
self.hostip = socket.gethostbyname(self.hostname)
self.lj_proc = None
self.sampleRate = sampRate
def start(self):
self.outfile_desc = open(self.outfile_name,'w')
timeRef = datetime.now()
self.outfile_desc.write('%% Start time: %s\n' % str(timeRef))
self.outfile_desc.flush()
self.lj_proc = subprocess.Popen(['ue9stream2', self.hostip, str(self.sampleRate)], stdout = self.outfile_desc, cwd = os.getcwd())
# subprocess.communicate to hang until it finishes
def stop(self):
self.lj_proc.terminate()
self.lj_proc = None
# flush stdout
self.outfile_desc.close()
self.outfile_desc = None
RUNNING = True
def handler(signum, frame):
global RUNNING
RUNNING = False
# Set the signal handler to allow clean exit with a TERM signal
signal.signal(signal.SIGTERM, handler)
if __name__ == "__main__":
if len(sys.argv) > 1:
filename = sys.argv[1]
else:
filename = time.strftime('biopac_%Y%m%d_%H%M%S.csv')
if len(sys.argv) > 2:
runDuration = float(sys.argv[2])
else:
runDuration = 0.0
if len(sys.argv) > 3:
samp_rate = float(sys.argv[3])
else:
samp_rate = 1000
if runDuration>0:
print "Will record to %s for %0.2f seconds." % (filename, runDuration)
else:
print "Will record to %s forever (or until you hit ctrl-c)." % filename
lj = LabjackRunner(filename, LABJACK_HOSTNAME, samp_rate)
print "Starting recording now"
lj.start() # returns immediately
startSecs = time.time()
while RUNNING:
try:
time.sleep(0.1) # a caught signal (like TERM) will abort the sleep
except:
RUNNING = False
if runDuration>0 and time.time()-startSecs>=runDuration:
RUNNING = False
lj.stop() # halt recording and close the output file
print "Finished recording."