2 * This file is part of the PulseView project.
4 * Copyright (C) 2012 Joel Holdsworth <joel@airwebreathe.org.uk>
5 * Copyright (C) 2016 Soeren Apel <soeren@apelpie.net>
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.
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.
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/>.
22 #include "analogsegment.hpp"
23 #include "decode/row.hpp"
25 #include "logicsegment.hpp"
26 #include "signalbase.hpp"
27 #include "signaldata.hpp"
31 #include <pv/binding/decoder.hpp>
32 #include <pv/session.hpp>
34 using std::dynamic_pointer_cast;
35 using std::make_shared;
36 using std::out_of_range;
37 using std::shared_ptr;
39 using std::unique_lock;
44 const int SignalBase::ColourBGAlpha = 8 * 256 / 100;
45 const uint64_t SignalBase::ConversionBlockSize = 4096;
46 const uint32_t SignalBase::ConversionDelay = 1000; // 1 second
48 SignalBase::SignalBase(shared_ptr<sigrok::Channel> channel, ChannelType channel_type) :
50 channel_type_(channel_type),
51 conversion_type_(NoConversion),
56 internal_name_ = QString::fromStdString(channel_->name());
58 connect(&delayed_conversion_starter_, SIGNAL(timeout()),
59 this, SLOT(on_delayed_conversion_start()));
60 delayed_conversion_starter_.setSingleShot(true);
61 delayed_conversion_starter_.setInterval(ConversionDelay);
64 SignalBase::~SignalBase()
69 shared_ptr<sigrok::Channel> SignalBase::channel() const
74 QString SignalBase::name() const
76 return (channel_) ? QString::fromStdString(channel_->name()) : name_;
79 QString SignalBase::internal_name() const
81 return internal_name_;
84 QString SignalBase::display_name() const
86 if (name() != internal_name_)
87 return name() + " (" + internal_name_ + ")";
92 void SignalBase::set_name(QString name)
95 channel_->set_name(name.toUtf8().constData());
102 bool SignalBase::enabled() const
104 return (channel_) ? channel_->enabled() : true;
107 void SignalBase::set_enabled(bool value)
110 channel_->set_enabled(value);
111 enabled_changed(value);
115 SignalBase::ChannelType SignalBase::type() const
117 return channel_type_;
120 unsigned int SignalBase::index() const
122 return (channel_) ? channel_->index() : 0;
125 unsigned int SignalBase::logic_bit_index() const
127 if (channel_type_ == LogicChannel)
128 return channel_->index();
133 QColor SignalBase::colour() const
138 void SignalBase::set_colour(QColor colour)
143 bgcolour_.setAlpha(ColourBGAlpha);
145 colour_changed(colour);
148 QColor SignalBase::bgcolour() const
153 void SignalBase::set_data(shared_ptr<pv::data::SignalData> data)
156 disconnect(data.get(), SIGNAL(samples_cleared()),
157 this, SLOT(on_samples_cleared()));
158 disconnect(data.get(), SIGNAL(samples_added(QObject*, uint64_t, uint64_t)),
159 this, SLOT(on_samples_added(QObject*, uint64_t, uint64_t)));
161 if (channel_type_ == AnalogChannel) {
162 shared_ptr<Analog> analog = analog_data();
165 disconnect(analog.get(), SIGNAL(min_max_changed(float, float)),
166 this, SLOT(on_min_max_changed(float, float)));
173 connect(data.get(), SIGNAL(samples_cleared()),
174 this, SLOT(on_samples_cleared()));
175 connect(data.get(), SIGNAL(samples_added(QObject*, uint64_t, uint64_t)),
176 this, SLOT(on_samples_added(QObject*, uint64_t, uint64_t)));
178 if (channel_type_ == AnalogChannel) {
179 shared_ptr<Analog> analog = analog_data();
182 connect(analog.get(), SIGNAL(min_max_changed(float, float)),
183 this, SLOT(on_min_max_changed(float, float)));
188 shared_ptr<data::Analog> SignalBase::analog_data() const
190 shared_ptr<Analog> result = nullptr;
192 if (channel_type_ == AnalogChannel)
193 result = dynamic_pointer_cast<Analog>(data_);
198 shared_ptr<data::Logic> SignalBase::logic_data() const
200 shared_ptr<Logic> result = nullptr;
202 if (channel_type_ == LogicChannel)
203 result = dynamic_pointer_cast<Logic>(data_);
205 if (((conversion_type_ == A2LConversionByThreshold) ||
206 (conversion_type_ == A2LConversionBySchmittTrigger)))
207 result = dynamic_pointer_cast<Logic>(converted_data_);
212 bool SignalBase::segment_is_complete(uint32_t segment_id) const
216 if (channel_type_ == AnalogChannel)
218 shared_ptr<Analog> data = dynamic_pointer_cast<Analog>(data_);
219 auto segments = data->analog_segments();
221 result = segments.at(segment_id)->is_complete();
222 } catch (out_of_range&) {
227 if (channel_type_ == LogicChannel)
229 shared_ptr<Logic> data = dynamic_pointer_cast<Logic>(data_);
230 auto segments = data->logic_segments();
232 result = segments.at(segment_id)->is_complete();
233 } catch (out_of_range&) {
241 SignalBase::ConversionType SignalBase::get_conversion_type() const
243 return conversion_type_;
246 void SignalBase::set_conversion_type(ConversionType t)
248 if (conversion_type_ != NoConversion) {
251 // Discard converted data
252 converted_data_.reset();
256 conversion_type_ = t;
258 // Re-create an empty container
259 // so that the signal is recognized as providing logic data
260 // and thus can be assigned to a decoder
261 if (conversion_is_a2l())
262 if (!converted_data_)
263 converted_data_ = make_shared<Logic>(1); // Contains only one channel
267 conversion_type_changed(t);
270 map<QString, QVariant> SignalBase::get_conversion_options() const
272 return conversion_options_;
275 bool SignalBase::set_conversion_option(QString key, QVariant value)
279 auto key_iter = conversion_options_.find(key);
280 if (key_iter != conversion_options_.end())
281 old_value = key_iter->second;
283 conversion_options_[key] = value;
285 return (value != old_value);
288 vector<double> SignalBase::get_conversion_thresholds(const ConversionType t,
289 const bool always_custom) const
291 vector<double> result;
292 ConversionType conv_type = t;
293 ConversionPreset preset;
295 // Use currently active conversion if no conversion type was supplied
296 if (conv_type == NoConversion)
297 conv_type = conversion_type_;
302 preset = get_current_conversion_preset();
304 if (conv_type == A2LConversionByThreshold) {
307 if (preset == NoPreset) {
308 auto thr_iter = conversion_options_.find("threshold_value");
309 if (thr_iter != conversion_options_.end())
310 thr = (thr_iter->second).toDouble();
313 if (preset == DynamicPreset)
314 thr = (min_value_ + max_value_) * 0.5; // middle between min and max
316 if ((int)preset == 1) thr = 0.9;
317 if ((int)preset == 2) thr = 1.8;
318 if ((int)preset == 3) thr = 2.5;
319 if ((int)preset == 4) thr = 1.5;
321 result.push_back(thr);
324 if (conv_type == A2LConversionBySchmittTrigger) {
325 double thr_lo = 0, thr_hi = 0;
327 if (preset == NoPreset) {
328 auto thr_lo_iter = conversion_options_.find("threshold_value_low");
329 if (thr_lo_iter != conversion_options_.end())
330 thr_lo = (thr_lo_iter->second).toDouble();
332 auto thr_hi_iter = conversion_options_.find("threshold_value_high");
333 if (thr_hi_iter != conversion_options_.end())
334 thr_hi = (thr_hi_iter->second).toDouble();
337 if (preset == DynamicPreset) {
338 const double amplitude = max_value_ - min_value_;
339 const double center = min_value_ + (amplitude / 2);
340 thr_lo = center - (amplitude * 0.15); // 15% margin
341 thr_hi = center + (amplitude * 0.15); // 15% margin
344 if ((int)preset == 1) { thr_lo = 0.3; thr_hi = 1.2; }
345 if ((int)preset == 2) { thr_lo = 0.7; thr_hi = 2.5; }
346 if ((int)preset == 3) { thr_lo = 1.3; thr_hi = 3.7; }
347 if ((int)preset == 4) { thr_lo = 0.8; thr_hi = 2.0; }
349 result.push_back(thr_lo);
350 result.push_back(thr_hi);
356 vector< pair<QString, int> > SignalBase::get_conversion_presets() const
358 vector< pair<QString, int> > presets;
360 if (conversion_type_ == A2LConversionByThreshold) {
361 // Source: http://www.interfacebus.com/voltage_threshold.html
362 presets.emplace_back(tr("Signal average"), 0);
363 presets.emplace_back(tr("0.9V (for 1.8V CMOS)"), 1);
364 presets.emplace_back(tr("1.8V (for 3.3V CMOS)"), 2);
365 presets.emplace_back(tr("2.5V (for 5.0V CMOS)"), 3);
366 presets.emplace_back(tr("1.5V (for TTL)"), 4);
369 if (conversion_type_ == A2LConversionBySchmittTrigger) {
370 // Source: http://www.interfacebus.com/voltage_threshold.html
371 presets.emplace_back(tr("Signal average +/- 15%"), 0);
372 presets.emplace_back(tr("0.3V/1.2V (for 1.8V CMOS)"), 1);
373 presets.emplace_back(tr("0.7V/2.5V (for 3.3V CMOS)"), 2);
374 presets.emplace_back(tr("1.3V/3.7V (for 5.0V CMOS)"), 3);
375 presets.emplace_back(tr("0.8V/2.0V (for TTL)"), 4);
381 SignalBase::ConversionPreset SignalBase::get_current_conversion_preset() const
383 auto preset = conversion_options_.find("preset");
384 if (preset != conversion_options_.end())
385 return (ConversionPreset)((preset->second).toInt());
387 return DynamicPreset;
390 void SignalBase::set_conversion_preset(ConversionPreset id)
392 conversion_options_["preset"] = (int)id;
396 bool SignalBase::is_decode_signal() const
398 return (channel_type_ == DecodeChannel);
402 void SignalBase::save_settings(QSettings &settings) const
404 settings.setValue("name", name());
405 settings.setValue("enabled", enabled());
406 settings.setValue("colour", colour());
407 settings.setValue("conversion_type", (int)conversion_type_);
409 settings.setValue("conv_options", (int)(conversion_options_.size()));
411 for (auto kvp : conversion_options_) {
412 settings.setValue(QString("conv_option%1_key").arg(i), kvp.first);
413 settings.setValue(QString("conv_option%1_value").arg(i), kvp.second);
418 void SignalBase::restore_settings(QSettings &settings)
420 set_name(settings.value("name").toString());
421 set_enabled(settings.value("enabled").toBool());
422 set_colour(settings.value("colour").value<QColor>());
423 set_conversion_type((ConversionType)settings.value("conversion_type").toInt());
425 int conv_options = settings.value("conv_options").toInt();
428 for (int i = 0; i < conv_options; i++) {
429 QString key = settings.value(QString("conv_option%1_key").arg(i)).toString();
430 QVariant value = settings.value(QString("conv_option%1_value").arg(i));
431 conversion_options_[key] = value;
435 bool SignalBase::conversion_is_a2l() const
437 return ((channel_type_ == AnalogChannel) &&
438 ((conversion_type_ == A2LConversionByThreshold) ||
439 (conversion_type_ == A2LConversionBySchmittTrigger)));
442 void SignalBase::convert_single_segment_range(AnalogSegment *asegment,
443 LogicSegment *lsegment, uint64_t start_sample, uint64_t end_sample)
445 if (end_sample > start_sample) {
446 tie(min_value_, max_value_) = asegment->get_min_max();
448 // Create sigrok::Analog instance
449 float *asamples = new float[ConversionBlockSize];
450 uint8_t *lsamples = new uint8_t[ConversionBlockSize];
452 vector<shared_ptr<sigrok::Channel> > channels;
453 channels.push_back(channel_);
455 vector<const sigrok::QuantityFlag*> mq_flags;
456 const sigrok::Quantity * const mq = sigrok::Quantity::VOLTAGE;
457 const sigrok::Unit * const unit = sigrok::Unit::VOLT;
459 shared_ptr<sigrok::Packet> packet =
460 Session::sr_context->create_analog_packet(channels,
461 asamples, ConversionBlockSize, mq, unit, mq_flags);
463 shared_ptr<sigrok::Analog> analog =
464 dynamic_pointer_cast<sigrok::Analog>(packet->payload());
467 uint64_t i = start_sample;
469 if (conversion_type_ == A2LConversionByThreshold) {
470 const double threshold = get_conversion_thresholds()[0];
472 // Convert as many sample blocks as we can
473 while ((end_sample - i) > ConversionBlockSize) {
474 asegment->get_samples(i, i + ConversionBlockSize, asamples);
476 shared_ptr<sigrok::Logic> logic =
477 analog->get_logic_via_threshold(threshold, lsamples);
479 lsegment->append_payload(logic->data_pointer(), logic->data_length());
480 samples_added(lsegment->segment_id(), i, i + ConversionBlockSize);
481 i += ConversionBlockSize;
484 // Re-create sigrok::Analog and convert remaining samples
485 packet = Session::sr_context->create_analog_packet(channels,
486 asamples, end_sample - i, mq, unit, mq_flags);
488 analog = dynamic_pointer_cast<sigrok::Analog>(packet->payload());
490 asegment->get_samples(i, end_sample, asamples);
491 shared_ptr<sigrok::Logic> logic =
492 analog->get_logic_via_threshold(threshold, lsamples);
493 lsegment->append_payload(logic->data_pointer(), logic->data_length());
494 samples_added(lsegment->segment_id(), i, end_sample);
497 if (conversion_type_ == A2LConversionBySchmittTrigger) {
498 const vector<double> thresholds = get_conversion_thresholds();
499 const double lo_thr = thresholds[0];
500 const double hi_thr = thresholds[1];
502 uint8_t state = 0; // TODO Use value of logic sample n-1 instead of 0
504 // Convert as many sample blocks as we can
505 while ((end_sample - i) > ConversionBlockSize) {
506 asegment->get_samples(i, i + ConversionBlockSize, asamples);
508 shared_ptr<sigrok::Logic> logic =
509 analog->get_logic_via_schmitt_trigger(lo_thr, hi_thr,
512 lsegment->append_payload(logic->data_pointer(), logic->data_length());
513 samples_added(lsegment->segment_id(), i, i + ConversionBlockSize);
514 i += ConversionBlockSize;
517 // Re-create sigrok::Analog and convert remaining samples
518 packet = Session::sr_context->create_analog_packet(channels,
519 asamples, end_sample - i, mq, unit, mq_flags);
521 analog = dynamic_pointer_cast<sigrok::Analog>(packet->payload());
523 asegment->get_samples(i, end_sample, asamples);
524 shared_ptr<sigrok::Logic> logic =
525 analog->get_logic_via_schmitt_trigger(lo_thr, hi_thr,
527 lsegment->append_payload(logic->data_pointer(), logic->data_length());
528 samples_added(lsegment->segment_id(), i, end_sample);
531 // If acquisition is ongoing, start-/endsample may have changed
532 end_sample = asegment->get_sample_count();
539 void SignalBase::convert_single_segment(AnalogSegment *asegment, LogicSegment *lsegment)
541 uint64_t start_sample, end_sample, old_end_sample;
542 start_sample = end_sample = 0;
543 bool complete_state, old_complete_state;
545 start_sample = lsegment->get_sample_count();
546 end_sample = asegment->get_sample_count();
547 complete_state = asegment->is_complete();
549 // Don't do anything if the segment is still being filled and the sample count is too small
550 if ((!complete_state) && (end_sample - start_sample < ConversionBlockSize))
554 convert_single_segment_range(asegment, lsegment, start_sample, end_sample);
556 old_end_sample = end_sample;
557 old_complete_state = complete_state;
559 start_sample = lsegment->get_sample_count();
560 end_sample = asegment->get_sample_count();
561 complete_state = asegment->is_complete();
563 // If the segment has been incomplete when we were called and has been
564 // completed in the meanwhile, we convert the remaining samples as well.
565 // Also, if a sufficient number of samples was added in the meanwhile,
566 // we do another round of sample conversion.
567 } while ((complete_state != old_complete_state) ||
568 (end_sample - old_end_sample >= ConversionBlockSize));
571 void SignalBase::conversion_thread_proc()
573 shared_ptr<Analog> analog_data;
575 if (conversion_is_a2l()) {
576 analog_data = dynamic_pointer_cast<Analog>(data_);
578 if (analog_data->analog_segments().size() == 0) {
579 unique_lock<mutex> input_lock(conversion_input_mutex_);
580 conversion_input_cond_.wait(input_lock);
584 // Currently, we only handle A2L conversions
587 // If we had to wait for input data, we may have been notified to terminate
588 if (conversion_interrupt_)
591 uint32_t segment_id = 0;
593 AnalogSegment *asegment = analog_data->analog_segments().front().get();
596 const shared_ptr<Logic> logic_data = dynamic_pointer_cast<Logic>(converted_data_);
599 // Create the initial logic data segment if needed
600 if (logic_data->logic_segments().size() == 0) {
601 shared_ptr<LogicSegment> new_segment =
602 make_shared<LogicSegment>(*logic_data.get(), 0, 1, asegment->samplerate());
603 logic_data->push_segment(new_segment);
606 LogicSegment *lsegment = logic_data->logic_segments().front().get();
610 convert_single_segment(asegment, lsegment);
612 // Only advance to next segment if the current input segment is complete
613 if (asegment->is_complete() &&
614 analog_data->analog_segments().size() > logic_data->logic_segments().size()) {
615 // There are more segments to process
619 asegment = analog_data->analog_segments().at(segment_id).get();
620 } catch (out_of_range&) {
621 qDebug() << "Conversion error for" << name() << ": no analog segment" \
622 << segment_id << ", segments size is" << analog_data->analog_segments().size();
626 shared_ptr<LogicSegment> new_segment = make_shared<LogicSegment>(
627 *logic_data.get(), segment_id, 1, asegment->samplerate());
628 logic_data->push_segment(new_segment);
630 lsegment = logic_data->logic_segments().back().get();
632 // No more samples/segments to process, wait for data or interrupt
633 if (!conversion_interrupt_) {
634 unique_lock<mutex> input_lock(conversion_input_mutex_);
635 conversion_input_cond_.wait(input_lock);
638 } while (!conversion_interrupt_);
641 void SignalBase::start_conversion(bool delayed_start)
644 delayed_conversion_starter_.start();
651 converted_data_->clear();
654 conversion_interrupt_ = false;
655 conversion_thread_ = std::thread(
656 &SignalBase::conversion_thread_proc, this);
659 void SignalBase::stop_conversion()
661 // Stop conversion so we can restart it from the beginning
662 conversion_interrupt_ = true;
663 conversion_input_cond_.notify_one();
664 if (conversion_thread_.joinable())
665 conversion_thread_.join();
668 void SignalBase::on_samples_cleared()
671 converted_data_->clear();
676 void SignalBase::on_samples_added(QObject* segment, uint64_t start_sample,
679 if (conversion_type_ != NoConversion) {
680 if (conversion_thread_.joinable()) {
681 // Notify the conversion thread since it's running
682 conversion_input_cond_.notify_one();
684 // Start the conversion thread unless the delay timer is running
685 if (!delayed_conversion_starter_.isActive())
690 data::Segment* s = qobject_cast<data::Segment*>(segment);
691 samples_added(s->segment_id(), start_sample, end_sample);
694 void SignalBase::on_min_max_changed(float min, float max)
696 // Restart conversion if one is enabled and uses a calculated threshold
697 if ((conversion_type_ != NoConversion) &&
698 (get_current_conversion_preset() == DynamicPreset))
699 start_conversion(true);
701 min_max_changed(min, max);
704 void SignalBase::on_capture_state_changed(int state)
706 if (state == Session::Running) {
707 // Restart conversion if one is enabled
708 if (conversion_type_ != NoConversion)
713 void SignalBase::on_delayed_conversion_start()