-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDevice.m
2034 lines (1770 loc) · 85.3 KB
/
Device.m
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
classdef Device < TMSiSAGA.HiddenHandle
%DEVICE Class provides access to a single TMSi device.
%
% When a device object is created the initial device config is retrieved from
% the device all properties are set and the connection is closed. Depending on
% which functions you call some will require to "sync" your MATLAB device object
% with the actual device. This will require a call to updateDeviceConfig(). In case
% you forgot a warning will be shown in the console.
%
%DEVICE Properties:
% device_id - Device ID
% handle - Internal device handle for TMSi device
% is_connected - Keep track whether or not device is connected
% docking_station - Contains information about docking station
% data_recorder - Contains information about recording device
% api_version - Current API version
% num_batteries - Number of batteries available
% num_channels - Number of channels available
% num_hw_channels - Number of hardware channels
% num_sensors - Number of sensors
% power_state - Current power state of system
% batteries - Battery information
% time - Time information
% max_storage_size - Max available storage size
% available_storage_size - Still available storage size
% ambulant_recording - Ambulant recording enabled/disabled
% available_recordings - Recordings available
% name - Name of device
% channels - Channels
% sensors - Sensors
% impedance_mode - Impedance Mode
% num_active_channels - Num active channels
% num_active_impedance_channels - Num active impedance channels
% missing_samples - Missing samples
% sample_rate - Sample rate
% dividers - Dividers
% out_of_sync - Out of Sync with device
% is_sampling - True, if a sampler is sampling
% pinkey - Pin key
% configuration - Contains information on configuration settings
%
%DEVICE Methods:
% Device - Constructor for Device object.
% connect - Connect to the device.
% disconnect - Disconnect the device.
% start - Start sampling in sample or impedance mode.
% stop - Stop sampling.
% sample - Retrieve samples from the device.
% getMissingSamples - Get missing samples after a sampling session.
% changeDataRecorderInterfaceTo - Change the data recorder connection interface.
% resetDeviceConfig - Reset the device configuration to factory settings.
% enableChannels - Enable channels.
% disableChannels - Disable channels.
% getSensorChannels - Get all sensor channels.
% getActiveChannels - Get all active channels.
% updateDeviceConfig - Push the changed device configs to the actual TMSi device.
% getDeviceInfo - Get all device information from the device.
% updateDynamicInfo - Update dynamic calculated information for the device.
% getDeviceStatus - Get device status.
% getDeviceConfig - Get device config.
% setDeviceConfig - Set device config.
% getCurrentBandwidth - Calculates the used bandwidth of the channel configuration in use.
% setChannelConfig - Set channel configuration.
%
%DEVICE Example
% device = library.getFirstAvailableDevice('network', 'electrical');
%
% disp(['Sample Rate: ' num2str(device.sample_rate)]);
% disp(['Channel Name: ' device.channels{1}.alternative_name]);
% disp(['Unit: ' device.channels{1}.unit_name]);
%
properties
% Device ID
device_id
% Internal device handle for TMSi device
handle
% Keep track whether or not device is connected
is_connected
% Contains information about docking station
docking_station
% Contains information about recording device
data_recorder
% Current API version
api_version
% Number of batteries available
num_batteries
% Number of channels available
num_channels
% Number of hardware channels
num_hw_channels
% Number of sensors
num_sensors
% Current power state of system
power_state
% Battery information
batteries
% Time information
time
% % Max available storage size. (Card recording, not supported).
% max_storage_size
%
% % Still available storage size. (Card recording, not supported).
% available_storage_size
%
% % Ambulant recording enabled/disabled. (Card recording, not supported).
% ambulant_recording
%
% % Recordings available. (Card recording, not supported).
% available_recordings
% Name of device
name
% Channels
channels
% Sensors
sensors
% Impedance Mode
impedance_mode
% Num active channels
num_active_channels
% Num active impedance channels
num_active_impedance_channels
% Missing samples
missing_samples
% Sample rate
sample_rate
% Dividers
dividers
% Out of Sync with device
out_of_sync
% True, if a sampler is sampling
is_sampling
% True if sampler is recording
is_recording = false
% Pin key
pinkey
% Contains information on configuration settings
configuration
% Number of seconds we want to sample from the device (at most)
% with any call to `sample`
% desired_sample_buffer_length (1,1) double {mustBeInRange(desired_sample_buffer_length, 0.010, 10)} = 5
desired_sample_buffer_length (1,1) double {mustBeInRange(desired_sample_buffer_length, 0.010, 10)} = 10;
% desired_sample_buffer_length (1,1) double {mustBeInRange(desired_sample_buffer_length, 0.010, 10)} = 0.020;
% File expressions
impedance_file_expr
data_file_expr
recording_index = -1
verbose = 0
end
properties (GetAccess = public, SetAccess = protected)
% User tag for this device
tag = ""
% Active channel indices
active_channel_indices
% Current counter channel index
current_counter_channel_index
% Current status channel index
current_status_channel_index
% Current triggers channel index
current_triggers_channel_index
end
properties (Access = private)
% Library
lib
% Size of sample buffer
prepared_sample_buffer_length
% Sample buffer
prepared_sample_buffer
end
methods (Access = private)
function setChannelConfig_(obj, channelConfig)
%SETCHANNELCONFIG_ - Function that applies the specified channel configuration.
%
% setChannelConfig_(obj, ChannelConfig)
%
% Function that applies a specified channel configuration.
% When a channel is not present in the specified
% configuration, the channel will be disabled.
%
% obj [in] - Device object.
% ChannelConfig [in] - Desired channel configuration.
%
% ChannelConfig may contain the following name/value pairs:
% ChannelConfig.uni - UNI channels, 1-32 for SAGA 32+ or 1-64
% for SAGA 64+
% ChannelConfig.bip - BIP channels, 1-4
% ChannelConfig.aux - AUX channels, 1-9
% ChannelConfig.acc - internal accelerometer channels 0 or 1
% for disable/enable
% ChannelConfig.dig - DIGI configuration, 0 for DIGI Trigger
% or 1 saturation sensor
if numel(obj) > 1
if numel(channelConfig) == 1
channelConfig = repmat(channelConfig, size(obj));
end
for ii = 1:numel(obj)
setChannelConfig_(obj(ii), channelConfig(ii));
end
return;
end
% Check what type of channels need to be configured.
if ~isfield(channelConfig, 'uni')
channelConfig.uni=0;
end
if ~isfield(channelConfig, 'bip')
channelConfig.bip=0;
end
if ~isfield(channelConfig, 'aux')
channelConfig.aux=0;
end
if ~isfield(channelConfig, 'acc')
channelConfig.acc=0;
end
if ~isfield(channelConfig, 'dig')
channelConfig.dig=0;
end
count_UNI = 0;
count_BIP = 0;
count_AUX = 0;
count_Dig = 0;
% Enable used channels
for i=1:length(obj.channels)
% Enable desired BIP channels
if (obj.channels(i).isBip())
count_BIP = count_BIP + 1;
if ismember(count_BIP, channelConfig.bip)
obj.enableChannels(i);
else
obj.disableChannels(i);
end
% Enable desired UNI (ExG) channels
elseif (obj.channels(i).isExG())
count_UNI = count_UNI + 1;
if ismember(count_UNI, channelConfig.uni + 1) && ~strcmp(obj.channels(i).name,'CREF') %+1 for CREF channel
obj.enableChannels(i);
else
obj.disableChannels(i);
end
% Enable desired AUX channels
elseif (obj.channels(i).isAux())
count_AUX = count_AUX + 1;
if ismember(count_AUX, channelConfig.aux)
obj.enableChannels(i);
else
obj.disableChannels(i);
end
% Enable desired Digital/sensor channels
elseif (obj.channels(i).isDig())
count_Dig=count_Dig+1;
if channelConfig.dig&&(count_Dig>1)&&(count_Dig<=5) %Enable saturation channels
obj.enableChannels(i);
elseif channelConfig.acc&&(count_Dig>5)&&(count_Dig<=8)%Enable accelerometer channels
obj.enableChannels(i);
else
obj.disableChannels(i);
end
end
end
% Update the device configuration
% obj.updateDeviceConfig();
end
function setDeviceConfig_(obj, config)
%SETDEVICECONFIG_ - Set the device configuration to the desired
% settings.
%
% setDeviceConfig_(obj, config)
%
% Method takes a single struct as input which contains
% information on which configuration settings to update and
% to what value.
%
% obj [in] - Device object.
% config [in] - Struct containing keyword-value combinations
% to update the device configuration
%
% The following keywords are used to update the device
% configuration. All parameters are optional:
%
% - ImpedanceMode - Turn on/off impedance mode.
% Input: true/false
%
% - Dividers - Set the dividers to configure the sample
% rate for a given type of sensor (base_sample_rate /
% 2^divider).
% Input: Cell array with channel type
% ('exg'/'bip'/'aux'/'dig') and integer value.
%
% - BaseSampleRate - Change base sample rate of the
% device.
% Input: 4000/4096.
%
% - Triggers - Turn on/off triggers.
% Input: true/false
%
% - ReferenceMethod - Sets the reference method used by
% the device. Common Reference mode uses a single channel,
% average reference mod uses the average of all connected
% channels to determine the reference.
% Input: 'common'/'average'
%
% - AutoReferenceMethod - Sets whether the device will
% automatically change from common reference mode to average
% reference mode when the common reference channel is
% disconnected.
% Input: true/false
%
% - RepairLogging - Turns repair logging on or off, so
% that missing samples can be retrieved later on.
% Input: true/false
%
% - SyncOutDivider - Sets the sync out divider
% of the Data Recorder. (sample_rate / SyncOutDivider)
% Input: Integer, maximum frequency is Fs/8.
%
% - SyncOutDutyCycle - Sets the duty cycle of
% the Data Recorder.
% Input: Integer, between 125 and 875 (12.5% to 87.5%)
%
%EXAMPLE:
% % Update the device configuration to sample all unipolar
% % channels at 2000 Hz and all bipolar channels at 1000 Hz.
% config = struct('BaseSampleRate', 4000, ...
% 'Dividers', {{'exg', 1; 'bip', 2;}});
% device.setDeviceConfig(config);
if numel(obj) > 1
if numel(config) ~= numel(obj)
if ~iscell(config)
config = repmat({config}, size(obj));
else
config = repmat(config, size(obj));
end
end
for ii = 1:numel(obj)
obj(ii).setDeviceConfig_(config{ii});
end
return;
end
% Device configuration can only be set when the device is
% connected and not sampling.
if (~obj.is_connected)
throw(MException('Device:setDeviceConfig_', 'Device has not been connected.'));
end
if (obj.is_sampling)
throw(MException('Device:setDeviceConfig_', 'Cannot change data recorder configuration while sampling.'));
end
% Set the ImpedanceMode
if isfield(config, 'ImpedanceMode')
obj.impedance_mode = logical(config.ImpedanceMode);
obj.out_of_sync = true;
end
% Set the Dividers
if isfield(config, 'Dividers')
if isstring(config.Dividers)
config.Dividers = cellstr(config.Dividers);
end
for i = 1:size(config.Dividers,1)
if ~isa(config.Dividers{i,1}, 'char')
throw(MException('Device:setDividers', 'Divider argument type should be a string.'));
end
obj.dividers(TMSiSAGA.TMSiUtils.toChannelTypeNumber(config.Dividers{i,1})) = config.Dividers{i,2};
end
obj.out_of_sync = true;
end
% Set the BaseSampleRate
if isfield(config, 'BaseSampleRate')
if config.BaseSampleRate ~= 4000 && config.BaseSampleRate ~= 4096
throw(MException('Device:setBaseSampleRate', 'Currently only sample rates of 4000 and 4096 are supported as base sample rate.'));
end
obj.configuration.base_sample_rate = config.BaseSampleRate;
obj.out_of_sync = true;
end
% Set the Triggers
if isfield(config, 'Triggers')
if ~isa(config.Triggers, 'logical')
throw(MException('Device:setTriggers', 'Triggers argument should be true or false.'));
end
obj.configuration.triggers = config.Triggers;
obj.out_of_sync = true;
end
% Set the ReferenceMethod
if isfield(config, 'ReferenceMethod')
if isstring(config.ReferenceMethod)
config.ReferenceMethod = char(config.ReferenceMethod);
end
if ~isa(config.ReferenceMethod, 'char')
throw(MException('Device:setReferenceMethod', 'Reference method argument should be a string (common, average).'));
end
if ~strcmp(config.ReferenceMethod, 'common') && ~strcmp(config.ReferenceMethod, 'average')
throw(MException('Device:setReferenceMethod', 'Reference method argument should be common or average.'));
end
obj.configuration.reference_method = config.ReferenceMethod;
obj.out_of_sync = true;
end
% Set the AutoReferenceMethod
if isfield(config, 'AutoReferenceMethod')
obj.configuration.auto_reference_method = logical(config.AutoReferenceMethod);
obj.out_of_sync = true;
end
% Set the RepairLogging
if isfield(config, 'RepairLogging')
obj.configuration.repair_logging = logical(config.RepairLogging);
obj.out_of_sync = true;
end
% Set the SyncOutDivider
if isfield(config, 'SyncOutDivider')
obj.data_recorder.sync_out_divider = config.SyncOutDivider;
obj.out_of_sync = true;
end
% Set the SyncOutDutyCycle
if isfield(config, 'SyncOutDutyCycle')
obj.data_recorder.sync_out_duty_cycle = config.SyncOutDutyCycle;
obj.out_of_sync = true;
end
end
function updateDeviceConfig_(obj, perform_factory_reset, store_as_default, web_interface_control)
if ~exist('perform_factory_reset', 'var')
perform_factory_reset = 0;
parse_config = true;
else
if isstruct(perform_factory_reset)
parse_config = false;
device_config = perform_factory_reset;
perform_factory_reset = device_config.PerformFactoryReset;
store_as_default = device_config.StoreAsDefault;
web_interface_control = device_config.WebIfCtrl;
else
parse_config = true;
end
end
if parse_config
if ~exist('store_as_default', 'var')
store_as_default = 1;
end
if ~exist('web_interface_control', 'var')
web_interface_control = 0;
end
device_config = struct( ...
'DRSerialNumber', obj.data_recorder.serial_number, ...
'NrOfChannels', obj.num_channels, ...
'SetBaseSampleRateHz', uint16(obj.configuration.base_sample_rate), ...
'SetConfiguredInterface', uint16(TMSiSAGA.TMSiUtils.toInterfaceTypeNumber(obj.data_recorder.interface_type)), ...
'SetTriggers', int16(obj.configuration.triggers), ...
'SetRefMethod', int16(TMSiSAGA.TMSiUtils.toReferenceMethodNumber(obj.configuration.reference_method)), ...
'SetAutoRefMethod', int16(obj.configuration.auto_reference_method), ...
'SetDRSyncOutDiv', int16(obj.data_recorder.sync_out_divider), ...
'DRSyncOutDutyCycl', int16(obj.data_recorder.sync_out_duty_cycle), ...
'SetRepairLogging', int16(obj.configuration.repair_logging), ...
'PerformFactoryReset', perform_factory_reset, ...
'StoreAsDefault', store_as_default, ...
'WebIfCtrl', web_interface_control, ...
'PinKey', uint8(obj.pinkey) ...
);
end
channels = struct();
for i=1:numel(obj.channels)
channels(i).ChanNr = obj.channels(i).number;
if obj.channels(i).divider ~= -1
% divider per channel type
channels(i).ChanDivider = obj.dividers(obj.channels(i).type);
else
channels(i).ChanDivider = -1;
end
channels(i).AltChanName = obj.channels(i).alternative_name;
end
TMSiSAGA.DeviceLib.setDeviceConfig(obj.handle, device_config, channels);
TMSiSAGA.TMSiUtils.info(obj.name, 'sent device configuration')
if perform_factory_reset
msg=cell(10,1);
msg{1}=sprintf('Please repower Data Recorder to activate factory settings.');
msg{3}=sprintf('To do this:');
msg{4}=sprintf('1) Undock Data Recorder from Docking Station.');
msg{5}=sprintf('2) Remove batteries from Data Recorder.');
msg{6}=sprintf('3) Wait for 5 seconds.');
msg{7}=sprintf('4) Insert batteries again.');
msg{8}=sprintf('5) Dock Data Recorder onto Docking Station.');
msg{9}=sprintf('6) Press the power button of the Data Recorder.');
msg{10}=sprintf('7) The default settings are now activated.');
msgbox(msg)
end
end
end
methods
function obj = Device(lib, device_id, dr_interface_type)
%DEVICE - Constructor for device object.
%
% obj = Device(lib, device_id, dr_interface_type)
%
% Constructor for a device object. The library is required to be initialized and to
% keep track of all connected en sampling devices. Creation of device can be done with
% and id and interface type.
%
% obj [out] - Device object.
% lib [in] - Library object that keeps track of all the open devices.
% device_id [in] - Unique device id for this device.
% dr_interface_type [in] - Interface type that is used by the data recorder.
%
obj.lib = lib;
obj.data_recorder = TMSiSAGA.DataRecorderInfo();
obj.docking_station = TMSiSAGA.DockingStationInfo();
obj.device_id = device_id;
obj.data_recorder.interface_type = dr_interface_type;
obj.is_connected = false;
obj.api_version = 0;
obj.num_batteries = 0;
obj.num_channels = 0;
obj.power_state = 0;
obj.batteries = struct();
obj.time = struct();
obj.channels = {};
obj.configuration = struct();
% % Configuration for card recording, not supported.
% obj.max_storage_size = 0;
% obj.available_storage_size = 0;
obj.impedance_mode = false;
obj.num_active_channels = 0;
obj.out_of_sync = true;
obj.dividers = [0, 0, 0, 0, 0, 0];
obj.pinkey = [0, 0, 0, 0];
obj.prepared_sample_buffer_length = 0;
end
function delete(obj)
%DELETE - Overloaded `delete` to ensure device wrapper shuts down gracefully.
try %#ok<*TRYNC>
obj.stop();
end
try
obj.disconnect();
end
end
function connect(obj, dr_interface_type)
%CONNECT - Open a connection to a TMSi SAGA device.
%
% connect(obj, dr_interface_type)
%
% Opens a connection to a TMSi SAGA device.
%
% obj [in] - Device object.
% dr_interface_type [in] - (Optional) Interface type with which to connect. Defaults
% to the one set previously.
%
if numel(obj) > 1
for ii = 1:numel(obj)
if nargin < 2
connect(obj(ii));
else
connect(obj(ii), dr_interface_type);
end
end
return;
end
if (obj.is_connected)
return
end
if ~exist('dr_interface_type', 'var')
dr_interface_type = obj.data_recorder.interface_type;
end
% Connect device
obj.handle = TMSiSAGA.DeviceLib.openDevice(obj.device_id, ...
TMSiSAGA.TMSiUtils.toInterfaceTypeNumber(dr_interface_type));
obj.is_connected = true;
TMSiSAGA.TMSiUtils.info('MATLAB', 'opened connection to device')
obj.lib.deviceConnected(obj);
% Get the device information
obj.getDeviceInfo();
end
function disconnect(obj)
%DISCONNECT - Closes the connection to a TMSi device.
%
% disconnect(obj)
%
% Closes a connection to a TMSi Device.
%
% obj [in] - Device object.
%
if numel(obj) > 1
for ii = 1:numel(obj)
disconnect(obj(ii));
end
return;
end
if (~obj.is_connected)
return
end
TMSiSAGA.DeviceLib.closeDevice(obj.handle);
obj.is_connected = false;
TMSiSAGA.TMSiUtils.info(obj.name, 'closed connection to device')
obj.lib.deviceDisconnected(obj);
end
function [data_str, imp_str] = get_new_names(obj)
if numel(obj) > 1
data_str = strings(size(obj));
imp_str = strings(size(obj));
for ii = 1:numel(obj)
[data_str(ii), imp_str(ii)] = get_new_names(obj(ii));
end
return;
end
if isempty(obj.impedance_file_expr)
error('Must set impedance file expression first!');
end
if isempty(obj.data_file_expr)
error('Must set data file expression first!');
end
obj.recording_index = obj.recording_index + 1;
imp_str = string(sprintf(obj.impedance_file_expr, ...
obj.tag, obj.recording_index));
data_str = string(sprintf(obj.data_file_expr, ...
obj.tag, obj.recording_index));
end
function [start_sample, teensy] = start_sync(obj, sync_bit, com_port, baud_rate, sync_on_cmd, sync_off_cmd, teensy)
%START_SYNC Starts all device objects in array and attempts to synchronize them using the corresponding TRIGGERS sync bit mask.
%
% Syntax:
% start_sample = start_sync(devices, sync_bit);
% [start_sample, teensy] = start_sync(devices, sync_bit, com_port, baud_rate, sync_on_cmd, sync_off_cmd, teensy);
%
% Inputs:
% devices - Array of TMSiSAGA.Device objects
% sync_bit - Scalar integer 0 - 15 indicating which BIT to
% check for the synchronization pulse. A single
% logic HIGH to logic LOW pulse is required on
% this 0-indexed bit for the normal acquisition
% loop to begin.
% com_port (optional): Default is "COM6" -- microcontroller
% COM port. Note that this method REQUIRES a
% connected microcontroller!
% baud_rate (optional): Default is 115200 -- baudrate for
% communication with connected microcontroller.
% sync_on_cmd (optional): Default is '1' -- Byte to
% communicate with microcontroller
% for start of pulse sequence.
% sync_off_cmd (optional): Default is '0' -- Byte to
% communicate with microcontroller
% for end of pulse sequence.
% teensy (optional): Default is [] -- Can pass the
% microcontroller directly to avoid
% creating new microcontroller instance
% if required.
arguments
obj
sync_bit (1,1) {mustBeMember(sync_bit, 0:15)}
com_port {mustBeTextScalar} = "COM6";
baud_rate (1,1) {mustBeInteger, mustBePositive} = 115200;
sync_on_cmd (1,1) char = '1';
sync_off_cmd (1,1) char = '0';
teensy = [];
end
if isempty(teensy)
teensy = serialport(com_port, baud_rate);
end
sync_mask = 2^sync_bit;
n_dev = numel(obj);
dev_state = zeros(1,n_dev);
start_sample = zeros(1,n_dev);
teensy.write(sync_on_cmd,'char');
start(obj);
pause(0.500);
teensy.write(sync_off_cmd,'char');
vec = 1:n_dev;
while ~isempty(vec)
pause(0.000001);
for iObj = vec
[buffer, buffer_size] = get_n_sample_buffer(obj(iObj), 1);
data = test_sample(obj(iObj), buffer, buffer_size);
if ~isempty(data)
if dev_state(iObj) == 0
dev_state(iObj) = dev_state(iObj) + all((bitand(data(obj(iObj).current_triggers_channel_index,:),sync_mask)==0) & (bitand(data(obj(iObj).current_status_channel_index,:), 2^11)==0)); % Block while logic LOW is asserted
else
dev_state(iObj) = dev_state(iObj) + all(bitand(data(obj(iObj).current_triggers_channel_index,:),sync_mask)==sync_mask); % Block while logic HIGH is asserted
end
end
if dev_state(iObj) == 2
start_sample(iObj) = data(obj(iObj).current_counter_channel_index);
end
end
vec = find(dev_state < 2);
end
end
function data = sample_sync(obj, n_samples)
%SAMPLE_SYNC Attempts to pull synchronized sample batch from all devices in array.
%
% Syntax:
% data = sample_sync(devices, n_samples, n_total_channels);
%
% Inputs:
% devices - Array of TMSiSAGA.Device objects
% n_samples - Number of samples in requested batch
arguments
obj
n_samples (1,1) {mustBePositive, mustBeInteger}
end
n_dev = numel(obj);
n_total = zeros(1,n_dev);
data = cell(1,n_dev);
for iObj = 1:n_dev
data{iObj} = zeros(obj(iObj).num_active_channels, n_samples);
end
vec = 1:n_dev;
while ~isempty(vec)
pause(0.00025);
for iObj = vec
n_request = (n_samples-n_total(iObj));
[buffer, buffer_size] = get_n_sample_buffer(obj(iObj), n_request);
[tmp, tmp_n] = test_sample(obj(iObj), buffer, buffer_size);
data{iObj}(:,(n_total(iObj)+1):(n_total(iObj)+tmp_n)) = tmp;
n_total(iObj) = n_total(iObj) + tmp_n;
end
vec = find(n_total<n_samples);
end
data = vertcat(data{:});
end
function start(obj, disable_avg_ref_calculation)
%START - Start sampling on a TMSi device.
%
% start(obj, disable_avg_ref_calculation)
%
% Starts sampling of a TMSi device.
%
% obj - Device object.
% disable_avg_ref_calculation - (Optional) Disable the average reference calculation for
% during this sample session.
if numel(obj) > 1
for ii = 1:numel(obj)
if nargin < 2
start(obj(ii));
else
start(obj(ii), disable_avg_ref_calculation);
end
end
return;
end
if ~obj.is_connected
throw(MException('Device:start', 'Device has not been connected.'));
end
% Show out of sync warning
if obj.out_of_sync
warning('Are you sure you want to start sampling, it seems that the device config is out of sync with your current settings.');
end
if obj.is_sampling
return;
end
if ~exist('disable_avg_ref_calculation', 'var')
disable_avg_ref_calculation = false;
end
% Prepare sample buffer
if obj.prepared_sample_buffer_length == 0
obj.prepared_sample_buffer_length = round(max(obj.configuration.base_sample_rate, obj.configuration.alternative_base_sample_rate) * obj.desired_sample_buffer_length) * obj.num_channels;
obj.prepared_sample_buffer = TMSiSAGA.DeviceLib.createDataBuffer(obj.prepared_sample_buffer_length);
end
% Get channel info values
% 1. Look up STATUS and COUNTER index
aci = [];
for channel_index=1:numel(obj.channels)
if obj.channels(channel_index).isActive(obj.impedance_mode)
aci(numel(aci) + 1) = channel_index; %#ok<AGROW>
if obj.channels(channel_index).isCounter()
obj.current_counter_channel_index = numel(aci);
end
if obj.channels(channel_index).isStatus()
obj.current_status_channel_index = numel(aci);
end
if obj.channels(channel_index).isTrigger()
obj.current_triggers_channel_index = numel(aci);
end
end
end
obj.active_channel_indices = aci;
obj.missing_samples = [];
TMSiSAGA.DeviceLib.resetDeviceDataBuffer(obj.handle);
% Set sampling request
if obj.impedance_mode
TMSiSAGA.DeviceLib.setDeviceImpedance(obj.handle, struct('SetImpedanceMode', uint16(1)));
else
device_sample_request = struct( ...
'SetSamplingMode', uint16(1), ...
'DisableAutoswitch', ~obj.configuration.auto_reference_method, ...
'DisableRepairLogging', ~obj.configuration.repair_logging, ...
'DisableAvrRefCalc', disable_avg_ref_calculation ...
);
TMSiSAGA.DeviceLib.setDeviceSampling(obj.handle, device_sample_request);
end
obj.is_sampling = true;
% Inform user on start of sampling
TMSiSAGA.TMSiUtils.info(obj.name, 'running')
if obj.verbose > 0
TMSiSAGA.TMSiUtils.info(obj.name, [' autoswitch=' num2str(obj.configuration.auto_reference_method)])
TMSiSAGA.TMSiUtils.info(obj.name, [' repair_logging=' num2str(obj.configuration.repair_logging)])
TMSiSAGA.TMSiUtils.info(obj.name, [' avr_ref_calc=' num2str(~disable_avg_ref_calculation)])
end
obj.lib.deviceStartedSampling(obj);
end
function [buffer, buffer_size] = get_n_sample_buffer(obj, n)
%GET_N_SAMPLE_BUFFER Returns buffer singleton for use with test_sample of desired samples size.
buffer_size = obj(1).num_active_channels * n;
buffer = TMSiSAGA.DeviceLib.createDataBuffer(buffer_size);
end
function stop(obj)
%STOP - Stop sampling on a TMSi device.
%
% stop(obj)
%
% Stops sampling of a TMSi device.
%
% obj - Device object.
%
% Can be called when:
% - Device is connected.
% - Device is (not) sampling.
if numel(obj) > 1
for ii = 1:numel(obj)
stop(obj(ii));
end
return;
end
obj.is_recording = false;
if ~obj.is_connected
throw(MException('Device:stop', 'Device has not been connected.'));
end
if ~obj.is_sampling
return
end
% Stop sampling request
if obj.impedance_mode
TMSiSAGA.DeviceLib.setDeviceImpedance(obj.handle, struct('SetImpedanceMode', uint16(0)));
else
device_sample_request = struct( ...
'SetSamplingMode', uint16(0), ...
'DisableAutoswitch', false, ...
'DisableRepairLogging', false, ...
'DisableAvrRefCalc', false ...
);
TMSiSAGA.DeviceLib.setDeviceSampling(obj.handle, device_sample_request);
end
obj.is_sampling = false;
% Inform user that sampling has stopped
TMSiSAGA.TMSiUtils.info(obj.name, 'idle')
obj.lib.deviceStoppedSampling(obj);
end
function [data, num_sets, data_type] = test_sample(obj, buffer, buffer_len)
%TEST_SAMPLE Low-level sample call that requires a specified buffer and buffer size.
[raw_data, num_sets, data_type] = TMSiSAGA.DeviceLib.getDeviceData(obj.handle, buffer, buffer_len);
% Data in double format
raw_data = reshape(raw_data(1:(num_sets*obj.num_active_channels)),obj.num_active_channels,num_sets);
if num_sets < 1
data = [];
return;
end
data = zeros(obj.num_active_channels, num_sets);
% Loop over channels and transform raw_data to data
for i=1:obj.num_active_channels
channel = obj.channels(obj.active_channel_indices(i));