]> sigrok.org Git - pulseview.git/blob - pv/data/signalbase.cpp
Restart min-max-based conversion if min or max change
[pulseview.git] / pv / data / signalbase.cpp
1 /*
2  * This file is part of the PulseView project.
3  *
4  * Copyright (C) 2012 Joel Holdsworth <joel@airwebreathe.org.uk>
5  * Copyright (C) 2016 Soeren Apel <soeren@apelpie.net>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #include "analog.hpp"
22 #include "analogsegment.hpp"
23 #include "decode/row.hpp"
24 #include "logic.hpp"
25 #include "logicsegment.hpp"
26 #include "signalbase.hpp"
27 #include "signaldata.hpp"
28
29 #include <pv/binding/decoder.hpp>
30 #include <pv/session.hpp>
31
32 using std::dynamic_pointer_cast;
33 using std::make_shared;
34 using std::shared_ptr;
35 using std::tie;
36 using std::unique_lock;
37
38 namespace pv {
39 namespace data {
40
41 const int SignalBase::ColourBGAlpha = 8 * 256 / 100;
42 const uint64_t SignalBase::ConversionBlockSize = 4096;
43
44 SignalBase::SignalBase(shared_ptr<sigrok::Channel> channel, ChannelType channel_type) :
45         channel_(channel),
46         channel_type_(channel_type),
47         conversion_type_(NoConversion),
48         min_value_(0),
49         max_value_(0)
50 {
51         if (channel_)
52                 internal_name_ = QString::fromStdString(channel_->name());
53 }
54
55 SignalBase::~SignalBase()
56 {
57         stop_conversion();
58 }
59
60 shared_ptr<sigrok::Channel> SignalBase::channel() const
61 {
62         return channel_;
63 }
64
65 QString SignalBase::name() const
66 {
67         return (channel_) ? QString::fromStdString(channel_->name()) : name_;
68 }
69
70 QString SignalBase::internal_name() const
71 {
72         return internal_name_;
73 }
74
75 void SignalBase::set_name(QString name)
76 {
77         if (channel_)
78                 channel_->set_name(name.toUtf8().constData());
79
80         name_ = name;
81
82         name_changed(name);
83 }
84
85 bool SignalBase::enabled() const
86 {
87         return (channel_) ? channel_->enabled() : true;
88 }
89
90 void SignalBase::set_enabled(bool value)
91 {
92         if (channel_) {
93                 channel_->set_enabled(value);
94                 enabled_changed(value);
95         }
96 }
97
98 SignalBase::ChannelType SignalBase::type() const
99 {
100         return channel_type_;
101 }
102
103 unsigned int SignalBase::index() const
104 {
105         return (channel_) ? channel_->index() : 0;
106 }
107
108 unsigned int SignalBase::logic_bit_index() const
109 {
110         if (channel_type_ == LogicChannel)
111                 return channel_->index();
112         else
113                 return 0;
114 }
115
116 QColor SignalBase::colour() const
117 {
118         return colour_;
119 }
120
121 void SignalBase::set_colour(QColor colour)
122 {
123         colour_ = colour;
124
125         bgcolour_ = colour;
126         bgcolour_.setAlpha(ColourBGAlpha);
127
128         colour_changed(colour);
129 }
130
131 QColor SignalBase::bgcolour() const
132 {
133         return bgcolour_;
134 }
135
136 void SignalBase::set_data(shared_ptr<pv::data::SignalData> data)
137 {
138         if (data_) {
139                 disconnect(data.get(), SIGNAL(samples_cleared()),
140                         this, SLOT(on_samples_cleared()));
141                 disconnect(data.get(), SIGNAL(samples_added(QObject*, uint64_t, uint64_t)),
142                         this, SLOT(on_samples_added(QObject*, uint64_t, uint64_t)));
143
144                 if (channel_type_ == AnalogChannel) {
145                         shared_ptr<Analog> analog = analog_data();
146                         assert(analog);
147
148                         disconnect(analog.get(), SIGNAL(min_max_changed(float, float)),
149                                 this, SLOT(on_min_max_changed(float, float)));
150                 }
151         }
152
153         data_ = data;
154
155         if (data_) {
156                 connect(data.get(), SIGNAL(samples_cleared()),
157                         this, SLOT(on_samples_cleared()));
158                 connect(data.get(), SIGNAL(samples_added(QObject*, uint64_t, uint64_t)),
159                         this, SLOT(on_samples_added(QObject*, uint64_t, uint64_t)));
160
161                 if (channel_type_ == AnalogChannel) {
162                         shared_ptr<Analog> analog = analog_data();
163                         assert(analog);
164
165                         connect(analog.get(), SIGNAL(min_max_changed(float, float)),
166                                 this, SLOT(on_min_max_changed(float, float)));
167                 }
168         }
169 }
170
171 shared_ptr<data::Analog> SignalBase::analog_data() const
172 {
173         shared_ptr<Analog> result = nullptr;
174
175         if (channel_type_ == AnalogChannel)
176                 result = dynamic_pointer_cast<Analog>(data_);
177
178         return result;
179 }
180
181 shared_ptr<data::Logic> SignalBase::logic_data() const
182 {
183         shared_ptr<Logic> result = nullptr;
184
185         if (channel_type_ == LogicChannel)
186                 result = dynamic_pointer_cast<Logic>(data_);
187
188         if (((conversion_type_ == A2LConversionByThreshold) ||
189                 (conversion_type_ == A2LConversionBySchmittTrigger)))
190                 result = dynamic_pointer_cast<Logic>(converted_data_);
191
192         return result;
193 }
194
195 SignalBase::ConversionType SignalBase::get_conversion_type() const
196 {
197         return conversion_type_;
198 }
199
200 void SignalBase::set_conversion_type(ConversionType t)
201 {
202         if (conversion_type_ != NoConversion) {
203                 stop_conversion();
204
205                 // Discard converted data
206                 converted_data_.reset();
207                 samples_cleared();
208         }
209
210         conversion_type_ = t;
211
212         // Re-create an empty container
213         // so that the signal is recognized as providing logic data
214         // and thus can be assigned to a decoder
215         if (conversion_is_a2l())
216                 if (!converted_data_)
217                         converted_data_ = make_shared<Logic>(1);  // Contains only one channel
218
219         start_conversion();
220
221         conversion_type_changed(t);
222 }
223
224 map<QString, QVariant> SignalBase::get_conversion_options() const
225 {
226         return conversion_options_;
227 }
228
229 bool SignalBase::set_conversion_option(QString key, QVariant value)
230 {
231         QVariant old_value;
232
233         auto key_iter = conversion_options_.find(key);
234         if (key_iter != conversion_options_.end())
235                 old_value = key_iter->second;
236
237         conversion_options_[key] = value;
238
239         return (value != old_value);
240 }
241
242 vector<double> SignalBase::get_conversion_thresholds(const ConversionType t,
243         const bool always_custom) const
244 {
245         vector<double> result;
246         ConversionType conv_type = t;
247         int preset;
248
249         // Use currently active conversion if no conversion type was supplied
250         if (conv_type == NoConversion)
251                 conv_type = conversion_type_;
252
253         if (always_custom)
254                 preset = -1;
255         else
256                 preset = get_current_conversion_preset();
257
258         if (conv_type == A2LConversionByThreshold) {
259                 double thr = 0;
260
261                 if (preset == -1) {
262                         auto thr_iter = conversion_options_.find("threshold_value");
263                         if (thr_iter != conversion_options_.end())
264                                 thr = (thr_iter->second).toDouble();
265                 }
266
267                 if (preset == 0)
268                         thr = (min_value_ + max_value_) * 0.5;  // middle between min and max
269
270                 if (preset == 1) thr = 0.9;
271                 if (preset == 2) thr = 1.8;
272                 if (preset == 3) thr = 2.5;
273                 if (preset == 4) thr = 1.5;
274
275                 result.push_back(thr);
276         }
277
278         if (conv_type == A2LConversionBySchmittTrigger) {
279                 double thr_lo = 0, thr_hi = 0;
280
281                 if (preset == -1) {
282                         auto thr_lo_iter = conversion_options_.find("threshold_value_low");
283                         if (thr_lo_iter != conversion_options_.end())
284                                 thr_lo = (thr_lo_iter->second).toDouble();
285
286                         auto thr_hi_iter = conversion_options_.find("threshold_value_high");
287                         if (thr_hi_iter != conversion_options_.end())
288                                 thr_hi = (thr_hi_iter->second).toDouble();
289                 }
290
291                 if (preset == 0) {
292                         const double amplitude = max_value_ - min_value_;
293                         const double center = min_value_ + (amplitude / 2);
294                         thr_lo = center - (amplitude * 0.15);  // 15% margin
295                         thr_hi = center + (amplitude * 0.15);  // 15% margin
296                 }
297
298                 if (preset == 1) { thr_lo = 0.3; thr_hi = 1.2; }
299                 if (preset == 2) { thr_lo = 0.7; thr_hi = 2.5; }
300                 if (preset == 3) { thr_lo = 1.3; thr_hi = 3.7; }
301                 if (preset == 4) { thr_lo = 0.8; thr_hi = 2.0; }
302
303                 result.push_back(thr_lo);
304                 result.push_back(thr_hi);
305         }
306
307         return result;
308 }
309
310 vector< pair<QString, int> > SignalBase::get_conversion_presets() const
311 {
312         vector< pair<QString, int> > presets;
313
314         if (conversion_type_ == A2LConversionByThreshold) {
315                 // Source: http://www.interfacebus.com/voltage_threshold.html
316                 presets.emplace_back(tr("Signal average"), 0);
317                 presets.emplace_back(tr("0.9V (for 1.8V CMOS)"), 1);
318                 presets.emplace_back(tr("1.8V (for 3.3V CMOS)"), 2);
319                 presets.emplace_back(tr("2.5V (for 5.0V CMOS)"), 3);
320                 presets.emplace_back(tr("1.5V (for TTL)"), 4);
321         }
322
323         if (conversion_type_ == A2LConversionBySchmittTrigger) {
324                 // Source: http://www.interfacebus.com/voltage_threshold.html
325                 presets.emplace_back(tr("Signal average +/- 15%"), 0);
326                 presets.emplace_back(tr("0.3V/1.2V (for 1.8V CMOS)"), 1);
327                 presets.emplace_back(tr("0.7V/2.5V (for 3.3V CMOS)"), 2);
328                 presets.emplace_back(tr("1.3V/3.7V (for 5.0V CMOS)"), 3);
329                 presets.emplace_back(tr("0.8V/2.0V (for TTL)"), 4);
330         }
331
332         return presets;
333 }
334
335 int SignalBase::get_current_conversion_preset() const
336 {
337         auto preset = conversion_options_.find("preset");
338         if (preset != conversion_options_.end())
339                 return (preset->second).toInt();
340
341         return -1;
342 }
343
344 void SignalBase::set_conversion_preset(int id)
345 {
346         conversion_options_["preset"] = id;
347 }
348
349 #ifdef ENABLE_DECODE
350 bool SignalBase::is_decode_signal() const
351 {
352         return (channel_type_ == DecodeChannel);
353 }
354 #endif
355
356 void SignalBase::save_settings(QSettings &settings) const
357 {
358         settings.setValue("name", name());
359         settings.setValue("enabled", enabled());
360         settings.setValue("colour", colour());
361         settings.setValue("conversion_type", (int)conversion_type_);
362
363         settings.setValue("conv_options", (int)(conversion_options_.size()));
364         int i = 0;
365         for (auto kvp : conversion_options_) {
366                 settings.setValue(QString("conv_option%1_key").arg(i), kvp.first);
367                 settings.setValue(QString("conv_option%1_value").arg(i), kvp.second);
368                 i++;
369         }
370 }
371
372 void SignalBase::restore_settings(QSettings &settings)
373 {
374         set_name(settings.value("name").toString());
375         set_enabled(settings.value("enabled").toBool());
376         set_colour(settings.value("colour").value<QColor>());
377         set_conversion_type((ConversionType)settings.value("conversion_type").toInt());
378
379         int conv_options = settings.value("conv_options").toInt();
380
381         if (conv_options)
382                 for (int i = 0; i < conv_options; i++) {
383                         QString key = settings.value(QString("conv_option%1_key").arg(i)).toString();
384                         QVariant value = settings.value(QString("conv_option%1_value").arg(i));
385                         conversion_options_[key] = value;
386                 }
387 }
388
389 bool SignalBase::conversion_is_a2l() const
390 {
391         return ((channel_type_ == AnalogChannel) &&
392                 ((conversion_type_ == A2LConversionByThreshold) ||
393                 (conversion_type_ == A2LConversionBySchmittTrigger)));
394 }
395
396 void SignalBase::conversion_thread_proc(QObject* segment)
397 {
398         // TODO Support for multiple segments is missing
399
400         uint64_t start_sample, end_sample;
401         start_sample = end_sample = 0;
402
403         do {
404                 if (conversion_is_a2l()) {
405
406                         AnalogSegment *asegment = qobject_cast<AnalogSegment*>(segment);
407
408                         const shared_ptr<Logic> logic_data = dynamic_pointer_cast<Logic>(converted_data_);
409
410                         // Create the initial logic data segment if needed
411                         if (logic_data->segments().size() == 0) {
412                                 shared_ptr<LogicSegment> lsegment =
413                                         make_shared<LogicSegment>(*logic_data.get(), 1, asegment->samplerate());
414                                 logic_data->push_segment(lsegment);
415                         }
416
417                         LogicSegment *lsegment = dynamic_cast<LogicSegment*>(logic_data->segments().front().get());
418
419                         start_sample = lsegment->get_sample_count();
420                         end_sample = asegment->get_sample_count();
421
422                         if (end_sample > start_sample) {
423                                 tie(min_value_, max_value_) = asegment->get_min_max();
424
425                                 // Create sigrok::Analog instance
426                                 float *asamples = new float[ConversionBlockSize];
427                                 uint8_t *lsamples = new uint8_t[ConversionBlockSize];
428
429                                 vector<shared_ptr<sigrok::Channel> > channels;
430                                 channels.push_back(channel_);
431
432                                 vector<const sigrok::QuantityFlag*> mq_flags;
433                                 const sigrok::Quantity * const mq = sigrok::Quantity::VOLTAGE;
434                                 const sigrok::Unit * const unit = sigrok::Unit::VOLT;
435
436                                 shared_ptr<sigrok::Packet> packet =
437                                         Session::sr_context->create_analog_packet(channels,
438                                         asamples, ConversionBlockSize, mq, unit, mq_flags);
439
440                                 shared_ptr<sigrok::Analog> analog =
441                                         dynamic_pointer_cast<sigrok::Analog>(packet->payload());
442
443                                 // Convert
444                                 uint64_t i = start_sample;
445
446                                 if (conversion_type_ == A2LConversionByThreshold) {
447                                         const double threshold = get_conversion_thresholds()[0];
448
449                                         // Convert as many sample blocks as we can
450                                         while ((end_sample - i) > ConversionBlockSize) {
451                                                 asegment->get_samples(i, i + ConversionBlockSize, asamples);
452
453                                                 shared_ptr<sigrok::Logic> logic =
454                                                         analog->get_logic_via_threshold(threshold, lsamples);
455
456                                                 lsegment->append_payload(logic->data_pointer(), logic->data_length());
457
458                                                 samples_added(lsegment, i, i + ConversionBlockSize);
459                                                 i += ConversionBlockSize;
460                                         }
461
462                                         // Re-create sigrok::Analog and convert remaining samples
463                                         packet = Session::sr_context->create_analog_packet(channels,
464                                                 asamples, end_sample - i, mq, unit, mq_flags);
465
466                                         analog = dynamic_pointer_cast<sigrok::Analog>(packet->payload());
467
468                                         asegment->get_samples(i, end_sample, asamples);
469                                         shared_ptr<sigrok::Logic> logic =
470                                                 analog->get_logic_via_threshold(threshold, lsamples);
471                                         lsegment->append_payload(logic->data_pointer(), logic->data_length());
472                                         samples_added(lsegment, i, end_sample);
473                                 }
474
475                                 if (conversion_type_ == A2LConversionBySchmittTrigger) {
476                                         const vector<double> thresholds = get_conversion_thresholds();
477                                         const double lo_thr = thresholds[0];
478                                         const double hi_thr = thresholds[1];
479
480                                         uint8_t state = 0;  // TODO Use value of logic sample n-1 instead of 0
481
482                                         // Convert as many sample blocks as we can
483                                         while ((end_sample - i) > ConversionBlockSize) {
484                                                 asegment->get_samples(i, i + ConversionBlockSize, asamples);
485
486                                                 shared_ptr<sigrok::Logic> logic =
487                                                         analog->get_logic_via_schmitt_trigger(lo_thr, hi_thr,
488                                                                 &state, lsamples);
489
490                                                 lsegment->append_payload(logic->data_pointer(), logic->data_length());
491
492                                                 samples_added(lsegment, i, i + ConversionBlockSize);
493                                                 i += ConversionBlockSize;
494                                         }
495
496                                         // Re-create sigrok::Analog and convert remaining samples
497                                         packet = Session::sr_context->create_analog_packet(channels,
498                                                 asamples, end_sample - i, mq, unit, mq_flags);
499
500                                         analog = dynamic_pointer_cast<sigrok::Analog>(packet->payload());
501
502                                         asegment->get_samples(i, end_sample, asamples);
503                                         shared_ptr<sigrok::Logic> logic =
504                                                 analog->get_logic_via_schmitt_trigger(lo_thr, hi_thr,
505                                                         &state, lsamples);
506                                         lsegment->append_payload(logic->data_pointer(), logic->data_length());
507                                         samples_added(lsegment, i, end_sample);
508                                 }
509
510                                 // If acquisition is ongoing, start-/endsample may have changed
511                                 end_sample = asegment->get_sample_count();
512
513                                 delete[] lsamples;
514                                 delete[] asamples;
515                         }
516                 }
517
518                 if (!conversion_interrupt_ && (start_sample == end_sample)) {
519                         unique_lock<mutex> input_lock(conversion_input_mutex_);
520                         conversion_input_cond_.wait(input_lock);
521                 }
522         } while (!conversion_interrupt_);
523 }
524
525 void SignalBase::start_conversion()
526 {
527         stop_conversion();
528
529         if (converted_data_)
530                 converted_data_->clear();
531
532         if (conversion_is_a2l()) {
533                 shared_ptr<Analog> analog_data = dynamic_pointer_cast<Analog>(data_);
534
535                 if (analog_data->analog_segments().size() > 0) {
536                         // TODO Support for multiple segments is missing
537                         AnalogSegment *asegment = analog_data->analog_segments().front().get();
538
539                         conversion_interrupt_ = false;
540                         conversion_thread_ = std::thread(
541                                 &SignalBase::conversion_thread_proc, this, asegment);
542                 }
543         }
544 }
545
546 void SignalBase::stop_conversion()
547 {
548         // Stop conversion so we can restart it from the beginning
549         conversion_interrupt_ = true;
550         conversion_input_cond_.notify_one();
551         if (conversion_thread_.joinable())
552                 conversion_thread_.join();
553 }
554
555 void SignalBase::on_samples_cleared()
556 {
557         if (converted_data_)
558                 converted_data_->clear();
559
560         samples_cleared();
561 }
562
563 void SignalBase::on_samples_added(QObject* segment, uint64_t start_sample,
564         uint64_t end_sample)
565 {
566         if (conversion_type_ != NoConversion) {
567                 if (conversion_thread_.joinable()) {
568                         // Notify the conversion thread since it's running
569                         conversion_input_cond_.notify_one();
570                 } else {
571                         // Start the conversion thread
572                         start_conversion();
573                 }
574         }
575
576         samples_added(segment, start_sample, end_sample);
577 }
578
579 void SignalBase::on_min_max_changed(float min, float max)
580 {
581         (void)min;
582         (void)max;
583
584         // Restart conversion if one is enabled and uses an automatic threshold
585         if ((conversion_type_ != NoConversion) &&
586                 (get_current_conversion_preset() == 0))
587                 start_conversion();
588 }
589
590 void SignalBase::on_capture_state_changed(int state)
591 {
592         if (state == Session::Running) {
593                 // Restart conversion if one is enabled
594                 if (conversion_type_ != NoConversion)
595                         start_conversion();
596         }
597 }
598
599 } // namespace data
600 } // namespace pv