-
Notifications
You must be signed in to change notification settings - Fork 24
/
pytrigno.py
290 lines (239 loc) · 9.13 KB
/
pytrigno.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
import socket
import struct
import numpy
class _BaseTrignoDaq(object):
"""
Delsys Trigno wireless EMG system.
Requires the Trigno Control Utility to be running.
Parameters
----------
host : str
IP address the TCU server is running on.
cmd_port : int
Port of TCU command messages.
data_port : int
Port of TCU data access.
rate : int
Sampling rate of the data source.
total_channels : int
Total number of channels supported by the device.
timeout : float
Number of seconds before socket returns a timeout exception
Attributes
----------
BYTES_PER_CHANNEL : int
Number of bytes per sample per channel. EMG and accelerometer data
CMD_TERM : str
Command string termination.
Notes
-----
Implementation details can be found in the Delsys SDK reference:
http://www.delsys.com/integration/sdk/
"""
BYTES_PER_CHANNEL = 4
CMD_TERM = '\r\n\r\n'
def __init__(self, host, cmd_port, data_port, total_channels, timeout):
self.host = host
self.cmd_port = cmd_port
self.data_port = data_port
self.total_channels = total_channels
self.timeout = timeout
self._min_recv_size = self.total_channels * self.BYTES_PER_CHANNEL
self._initialize()
def _initialize(self):
# create command socket and consume the servers initial response
self._comm_socket = socket.create_connection(
(self.host, self.cmd_port), self.timeout)
self._comm_socket.recv(1024)
# create the data socket
self._data_socket = socket.create_connection(
(self.host, self.data_port), self.timeout)
def start(self):
"""
Tell the device to begin streaming data.
You should call ``read()`` soon after this, though the device typically
takes about two seconds to send back the first batch of data.
"""
self._send_cmd('START')
def read(self, num_samples):
"""
Request a sample of data from the device.
This is a blocking method, meaning it returns only once the requested
number of samples are available.
Parameters
----------
num_samples : int
Number of samples to read per channel.
Returns
-------
data : ndarray, shape=(total_channels, num_samples)
Data read from the device. Each channel is a row and each column
is a point in time.
"""
l_des = num_samples * self._min_recv_size
l = 0
packet = bytes()
while l < l_des:
try:
packet += self._data_socket.recv(l_des - l)
except socket.timeout:
l = len(packet)
packet += b'\x00' * (l_des - l)
raise IOError("Device disconnected.")
l = len(packet)
data = numpy.asarray(
struct.unpack('<'+'f'*self.total_channels*num_samples, packet))
data = numpy.transpose(data.reshape((-1, self.total_channels)))
return data
def stop(self):
"""Tell the device to stop streaming data."""
self._send_cmd('STOP')
def reset(self):
"""Restart the connection to the Trigno Control Utility server."""
self._initialize()
def __del__(self):
try:
self._comm_socket.close()
except:
pass
def _send_cmd(self, command):
self._comm_socket.send(self._cmd(command))
resp = self._comm_socket.recv(128)
self._validate(resp)
@staticmethod
def _cmd(command):
return bytes("{}{}".format(command, _BaseTrignoDaq.CMD_TERM),
encoding='ascii')
@staticmethod
def _validate(response):
s = str(response)
if 'OK' not in s:
print("warning: TrignoDaq command failed: {}".format(s))
class TrignoEMG(_BaseTrignoDaq):
"""
Delsys Trigno wireless EMG system EMG data.
Requires the Trigno Control Utility to be running.
Parameters
----------
channel_range : tuple with 2 ints
Sensor channels to use, e.g. (lowchan, highchan) obtains data from
channels lowchan through highchan. Each sensor has a single EMG
channel.
samples_per_read : int
Number of samples per channel to read in each read operation.
units : {'V', 'mV', 'normalized'}, optional
Units in which to return data. If 'V', the data is returned in its
un-scaled form (volts). If 'mV', the data is scaled to millivolt level.
If 'normalized', the data is scaled by its maximum level so that its
range is [-1, 1].
host : str, optional
IP address the TCU server is running on. By default, the device is
assumed to be attached to the local machine.
cmd_port : int, optional
Port of TCU command messages.
data_port : int, optional
Port of TCU EMG data access. By default, 50041 is used, but it is
configurable through the TCU graphical user interface.
timeout : float, optional
Number of seconds before socket returns a timeout exception.
Attributes
----------
rate : int
Sampling rate in Hz.
scaler : float
Multiplicative scaling factor to convert the signals to the desired
units.
"""
def __init__(self, channel_range, samples_per_read, units='V',
host='localhost', cmd_port=50040, data_port=50041, timeout=10):
super(TrignoEMG, self).__init__(
host=host, cmd_port=cmd_port, data_port=data_port,
total_channels=16, timeout=timeout)
self.channel_range = channel_range
self.samples_per_read = samples_per_read
self.rate = 2000
self.scaler = 1.
if units == 'mV':
self.scaler = 1000.
elif units == 'normalized':
# max range of EMG data is 11 mV
self.scaler = 1 / 0.011
def set_channel_range(self, channel_range):
"""
Sets the number of channels to read from the device.
Parameters
----------
channel_range : tuple
Sensor channels to use (lowchan, highchan).
"""
self.channel_range = channel_range
self.num_channels = channel_range[1] - channel_range[0] + 1
def read(self):
"""
Request a sample of data from the device.
This is a blocking method, meaning it returns only once the requested
number of samples are available.
Returns
-------
data : ndarray, shape=(num_channels, num_samples)
Data read from the device. Each channel is a row and each column
is a point in time.
"""
data = super(TrignoEMG, self).read(self.samples_per_read)
data = data[self.channel_range[0]:self.channel_range[1]+1, :]
return self.scaler * data
class TrignoAccel(_BaseTrignoDaq):
"""
Delsys Trigno wireless EMG system accelerometer data.
Requires the Trigno Control Utility to be running.
Parameters
----------
channel_range : tuple with 2 ints
Sensor channels to use, e.g. (lowchan, highchan) obtains data from
channels lowchan through highchan. Each sensor has three accelerometer
channels.
samples_per_read : int
Number of samples per channel to read in each read operation.
host : str, optional
IP address the TCU server is running on. By default, the device is
assumed to be attached to the local machine.
cmd_port : int, optional
Port of TCU command messages.
data_port : int, optional
Port of TCU accelerometer data access. By default, 50042 is used, but
it is configurable through the TCU graphical user interface.
timeout : float, optional
Number of seconds before socket returns a timeout exception.
"""
def __init__(self, channel_range, samples_per_read, host='localhost',
cmd_port=50040, data_port=50042, timeout=10):
super(TrignoAccel, self).__init__(
host=host, cmd_port=cmd_port, data_port=data_port,
total_channels=48, timeout=timeout)
self.channel_range = channel_range
self.samples_per_read = samples_per_read
self.rate = 148.1
def set_channel_range(self, channel_range):
"""
Sets the number of channels to read from the device.
Parameters
----------
channel_range : tuple
Sensor channels to use (lowchan, highchan).
"""
self.channel_range = channel_range
self.num_channels = channel_range[1] - channel_range[0] + 1
def read(self):
"""
Request a sample of data from the device.
This is a blocking method, meaning it returns only once the requested
number of samples are available.
Returns
-------
data : ndarray, shape=(num_channels, num_samples)
Data read from the device. Each channel is a row and each column
is a point in time.
"""
data = super(TrignoAccel, self).read(self.samples_per_read)
data = data[self.channel_range[0]:self.channel_range[1]+1, :]
return data