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 settings.setValue("name", base->name());
206 settings.setValue("enabled", base->enabled());
207 settings.setValue("colour", base->colour());
212 settings.setValue("decoder_stacks", stacks);
217 void Session::restore_settings(QSettings &settings)
219 map<string, string> dev_info;
220 list<string> key_list;
221 shared_ptr<devices::HardwareDevice> device;
223 // Re-select last used device if possible but only if it's not demo
224 settings.beginGroup("Device");
225 key_list.push_back("vendor");
226 key_list.push_back("model");
227 key_list.push_back("version");
228 key_list.push_back("serial_num");
229 key_list.push_back("connection_id");
231 for (string key : key_list) {
232 const QString k = QString::fromStdString(key);
233 if (!settings.contains(k))
236 const string value = settings.value(k).toString().toStdString();
238 dev_info.insert(std::make_pair(key, value));
241 if (dev_info.count("model") > 0)
242 device = device_manager_.find_device_from_info(dev_info);
248 for (shared_ptr<data::SignalBase> base : signalbases_) {
249 settings.beginGroup(base->internal_name());
250 base->set_name(settings.value("name").toString());
251 base->set_enabled(settings.value("enabled").toBool());
252 base->set_colour(settings.value("colour").value<QColor>());
258 int stacks = settings.value("decoder_stacks").toInt();
260 for (int i = 0; i < stacks; i++) {
261 settings.beginGroup("decoder_stack" + QString::number(i++));
263 QString id = settings.value("id").toString();
264 add_decoder(srd_decoder_get_by_id(id.toStdString().c_str()));
274 void Session::set_device(shared_ptr<devices::Device> device)
278 // Ensure we are not capturing before setting the device
286 // Revert name back to default name (e.g. "Untitled-1") as the data is gone
287 name_ = default_name_;
290 // Remove all stored data
291 for (std::shared_ptr<pv::view::View> view : views_) {
292 view->clear_signals();
294 view->clear_decode_traces();
297 for (const shared_ptr<data::SignalData> d : all_signal_data_)
299 all_signal_data_.clear();
300 signalbases_.clear();
301 cur_logic_segment_.reset();
303 for (auto entry : cur_analog_segments_) {
304 shared_ptr<sigrok::Channel>(entry.first).reset();
305 shared_ptr<data::AnalogSegment>(entry.second).reset();
312 device_ = std::move(device);
316 } catch (const QString &e) {
322 device_->session()->add_datafeed_callback([=]
323 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
324 data_feed_in(device, packet);
331 void Session::set_default_device()
333 const list< shared_ptr<devices::HardwareDevice> > &devices =
334 device_manager_.devices();
339 // Try and find the demo device and select that by default
340 const auto iter = std::find_if(devices.begin(), devices.end(),
341 [] (const shared_ptr<devices::HardwareDevice> &d) {
342 return d->hardware_device()->driver()->name() ==
344 set_device((iter == devices.end()) ? devices.front() : *iter);
347 Session::capture_state Session::get_capture_state() const
349 lock_guard<mutex> lock(sampling_mutex_);
350 return capture_state_;
353 void Session::start_capture(function<void (const QString)> error_handler)
356 error_handler(tr("No active device set, can't start acquisition."));
362 // Check that at least one channel is enabled
363 const shared_ptr<sigrok::Device> sr_dev = device_->device();
365 const auto channels = sr_dev->channels();
366 if (!std::any_of(channels.begin(), channels.end(),
367 [](shared_ptr<Channel> channel) {
368 return channel->enabled(); })) {
369 error_handler(tr("No channels enabled."));
375 for (const shared_ptr<data::SignalData> d : all_signal_data_)
378 // Revert name back to default name (e.g. "Untitled-1") as the data is gone
379 name_ = default_name_;
383 sampling_thread_ = std::thread(
384 &Session::sample_thread_proc, this, error_handler);
387 void Session::stop_capture()
389 if (get_capture_state() != Stopped)
392 // Check that sampling stopped
393 if (sampling_thread_.joinable())
394 sampling_thread_.join();
397 void Session::register_view(std::shared_ptr<pv::view::View> view)
399 if (views_.empty()) {
406 void Session::deregister_view(std::shared_ptr<pv::view::View> view)
410 if (views_.empty()) {
413 // Without a view there can be no main bar
418 bool Session::has_view(std::shared_ptr<pv::view::View> view)
420 return views_.find(view) != views_.end();
423 double Session::get_samplerate() const
425 double samplerate = 0.0;
427 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
429 const vector< shared_ptr<pv::data::Segment> > segments =
431 for (const shared_ptr<pv::data::Segment> &s : segments)
432 samplerate = std::max(samplerate, s->samplerate());
434 // If there is no sample rate given we use samples as unit
435 if (samplerate == 0.0)
441 const std::unordered_set< std::shared_ptr<data::SignalBase> >
442 Session::signalbases() const
448 bool Session::add_decoder(srd_decoder *const dec)
450 map<const srd_channel*, shared_ptr<data::SignalBase> > channels;
451 shared_ptr<data::DecoderStack> decoder_stack;
454 // Create the decoder
455 decoder_stack = shared_ptr<data::DecoderStack>(
456 new data::DecoderStack(*this, dec));
458 // Make a list of all the channels
459 std::vector<const srd_channel*> all_channels;
460 for (const GSList *i = dec->channels; i; i = i->next)
461 all_channels.push_back((const srd_channel*)i->data);
462 for (const GSList *i = dec->opt_channels; i; i = i->next)
463 all_channels.push_back((const srd_channel*)i->data);
465 // Auto select the initial channels
466 for (const srd_channel *pdch : all_channels)
467 for (shared_ptr<data::SignalBase> b : signalbases_) {
468 if (b->type() == ChannelType::LOGIC) {
469 if (QString::fromUtf8(pdch->name).toLower().
470 contains(b->name().toLower()))
475 assert(decoder_stack);
476 assert(!decoder_stack->stack().empty());
477 assert(decoder_stack->stack().front());
478 decoder_stack->stack().front()->set_channels(channels);
480 // Create the decode signal
481 shared_ptr<data::SignalBase> signalbase =
482 shared_ptr<data::SignalBase>(new data::SignalBase(nullptr));
484 signalbase->set_decoder_stack(decoder_stack);
485 signalbases_.insert(signalbase);
487 for (std::shared_ptr<pv::view::View> view : views_)
488 view->add_decode_trace(signalbase);
489 } catch (std::runtime_error e) {
495 // Do an initial decode
496 decoder_stack->begin_decode();
501 void Session::remove_decode_signal(shared_ptr<data::SignalBase> signalbase)
503 for (std::shared_ptr<pv::view::View> view : views_)
504 view->remove_decode_trace(signalbase);
508 void Session::set_capture_state(capture_state state)
513 lock_guard<mutex> lock(sampling_mutex_);
514 changed = capture_state_ != state;
515 capture_state_ = state;
519 capture_state_changed(state);
522 void Session::update_signals()
525 signalbases_.clear();
527 for (std::shared_ptr<pv::view::View> view : views_) {
528 view->clear_signals();
530 view->clear_decode_traces();
536 lock_guard<recursive_mutex> lock(data_mutex_);
538 const shared_ptr<sigrok::Device> sr_dev = device_->device();
540 signalbases_.clear();
542 for (std::shared_ptr<pv::view::View> view : views_) {
543 view->clear_signals();
545 view->clear_decode_traces();
551 // Detect what data types we will receive
552 auto channels = sr_dev->channels();
553 unsigned int logic_channel_count = std::count_if(
554 channels.begin(), channels.end(),
555 [] (shared_ptr<Channel> channel) {
556 return channel->type() == ChannelType::LOGIC; });
558 // Create data containers for the logic data segments
560 lock_guard<recursive_mutex> data_lock(data_mutex_);
562 if (logic_channel_count == 0) {
564 } else if (!logic_data_ ||
565 logic_data_->num_channels() != logic_channel_count) {
566 logic_data_.reset(new data::Logic(
567 logic_channel_count));
572 // Make the signals list
573 for (std::shared_ptr<pv::view::View> view : views_) {
574 unordered_set< shared_ptr<view::Signal> > prev_sigs(view->signals());
575 view->clear_signals();
577 for (auto channel : sr_dev->channels()) {
578 shared_ptr<data::SignalBase> signalbase;
579 shared_ptr<view::Signal> signal;
581 // Find the channel in the old signals
582 const auto iter = std::find_if(
583 prev_sigs.cbegin(), prev_sigs.cend(),
584 [&](const shared_ptr<view::Signal> &s) {
585 return s->base()->channel() == channel;
587 if (iter != prev_sigs.end()) {
588 // Copy the signal from the old set to the new
591 // Find the signalbase for this channel if possible
593 for (const shared_ptr<data::SignalBase> b : signalbases_)
594 if (b->channel() == channel)
597 switch(channel->type()->id()) {
598 case SR_CHANNEL_LOGIC:
600 signalbase = shared_ptr<data::SignalBase>(
601 new data::SignalBase(channel));
602 signalbases_.insert(signalbase);
604 all_signal_data_.insert(logic_data_);
605 signalbase->set_data(logic_data_);
608 signal = shared_ptr<view::Signal>(
609 new view::LogicSignal(*this,
610 device_, signalbase));
611 view->add_signal(signal);
614 case SR_CHANNEL_ANALOG:
617 signalbase = shared_ptr<data::SignalBase>(
618 new data::SignalBase(channel));
619 signalbases_.insert(signalbase);
621 shared_ptr<data::Analog> data(new data::Analog());
622 all_signal_data_.insert(data);
623 signalbase->set_data(data);
626 signal = shared_ptr<view::Signal>(
627 new view::AnalogSignal(
629 view->add_signal(signal);
644 shared_ptr<data::SignalBase> Session::signalbase_from_channel(
645 shared_ptr<sigrok::Channel> channel) const
647 for (shared_ptr<data::SignalBase> sig : signalbases_) {
649 if (sig->channel() == channel)
652 return shared_ptr<data::SignalBase>();
655 void Session::sample_thread_proc(function<void (const QString)> error_handler)
657 assert(error_handler);
662 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
664 out_of_memory_ = false;
669 error_handler(e.what());
673 set_capture_state(device_->session()->trigger() ?
674 AwaitingTrigger : Running);
677 set_capture_state(Stopped);
679 // Confirm that SR_DF_END was received
680 if (cur_logic_segment_) {
681 qDebug("SR_DF_END was not received.");
686 error_handler(tr("Out of memory, acquisition stopped."));
689 void Session::feed_in_header()
691 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
694 void Session::feed_in_meta(shared_ptr<Meta> meta)
696 for (auto entry : meta->config()) {
697 switch (entry.first->id()) {
698 case SR_CONF_SAMPLERATE:
699 // We can't rely on the header to always contain the sample rate,
700 // so in case it's supplied via a meta packet, we use it.
701 if (!cur_samplerate_)
702 cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
704 /// @todo handle samplerate changes
707 // Unknown metadata is not an error.
715 void Session::feed_in_trigger()
717 // The channel containing most samples should be most accurate
718 uint64_t sample_count = 0;
721 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
723 uint64_t temp_count = 0;
725 const vector< shared_ptr<pv::data::Segment> > segments =
727 for (const shared_ptr<pv::data::Segment> &s : segments)
728 temp_count += s->get_sample_count();
730 if (temp_count > sample_count)
731 sample_count = temp_count;
735 trigger_event(sample_count / get_samplerate());
738 void Session::feed_in_frame_begin()
740 if (cur_logic_segment_ || !cur_analog_segments_.empty())
744 void Session::feed_in_logic(shared_ptr<Logic> logic)
746 lock_guard<recursive_mutex> lock(data_mutex_);
748 const size_t sample_count = logic->data_length() / logic->unit_size();
751 // The only reason logic_data_ would not have been created is
752 // if it was not possible to determine the signals when the
753 // device was created.
757 if (!cur_logic_segment_) {
758 // This could be the first packet after a trigger
759 set_capture_state(Running);
761 // Create a new data segment
762 cur_logic_segment_ = shared_ptr<data::LogicSegment>(
763 new data::LogicSegment(
764 logic, cur_samplerate_, sample_count));
765 logic_data_->push_segment(cur_logic_segment_);
767 // @todo Putting this here means that only listeners querying
768 // for logic will be notified. Currently the only user of
769 // frame_began is DecoderStack, but in future we need to signal
770 // this after both analog and logic sweeps have begun.
773 // Append to the existing data segment
774 cur_logic_segment_->append_payload(logic);
780 void Session::feed_in_analog(shared_ptr<Analog> analog)
782 lock_guard<recursive_mutex> lock(data_mutex_);
784 const vector<shared_ptr<Channel>> channels = analog->channels();
785 const unsigned int channel_count = channels.size();
786 const size_t sample_count = analog->num_samples() / channel_count;
787 const float *data = static_cast<const float *>(analog->data_pointer());
788 bool sweep_beginning = false;
790 if (signalbases_.empty())
793 for (auto channel : channels) {
794 shared_ptr<data::AnalogSegment> segment;
796 // Try to get the segment of the channel
797 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
798 iterator iter = cur_analog_segments_.find(channel);
799 if (iter != cur_analog_segments_.end())
800 segment = (*iter).second;
802 // If no segment was found, this means we haven't
803 // created one yet. i.e. this is the first packet
804 // in the sweep containing this segment.
805 sweep_beginning = true;
807 // Create a segment, keep it in the maps of channels
808 segment = shared_ptr<data::AnalogSegment>(
809 new data::AnalogSegment(
810 cur_samplerate_, sample_count));
811 cur_analog_segments_[channel] = segment;
813 // Find the analog data associated with the channel
814 shared_ptr<data::SignalBase> base = signalbase_from_channel(channel);
817 shared_ptr<data::Analog> data(base->analog_data());
820 // Push the segment into the analog data.
821 data->push_segment(segment);
826 // Append the samples in the segment
827 segment->append_interleaved_samples(data++, sample_count,
831 if (sweep_beginning) {
832 // This could be the first packet after a trigger
833 set_capture_state(Running);
839 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
840 shared_ptr<Packet> packet)
845 assert(device == device_->device());
848 switch (packet->type()->id()) {
854 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
861 case SR_DF_FRAME_BEGIN:
862 feed_in_frame_begin();
867 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
868 } catch (std::bad_alloc) {
869 out_of_memory_ = true;
876 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
877 } catch (std::bad_alloc) {
878 out_of_memory_ = true;
886 lock_guard<recursive_mutex> lock(data_mutex_);
887 cur_logic_segment_.reset();
888 cur_analog_segments_.clear();