-
Notifications
You must be signed in to change notification settings - Fork 3
/
digitizer_block_impl.cc
1260 lines (1044 loc) · 37.9 KB
/
digitizer_block_impl.cc
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
/* -*- c++ -*- */
/* Copyright (C) 2018 GSI Darmstadt, Germany - All Rights Reserved
* co-developed with: Cosylab, Ljubljana, Slovenia and CERN, Geneva, Switzerland
* You may use, distribute and modify this code under the terms of the GPL v.3 license.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "digitizer_block_impl.h"
#include "utils.h"
#include <thread>
#include <chrono>
#include <boost/lexical_cast.hpp>
#include <digitizers/tags.h>
#include <gnuradio/thread/thread.h> // set_name
namespace gr {
namespace digitizers {
/**********************************************************************
* Error codes
*********************************************************************/
struct digitizer_block_err_category : std::error_category
{
const char* name() const noexcept override;
std::string message(int ev) const override;
};
const char*
digitizer_block_err_category::name() const noexcept
{
return "digitizer_block";
}
std::string
digitizer_block_err_category::message(int ev) const
{
switch (static_cast<digitizer_block_errc>(ev))
{
case digitizer_block_errc::Interrupted:
return "Wit interrupted";
default:
return "(unrecognized error)";
}
}
const digitizer_block_err_category __digitizer_block_category {};
std::error_code
make_error_code(digitizer_block_errc e)
{
return {static_cast<int>(e), __digitizer_block_category};
}
/**********************************************************************
* Structors
*********************************************************************/
// Relevant for debugging. If gnuradio calls this block not often enough, we will get "WARN: XX digitizer data buffers lost"
// The rate in which this block is called is given by the number of free slots on its output buffer. So we choose a big value via set_min_output_buffer
uint64_t last_call_utc = 0;
static const int AVERAGE_HISTORY_LENGTH = 100000;
digitizer_block_impl::digitizer_block_impl(int ai_channels, int di_ports, bool auto_arm) :
d_samp_rate(10000),
d_actual_samp_rate(d_samp_rate),
d_time_per_sample_ns(1000000000. / d_samp_rate),
d_pre_samples(1000),
d_post_samples(9000),
d_nr_captures(1),
d_buffer_size(8192),
d_nr_buffers(100),
d_driver_buffer_size(100000),
d_acquisition_mode(acquisition_mode_t::STREAMING),
d_poll_rate(0.001),
d_downsampling_mode(downsampling_mode_t::DOWNSAMPLING_MODE_NONE),
d_downsampling_factor(1),
d_ai_channels(ai_channels),
d_ports(di_ports),
d_channel_settings(),
d_port_settings(),
d_trigger_settings(),
d_status(ai_channels),
d_app_buffer(),
d_was_last_callback_timestamp_taken(false),
d_estimated_sample_rate(AVERAGE_HISTORY_LENGTH),
d_initialized(false),
d_closed(false),
d_armed(false),
d_auto_arm(auto_arm),
d_trigger_once(false),
d_was_triggered_once(false),
d_timebase_published(false),
ai_buffers(ai_channels),
ai_error_buffers(ai_channels),
port_buffers(di_ports),
d_data_rdy(false),
d_trigger_state(0),
d_read_idx(0),
d_buffer_samples(0),
d_errors(128),
d_poller_state(poller_state_t::IDLE)
{
d_ai_buffers = std::vector<std::vector<float>>(d_ai_channels);
d_ai_error_buffers = std::vector<std::vector<float>>(d_ai_channels);
if (di_ports) {
d_port_buffers = std::vector<std::vector<uint8_t>>(di_ports);
}
assert(d_ai_channels < MAX_SUPPORTED_AI_CHANNELS);
assert(d_ports < MAX_SUPPORTED_PORTS);
}
digitizer_block_impl::~digitizer_block_impl()
{
}
/**********************************************************************
* Helpers
**********************************************************************/
uint32_t
digitizer_block_impl::get_pre_trigger_samples_with_downsampling() const
{
if (d_downsampling_mode != downsampling_mode_t::DOWNSAMPLING_MODE_NONE)
return d_pre_samples / d_downsampling_factor;
return d_pre_samples;
}
uint32_t
digitizer_block_impl::get_post_trigger_samples_with_downsampling() const
{
if (d_downsampling_mode != downsampling_mode_t::DOWNSAMPLING_MODE_NONE)
return d_post_samples / d_downsampling_factor;
return d_post_samples;
}
uint32_t
digitizer_block_impl::get_block_size() const
{
return d_post_samples + d_pre_samples;
}
uint32_t
digitizer_block_impl::get_block_size_with_downsampling() const
{
return get_pre_trigger_samples_with_downsampling() + get_post_trigger_samples_with_downsampling();
}
double
digitizer_block_impl::get_timebase_with_downsampling() const
{
if (d_downsampling_mode == downsampling_mode_t::DOWNSAMPLING_MODE_NONE) {
return 1.0 / d_actual_samp_rate;
}
else {
return d_downsampling_factor / d_actual_samp_rate;
}
}
void
digitizer_block_impl::add_error_code(std::error_code ec)
{
d_errors.push(ec);
}
std::vector<int>
digitizer_block_impl::find_analog_triggers(float const * const samples, int nsamples)
{
std::vector<int> trigger_offsets; // relative offset of detected triggers
assert(nsamples >= 0);
if (!d_trigger_settings.is_enabled() || nsamples == 0) {
return trigger_offsets;
}
assert(d_trigger_settings.is_analog());
auto aichan = convert_to_aichan_idx(d_trigger_settings.source);
if (d_trigger_settings.direction == TRIGGER_DIRECTION_RISING
|| d_trigger_settings.direction == TRIGGER_DIRECTION_HIGH) {
float band = d_channel_settings[aichan].range / 100.0;
float lo = static_cast<float>(d_trigger_settings.threshold - band);
for(auto i = 0; i < nsamples; i++) {
if(!d_trigger_state && samples[i] >= d_trigger_settings.threshold) {
d_trigger_state = 1;
trigger_offsets.push_back(i);
}
else if(d_trigger_state && samples[i] <= lo) {
d_trigger_state = 0;
}
}
}
else if (d_trigger_settings.direction == TRIGGER_DIRECTION_FALLING
|| d_trigger_settings.direction == TRIGGER_DIRECTION_LOW) {
float band = d_channel_settings[aichan].range / 100.0;
float hi = static_cast<float>(d_trigger_settings.threshold + band);
for(auto i = 0; i < nsamples; i++) {
if(d_trigger_state && samples[i] <= d_trigger_settings.threshold) {
d_trigger_state = 0;
trigger_offsets.push_back(i);
}
else if(!d_trigger_state && samples[i] >= hi) {
d_trigger_state = 1;
}
}
}
return trigger_offsets;
}
std::vector<int>
digitizer_block_impl::find_digital_triggers(uint8_t const * const samples, int nsamples, uint8_t mask)
{
std::vector<int> trigger_offsets;
if (d_trigger_settings.direction == TRIGGER_DIRECTION_RISING
|| d_trigger_settings.direction == TRIGGER_DIRECTION_HIGH) {
for(auto i = 0; i < nsamples; i++) {
if(!d_trigger_state && (samples[i] & mask)) {
d_trigger_state = 1;
trigger_offsets.push_back(i);
}
else if(d_trigger_state && !(samples[i] & mask)) {
d_trigger_state = 0;
}
}
}
else if (d_trigger_settings.direction == TRIGGER_DIRECTION_FALLING
|| d_trigger_settings.direction == TRIGGER_DIRECTION_LOW) {
for(auto i = 0; i < nsamples; i++) {
if(d_trigger_state && !(samples[i] & mask)) {
d_trigger_state = 0;
trigger_offsets.push_back(i);
}
else if(!d_trigger_state && (samples[i] & mask)) {
d_trigger_state = 1;
}
}
}
return trigger_offsets;
}
/**********************************************************************
* Public API
**********************************************************************/
acquisition_mode_t
digitizer_block_impl::get_acquisition_mode()
{
return d_acquisition_mode;
}
void
digitizer_block_impl::set_samples(int pre_samples, int post_samples)
{
if (post_samples < 1)
{
std::ostringstream message;
message << "Exception in " << __FILE__ << ":" << __LINE__ << ": post-trigger samples can't be less than one";
throw std::invalid_argument(message.str());
}
if (pre_samples < 0)
{
std::ostringstream message;
message << "Exception in " << __FILE__ << ":" << __LINE__ << ": pre-trigger samples can't be less than zero";
throw std::invalid_argument(message.str());
}
d_post_samples = static_cast<uint32_t>(post_samples);
d_pre_samples = static_cast<uint32_t>(pre_samples);
d_buffer_size = d_post_samples + d_pre_samples;
}
void
digitizer_block_impl::set_samp_rate(double rate)
{
if (rate <= 0.0)
{
std::ostringstream message;
message << "Exception in " << __FILE__ << ":" << __LINE__ << ": sample rate has to be greater than zero";
throw std::invalid_argument(message.str());
}
d_samp_rate = rate;
d_actual_samp_rate = rate;
d_time_per_sample_ns = 1000000000. / d_actual_samp_rate;
}
double
digitizer_block_impl::get_samp_rate()
{
return d_actual_samp_rate;
}
void
digitizer_block_impl::set_buffer_size(int buffer_size)
{
if (buffer_size < 0)
{
std::ostringstream message;
message << "Exception in " << __FILE__ << ":" << __LINE__ << ": buffer size can't be negative:" << buffer_size;
throw std::invalid_argument(message.str());
}
d_buffer_size = static_cast<uint32_t>(buffer_size);
set_output_multiple(buffer_size);
}
void
digitizer_block_impl::set_nr_buffers(int nr_buffers)
{
if (nr_buffers < 1)
{
std::ostringstream message;
message << "Exception in " << __FILE__ << ":" << __LINE__ << ": number of buffers can't be a negative number:" << nr_buffers;
throw std::invalid_argument(message.str());
}
d_nr_buffers = static_cast<uint32_t>(nr_buffers);
}
void
digitizer_block_impl::set_driver_buffer_size(int driver_buffer_size)
{
if (driver_buffer_size < 1)
{
std::ostringstream message;
message << "Exception in " << __FILE__ << ":" << __LINE__ << ": driver buffer size can't be a negative number:" << driver_buffer_size;
throw std::invalid_argument(message.str());
}
d_driver_buffer_size = static_cast<uint32_t>(driver_buffer_size);
}
void
digitizer_block_impl::set_auto_arm(bool auto_arm)
{
d_auto_arm = auto_arm;
}
void
digitizer_block_impl::set_trigger_once(bool once)
{
d_trigger_once = once;
}
// Poll rate is in seconds
void
digitizer_block_impl::set_streaming(double poll_rate)
{
if (poll_rate < 0.0)
{
std::ostringstream message;
message << "Exception in " << __FILE__ << ":" << __LINE__ << ": poll rate can't be negative:" << poll_rate;
throw std::invalid_argument(message.str());
}
d_acquisition_mode = acquisition_mode_t::STREAMING;
d_poll_rate = poll_rate;
// just in case
d_nr_captures = 1;
}
void
digitizer_block_impl::set_rapid_block(int nr_captures)
{
if (nr_captures < 1)
{
std::ostringstream message;
message << "Exception in " << __FILE__ << ":" << __LINE__ << ": nr waveforms should be at least one" << nr_captures;
throw std::invalid_argument(message.str());
}
d_acquisition_mode = acquisition_mode_t::RAPID_BLOCK;
d_nr_captures = static_cast<uint32_t>(nr_captures);
}
void
digitizer_block_impl::set_downsampling(downsampling_mode_t mode, int downsample_factor)
{
if (mode == downsampling_mode_t::DOWNSAMPLING_MODE_NONE) {
downsample_factor = 1;
}
else if (downsample_factor < 2)
{
std::ostringstream message;
message << "Exception in " << __FILE__ << ":" << __LINE__ << ": downsampling factor should be at least 2: " << downsample_factor;
throw std::invalid_argument(message.str());
}
d_downsampling_mode = mode;
d_downsampling_factor = static_cast<uint32_t>(downsample_factor);
}
int
digitizer_block_impl::convert_to_aichan_idx(const std::string &id) const
{
if (id.length() != 1)
{
std::ostringstream message;
message << "Exception in " << __FILE__ << ":" << __LINE__ << ": aichan id should be a single character: " << id;
throw std::invalid_argument(message.str());
}
int idx = std::toupper(id[0]) - 'A';
if (idx < 0 || idx > MAX_SUPPORTED_AI_CHANNELS)
{
std::ostringstream message;
message << "Exception in " << __FILE__ << ":" << __LINE__ << ": invalid aichan id: " << id;
throw std::invalid_argument(message.str());
}
return idx;
}
void
digitizer_block_impl::set_aichan(const std::string &id, bool enabled, double range, coupling_t coupling, double range_offset)
{
auto idx = convert_to_aichan_idx(id);
d_channel_settings[idx].range = range;
d_channel_settings[idx].offset = range_offset;
d_channel_settings[idx].enabled = enabled;
d_channel_settings[idx].coupling = coupling;
}
int
digitizer_block_impl::get_enabled_aichan_count() const
{
auto count = 0;
for (const auto &c : d_channel_settings) {
count += c.enabled;
}
return count;
}
void
digitizer_block_impl::set_aichan_range(const std::string &id, double range, double range_offset)
{
auto idx = convert_to_aichan_idx(id);
d_channel_settings[idx].range = range;
d_channel_settings[idx].offset = range_offset;
}
void
digitizer_block_impl::set_aichan_trigger(const std::string &id, trigger_direction_t direction, double threshold)
{
// Some scopes have an dedicated AUX Trigger-Input. Skip id verification for them
if (id != "AUX")
convert_to_aichan_idx(id); // Just to verify id
d_trigger_settings.source = id;
d_trigger_settings.threshold = threshold;
d_trigger_settings.direction = direction;
d_trigger_settings.pin_number = 0; // not used
}
int
digitizer_block_impl::convert_to_port_idx(const std::string &id) const
{
if (id.length() != 5)
{
std::ostringstream message;
message << "Exception in " << __FILE__ << ":" << __LINE__ << ": invalid port id: " << id << ", should be of the following format 'port<d>'";
throw std::invalid_argument(message.str());
}
int idx = boost::lexical_cast<int>(id[4]);
if (idx < 0 || idx > MAX_SUPPORTED_PORTS)
{
std::ostringstream message;
message << "Exception in " << __FILE__ << ":" << __LINE__ << ": invalid port number: " << id;
throw std::invalid_argument(message.str());
}
return idx;
}
void
digitizer_block_impl::set_diport(const std::string &id, bool enabled, double thresh_voltage)
{
auto port_number = convert_to_port_idx(id);
d_port_settings[port_number].logic_level = thresh_voltage;
d_port_settings[port_number].enabled = enabled;
}
int
digitizer_block_impl::get_enabled_diport_count() const
{
auto count = 0;
for (const auto &p : d_port_settings) {
count += p.enabled;
}
return count;
}
void
digitizer_block_impl::set_di_trigger(uint32_t pin, trigger_direction_t direction)
{
d_trigger_settings.source = TRIGGER_DIGITAL_SOURCE;
d_trigger_settings.threshold = 0.0; // not used
d_trigger_settings.direction = direction;
d_trigger_settings.pin_number = pin;
}
void
digitizer_block_impl::disable_triggers()
{
d_trigger_settings.source = TRIGGER_NONE_SOURCE;
}
void
digitizer_block_impl::initialize()
{
if (d_initialized) {
return;
}
auto ec = driver_initialize();
if (ec) {
add_error_code(ec);
std::ostringstream message;
message << "Exception in " << __FILE__ << ":" << __LINE__ << ": initialize failed. ErrorCode: " << ec;
throw std::runtime_error(message.str());
}
d_initialized = true;
}
void
digitizer_block_impl::configure()
{
if (!d_initialized)
{
std::ostringstream message;
message << "Exception in " << __FILE__ << ":" << __LINE__ << ": initialize first!";
throw std::runtime_error(message.str());
}
if (d_armed)
{
std::ostringstream message;
message << "Exception in " << __FILE__ << ":" << __LINE__ << ": disarm first!";
throw std::runtime_error(message.str());
}
auto ec = driver_configure();
if (ec) {
add_error_code(ec);
std::ostringstream message;
message << "Exception in " << __FILE__ << ":" << __LINE__ << ": configure failed. ErrorCode: " << ec;
throw std::runtime_error(message.str());
}
// initialize application buffer
d_app_buffer.initialize(get_enabled_aichan_count(),
get_enabled_diport_count(), d_buffer_size, d_nr_buffers);
}
void
digitizer_block_impl::arm()
{
if (d_armed) {
return;
}
// set estimated sample rate to expected
float expected = static_cast<float>(get_samp_rate());
for (auto i=0; i < AVERAGE_HISTORY_LENGTH; i++) {
d_estimated_sample_rate.add(expected);
}
// arm the driver
auto ec = driver_arm();
if (ec) {
add_error_code(ec);
std::ostringstream message;
message << "Exception in " << __FILE__ << ":" << __LINE__ << ": arm failed. ErrorCode: " << ec;
throw std::runtime_error(message.str());
}
d_armed = true;
d_timebase_published = false;
d_was_last_callback_timestamp_taken = false;
// clear error condition in the application buffer
d_app_buffer.notify_data_ready(std::error_code {});
// notify poll thread to start with the poll request
if(d_acquisition_mode == acquisition_mode_t::STREAMING) {
transit_poll_thread_to_running();
}
//allocate buffer pointer vectors.
int num_enabled_ai_channels = 0;
int num_enabled_di_ports = 0;
for (auto i = 0; i < d_ai_channels; i++) {
if (d_channel_settings[i].enabled) {
num_enabled_ai_channels++;
}
}
for (auto i = 0; i < d_ports; i++) {
if (d_port_settings[i].enabled) {
num_enabled_di_ports++;
}
}
ai_buffers.resize(num_enabled_ai_channels);
ai_error_buffers.resize(num_enabled_ai_channels);
port_buffers.resize(num_enabled_di_ports);
}
bool
digitizer_block_impl::is_armed()
{
return d_armed;
}
void
digitizer_block_impl::disarm()
{
if (!d_armed) {
return;
}
if(d_acquisition_mode == acquisition_mode_t::STREAMING) {
transit_poll_thread_to_idle();
}
auto ec = driver_disarm();
if (ec) {
add_error_code(ec);
GR_LOG_WARN(d_logger, "disarm failed: " + to_string(ec));
}
d_armed = false;
}
void
digitizer_block_impl::close()
{
auto ec = driver_close();
if (ec) {
add_error_code(ec);
GR_LOG_WARN(d_logger, "close failed: " + to_string(ec));
}
d_closed = true;
d_initialized = false;
}
std::vector<error_info_t>
digitizer_block_impl::get_errors()
{
return d_errors.get();
}
std::string
digitizer_block_impl::getConfigureExceptionMessage()
{
return d_configure_exception_message;
}
bool
digitizer_block_impl::start()
{
try {
initialize();
configure();
// Needed in case start/run is called multiple times without destructing the flowgraph
d_was_triggered_once = false;
d_data_rdy_errc = std::error_code {};
d_data_rdy = false;
if (d_acquisition_mode == acquisition_mode_t::STREAMING) {
start_poll_thread();
}
if(d_auto_arm && d_acquisition_mode == acquisition_mode_t::STREAMING) {
arm();
}
} catch (const std::exception& ex) {
d_configure_exception_message = ex.what();
GR_LOG_ERROR(d_logger, d_configure_exception_message );
// No matter if true or false is returned here, gnuradio will continue to run the block, so we stop in manually
// Re-throwing the exception would result in the binary getting stuck
this->stop();
return false;
} catch (...) {
d_configure_exception_message = "Unknown Exception received in digitizer_block_impl::start";
GR_LOG_ERROR(d_logger, d_configure_exception_message );
this->stop();
return false;
}
return true;
}
bool
digitizer_block_impl::stop()
{
if (!d_initialized) {
return true;
}
if (d_armed) {
// Interrupt waiting function (workaround). From the scheduler point of view this is not
// needed because it makes sure that the worker thread gets interrupted before the stop
// method is called. But we have this in place in order to allow for manual intervention.
notify_data_ready(digitizer_block_errc::Stopped);
disarm();
}
if(d_acquisition_mode == acquisition_mode_t::STREAMING) {
stop_poll_thread();
}
d_configure_exception_message = "";
return true;
}
/**********************************************************************
* Driver interface
**********************************************************************/
void
digitizer_block_impl::notify_data_ready(std::error_code ec)
{
if(ec) {
add_error_code(ec);
}
{
boost::mutex::scoped_lock lock(d_mutex);
d_data_rdy = true;
d_data_rdy_errc = ec;
}
d_data_rdy_cv.notify_one();
}
std::error_code
digitizer_block_impl::wait_data_ready()
{
boost::mutex::scoped_lock lock(d_mutex);
d_data_rdy_cv.wait(lock, [this] { return d_data_rdy; });
return d_data_rdy_errc;
}
void digitizer_block_impl::clear_data_ready()
{
boost::mutex::scoped_lock lock(d_mutex);
d_data_rdy = false;
d_data_rdy_errc = std::error_code {};
}
/**********************************************************************
* GR worker functions
**********************************************************************/
int
digitizer_block_impl::work_rapid_block(int noutput_items, gr_vector_void_star &output_items)
{
if (d_bstate.state == rapid_block_state_t::WAITING) {
if (d_trigger_once && d_was_triggered_once) {
return -1;
}
if (d_auto_arm) {
disarm();
while(true) {
try {
arm();
break;
}
catch (...) {
return -1;
}
}
}
// Wait conditional variable, when waken clear it
auto ec = wait_data_ready();
clear_data_ready();
// Stop requested
if (ec == digitizer_block_errc::Stopped) {
GR_LOG_INFO(d_logger, "stop requested");
return -1;
}
else if (ec) {
GR_LOG_ERROR(d_logger, "error occurred while waiting for data: " + to_string(ec));
return 0;
}
// we assume all the blocks are ready
d_bstate.initialize(d_nr_captures);
}
if (d_bstate.state == rapid_block_state_t::READING_PART1) {
// If d_trigger_once is true we will signal all done in the next iteration
// with the block state set to WAITING
d_was_triggered_once = true;
auto samples_to_fetch = get_block_size();
auto downsampled_samples = get_block_size_with_downsampling();
// Instruct the driver to prefetch samples. Drivers might choose to ignore this call
auto ec = driver_prefetch_block(samples_to_fetch, d_bstate.waveform_idx);
if (ec) {
add_error_code(ec);
return -1;
}
// Initiate state machine for the current waveform. Note state machine track
// and adjust the waveform index.
d_bstate.set_waveform_params(0, downsampled_samples);
timespec start_time;
clock_gettime(CLOCK_REALTIME, &start_time);
uint64_t timestamp_now_ns_utc = (start_time.tv_sec * 1000000000) + (start_time.tv_nsec);
// We are good to read first batch of samples
noutput_items = std::min(noutput_items, d_bstate.samples_left);
ec = driver_get_rapid_block_data(d_bstate.offset,
noutput_items, d_bstate.waveform_idx, output_items, d_status);
if (ec) {
add_error_code(ec);
return -1;
}
// Attach trigger info to value outputs and to all ports
auto vec_idx = 0;
uint32_t pre_trigger_samples_with_downsampling = get_pre_trigger_samples_with_downsampling();
double time_per_sample_with_downsampling_ns = d_time_per_sample_ns * d_downsampling_factor;
for (auto i = 0; i < d_ai_channels && vec_idx < (int)output_items.size(); i++, vec_idx+=2)
{
if (!d_channel_settings[i].enabled)
{
continue;
}
auto trigger_tag = make_trigger_tag(
d_downsampling_factor,
timestamp_now_ns_utc + (pre_trigger_samples_with_downsampling * time_per_sample_with_downsampling_ns),
nitems_written(0) + pre_trigger_samples_with_downsampling,
d_status[i]);
add_item_tag(vec_idx, trigger_tag);
}
auto trigger_tag = make_trigger_tag(
d_downsampling_factor,
timestamp_now_ns_utc + (pre_trigger_samples_with_downsampling * time_per_sample_with_downsampling_ns),
nitems_written(0) + pre_trigger_samples_with_downsampling,
0 ); //status
// Add tags to digital port
for (auto i = 0; i < d_ports && vec_idx < (int)output_items.size(); i++, vec_idx++)
{
if (d_port_settings[i].enabled)
add_item_tag(vec_idx, trigger_tag);
}
// update state
d_bstate.update_state(noutput_items);
return noutput_items;
}
else if (d_bstate.state == rapid_block_state_t::READING_THE_REST) {
noutput_items = std::min(noutput_items, d_bstate.samples_left);
auto ec = driver_get_rapid_block_data(d_bstate.offset, noutput_items,
d_bstate.waveform_idx, output_items, d_status);
if (ec) {
add_error_code(ec);
return -1;
}
// update state
d_bstate.update_state(noutput_items);
return noutput_items;
}
return -1;
}
void
digitizer_block_impl::poll_work_function()
{
boost::unique_lock<boost::mutex> lock(d_poller_mutex, boost::defer_lock);
std::chrono::duration<float> poll_duration(d_poll_rate);
std::chrono::duration<float> sleep_time;
gr::thread::set_thread_name(pthread_self(), "poller");
//relax cpu with less lock calls.
unsigned int check_every_n_times = 10;
unsigned int poller_state_check_counter = check_every_n_times;
poller_state_t state = poller_state_t::IDLE;
while (true) {
poller_state_check_counter++;
if(poller_state_check_counter >= check_every_n_times) {
lock.lock();
state = d_poller_state;
lock.unlock();
poller_state_check_counter = 0;
}
if (state == poller_state_t::RUNNING) {
// Start watchdog a new
auto poll_start = std::chrono::high_resolution_clock::now();
auto ec = driver_poll();
if (ec) {
// Only print out an error message
GR_LOG_ERROR(d_logger, "poll failed with: " + to_string(ec));
// Notify work method about the error... Work method will re-arm the driver if required.
d_app_buffer.notify_data_ready(ec);
// Prevent error-flood on close
if(d_closed)
return;
}
// Watchdog is "turned on" only some time after the acquisition start for two reasons:
// - to avoid false positives
// - to avoid fast rearm attempts
float estimated_samp_rate = 0.0;
{
// Note, mutex is not needed in case of PicoScope implementations but in order to make
// the base class relatively generic we use mutex (streaming callback is called from this
// thread).
boost::mutex::scoped_lock watchdog_guard(d_watchdog_mutex);
estimated_samp_rate = d_estimated_sample_rate.get_avg_value();
}
if (estimated_samp_rate < (get_samp_rate() * WATCHDOG_SAMPLE_RATE_THRESHOLD)) {
// This will wake up the worker thread (see do_work method), and that thread will
// then rearm the device...
GR_LOG_ERROR(d_logger, "Watchdog: estimated sample rate " + std::to_string(estimated_samp_rate)
+ "Hz, expected: " + std::to_string(get_samp_rate()) + "Hz");
d_app_buffer.notify_data_ready(digitizer_block_errc::Watchdog);
}
// Substract the time each iteration itself took in order to get closer to the desired poll duration
std::chrono::duration<float> elapsed_poll_duration = std::chrono::high_resolution_clock::now() - poll_start;
if(elapsed_poll_duration > poll_duration) {
sleep_time = std::chrono::duration<float>::zero();
}
else {
sleep_time = poll_duration - elapsed_poll_duration;
}
std::this_thread::sleep_for(sleep_time);
}
else {
if (state == poller_state_t::PEND_IDLE) {
lock.lock();
d_poller_state = state = poller_state_t::IDLE;
lock.unlock();
d_poller_cv.notify_all();
}
else if (state == poller_state_t::PEND_EXIT) {