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>
37 #include "session.hpp"
38 #include "devicemanager.hpp"
40 #include "data/analog.hpp"
41 #include "data/analogsegment.hpp"
42 #include "data/decoderstack.hpp"
43 #include "data/logic.hpp"
44 #include "data/logicsegment.hpp"
45 #include "data/signalbase.hpp"
46 #include "data/decode/decoder.hpp"
48 #include "devices/hardwaredevice.hpp"
49 #include "devices/sessionfile.hpp"
51 #include "toolbars/mainbar.hpp"
53 #include "view/analogsignal.hpp"
54 #include "view/decodetrace.hpp"
55 #include "view/logicsignal.hpp"
56 #include "view/signal.hpp"
57 #include "view/view.hpp"
59 #include <libsigrokcxx/libsigrokcxx.hpp>
62 #include <libsigrokdecode/libsigrokdecode.h>
65 using boost::shared_lock;
66 using boost::shared_mutex;
67 using boost::unique_lock;
69 using std::dynamic_pointer_cast;
71 using std::lock_guard;
75 using std::recursive_mutex;
77 using std::shared_ptr;
79 using std::unordered_set;
83 using sigrok::Channel;
84 using sigrok::ChannelType;
85 using sigrok::ConfigKey;
86 using sigrok::DatafeedCallbackFunction;
92 using sigrok::PacketPayload;
93 using sigrok::Session;
94 using sigrok::SessionDevice;
96 using Glib::VariantBase;
100 Session::Session(DeviceManager &device_manager, QString name) :
101 device_manager_(device_manager),
104 capture_state_(Stopped),
111 // Stop and join to the thread
115 DeviceManager& Session::device_manager()
117 return device_manager_;
120 const DeviceManager& Session::device_manager() const
122 return device_manager_;
125 shared_ptr<sigrok::Session> Session::session() const
128 return shared_ptr<sigrok::Session>();
129 return device_->session();
132 shared_ptr<devices::Device> Session::device() const
137 QString Session::name() const
142 void Session::set_name(QString name)
144 if (default_name_.isEmpty())
145 default_name_ = name;
152 const std::list< std::shared_ptr<views::ViewBase> > Session::views() const
157 std::shared_ptr<views::ViewBase> Session::main_view() const
162 void Session::set_main_bar(std::shared_ptr<pv::toolbars::MainBar> main_bar)
164 main_bar_ = main_bar;
167 shared_ptr<pv::toolbars::MainBar> Session::main_bar() const
172 void Session::save_settings(QSettings &settings) const
174 map<string, string> dev_info;
175 list<string> key_list;
176 int stacks = 0, views = 0;
179 shared_ptr<devices::HardwareDevice> hw_device =
180 dynamic_pointer_cast< devices::HardwareDevice >(device_);
183 settings.setValue("device_type", "hardware");
184 settings.beginGroup("device");
186 key_list.push_back("vendor");
187 key_list.push_back("model");
188 key_list.push_back("version");
189 key_list.push_back("serial_num");
190 key_list.push_back("connection_id");
192 dev_info = device_manager_.get_device_info(device_);
194 for (string key : key_list) {
195 if (dev_info.count(key))
196 settings.setValue(QString::fromUtf8(key.c_str()),
197 QString::fromUtf8(dev_info.at(key).c_str()));
199 settings.remove(QString::fromUtf8(key.c_str()));
205 shared_ptr<devices::SessionFile> sessionfile_device =
206 dynamic_pointer_cast< devices::SessionFile >(device_);
208 if (sessionfile_device) {
209 settings.setValue("device_type", "sessionfile");
210 settings.beginGroup("device");
211 settings.setValue("filename", QString::fromStdString(
212 sessionfile_device->full_name()));
216 // Save channels and decoders
217 for (shared_ptr<data::SignalBase> base : signalbases_) {
219 if (base->is_decode_signal()) {
220 shared_ptr<pv::data::DecoderStack> decoder_stack =
221 base->decoder_stack();
222 std::shared_ptr<data::decode::Decoder> top_decoder =
223 decoder_stack->stack().front();
225 settings.beginGroup("decoder_stack" + QString::number(stacks++));
226 settings.setValue("id", top_decoder->decoder()->id);
227 settings.setValue("name", top_decoder->decoder()->name);
232 settings.beginGroup(base->internal_name());
233 base->save_settings(settings);
238 settings.setValue("decoder_stacks", stacks);
240 // Save view states and their signal settings
241 // Note: main_view must be saved as view0
242 settings.beginGroup("view" + QString::number(views++));
243 main_view_->save_settings(settings);
246 for (shared_ptr<views::ViewBase> view : views_) {
247 if (view != main_view_) {
248 settings.beginGroup("view" + QString::number(views++));
249 view->save_settings(settings);
254 settings.setValue("views", views);
258 void Session::restore_settings(QSettings &settings)
260 shared_ptr<devices::Device> device;
262 QString device_type = settings.value("device_type").toString();
264 if (device_type == "hardware") {
265 map<string, string> dev_info;
266 list<string> key_list;
268 // Re-select last used device if possible but only if it's not demo
269 settings.beginGroup("device");
270 key_list.push_back("vendor");
271 key_list.push_back("model");
272 key_list.push_back("version");
273 key_list.push_back("serial_num");
274 key_list.push_back("connection_id");
276 for (string key : key_list) {
277 const QString k = QString::fromStdString(key);
278 if (!settings.contains(k))
281 const string value = settings.value(k).toString().toStdString();
283 dev_info.insert(std::make_pair(key, value));
286 if (dev_info.count("model") > 0)
287 device = device_manager_.find_device_from_info(dev_info);
295 if (device_type == "sessionfile") {
296 settings.beginGroup("device");
297 QString filename = settings.value("filename").toString();
300 if (QFileInfo(filename).isReadable()) {
301 device = std::make_shared<devices::SessionFile>(device_manager_.context(),
302 filename.toStdString());
305 // TODO Perform error handling
306 start_capture([](QString infoMessage) { (void)infoMessage; });
308 set_name(QFileInfo(filename).fileName());
314 for (shared_ptr<data::SignalBase> base : signalbases_) {
315 settings.beginGroup(base->internal_name());
316 base->restore_settings(settings);
322 int stacks = settings.value("decoder_stacks").toInt();
324 for (int i = 0; i < stacks; i++) {
325 settings.beginGroup("decoder_stack" + QString::number(i++));
327 QString id = settings.value("id").toString();
328 add_decoder(srd_decoder_get_by_id(id.toStdString().c_str()));
335 int views = settings.value("views").toInt();
337 for (int i = 0; i < views; i++) {
338 settings.beginGroup("view" + QString::number(i));
341 views::ViewType type = (views::ViewType)settings.value("type").toInt();
342 add_view(name_, type, this);
343 views_.back()->restore_settings(settings);
345 main_view_->restore_settings(settings);
352 void Session::set_device(shared_ptr<devices::Device> device)
356 // Ensure we are not capturing before setting the device
364 // Revert name back to default name (e.g. "Untitled-1") as the data is gone
365 name_ = default_name_;
368 // Remove all stored data
369 for (std::shared_ptr<views::ViewBase> view : views_) {
370 view->clear_signals();
372 view->clear_decode_signals();
375 for (const shared_ptr<data::SignalData> d : all_signal_data_)
377 all_signal_data_.clear();
378 signalbases_.clear();
379 cur_logic_segment_.reset();
381 for (auto entry : cur_analog_segments_) {
382 shared_ptr<sigrok::Channel>(entry.first).reset();
383 shared_ptr<data::AnalogSegment>(entry.second).reset();
390 device_ = std::move(device);
394 } catch (const QString &e) {
400 device_->session()->add_datafeed_callback([=]
401 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
402 data_feed_in(device, packet);
409 void Session::set_default_device()
411 const list< shared_ptr<devices::HardwareDevice> > &devices =
412 device_manager_.devices();
417 // Try and find the demo device and select that by default
418 const auto iter = std::find_if(devices.begin(), devices.end(),
419 [] (const shared_ptr<devices::HardwareDevice> &d) {
420 return d->hardware_device()->driver()->name() ==
422 set_device((iter == devices.end()) ? devices.front() : *iter);
425 Session::capture_state Session::get_capture_state() const
427 lock_guard<mutex> lock(sampling_mutex_);
428 return capture_state_;
431 void Session::start_capture(function<void (const QString)> error_handler)
434 error_handler(tr("No active device set, can't start acquisition."));
440 // Check that at least one channel is enabled
441 const shared_ptr<sigrok::Device> sr_dev = device_->device();
443 const auto channels = sr_dev->channels();
444 if (!std::any_of(channels.begin(), channels.end(),
445 [](shared_ptr<Channel> channel) {
446 return channel->enabled(); })) {
447 error_handler(tr("No channels enabled."));
453 for (const shared_ptr<data::SignalData> d : all_signal_data_)
456 // Revert name back to default name (e.g. "Untitled-1") as the data is gone
457 name_ = default_name_;
461 sampling_thread_ = std::thread(
462 &Session::sample_thread_proc, this, error_handler);
465 void Session::stop_capture()
467 if (get_capture_state() != Stopped)
470 // Check that sampling stopped
471 if (sampling_thread_.joinable())
472 sampling_thread_.join();
475 void Session::register_view(std::shared_ptr<views::ViewBase> view)
477 if (views_.empty()) {
481 views_.push_back(view);
486 void Session::deregister_view(std::shared_ptr<views::ViewBase> view)
488 views_.remove_if([&](std::shared_ptr<views::ViewBase> v) {
489 return v == view; });
491 if (views_.empty()) {
494 // Without a view there can be no main bar
499 bool Session::has_view(std::shared_ptr<views::ViewBase> view)
501 for (std::shared_ptr<views::ViewBase> v : views_)
508 double Session::get_samplerate() const
510 double samplerate = 0.0;
512 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
514 const vector< shared_ptr<pv::data::Segment> > segments =
516 for (const shared_ptr<pv::data::Segment> &s : segments)
517 samplerate = std::max(samplerate, s->samplerate());
519 // If there is no sample rate given we use samples as unit
520 if (samplerate == 0.0)
526 const std::unordered_set< std::shared_ptr<data::SignalBase> >
527 Session::signalbases() const
533 bool Session::add_decoder(srd_decoder *const dec)
535 map<const srd_channel*, shared_ptr<data::SignalBase> > channels;
536 shared_ptr<data::DecoderStack> decoder_stack;
539 // Create the decoder
540 decoder_stack = shared_ptr<data::DecoderStack>(
541 new data::DecoderStack(*this, dec));
543 // Make a list of all the channels
544 std::vector<const srd_channel*> all_channels;
545 for (const GSList *i = dec->channels; i; i = i->next)
546 all_channels.push_back((const srd_channel*)i->data);
547 for (const GSList *i = dec->opt_channels; i; i = i->next)
548 all_channels.push_back((const srd_channel*)i->data);
550 // Auto select the initial channels
551 for (const srd_channel *pdch : all_channels)
552 for (shared_ptr<data::SignalBase> b : signalbases_) {
553 if (b->type() == ChannelType::LOGIC) {
554 if (QString::fromUtf8(pdch->name).toLower().
555 contains(b->name().toLower()))
560 assert(decoder_stack);
561 assert(!decoder_stack->stack().empty());
562 assert(decoder_stack->stack().front());
563 decoder_stack->stack().front()->set_channels(channels);
565 // Create the decode signal
566 shared_ptr<data::SignalBase> signalbase =
567 shared_ptr<data::SignalBase>(new data::SignalBase(nullptr));
569 signalbase->set_decoder_stack(decoder_stack);
570 signalbases_.insert(signalbase);
572 for (std::shared_ptr<views::ViewBase> view : views_)
573 view->add_decode_signal(signalbase);
574 } catch (std::runtime_error e) {
580 // Do an initial decode
581 decoder_stack->begin_decode();
586 void Session::remove_decode_signal(shared_ptr<data::SignalBase> signalbase)
588 for (std::shared_ptr<views::ViewBase> view : views_)
589 view->remove_decode_signal(signalbase);
593 void Session::set_capture_state(capture_state state)
598 lock_guard<mutex> lock(sampling_mutex_);
599 changed = capture_state_ != state;
600 capture_state_ = state;
604 capture_state_changed(state);
607 void Session::update_signals()
610 signalbases_.clear();
612 for (std::shared_ptr<views::ViewBase> view : views_) {
613 view->clear_signals();
615 view->clear_decode_signals();
621 lock_guard<recursive_mutex> lock(data_mutex_);
623 const shared_ptr<sigrok::Device> sr_dev = device_->device();
625 signalbases_.clear();
627 for (std::shared_ptr<views::ViewBase> view : views_) {
628 view->clear_signals();
630 view->clear_decode_signals();
636 // Detect what data types we will receive
637 auto channels = sr_dev->channels();
638 unsigned int logic_channel_count = std::count_if(
639 channels.begin(), channels.end(),
640 [] (shared_ptr<Channel> channel) {
641 return channel->type() == ChannelType::LOGIC; });
643 // Create data containers for the logic data segments
645 lock_guard<recursive_mutex> data_lock(data_mutex_);
647 if (logic_channel_count == 0) {
649 } else if (!logic_data_ ||
650 logic_data_->num_channels() != logic_channel_count) {
651 logic_data_.reset(new data::Logic(
652 logic_channel_count));
657 // Make the signals list
658 for (std::shared_ptr<views::ViewBase> viewbase : views_) {
659 views::TraceView::View *trace_view =
660 qobject_cast<views::TraceView::View*>(viewbase.get());
663 unordered_set< shared_ptr<views::TraceView::Signal> >
664 prev_sigs(trace_view->signals());
665 trace_view->clear_signals();
667 for (auto channel : sr_dev->channels()) {
668 shared_ptr<data::SignalBase> signalbase;
669 shared_ptr<views::TraceView::Signal> signal;
671 // Find the channel in the old signals
672 const auto iter = std::find_if(
673 prev_sigs.cbegin(), prev_sigs.cend(),
674 [&](const shared_ptr<views::TraceView::Signal> &s) {
675 return s->base()->channel() == channel;
677 if (iter != prev_sigs.end()) {
678 // Copy the signal from the old set to the new
680 trace_view->add_signal(signal);
682 // Find the signalbase for this channel if possible
684 for (const shared_ptr<data::SignalBase> b : signalbases_)
685 if (b->channel() == channel)
688 switch(channel->type()->id()) {
689 case SR_CHANNEL_LOGIC:
691 signalbase = shared_ptr<data::SignalBase>(
692 new data::SignalBase(channel));
693 signalbases_.insert(signalbase);
695 all_signal_data_.insert(logic_data_);
696 signalbase->set_data(logic_data_);
699 signal = shared_ptr<views::TraceView::Signal>(
700 new views::TraceView::LogicSignal(*this,
701 device_, signalbase));
702 trace_view->add_signal(signal);
705 case SR_CHANNEL_ANALOG:
708 signalbase = shared_ptr<data::SignalBase>(
709 new data::SignalBase(channel));
710 signalbases_.insert(signalbase);
712 shared_ptr<data::Analog> data(new data::Analog());
713 all_signal_data_.insert(data);
714 signalbase->set_data(data);
717 signal = shared_ptr<views::TraceView::Signal>(
718 new views::TraceView::AnalogSignal(
720 trace_view->add_signal(signal);
736 shared_ptr<data::SignalBase> Session::signalbase_from_channel(
737 shared_ptr<sigrok::Channel> channel) const
739 for (shared_ptr<data::SignalBase> sig : signalbases_) {
741 if (sig->channel() == channel)
744 return shared_ptr<data::SignalBase>();
747 void Session::sample_thread_proc(function<void (const QString)> error_handler)
749 assert(error_handler);
754 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
756 out_of_memory_ = false;
761 error_handler(e.what());
765 set_capture_state(device_->session()->trigger() ?
766 AwaitingTrigger : Running);
769 set_capture_state(Stopped);
771 // Confirm that SR_DF_END was received
772 if (cur_logic_segment_) {
773 qDebug("SR_DF_END was not received.");
778 error_handler(tr("Out of memory, acquisition stopped."));
781 void Session::feed_in_header()
783 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
786 void Session::feed_in_meta(shared_ptr<Meta> meta)
788 for (auto entry : meta->config()) {
789 switch (entry.first->id()) {
790 case SR_CONF_SAMPLERATE:
791 // We can't rely on the header to always contain the sample rate,
792 // so in case it's supplied via a meta packet, we use it.
793 if (!cur_samplerate_)
794 cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
796 /// @todo handle samplerate changes
799 // Unknown metadata is not an error.
807 void Session::feed_in_trigger()
809 // The channel containing most samples should be most accurate
810 uint64_t sample_count = 0;
813 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
815 uint64_t temp_count = 0;
817 const vector< shared_ptr<pv::data::Segment> > segments =
819 for (const shared_ptr<pv::data::Segment> &s : segments)
820 temp_count += s->get_sample_count();
822 if (temp_count > sample_count)
823 sample_count = temp_count;
827 trigger_event(sample_count / get_samplerate());
830 void Session::feed_in_frame_begin()
832 if (cur_logic_segment_ || !cur_analog_segments_.empty())
836 void Session::feed_in_logic(shared_ptr<Logic> logic)
838 lock_guard<recursive_mutex> lock(data_mutex_);
840 const size_t sample_count = logic->data_length() / logic->unit_size();
843 // The only reason logic_data_ would not have been created is
844 // if it was not possible to determine the signals when the
845 // device was created.
849 if (!cur_logic_segment_) {
850 // This could be the first packet after a trigger
851 set_capture_state(Running);
853 // Create a new data segment
854 cur_logic_segment_ = shared_ptr<data::LogicSegment>(
855 new data::LogicSegment(
856 logic, cur_samplerate_, sample_count));
857 logic_data_->push_segment(cur_logic_segment_);
859 // @todo Putting this here means that only listeners querying
860 // for logic will be notified. Currently the only user of
861 // frame_began is DecoderStack, but in future we need to signal
862 // this after both analog and logic sweeps have begun.
865 // Append to the existing data segment
866 cur_logic_segment_->append_payload(logic);
872 void Session::feed_in_analog(shared_ptr<Analog> analog)
874 lock_guard<recursive_mutex> lock(data_mutex_);
876 const vector<shared_ptr<Channel>> channels = analog->channels();
877 const unsigned int channel_count = channels.size();
878 const size_t sample_count = analog->num_samples() / channel_count;
879 const float *data = static_cast<const float *>(analog->data_pointer());
880 bool sweep_beginning = false;
882 if (signalbases_.empty())
885 for (auto channel : channels) {
886 shared_ptr<data::AnalogSegment> segment;
888 // Try to get the segment of the channel
889 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
890 iterator iter = cur_analog_segments_.find(channel);
891 if (iter != cur_analog_segments_.end())
892 segment = (*iter).second;
894 // If no segment was found, this means we haven't
895 // created one yet. i.e. this is the first packet
896 // in the sweep containing this segment.
897 sweep_beginning = true;
899 // Create a segment, keep it in the maps of channels
900 segment = shared_ptr<data::AnalogSegment>(
901 new data::AnalogSegment(
902 cur_samplerate_, sample_count));
903 cur_analog_segments_[channel] = segment;
905 // Find the analog data associated with the channel
906 shared_ptr<data::SignalBase> base = signalbase_from_channel(channel);
909 shared_ptr<data::Analog> data(base->analog_data());
912 // Push the segment into the analog data.
913 data->push_segment(segment);
918 // Append the samples in the segment
919 segment->append_interleaved_samples(data++, sample_count,
923 if (sweep_beginning) {
924 // This could be the first packet after a trigger
925 set_capture_state(Running);
931 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
932 shared_ptr<Packet> packet)
937 assert(device == device_->device());
940 switch (packet->type()->id()) {
946 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
953 case SR_DF_FRAME_BEGIN:
954 feed_in_frame_begin();
959 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
960 } catch (std::bad_alloc) {
961 out_of_memory_ = true;
968 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
969 } catch (std::bad_alloc) {
970 out_of_memory_ = true;
978 lock_guard<recursive_mutex> lock(data_mutex_);
979 cur_logic_segment_.reset();
980 cur_analog_segments_.clear();