2 * This file is part of the PulseView project.
4 * Copyright (C) 2012-14 Joel Holdsworth <joel@airwebreathe.org.uk>
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
22 // Windows: Avoid boost/thread namespace pollution (which includes windows.h).
26 #include <boost/thread/locks.hpp>
27 #include <boost/thread/shared_mutex.hpp>
35 #include "session.hpp"
36 #include "devicemanager.hpp"
38 #include "data/analog.hpp"
39 #include "data/analogsegment.hpp"
40 #include "data/decoderstack.hpp"
41 #include "data/logic.hpp"
42 #include "data/logicsegment.hpp"
43 #include "data/signalbase.hpp"
44 #include "data/decode/decoder.hpp"
46 #include "devices/hardwaredevice.hpp"
47 #include "devices/sessionfile.hpp"
49 #include "toolbars/mainbar.hpp"
51 #include "view/analogsignal.hpp"
52 #include "view/decodetrace.hpp"
53 #include "view/logicsignal.hpp"
54 #include "view/signal.hpp"
55 #include "view/view.hpp"
57 #include <libsigrokcxx/libsigrokcxx.hpp>
60 #include <libsigrokdecode/libsigrokdecode.h>
63 using boost::shared_lock;
64 using boost::shared_mutex;
65 using boost::unique_lock;
67 using std::dynamic_pointer_cast;
69 using std::lock_guard;
73 using std::recursive_mutex;
75 using std::shared_ptr;
77 using std::unordered_set;
81 using sigrok::Channel;
82 using sigrok::ChannelType;
83 using sigrok::ConfigKey;
84 using sigrok::DatafeedCallbackFunction;
90 using sigrok::PacketPayload;
91 using sigrok::Session;
92 using sigrok::SessionDevice;
94 using Glib::VariantBase;
98 Session::Session(DeviceManager &device_manager, QString name) :
99 device_manager_(device_manager),
101 capture_state_(Stopped),
108 // Stop and join to the thread
112 DeviceManager& Session::device_manager()
114 return device_manager_;
117 const DeviceManager& Session::device_manager() const
119 return device_manager_;
122 shared_ptr<sigrok::Session> Session::session() const
125 return shared_ptr<sigrok::Session>();
126 return device_->session();
129 shared_ptr<devices::Device> Session::device() const
134 QString Session::name() const
139 void Session::set_name(QString name)
141 if (default_name_.isEmpty())
142 default_name_ = name;
149 std::shared_ptr<pv::view::View> Session::main_view() const
154 void Session::set_main_bar(std::shared_ptr<pv::toolbars::MainBar> main_bar)
156 main_bar_ = main_bar;
159 shared_ptr<pv::toolbars::MainBar> Session::main_bar() const
164 void Session::save_settings(QSettings &settings) const
166 map<string, string> dev_info;
167 list<string> key_list;
171 settings.beginGroup("Device");
172 key_list.push_back("vendor");
173 key_list.push_back("model");
174 key_list.push_back("version");
175 key_list.push_back("serial_num");
176 key_list.push_back("connection_id");
178 dev_info = device_manager_.get_device_info(device_);
180 for (string key : key_list) {
181 if (dev_info.count(key))
182 settings.setValue(QString::fromUtf8(key.c_str()),
183 QString::fromUtf8(dev_info.at(key).c_str()));
185 settings.remove(QString::fromUtf8(key.c_str()));
188 // Save channels and decoders
189 for (shared_ptr<data::SignalBase> base : signalbases_) {
191 if (base->is_decode_signal()) {
192 shared_ptr<pv::data::DecoderStack> decoder_stack =
193 base->decoder_stack();
194 std::shared_ptr<data::decode::Decoder> top_decoder =
195 decoder_stack->stack().front();
197 settings.beginGroup("decoder_stack" + QString::number(stacks++));
198 settings.setValue("id", top_decoder->decoder()->id);
199 settings.setValue("name", top_decoder->decoder()->name);
204 settings.beginGroup(base->internal_name());
205 base->save_settings(settings);
210 settings.setValue("decoder_stacks", stacks);
215 void Session::restore_settings(QSettings &settings)
217 map<string, string> dev_info;
218 list<string> key_list;
219 shared_ptr<devices::HardwareDevice> device;
221 // Re-select last used device if possible but only if it's not demo
222 settings.beginGroup("Device");
223 key_list.push_back("vendor");
224 key_list.push_back("model");
225 key_list.push_back("version");
226 key_list.push_back("serial_num");
227 key_list.push_back("connection_id");
229 for (string key : key_list) {
230 const QString k = QString::fromStdString(key);
231 if (!settings.contains(k))
234 const string value = settings.value(k).toString().toStdString();
236 dev_info.insert(std::make_pair(key, value));
239 if (dev_info.count("model") > 0)
240 device = device_manager_.find_device_from_info(dev_info);
246 for (shared_ptr<data::SignalBase> base : signalbases_) {
247 settings.beginGroup(base->internal_name());
248 base->restore_settings(settings);
254 int stacks = settings.value("decoder_stacks").toInt();
256 for (int i = 0; i < stacks; i++) {
257 settings.beginGroup("decoder_stack" + QString::number(i++));
259 QString id = settings.value("id").toString();
260 add_decoder(srd_decoder_get_by_id(id.toStdString().c_str()));
270 void Session::set_device(shared_ptr<devices::Device> device)
274 // Ensure we are not capturing before setting the device
282 // Revert name back to default name (e.g. "Untitled-1") as the data is gone
283 name_ = default_name_;
286 // Remove all stored data
287 for (std::shared_ptr<pv::view::View> view : views_) {
288 view->clear_signals();
290 view->clear_decode_traces();
293 for (const shared_ptr<data::SignalData> d : all_signal_data_)
295 all_signal_data_.clear();
296 signalbases_.clear();
297 cur_logic_segment_.reset();
299 for (auto entry : cur_analog_segments_) {
300 shared_ptr<sigrok::Channel>(entry.first).reset();
301 shared_ptr<data::AnalogSegment>(entry.second).reset();
308 device_ = std::move(device);
312 } catch (const QString &e) {
318 device_->session()->add_datafeed_callback([=]
319 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
320 data_feed_in(device, packet);
327 void Session::set_default_device()
329 const list< shared_ptr<devices::HardwareDevice> > &devices =
330 device_manager_.devices();
335 // Try and find the demo device and select that by default
336 const auto iter = std::find_if(devices.begin(), devices.end(),
337 [] (const shared_ptr<devices::HardwareDevice> &d) {
338 return d->hardware_device()->driver()->name() ==
340 set_device((iter == devices.end()) ? devices.front() : *iter);
343 Session::capture_state Session::get_capture_state() const
345 lock_guard<mutex> lock(sampling_mutex_);
346 return capture_state_;
349 void Session::start_capture(function<void (const QString)> error_handler)
352 error_handler(tr("No active device set, can't start acquisition."));
358 // Check that at least one channel is enabled
359 const shared_ptr<sigrok::Device> sr_dev = device_->device();
361 const auto channels = sr_dev->channels();
362 if (!std::any_of(channels.begin(), channels.end(),
363 [](shared_ptr<Channel> channel) {
364 return channel->enabled(); })) {
365 error_handler(tr("No channels enabled."));
371 for (const shared_ptr<data::SignalData> d : all_signal_data_)
374 // Revert name back to default name (e.g. "Untitled-1") as the data is gone
375 name_ = default_name_;
379 sampling_thread_ = std::thread(
380 &Session::sample_thread_proc, this, error_handler);
383 void Session::stop_capture()
385 if (get_capture_state() != Stopped)
388 // Check that sampling stopped
389 if (sampling_thread_.joinable())
390 sampling_thread_.join();
393 void Session::register_view(std::shared_ptr<pv::view::View> view)
395 if (views_.empty()) {
402 void Session::deregister_view(std::shared_ptr<pv::view::View> view)
406 if (views_.empty()) {
409 // Without a view there can be no main bar
414 bool Session::has_view(std::shared_ptr<pv::view::View> view)
416 return views_.find(view) != views_.end();
419 double Session::get_samplerate() const
421 double samplerate = 0.0;
423 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
425 const vector< shared_ptr<pv::data::Segment> > segments =
427 for (const shared_ptr<pv::data::Segment> &s : segments)
428 samplerate = std::max(samplerate, s->samplerate());
430 // If there is no sample rate given we use samples as unit
431 if (samplerate == 0.0)
437 const std::unordered_set< std::shared_ptr<data::SignalBase> >
438 Session::signalbases() const
444 bool Session::add_decoder(srd_decoder *const dec)
446 map<const srd_channel*, shared_ptr<data::SignalBase> > channels;
447 shared_ptr<data::DecoderStack> decoder_stack;
450 // Create the decoder
451 decoder_stack = shared_ptr<data::DecoderStack>(
452 new data::DecoderStack(*this, dec));
454 // Make a list of all the channels
455 std::vector<const srd_channel*> all_channels;
456 for (const GSList *i = dec->channels; i; i = i->next)
457 all_channels.push_back((const srd_channel*)i->data);
458 for (const GSList *i = dec->opt_channels; i; i = i->next)
459 all_channels.push_back((const srd_channel*)i->data);
461 // Auto select the initial channels
462 for (const srd_channel *pdch : all_channels)
463 for (shared_ptr<data::SignalBase> b : signalbases_) {
464 if (b->type() == ChannelType::LOGIC) {
465 if (QString::fromUtf8(pdch->name).toLower().
466 contains(b->name().toLower()))
471 assert(decoder_stack);
472 assert(!decoder_stack->stack().empty());
473 assert(decoder_stack->stack().front());
474 decoder_stack->stack().front()->set_channels(channels);
476 // Create the decode signal
477 shared_ptr<data::SignalBase> signalbase =
478 shared_ptr<data::SignalBase>(new data::SignalBase(nullptr));
480 signalbase->set_decoder_stack(decoder_stack);
481 signalbases_.insert(signalbase);
483 for (std::shared_ptr<pv::view::View> view : views_)
484 view->add_decode_trace(signalbase);
485 } catch (std::runtime_error e) {
491 // Do an initial decode
492 decoder_stack->begin_decode();
497 void Session::remove_decode_signal(shared_ptr<data::SignalBase> signalbase)
499 for (std::shared_ptr<pv::view::View> view : views_)
500 view->remove_decode_trace(signalbase);
504 void Session::set_capture_state(capture_state state)
509 lock_guard<mutex> lock(sampling_mutex_);
510 changed = capture_state_ != state;
511 capture_state_ = state;
515 capture_state_changed(state);
518 void Session::update_signals()
521 signalbases_.clear();
523 for (std::shared_ptr<pv::view::View> view : views_) {
524 view->clear_signals();
526 view->clear_decode_traces();
532 lock_guard<recursive_mutex> lock(data_mutex_);
534 const shared_ptr<sigrok::Device> sr_dev = device_->device();
536 signalbases_.clear();
538 for (std::shared_ptr<pv::view::View> view : views_) {
539 view->clear_signals();
541 view->clear_decode_traces();
547 // Detect what data types we will receive
548 auto channels = sr_dev->channels();
549 unsigned int logic_channel_count = std::count_if(
550 channels.begin(), channels.end(),
551 [] (shared_ptr<Channel> channel) {
552 return channel->type() == ChannelType::LOGIC; });
554 // Create data containers for the logic data segments
556 lock_guard<recursive_mutex> data_lock(data_mutex_);
558 if (logic_channel_count == 0) {
560 } else if (!logic_data_ ||
561 logic_data_->num_channels() != logic_channel_count) {
562 logic_data_.reset(new data::Logic(
563 logic_channel_count));
568 // Make the signals list
569 for (std::shared_ptr<pv::view::View> view : views_) {
570 unordered_set< shared_ptr<view::Signal> > prev_sigs(view->signals());
571 view->clear_signals();
573 for (auto channel : sr_dev->channels()) {
574 shared_ptr<data::SignalBase> signalbase;
575 shared_ptr<view::Signal> signal;
577 // Find the channel in the old signals
578 const auto iter = std::find_if(
579 prev_sigs.cbegin(), prev_sigs.cend(),
580 [&](const shared_ptr<view::Signal> &s) {
581 return s->base()->channel() == channel;
583 if (iter != prev_sigs.end()) {
584 // Copy the signal from the old set to the new
587 // Find the signalbase for this channel if possible
589 for (const shared_ptr<data::SignalBase> b : signalbases_)
590 if (b->channel() == channel)
593 switch(channel->type()->id()) {
594 case SR_CHANNEL_LOGIC:
596 signalbase = shared_ptr<data::SignalBase>(
597 new data::SignalBase(channel));
598 signalbases_.insert(signalbase);
600 all_signal_data_.insert(logic_data_);
601 signalbase->set_data(logic_data_);
604 signal = shared_ptr<view::Signal>(
605 new view::LogicSignal(*this,
606 device_, signalbase));
607 view->add_signal(signal);
610 case SR_CHANNEL_ANALOG:
613 signalbase = shared_ptr<data::SignalBase>(
614 new data::SignalBase(channel));
615 signalbases_.insert(signalbase);
617 shared_ptr<data::Analog> data(new data::Analog());
618 all_signal_data_.insert(data);
619 signalbase->set_data(data);
622 signal = shared_ptr<view::Signal>(
623 new view::AnalogSignal(
625 view->add_signal(signal);
640 shared_ptr<data::SignalBase> Session::signalbase_from_channel(
641 shared_ptr<sigrok::Channel> channel) const
643 for (shared_ptr<data::SignalBase> sig : signalbases_) {
645 if (sig->channel() == channel)
648 return shared_ptr<data::SignalBase>();
651 void Session::sample_thread_proc(function<void (const QString)> error_handler)
653 assert(error_handler);
658 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
660 out_of_memory_ = false;
665 error_handler(e.what());
669 set_capture_state(device_->session()->trigger() ?
670 AwaitingTrigger : Running);
673 set_capture_state(Stopped);
675 // Confirm that SR_DF_END was received
676 if (cur_logic_segment_) {
677 qDebug("SR_DF_END was not received.");
682 error_handler(tr("Out of memory, acquisition stopped."));
685 void Session::feed_in_header()
687 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
690 void Session::feed_in_meta(shared_ptr<Meta> meta)
692 for (auto entry : meta->config()) {
693 switch (entry.first->id()) {
694 case SR_CONF_SAMPLERATE:
695 // We can't rely on the header to always contain the sample rate,
696 // so in case it's supplied via a meta packet, we use it.
697 if (!cur_samplerate_)
698 cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
700 /// @todo handle samplerate changes
703 // Unknown metadata is not an error.
711 void Session::feed_in_trigger()
713 // The channel containing most samples should be most accurate
714 uint64_t sample_count = 0;
717 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
719 uint64_t temp_count = 0;
721 const vector< shared_ptr<pv::data::Segment> > segments =
723 for (const shared_ptr<pv::data::Segment> &s : segments)
724 temp_count += s->get_sample_count();
726 if (temp_count > sample_count)
727 sample_count = temp_count;
731 trigger_event(sample_count / get_samplerate());
734 void Session::feed_in_frame_begin()
736 if (cur_logic_segment_ || !cur_analog_segments_.empty())
740 void Session::feed_in_logic(shared_ptr<Logic> logic)
742 lock_guard<recursive_mutex> lock(data_mutex_);
744 const size_t sample_count = logic->data_length() / logic->unit_size();
747 // The only reason logic_data_ would not have been created is
748 // if it was not possible to determine the signals when the
749 // device was created.
753 if (!cur_logic_segment_) {
754 // This could be the first packet after a trigger
755 set_capture_state(Running);
757 // Create a new data segment
758 cur_logic_segment_ = shared_ptr<data::LogicSegment>(
759 new data::LogicSegment(
760 logic, cur_samplerate_, sample_count));
761 logic_data_->push_segment(cur_logic_segment_);
763 // @todo Putting this here means that only listeners querying
764 // for logic will be notified. Currently the only user of
765 // frame_began is DecoderStack, but in future we need to signal
766 // this after both analog and logic sweeps have begun.
769 // Append to the existing data segment
770 cur_logic_segment_->append_payload(logic);
776 void Session::feed_in_analog(shared_ptr<Analog> analog)
778 lock_guard<recursive_mutex> lock(data_mutex_);
780 const vector<shared_ptr<Channel>> channels = analog->channels();
781 const unsigned int channel_count = channels.size();
782 const size_t sample_count = analog->num_samples() / channel_count;
783 const float *data = static_cast<const float *>(analog->data_pointer());
784 bool sweep_beginning = false;
786 if (signalbases_.empty())
789 for (auto channel : channels) {
790 shared_ptr<data::AnalogSegment> segment;
792 // Try to get the segment of the channel
793 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
794 iterator iter = cur_analog_segments_.find(channel);
795 if (iter != cur_analog_segments_.end())
796 segment = (*iter).second;
798 // If no segment was found, this means we haven't
799 // created one yet. i.e. this is the first packet
800 // in the sweep containing this segment.
801 sweep_beginning = true;
803 // Create a segment, keep it in the maps of channels
804 segment = shared_ptr<data::AnalogSegment>(
805 new data::AnalogSegment(
806 cur_samplerate_, sample_count));
807 cur_analog_segments_[channel] = segment;
809 // Find the analog data associated with the channel
810 shared_ptr<data::SignalBase> base = signalbase_from_channel(channel);
813 shared_ptr<data::Analog> data(base->analog_data());
816 // Push the segment into the analog data.
817 data->push_segment(segment);
822 // Append the samples in the segment
823 segment->append_interleaved_samples(data++, sample_count,
827 if (sweep_beginning) {
828 // This could be the first packet after a trigger
829 set_capture_state(Running);
835 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
836 shared_ptr<Packet> packet)
841 assert(device == device_->device());
844 switch (packet->type()->id()) {
850 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
857 case SR_DF_FRAME_BEGIN:
858 feed_in_frame_begin();
863 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
864 } catch (std::bad_alloc) {
865 out_of_memory_ = true;
872 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
873 } catch (std::bad_alloc) {
874 out_of_memory_ = true;
882 lock_guard<recursive_mutex> lock(data_mutex_);
883 cur_logic_segment_.reset();
884 cur_analog_segments_.clear();