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;
170 settings.beginGroup("Device");
171 key_list.push_back("vendor");
172 key_list.push_back("model");
173 key_list.push_back("version");
174 key_list.push_back("serial_num");
175 key_list.push_back("connection_id");
177 dev_info = device_manager_.get_device_info(device_);
179 for (string key : key_list) {
180 if (dev_info.count(key))
181 settings.setValue(QString::fromUtf8(key.c_str()),
182 QString::fromUtf8(dev_info.at(key).c_str()));
184 settings.remove(QString::fromUtf8(key.c_str()));
187 // TODO Save channel settings and decoders
193 void Session::restore_settings(QSettings &settings)
195 map<string, string> dev_info;
196 list<string> key_list;
197 shared_ptr<devices::HardwareDevice> device;
199 // Re-select last used device if possible but only if it's not demo
200 settings.beginGroup("Device");
201 key_list.push_back("vendor");
202 key_list.push_back("model");
203 key_list.push_back("version");
204 key_list.push_back("serial_num");
205 key_list.push_back("connection_id");
207 for (string key : key_list) {
208 const QString k = QString::fromStdString(key);
209 if (!settings.contains(k))
212 const string value = settings.value(k).toString().toStdString();
214 dev_info.insert(std::make_pair(key, value));
217 if (dev_info.count("model") > 0)
218 device = device_manager_.find_device_from_info(dev_info);
223 // TODO Restore channel settings and decoders
229 void Session::set_device(shared_ptr<devices::Device> device)
233 // Ensure we are not capturing before setting the device
241 // Revert name back to default name (e.g. "Untitled-1") as the data is gone
242 name_ = default_name_;
245 // Remove all stored data
246 for (std::shared_ptr<pv::view::View> view : views_) {
247 view->clear_signals();
249 view->clear_decode_traces();
252 for (const shared_ptr<data::SignalData> d : all_signal_data_)
254 all_signal_data_.clear();
255 signalbases_.clear();
256 cur_logic_segment_.reset();
258 for (auto entry : cur_analog_segments_) {
259 shared_ptr<sigrok::Channel>(entry.first).reset();
260 shared_ptr<data::AnalogSegment>(entry.second).reset();
267 device_ = std::move(device);
271 } catch (const QString &e) {
277 device_->session()->add_datafeed_callback([=]
278 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
279 data_feed_in(device, packet);
286 void Session::set_default_device()
288 const list< shared_ptr<devices::HardwareDevice> > &devices =
289 device_manager_.devices();
294 // Try and find the demo device and select that by default
295 const auto iter = std::find_if(devices.begin(), devices.end(),
296 [] (const shared_ptr<devices::HardwareDevice> &d) {
297 return d->hardware_device()->driver()->name() ==
299 set_device((iter == devices.end()) ? devices.front() : *iter);
302 Session::capture_state Session::get_capture_state() const
304 lock_guard<mutex> lock(sampling_mutex_);
305 return capture_state_;
308 void Session::start_capture(function<void (const QString)> error_handler)
311 error_handler(tr("No active device set, can't start acquisition."));
317 // Check that at least one channel is enabled
318 const shared_ptr<sigrok::Device> sr_dev = device_->device();
320 const auto channels = sr_dev->channels();
321 if (!std::any_of(channels.begin(), channels.end(),
322 [](shared_ptr<Channel> channel) {
323 return channel->enabled(); })) {
324 error_handler(tr("No channels enabled."));
330 for (const shared_ptr<data::SignalData> d : all_signal_data_)
333 // Revert name back to default name (e.g. "Untitled-1") as the data is gone
334 name_ = default_name_;
338 sampling_thread_ = std::thread(
339 &Session::sample_thread_proc, this, error_handler);
342 void Session::stop_capture()
344 if (get_capture_state() != Stopped)
347 // Check that sampling stopped
348 if (sampling_thread_.joinable())
349 sampling_thread_.join();
352 void Session::register_view(std::shared_ptr<pv::view::View> view)
354 if (views_.empty()) {
361 void Session::deregister_view(std::shared_ptr<pv::view::View> view)
365 if (views_.empty()) {
368 // Without a view there can be no main bar
373 bool Session::has_view(std::shared_ptr<pv::view::View> view)
375 return views_.find(view) != views_.end();
378 double Session::get_samplerate() const
380 double samplerate = 0.0;
382 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
384 const vector< shared_ptr<pv::data::Segment> > segments =
386 for (const shared_ptr<pv::data::Segment> &s : segments)
387 samplerate = std::max(samplerate, s->samplerate());
389 // If there is no sample rate given we use samples as unit
390 if (samplerate == 0.0)
396 const std::unordered_set< std::shared_ptr<data::SignalBase> >
397 Session::signalbases() const
403 bool Session::add_decoder(srd_decoder *const dec)
405 map<const srd_channel*, shared_ptr<data::SignalBase> > channels;
406 shared_ptr<data::DecoderStack> decoder_stack;
409 // Create the decoder
410 decoder_stack = shared_ptr<data::DecoderStack>(
411 new data::DecoderStack(*this, dec));
413 // Make a list of all the channels
414 std::vector<const srd_channel*> all_channels;
415 for (const GSList *i = dec->channels; i; i = i->next)
416 all_channels.push_back((const srd_channel*)i->data);
417 for (const GSList *i = dec->opt_channels; i; i = i->next)
418 all_channels.push_back((const srd_channel*)i->data);
420 // Auto select the initial channels
421 for (const srd_channel *pdch : all_channels)
422 for (shared_ptr<data::SignalBase> b : signalbases_) {
423 if (b->type() == ChannelType::LOGIC) {
424 if (QString::fromUtf8(pdch->name).toLower().
425 contains(b->name().toLower()))
430 assert(decoder_stack);
431 assert(!decoder_stack->stack().empty());
432 assert(decoder_stack->stack().front());
433 decoder_stack->stack().front()->set_channels(channels);
435 // Create the decode signal
436 shared_ptr<data::SignalBase> signalbase =
437 shared_ptr<data::SignalBase>(new data::SignalBase(nullptr));
439 signalbase->set_decoder_stack(decoder_stack);
441 for (std::shared_ptr<pv::view::View> view : views_)
442 view->add_decode_trace(signalbase);
443 } catch (std::runtime_error e) {
449 // Do an initial decode
450 decoder_stack->begin_decode();
455 void Session::remove_decode_signal(shared_ptr<data::SignalBase> signalbase)
457 for (std::shared_ptr<pv::view::View> view : views_)
458 view->remove_decode_trace(signalbase);
462 void Session::set_capture_state(capture_state state)
467 lock_guard<mutex> lock(sampling_mutex_);
468 changed = capture_state_ != state;
469 capture_state_ = state;
473 capture_state_changed(state);
476 void Session::update_signals()
479 signalbases_.clear();
481 for (std::shared_ptr<pv::view::View> view : views_) {
482 view->clear_signals();
484 view->clear_decode_traces();
490 lock_guard<recursive_mutex> lock(data_mutex_);
492 const shared_ptr<sigrok::Device> sr_dev = device_->device();
494 signalbases_.clear();
496 for (std::shared_ptr<pv::view::View> view : views_) {
497 view->clear_signals();
499 view->clear_decode_traces();
505 // Detect what data types we will receive
506 auto channels = sr_dev->channels();
507 unsigned int logic_channel_count = std::count_if(
508 channels.begin(), channels.end(),
509 [] (shared_ptr<Channel> channel) {
510 return channel->type() == ChannelType::LOGIC; });
512 // Create data containers for the logic data segments
514 lock_guard<recursive_mutex> data_lock(data_mutex_);
516 if (logic_channel_count == 0) {
518 } else if (!logic_data_ ||
519 logic_data_->num_channels() != logic_channel_count) {
520 logic_data_.reset(new data::Logic(
521 logic_channel_count));
526 // Make the signals list
527 for (std::shared_ptr<pv::view::View> view : views_) {
528 unordered_set< shared_ptr<view::Signal> > prev_sigs(view->signals());
529 view->clear_signals();
531 for (auto channel : sr_dev->channels()) {
532 shared_ptr<data::SignalBase> signalbase;
533 shared_ptr<view::Signal> signal;
535 // Find the channel in the old signals
536 const auto iter = std::find_if(
537 prev_sigs.cbegin(), prev_sigs.cend(),
538 [&](const shared_ptr<view::Signal> &s) {
539 return s->base()->channel() == channel;
541 if (iter != prev_sigs.end()) {
542 // Copy the signal from the old set to the new
545 // Find the signalbase for this channel if possible
547 for (const shared_ptr<data::SignalBase> b : signalbases_)
548 if (b->channel() == channel)
551 switch(channel->type()->id()) {
552 case SR_CHANNEL_LOGIC:
554 signalbase = shared_ptr<data::SignalBase>(
555 new data::SignalBase(channel));
556 signalbases_.insert(signalbase);
558 all_signal_data_.insert(logic_data_);
559 signalbase->set_data(logic_data_);
562 signal = shared_ptr<view::Signal>(
563 new view::LogicSignal(*this,
564 device_, signalbase));
565 view->add_signal(signal);
568 case SR_CHANNEL_ANALOG:
571 signalbase = shared_ptr<data::SignalBase>(
572 new data::SignalBase(channel));
573 signalbases_.insert(signalbase);
575 shared_ptr<data::Analog> data(new data::Analog());
576 all_signal_data_.insert(data);
577 signalbase->set_data(data);
580 signal = shared_ptr<view::Signal>(
581 new view::AnalogSignal(
583 view->add_signal(signal);
598 shared_ptr<data::SignalBase> Session::signalbase_from_channel(
599 shared_ptr<sigrok::Channel> channel) const
601 for (shared_ptr<data::SignalBase> sig : signalbases_) {
603 if (sig->channel() == channel)
606 return shared_ptr<data::SignalBase>();
609 void Session::sample_thread_proc(function<void (const QString)> error_handler)
611 assert(error_handler);
616 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
618 out_of_memory_ = false;
623 error_handler(e.what());
627 set_capture_state(device_->session()->trigger() ?
628 AwaitingTrigger : Running);
631 set_capture_state(Stopped);
633 // Confirm that SR_DF_END was received
634 if (cur_logic_segment_) {
635 qDebug("SR_DF_END was not received.");
640 error_handler(tr("Out of memory, acquisition stopped."));
643 void Session::feed_in_header()
645 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
648 void Session::feed_in_meta(shared_ptr<Meta> meta)
650 for (auto entry : meta->config()) {
651 switch (entry.first->id()) {
652 case SR_CONF_SAMPLERATE:
653 // We can't rely on the header to always contain the sample rate,
654 // so in case it's supplied via a meta packet, we use it.
655 if (!cur_samplerate_)
656 cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
658 /// @todo handle samplerate changes
661 // Unknown metadata is not an error.
669 void Session::feed_in_trigger()
671 // The channel containing most samples should be most accurate
672 uint64_t sample_count = 0;
675 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
677 uint64_t temp_count = 0;
679 const vector< shared_ptr<pv::data::Segment> > segments =
681 for (const shared_ptr<pv::data::Segment> &s : segments)
682 temp_count += s->get_sample_count();
684 if (temp_count > sample_count)
685 sample_count = temp_count;
689 trigger_event(sample_count / get_samplerate());
692 void Session::feed_in_frame_begin()
694 if (cur_logic_segment_ || !cur_analog_segments_.empty())
698 void Session::feed_in_logic(shared_ptr<Logic> logic)
700 lock_guard<recursive_mutex> lock(data_mutex_);
702 const size_t sample_count = logic->data_length() / logic->unit_size();
705 // The only reason logic_data_ would not have been created is
706 // if it was not possible to determine the signals when the
707 // device was created.
711 if (!cur_logic_segment_) {
712 // This could be the first packet after a trigger
713 set_capture_state(Running);
715 // Create a new data segment
716 cur_logic_segment_ = shared_ptr<data::LogicSegment>(
717 new data::LogicSegment(
718 logic, cur_samplerate_, sample_count));
719 logic_data_->push_segment(cur_logic_segment_);
721 // @todo Putting this here means that only listeners querying
722 // for logic will be notified. Currently the only user of
723 // frame_began is DecoderStack, but in future we need to signal
724 // this after both analog and logic sweeps have begun.
727 // Append to the existing data segment
728 cur_logic_segment_->append_payload(logic);
734 void Session::feed_in_analog(shared_ptr<Analog> analog)
736 lock_guard<recursive_mutex> lock(data_mutex_);
738 const vector<shared_ptr<Channel>> channels = analog->channels();
739 const unsigned int channel_count = channels.size();
740 const size_t sample_count = analog->num_samples() / channel_count;
741 const float *data = static_cast<const float *>(analog->data_pointer());
742 bool sweep_beginning = false;
744 if (signalbases_.empty())
747 for (auto channel : channels) {
748 shared_ptr<data::AnalogSegment> segment;
750 // Try to get the segment of the channel
751 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
752 iterator iter = cur_analog_segments_.find(channel);
753 if (iter != cur_analog_segments_.end())
754 segment = (*iter).second;
756 // If no segment was found, this means we haven't
757 // created one yet. i.e. this is the first packet
758 // in the sweep containing this segment.
759 sweep_beginning = true;
761 // Create a segment, keep it in the maps of channels
762 segment = shared_ptr<data::AnalogSegment>(
763 new data::AnalogSegment(
764 cur_samplerate_, sample_count));
765 cur_analog_segments_[channel] = segment;
767 // Find the analog data associated with the channel
768 shared_ptr<data::SignalBase> base = signalbase_from_channel(channel);
771 shared_ptr<data::Analog> data(base->analog_data());
774 // Push the segment into the analog data.
775 data->push_segment(segment);
780 // Append the samples in the segment
781 segment->append_interleaved_samples(data++, sample_count,
785 if (sweep_beginning) {
786 // This could be the first packet after a trigger
787 set_capture_state(Running);
793 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
794 shared_ptr<Packet> packet)
799 assert(device == device_->device());
802 switch (packet->type()->id()) {
808 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
815 case SR_DF_FRAME_BEGIN:
816 feed_in_frame_begin();
821 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
822 } catch (std::bad_alloc) {
823 out_of_memory_ = true;
830 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
831 } catch (std::bad_alloc) {
832 out_of_memory_ = true;
840 lock_guard<recursive_mutex> lock(data_mutex_);
841 cur_logic_segment_.reset();
842 cur_analog_segments_.clear();