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"
32 #include <pv/session.hpp>
33 #include <pv/binding/decoder.hpp>
35 using std::dynamic_pointer_cast;
36 using std::make_shared;
37 using std::out_of_range;
38 using std::shared_ptr;
40 using std::unique_lock;
45 const QColor SignalBase::AnalogSignalColors[8] =
47 QColor(0xC4, 0xA0, 0x00), // Yellow HSV: 49 / 100 / 77
48 QColor(0x87, 0x20, 0x7A), // Magenta HSV: 308 / 70 / 53
49 QColor(0x20, 0x4A, 0x87), // Blue HSV: 216 / 76 / 53
50 QColor(0x4E, 0x9A, 0x06), // Green HSV: 91 / 96 / 60
51 QColor(0xBF, 0x6E, 0x00), // Orange HSV: 35 / 100 / 75
52 QColor(0x5E, 0x20, 0x80), // Purple HSV: 280 / 75 / 50
53 QColor(0x20, 0x80, 0x7A), // Turqoise HSV: 177 / 75 / 50
54 QColor(0x80, 0x20, 0x24) // Red HSV: 358 / 75 / 50
57 const QColor SignalBase::LogicSignalColors[10] =
59 QColor(0x16, 0x19, 0x1A), // Black
60 QColor(0x8F, 0x52, 0x02), // Brown
61 QColor(0xCC, 0x00, 0x00), // Red
62 QColor(0xF5, 0x79, 0x00), // Orange
63 QColor(0xED, 0xD4, 0x00), // Yellow
64 QColor(0x73, 0xD2, 0x16), // Green
65 QColor(0x34, 0x65, 0xA4), // Blue
66 QColor(0x75, 0x50, 0x7B), // Violet
67 QColor(0x88, 0x8A, 0x85), // Grey
68 QColor(0xEE, 0xEE, 0xEC), // White
72 const int SignalBase::ColorBGAlpha = 8 * 256 / 100;
73 const uint64_t SignalBase::ConversionBlockSize = 4096;
74 const uint32_t SignalBase::ConversionDelay = 1000; // 1 second
77 SignalGroup::SignalGroup(const QString& name)
82 void SignalGroup::append_signal(shared_ptr<SignalBase> signal)
87 signals_.push_back(signal);
88 signal->set_group(this);
91 void SignalGroup::remove_signal(shared_ptr<SignalBase> signal)
96 signals_.erase(std::remove_if(signals_.begin(), signals_.end(),
97 [&](shared_ptr<SignalBase> s) { return s == signal; }),
101 deque<shared_ptr<SignalBase>> SignalGroup::signals() const
106 void SignalGroup::clear()
108 for (shared_ptr<SignalBase> sb : signals_)
109 sb->set_group(nullptr);
114 const QString SignalGroup::name() const
120 SignalBase::SignalBase(shared_ptr<sigrok::Channel> channel, ChannelType channel_type) :
122 channel_type_(channel_type),
124 conversion_type_(NoConversion),
130 internal_name_ = QString::fromStdString(channel_->name());
131 index_ = channel_->index();
134 connect(&delayed_conversion_starter_, SIGNAL(timeout()),
135 this, SLOT(on_delayed_conversion_start()));
136 delayed_conversion_starter_.setSingleShot(true);
137 delayed_conversion_starter_.setInterval(ConversionDelay);
139 // Only logic and analog SR channels can have their colors auto-set
140 // because for them, we have an index that can be used
141 if (channel_type == LogicChannel)
142 set_color(LogicSignalColors[index() % countof(LogicSignalColors)]);
143 else if (channel_type == AnalogChannel)
144 set_color(AnalogSignalColors[index() % countof(AnalogSignalColors)]);
147 SignalBase::~SignalBase()
152 shared_ptr<sigrok::Channel> SignalBase::channel() const
157 bool SignalBase::is_generated() const
159 // Only signals associated with a device have a corresponding sigrok channel
160 return channel_ == nullptr;
163 bool SignalBase::enabled() const
165 return (channel_) ? channel_->enabled() : true;
168 void SignalBase::set_enabled(bool value)
171 channel_->set_enabled(value);
172 enabled_changed(value);
176 SignalBase::ChannelType SignalBase::type() const
178 return channel_type_;
181 unsigned int SignalBase::index() const
186 void SignalBase::set_index(unsigned int index)
191 unsigned int SignalBase::logic_bit_index() const
193 if (channel_type_ == LogicChannel)
199 void SignalBase::set_group(SignalGroup* group)
204 SignalGroup* SignalBase::group() const
209 QString SignalBase::name() const
211 return (channel_) ? QString::fromStdString(channel_->name()) : name_;
214 QString SignalBase::internal_name() const
216 return internal_name_;
219 void SignalBase::set_internal_name(QString internal_name)
221 internal_name_ = internal_name;
224 QString SignalBase::display_name() const
226 if ((name() != internal_name_) && (!internal_name_.isEmpty()))
227 return name() + " (" + internal_name_ + ")";
232 void SignalBase::set_name(QString name)
235 channel_->set_name(name.toUtf8().constData());
242 QColor SignalBase::color() const
247 void SignalBase::set_color(QColor color)
252 bgcolor_.setAlpha(ColorBGAlpha);
254 color_changed(color);
257 QColor SignalBase::bgcolor() const
262 QString SignalBase::get_error_message() const
264 return error_message_;
267 void SignalBase::set_data(shared_ptr<pv::data::SignalData> data)
270 disconnect(data.get(), SIGNAL(samples_cleared()),
271 this, SLOT(on_samples_cleared()));
272 disconnect(data.get(), SIGNAL(samples_added(shared_ptr<Segment>, uint64_t, uint64_t)),
273 this, SLOT(on_samples_added(shared_ptr<Segment>, uint64_t, uint64_t)));
275 shared_ptr<Analog> analog = analog_data();
277 disconnect(analog.get(), SIGNAL(min_max_changed(float, float)),
278 this, SLOT(on_min_max_changed(float, float)));
284 connect(data.get(), SIGNAL(samples_cleared()),
285 this, SLOT(on_samples_cleared()));
286 connect(data.get(), SIGNAL(samples_added(SharedPtrToSegment, uint64_t, uint64_t)),
287 this, SLOT(on_samples_added(SharedPtrToSegment, uint64_t, uint64_t)));
289 shared_ptr<Analog> analog = analog_data();
291 connect(analog.get(), SIGNAL(min_max_changed(float, float)),
292 this, SLOT(on_min_max_changed(float, float)));
296 void SignalBase::clear_sample_data()
299 analog_data()->clear();
302 logic_data()->clear();
305 shared_ptr<data::Analog> SignalBase::analog_data() const
307 return dynamic_pointer_cast<Analog>(data_);
310 shared_ptr<data::Logic> SignalBase::logic_data() const
312 shared_ptr<Logic> result = dynamic_pointer_cast<Logic>(data_);
314 if (((conversion_type_ == A2LConversionByThreshold) ||
315 (conversion_type_ == A2LConversionBySchmittTrigger)))
316 result = dynamic_pointer_cast<Logic>(converted_data_);
321 bool SignalBase::segment_is_complete(uint32_t segment_id) const
325 shared_ptr<Analog> adata = analog_data();
328 auto segments = adata->analog_segments();
330 result = segments.at(segment_id)->is_complete();
331 } catch (out_of_range&) {
335 shared_ptr<Logic> ldata = logic_data();
337 shared_ptr<Logic> data = dynamic_pointer_cast<Logic>(data_);
338 auto segments = data->logic_segments();
340 result = segments.at(segment_id)->is_complete();
341 } catch (out_of_range&) {
350 bool SignalBase::has_samples() const
354 shared_ptr<Analog> adata = analog_data();
357 auto segments = adata->analog_segments();
358 if ((segments.size() > 0) && (segments.front()->get_sample_count() > 0))
361 shared_ptr<Logic> ldata = logic_data();
363 auto segments = ldata->logic_segments();
364 if ((segments.size() > 0) && (segments.front()->get_sample_count() > 0))
372 double SignalBase::get_samplerate() const
374 shared_ptr<Analog> adata = analog_data();
376 return adata->get_samplerate();
378 shared_ptr<Logic> ldata = logic_data();
380 return ldata->get_samplerate();
383 // Default samplerate is 1 Hz
387 SignalBase::ConversionType SignalBase::get_conversion_type() const
389 return conversion_type_;
392 void SignalBase::set_conversion_type(ConversionType t)
394 if (conversion_type_ != NoConversion) {
397 // Discard converted data
398 converted_data_.reset();
402 conversion_type_ = t;
404 // Re-create an empty container
405 // so that the signal is recognized as providing logic data
406 // and thus can be assigned to a decoder
407 if (conversion_is_a2l())
408 if (!converted_data_)
409 converted_data_ = make_shared<Logic>(1); // Contains only one channel
413 conversion_type_changed(t);
416 map<QString, QVariant> SignalBase::get_conversion_options() const
418 return conversion_options_;
421 bool SignalBase::set_conversion_option(QString key, QVariant value)
425 auto key_iter = conversion_options_.find(key);
426 if (key_iter != conversion_options_.end())
427 old_value = key_iter->second;
429 conversion_options_[key] = value;
431 return (value != old_value);
434 vector<double> SignalBase::get_conversion_thresholds(const ConversionType t,
435 const bool always_custom) const
437 vector<double> result;
438 ConversionType conv_type = t;
439 ConversionPreset preset;
441 // Use currently active conversion if no conversion type was supplied
442 if (conv_type == NoConversion)
443 conv_type = conversion_type_;
448 preset = get_current_conversion_preset();
450 if (conv_type == A2LConversionByThreshold) {
453 if (preset == NoPreset) {
454 auto thr_iter = conversion_options_.find("threshold_value");
455 if (thr_iter != conversion_options_.end())
456 thr = (thr_iter->second).toDouble();
459 if (preset == DynamicPreset)
460 thr = (min_value_ + max_value_) * 0.5; // middle between min and max
462 if ((int)preset == 1) thr = 0.9;
463 if ((int)preset == 2) thr = 1.8;
464 if ((int)preset == 3) thr = 2.5;
465 if ((int)preset == 4) thr = 1.5;
467 result.push_back(thr);
470 if (conv_type == A2LConversionBySchmittTrigger) {
471 double thr_lo = 0, thr_hi = 0;
473 if (preset == NoPreset) {
474 auto thr_lo_iter = conversion_options_.find("threshold_value_low");
475 if (thr_lo_iter != conversion_options_.end())
476 thr_lo = (thr_lo_iter->second).toDouble();
478 auto thr_hi_iter = conversion_options_.find("threshold_value_high");
479 if (thr_hi_iter != conversion_options_.end())
480 thr_hi = (thr_hi_iter->second).toDouble();
483 if (preset == DynamicPreset) {
484 const double amplitude = max_value_ - min_value_;
485 const double center = min_value_ + (amplitude / 2);
486 thr_lo = center - (amplitude * 0.15); // 15% margin
487 thr_hi = center + (amplitude * 0.15); // 15% margin
490 if ((int)preset == 1) { thr_lo = 0.3; thr_hi = 1.2; }
491 if ((int)preset == 2) { thr_lo = 0.7; thr_hi = 2.5; }
492 if ((int)preset == 3) { thr_lo = 1.3; thr_hi = 3.7; }
493 if ((int)preset == 4) { thr_lo = 0.8; thr_hi = 2.0; }
495 result.push_back(thr_lo);
496 result.push_back(thr_hi);
502 vector< pair<QString, int> > SignalBase::get_conversion_presets() const
504 vector< pair<QString, int> > presets;
506 if (conversion_type_ == A2LConversionByThreshold) {
507 // Source: http://www.interfacebus.com/voltage_threshold.html
508 presets.emplace_back(tr("Signal average"), 0);
509 presets.emplace_back(tr("0.9V (for 1.8V CMOS)"), 1);
510 presets.emplace_back(tr("1.8V (for 3.3V CMOS)"), 2);
511 presets.emplace_back(tr("2.5V (for 5.0V CMOS)"), 3);
512 presets.emplace_back(tr("1.5V (for TTL)"), 4);
515 if (conversion_type_ == A2LConversionBySchmittTrigger) {
516 // Source: http://www.interfacebus.com/voltage_threshold.html
517 presets.emplace_back(tr("Signal average +/- 15%"), 0);
518 presets.emplace_back(tr("0.3V/1.2V (for 1.8V CMOS)"), 1);
519 presets.emplace_back(tr("0.7V/2.5V (for 3.3V CMOS)"), 2);
520 presets.emplace_back(tr("1.3V/3.7V (for 5.0V CMOS)"), 3);
521 presets.emplace_back(tr("0.8V/2.0V (for TTL)"), 4);
527 SignalBase::ConversionPreset SignalBase::get_current_conversion_preset() const
529 auto preset = conversion_options_.find("preset");
530 if (preset != conversion_options_.end())
531 return (ConversionPreset)((preset->second).toInt());
533 return DynamicPreset;
536 void SignalBase::set_conversion_preset(ConversionPreset id)
538 conversion_options_["preset"] = (int)id;
542 bool SignalBase::is_decode_signal() const
544 return (channel_type_ == DecodeChannel);
548 void SignalBase::save_settings(QSettings &settings) const
550 settings.setValue("name", name());
551 settings.setValue("enabled", enabled());
552 settings.setValue("color", color().rgba());
553 settings.setValue("conversion_type", (int)conversion_type_);
555 settings.setValue("conv_options", (int)(conversion_options_.size()));
557 for (auto& kvp : conversion_options_) {
558 settings.setValue(QString("conv_option%1_key").arg(i), kvp.first);
559 settings.setValue(QString("conv_option%1_value").arg(i), kvp.second);
564 void SignalBase::restore_settings(QSettings &settings)
566 if (settings.contains("name"))
567 set_name(settings.value("name").toString());
569 if (settings.contains("enabled"))
570 set_enabled(settings.value("enabled").toBool());
572 if (settings.contains("color")) {
573 QVariant value = settings.value("color");
575 // Workaround for Qt QColor serialization bug on OSX
576 if ((QMetaType::Type)(value.type()) == QMetaType::QColor)
577 set_color(value.value<QColor>());
579 set_color(QColor::fromRgba(value.value<uint32_t>()));
581 // A color with an alpha value of 0 makes the signal marker invisible
582 if (color() == QColor(0, 0, 0, 0))
586 if (settings.contains("conversion_type"))
587 set_conversion_type((ConversionType)settings.value("conversion_type").toInt());
589 int conv_options = 0;
590 if (settings.contains("conv_options"))
591 conv_options = settings.value("conv_options").toInt();
594 for (int i = 0; i < conv_options; i++) {
595 const QString key_id = QString("conv_option%1_key").arg(i);
596 const QString value_id = QString("conv_option%1_value").arg(i);
598 if (settings.contains(key_id) && settings.contains(value_id))
599 conversion_options_[settings.value(key_id).toString()] =
600 settings.value(value_id);
604 bool SignalBase::conversion_is_a2l() const
606 return (((conversion_type_ == A2LConversionByThreshold) ||
607 (conversion_type_ == A2LConversionBySchmittTrigger)));
610 void SignalBase::convert_single_segment_range(shared_ptr<AnalogSegment> asegment,
611 shared_ptr<LogicSegment> lsegment, uint64_t start_sample, uint64_t end_sample)
613 if (end_sample > start_sample) {
614 tie(min_value_, max_value_) = asegment->get_min_max();
616 // Create sigrok::Analog instance
617 float *asamples = new float[ConversionBlockSize];
619 uint8_t *lsamples = new uint8_t[ConversionBlockSize];
622 vector<shared_ptr<sigrok::Channel> > channels;
624 channels.push_back(channel_);
626 vector<const sigrok::QuantityFlag*> mq_flags;
627 const sigrok::Quantity * const mq = sigrok::Quantity::VOLTAGE;
628 const sigrok::Unit * const unit = sigrok::Unit::VOLT;
630 shared_ptr<sigrok::Packet> packet =
631 Session::sr_context->create_analog_packet(channels,
632 asamples, ConversionBlockSize, mq, unit, mq_flags);
634 shared_ptr<sigrok::Analog> analog =
635 dynamic_pointer_cast<sigrok::Analog>(packet->payload());
638 uint64_t i = start_sample;
640 if (conversion_type_ == A2LConversionByThreshold) {
641 const double threshold = get_conversion_thresholds()[0];
643 // Convert as many sample blocks as we can
644 while ((end_sample - i) > ConversionBlockSize) {
645 asegment->get_samples(i, i + ConversionBlockSize, asamples);
647 shared_ptr<sigrok::Logic> logic =
648 analog->get_logic_via_threshold(threshold, lsamples);
650 lsegment->append_payload(logic->data_pointer(), logic->data_length());
651 samples_added(lsegment->segment_id(), i, i + ConversionBlockSize);
652 i += ConversionBlockSize;
655 // Re-create sigrok::Analog and convert remaining samples
656 packet = Session::sr_context->create_analog_packet(channels,
657 asamples, end_sample - i, mq, unit, mq_flags);
659 analog = dynamic_pointer_cast<sigrok::Analog>(packet->payload());
661 asegment->get_samples(i, end_sample, asamples);
662 shared_ptr<sigrok::Logic> logic =
663 analog->get_logic_via_threshold(threshold, lsamples);
664 lsegment->append_payload(logic->data_pointer(), logic->data_length());
665 samples_added(lsegment->segment_id(), i, end_sample);
668 if (conversion_type_ == A2LConversionBySchmittTrigger) {
669 const vector<double> thresholds = get_conversion_thresholds();
670 const double lo_thr = thresholds[0];
671 const double hi_thr = thresholds[1];
673 uint8_t state = 0; // TODO Use value of logic sample n-1 instead of 0
675 // Convert as many sample blocks as we can
676 while ((end_sample - i) > ConversionBlockSize) {
677 asegment->get_samples(i, i + ConversionBlockSize, asamples);
679 shared_ptr<sigrok::Logic> logic =
680 analog->get_logic_via_schmitt_trigger(lo_thr, hi_thr,
683 lsegment->append_payload(logic->data_pointer(), logic->data_length());
684 samples_added(lsegment->segment_id(), i, i + ConversionBlockSize);
686 i += ConversionBlockSize;
689 // Re-create sigrok::Analog and convert remaining samples
690 packet = Session::sr_context->create_analog_packet(channels,
691 asamples, end_sample - i, mq, unit, mq_flags);
693 analog = dynamic_pointer_cast<sigrok::Analog>(packet->payload());
695 asegment->get_samples(i, end_sample, asamples);
696 shared_ptr<sigrok::Logic> logic =
697 analog->get_logic_via_schmitt_trigger(lo_thr, hi_thr,
699 lsegment->append_payload(logic->data_pointer(), logic->data_length());
700 samples_added(lsegment->segment_id(), i, end_sample);
703 // If acquisition is ongoing, start-/endsample may have changed
704 end_sample = asegment->get_sample_count();
711 void SignalBase::convert_single_segment(shared_ptr<AnalogSegment> asegment,
712 shared_ptr<LogicSegment> lsegment)
714 uint64_t start_sample, end_sample, old_end_sample;
715 start_sample = end_sample = 0;
716 bool complete_state, old_complete_state;
718 start_sample = lsegment->get_sample_count();
719 end_sample = asegment->get_sample_count();
720 complete_state = asegment->is_complete();
722 // Don't do anything if the segment is still being filled and the sample count is too small
723 if ((!complete_state) && (end_sample - start_sample < ConversionBlockSize))
727 convert_single_segment_range(asegment, lsegment, start_sample, end_sample);
729 old_end_sample = end_sample;
730 old_complete_state = complete_state;
732 start_sample = lsegment->get_sample_count();
733 end_sample = asegment->get_sample_count();
734 complete_state = asegment->is_complete();
736 // If the segment has been incomplete when we were called and has been
737 // completed in the meanwhile, we convert the remaining samples as well.
738 // Also, if a sufficient number of samples was added in the meanwhile,
739 // we do another round of sample conversion.
740 } while ((complete_state != old_complete_state) ||
741 (end_sample - old_end_sample >= ConversionBlockSize));
744 void SignalBase::conversion_thread_proc()
746 shared_ptr<Analog> analog_data;
748 if (conversion_is_a2l()) {
749 analog_data = dynamic_pointer_cast<Analog>(data_);
751 if (analog_data->analog_segments().size() == 0) {
752 unique_lock<mutex> input_lock(conversion_input_mutex_);
753 conversion_input_cond_.wait(input_lock);
757 // Currently, we only handle A2L conversions
760 // If we had to wait for input data, we may have been notified to terminate
761 if (conversion_interrupt_)
764 uint32_t segment_id = 0;
766 shared_ptr<AnalogSegment> asegment = analog_data->analog_segments().front();
769 const shared_ptr<Logic> logic_data = dynamic_pointer_cast<Logic>(converted_data_);
772 // Create the initial logic data segment if needed
773 if (logic_data->logic_segments().size() == 0) {
774 shared_ptr<LogicSegment> new_segment =
775 make_shared<LogicSegment>(*logic_data.get(), 0, 1, asegment->samplerate());
776 logic_data->push_segment(new_segment);
779 shared_ptr<LogicSegment> lsegment = logic_data->logic_segments().front();
783 convert_single_segment(asegment, lsegment);
785 // Only advance to next segment if the current input segment is complete
786 if (asegment->is_complete() &&
787 analog_data->analog_segments().size() > logic_data->logic_segments().size()) {
789 // There are more segments to process
793 asegment = analog_data->analog_segments().at(segment_id);
794 } catch (out_of_range&) {
795 qDebug() << "Conversion error for" << name() << ": no analog segment" \
796 << segment_id << ", segments size is" << analog_data->analog_segments().size();
800 shared_ptr<LogicSegment> new_segment = make_shared<LogicSegment>(
801 *logic_data.get(), segment_id, 1, asegment->samplerate());
802 logic_data->push_segment(new_segment);
804 lsegment = logic_data->logic_segments().back();
807 // No more samples/segments to process, wait for data or interrupt
808 if (!conversion_interrupt_) {
809 unique_lock<mutex> input_lock(conversion_input_mutex_);
810 conversion_input_cond_.wait(input_lock);
812 } while (!conversion_interrupt_);
815 void SignalBase::start_conversion(bool delayed_start)
818 delayed_conversion_starter_.start();
825 converted_data_->clear();
829 conversion_interrupt_ = false;
830 conversion_thread_ = std::thread(&SignalBase::conversion_thread_proc, this);
833 void SignalBase::set_error_message(QString msg)
835 error_message_ = msg;
836 // TODO Emulate noquote()
837 qDebug().nospace() << name() << ": " << msg;
839 error_message_changed(msg);
842 void SignalBase::stop_conversion()
844 // Stop conversion so we can restart it from the beginning
845 conversion_interrupt_ = true;
846 conversion_input_cond_.notify_one();
847 if (conversion_thread_.joinable())
848 conversion_thread_.join();
851 void SignalBase::on_samples_cleared()
854 converted_data_->clear();
859 void SignalBase::on_samples_added(SharedPtrToSegment segment, uint64_t start_sample,
862 if (conversion_type_ != NoConversion) {
863 if (conversion_thread_.joinable()) {
864 // Notify the conversion thread since it's running
865 conversion_input_cond_.notify_one();
867 // Start the conversion thread unless the delay timer is running
868 if (!delayed_conversion_starter_.isActive())
873 samples_added(segment->segment_id(), start_sample, end_sample);
876 void SignalBase::on_min_max_changed(float min, float max)
878 // Restart conversion if one is enabled and uses a calculated threshold
879 if ((conversion_type_ != NoConversion) &&
880 (get_current_conversion_preset() == DynamicPreset))
881 start_conversion(true);
883 min_max_changed(min, max);
886 void SignalBase::on_capture_state_changed(int state)
888 if (state == Session::Running) {
889 // Restart conversion if one is enabled
890 if (conversion_type_ != NoConversion)
895 void SignalBase::on_delayed_conversion_start()