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, see <http://www.gnu.org/licenses/>.
28 #include "devicemanager.hpp"
29 #include "session.hpp"
31 #include "data/analog.hpp"
32 #include "data/analogsegment.hpp"
33 #include "data/decode/decoder.hpp"
34 #include "data/decoderstack.hpp"
35 #include "data/logic.hpp"
36 #include "data/logicsegment.hpp"
37 #include "data/signalbase.hpp"
39 #include "devices/hardwaredevice.hpp"
40 #include "devices/inputfile.hpp"
41 #include "devices/sessionfile.hpp"
43 #include "toolbars/mainbar.hpp"
45 #include "view/analogsignal.hpp"
46 #include "view/decodetrace.hpp"
47 #include "view/logicsignal.hpp"
48 #include "view/signal.hpp"
49 #include "view/view.hpp"
51 #include <libsigrokcxx/libsigrokcxx.hpp>
54 #include <libsigrokdecode/libsigrokdecode.h>
58 using std::dynamic_pointer_cast;
61 using std::lock_guard;
64 using std::make_shared;
70 using std::recursive_mutex;
71 using std::runtime_error;
72 using std::shared_ptr;
74 using std::unordered_set;
78 using sigrok::Channel;
79 using sigrok::ConfigKey;
80 using sigrok::DatafeedCallbackFunction;
82 using sigrok::InputFormat;
86 using sigrok::Session;
88 using Glib::VariantBase;
91 Session::Session(DeviceManager &device_manager, QString name) :
92 device_manager_(device_manager),
95 capture_state_(Stopped),
103 // Stop and join to the thread
107 DeviceManager& Session::device_manager()
109 return device_manager_;
112 const DeviceManager& Session::device_manager() const
114 return device_manager_;
117 shared_ptr<sigrok::Session> Session::session() const
120 return shared_ptr<sigrok::Session>();
121 return device_->session();
124 shared_ptr<devices::Device> Session::device() const
129 QString Session::name() const
134 void Session::set_name(QString name)
136 if (default_name_.isEmpty())
137 default_name_ = name;
144 const list< shared_ptr<views::ViewBase> > Session::views() const
149 shared_ptr<views::ViewBase> Session::main_view() const
154 void Session::set_main_bar(shared_ptr<pv::toolbars::MainBar> main_bar)
156 main_bar_ = main_bar;
159 shared_ptr<pv::toolbars::MainBar> Session::main_bar() const
164 bool Session::data_saved() const
169 void Session::save_settings(QSettings &settings) const
171 map<string, string> dev_info;
172 list<string> key_list;
173 int stacks = 0, views = 0;
176 shared_ptr<devices::HardwareDevice> hw_device =
177 dynamic_pointer_cast< devices::HardwareDevice >(device_);
180 settings.setValue("device_type", "hardware");
181 settings.beginGroup("device");
183 key_list.emplace_back("vendor");
184 key_list.emplace_back("model");
185 key_list.emplace_back("version");
186 key_list.emplace_back("serial_num");
187 key_list.emplace_back("connection_id");
189 dev_info = device_manager_.get_device_info(device_);
191 for (string key : key_list) {
192 if (dev_info.count(key))
193 settings.setValue(QString::fromUtf8(key.c_str()),
194 QString::fromUtf8(dev_info.at(key).c_str()));
196 settings.remove(QString::fromUtf8(key.c_str()));
202 shared_ptr<devices::SessionFile> sessionfile_device =
203 dynamic_pointer_cast< devices::SessionFile >(device_);
205 if (sessionfile_device) {
206 settings.setValue("device_type", "sessionfile");
207 settings.beginGroup("device");
208 settings.setValue("filename", QString::fromStdString(
209 sessionfile_device->full_name()));
213 // Save channels and decoders
214 for (shared_ptr<data::SignalBase> base : signalbases_) {
216 if (base->is_decode_signal()) {
217 shared_ptr<pv::data::DecoderStack> decoder_stack =
218 base->decoder_stack();
219 shared_ptr<data::decode::Decoder> top_decoder =
220 decoder_stack->stack().front();
222 settings.beginGroup("decoder_stack" + QString::number(stacks++));
223 settings.setValue("id", top_decoder->decoder()->id);
224 settings.setValue("name", top_decoder->decoder()->name);
229 settings.beginGroup(base->internal_name());
230 base->save_settings(settings);
235 settings.setValue("decoder_stacks", stacks);
237 // Save view states and their signal settings
238 // Note: main_view must be saved as view0
239 settings.beginGroup("view" + QString::number(views++));
240 main_view_->save_settings(settings);
243 for (shared_ptr<views::ViewBase> view : views_) {
244 if (view != main_view_) {
245 settings.beginGroup("view" + QString::number(views++));
246 view->save_settings(settings);
251 settings.setValue("views", views);
255 void Session::restore_settings(QSettings &settings)
257 shared_ptr<devices::Device> device;
259 QString device_type = settings.value("device_type").toString();
261 if (device_type == "hardware") {
262 map<string, string> dev_info;
263 list<string> key_list;
265 // Re-select last used device if possible but only if it's not demo
266 settings.beginGroup("device");
267 key_list.emplace_back("vendor");
268 key_list.emplace_back("model");
269 key_list.emplace_back("version");
270 key_list.emplace_back("serial_num");
271 key_list.emplace_back("connection_id");
273 for (string key : key_list) {
274 const QString k = QString::fromStdString(key);
275 if (!settings.contains(k))
278 const string value = settings.value(k).toString().toStdString();
280 dev_info.insert(make_pair(key, value));
283 if (dev_info.count("model") > 0)
284 device = device_manager_.find_device_from_info(dev_info);
292 if (device_type == "sessionfile") {
293 settings.beginGroup("device");
294 QString filename = settings.value("filename").toString();
297 if (QFileInfo(filename).isReadable()) {
298 device = make_shared<devices::SessionFile>(device_manager_.context(),
299 filename.toStdString());
302 // TODO Perform error handling
303 start_capture([](QString infoMessage) { (void)infoMessage; });
305 set_name(QFileInfo(filename).fileName());
311 for (shared_ptr<data::SignalBase> base : signalbases_) {
312 settings.beginGroup(base->internal_name());
313 base->restore_settings(settings);
319 int stacks = settings.value("decoder_stacks").toInt();
321 for (int i = 0; i < stacks; i++) {
322 settings.beginGroup("decoder_stack" + QString::number(i++));
324 QString id = settings.value("id").toString();
325 add_decoder(srd_decoder_get_by_id(id.toStdString().c_str()));
332 int views = settings.value("views").toInt();
334 for (int i = 0; i < views; i++) {
335 settings.beginGroup("view" + QString::number(i));
338 views::ViewType type = (views::ViewType)settings.value("type").toInt();
339 add_view(name_, type, this);
340 views_.back()->restore_settings(settings);
342 main_view_->restore_settings(settings);
349 void Session::select_device(shared_ptr<devices::Device> device)
355 set_default_device();
356 } catch (const QString &e) {
357 main_bar_->session_error(tr("Failed to Select Device"),
358 tr("Failed to Select Device"));
362 void Session::set_device(shared_ptr<devices::Device> device)
366 // Ensure we are not capturing before setting the device
374 // Revert name back to default name (e.g. "Session 1") as the data is gone
375 name_ = default_name_;
378 // Remove all stored data
379 for (shared_ptr<views::ViewBase> view : views_) {
380 view->clear_signals();
382 view->clear_decode_signals();
385 for (const shared_ptr<data::SignalData> d : all_signal_data_)
387 all_signal_data_.clear();
388 signalbases_.clear();
389 cur_logic_segment_.reset();
391 for (auto entry : cur_analog_segments_) {
392 shared_ptr<sigrok::Channel>(entry.first).reset();
393 shared_ptr<data::AnalogSegment>(entry.second).reset();
400 device_ = move(device);
404 } catch (const QString &e) {
409 device_->session()->add_datafeed_callback([=]
410 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
411 data_feed_in(device, packet);
420 void Session::set_default_device()
422 const list< shared_ptr<devices::HardwareDevice> > &devices =
423 device_manager_.devices();
428 // Try and find the demo device and select that by default
429 const auto iter = find_if(devices.begin(), devices.end(),
430 [] (const shared_ptr<devices::HardwareDevice> &d) {
431 return d->hardware_device()->driver()->name() == "demo"; });
432 set_device((iter == devices.end()) ? devices.front() : *iter);
435 void Session::load_init_file(const string &file_name, const string &format)
437 shared_ptr<InputFormat> input_format;
439 if (!format.empty()) {
440 const map<string, shared_ptr<InputFormat> > formats =
441 device_manager_.context()->input_formats();
442 const auto iter = find_if(formats.begin(), formats.end(),
443 [&](const pair<string, shared_ptr<InputFormat> > f) {
444 return f.first == format; });
445 if (iter == formats.end()) {
446 main_bar_->session_error(tr("Error"),
447 tr("Unexpected input format: %s").arg(QString::fromStdString(format)));
451 input_format = (*iter).second;
454 load_file(QString::fromStdString(file_name), input_format);
457 void Session::load_file(QString file_name,
458 shared_ptr<sigrok::InputFormat> format,
459 const map<string, Glib::VariantBase> &options)
461 const QString errorMessage(
462 QString("Failed to load file %1").arg(file_name));
466 set_device(shared_ptr<devices::Device>(
467 new devices::InputFile(
468 device_manager_.context(),
469 file_name.toStdString(),
472 set_device(shared_ptr<devices::Device>(
473 new devices::SessionFile(
474 device_manager_.context(),
475 file_name.toStdString())));
477 main_bar_->session_error(tr("Failed to load ") + file_name, e.what());
478 set_default_device();
479 main_bar_->update_device_list();
483 main_bar_->update_device_list();
485 start_capture([&, errorMessage](QString infoMessage) {
486 main_bar_->session_error(errorMessage, infoMessage); });
488 set_name(QFileInfo(file_name).fileName());
491 Session::capture_state Session::get_capture_state() const
493 lock_guard<mutex> lock(sampling_mutex_);
494 return capture_state_;
497 void Session::start_capture(function<void (const QString)> error_handler)
500 error_handler(tr("No active device set, can't start acquisition."));
506 // Check that at least one channel is enabled
507 const shared_ptr<sigrok::Device> sr_dev = device_->device();
509 const auto channels = sr_dev->channels();
510 if (!any_of(channels.begin(), channels.end(),
511 [](shared_ptr<Channel> channel) {
512 return channel->enabled(); })) {
513 error_handler(tr("No channels enabled."));
519 for (const shared_ptr<data::SignalData> d : all_signal_data_)
522 // Revert name back to default name (e.g. "Session 1") for real devices
523 // as the (possibly saved) data is gone. File devices keep their name.
524 shared_ptr<devices::HardwareDevice> hw_device =
525 dynamic_pointer_cast< devices::HardwareDevice >(device_);
528 name_ = default_name_;
533 sampling_thread_ = std::thread(
534 &Session::sample_thread_proc, this, error_handler);
537 void Session::stop_capture()
539 if (get_capture_state() != Stopped)
542 // Check that sampling stopped
543 if (sampling_thread_.joinable())
544 sampling_thread_.join();
547 void Session::register_view(shared_ptr<views::ViewBase> view)
549 if (views_.empty()) {
553 views_.push_back(view);
558 void Session::deregister_view(shared_ptr<views::ViewBase> view)
560 views_.remove_if([&](shared_ptr<views::ViewBase> v) { return v == view; });
562 if (views_.empty()) {
565 // Without a view there can be no main bar
570 bool Session::has_view(shared_ptr<views::ViewBase> view)
572 for (shared_ptr<views::ViewBase> v : views_)
579 double Session::get_samplerate() const
581 double samplerate = 0.0;
583 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
585 const vector< shared_ptr<pv::data::Segment> > segments =
587 for (const shared_ptr<pv::data::Segment> &s : segments)
588 samplerate = max(samplerate, s->samplerate());
590 // If there is no sample rate given we use samples as unit
591 if (samplerate == 0.0)
597 const unordered_set< shared_ptr<data::SignalBase> > Session::signalbases() const
603 bool Session::add_decoder(srd_decoder *const dec)
608 map<const srd_channel*, shared_ptr<data::SignalBase> > channels;
609 shared_ptr<data::DecoderStack> decoder_stack;
612 // Create the decoder
613 decoder_stack = make_shared<data::DecoderStack>(*this, dec);
615 // Make a list of all the channels
616 vector<const srd_channel*> all_channels;
617 for (const GSList *i = dec->channels; i; i = i->next)
618 all_channels.push_back((const srd_channel*)i->data);
619 for (const GSList *i = dec->opt_channels; i; i = i->next)
620 all_channels.push_back((const srd_channel*)i->data);
622 // Auto select the initial channels
623 for (const srd_channel *pdch : all_channels)
624 for (shared_ptr<data::SignalBase> b : signalbases_) {
625 if (b->logic_data()) {
626 if (QString::fromUtf8(pdch->name).toLower().
627 contains(b->name().toLower()))
632 assert(decoder_stack);
633 assert(!decoder_stack->stack().empty());
634 assert(decoder_stack->stack().front());
635 decoder_stack->stack().front()->set_channels(channels);
637 // Create the decode signal
638 shared_ptr<data::SignalBase> signalbase =
639 make_shared<data::SignalBase>(nullptr, data::SignalBase::DecodeChannel);
641 signalbase->set_decoder_stack(decoder_stack);
642 signalbases_.insert(signalbase);
644 for (shared_ptr<views::ViewBase> view : views_)
645 view->add_decode_signal(signalbase);
646 } catch (runtime_error e) {
652 // Do an initial decode
653 decoder_stack->begin_decode();
658 void Session::remove_decode_signal(shared_ptr<data::SignalBase> signalbase)
660 signalbases_.erase(signalbase);
662 for (shared_ptr<views::ViewBase> view : views_)
663 view->remove_decode_signal(signalbase);
669 void Session::set_capture_state(capture_state state)
674 lock_guard<mutex> lock(sampling_mutex_);
675 changed = capture_state_ != state;
676 capture_state_ = state;
680 capture_state_changed(state);
683 void Session::update_signals()
686 signalbases_.clear();
688 for (shared_ptr<views::ViewBase> view : views_) {
689 view->clear_signals();
691 view->clear_decode_signals();
697 lock_guard<recursive_mutex> lock(data_mutex_);
699 const shared_ptr<sigrok::Device> sr_dev = device_->device();
701 signalbases_.clear();
703 for (shared_ptr<views::ViewBase> view : views_) {
704 view->clear_signals();
706 view->clear_decode_signals();
712 // Detect what data types we will receive
713 auto channels = sr_dev->channels();
714 unsigned int logic_channel_count = count_if(
715 channels.begin(), channels.end(),
716 [] (shared_ptr<Channel> channel) {
717 return channel->type() == sigrok::ChannelType::LOGIC; });
719 // Create data containers for the logic data segments
721 lock_guard<recursive_mutex> data_lock(data_mutex_);
723 if (logic_channel_count == 0) {
725 } else if (!logic_data_ ||
726 logic_data_->num_channels() != logic_channel_count) {
727 logic_data_.reset(new data::Logic(
728 logic_channel_count));
733 // Make the signals list
734 for (shared_ptr<views::ViewBase> viewbase : views_) {
735 views::TraceView::View *trace_view =
736 qobject_cast<views::TraceView::View*>(viewbase.get());
739 unordered_set< shared_ptr<views::TraceView::Signal> >
740 prev_sigs(trace_view->signals());
741 trace_view->clear_signals();
743 for (auto channel : sr_dev->channels()) {
744 shared_ptr<data::SignalBase> signalbase;
745 shared_ptr<views::TraceView::Signal> signal;
747 // Find the channel in the old signals
748 const auto iter = find_if(
749 prev_sigs.cbegin(), prev_sigs.cend(),
750 [&](const shared_ptr<views::TraceView::Signal> &s) {
751 return s->base()->channel() == channel;
753 if (iter != prev_sigs.end()) {
754 // Copy the signal from the old set to the new
756 trace_view->add_signal(signal);
758 // Find the signalbase for this channel if possible
760 for (const shared_ptr<data::SignalBase> b : signalbases_)
761 if (b->channel() == channel)
764 switch(channel->type()->id()) {
765 case SR_CHANNEL_LOGIC:
767 signalbase = make_shared<data::SignalBase>(channel,
768 data::SignalBase::LogicChannel);
769 signalbases_.insert(signalbase);
771 all_signal_data_.insert(logic_data_);
772 signalbase->set_data(logic_data_);
774 connect(this, SIGNAL(capture_state_changed(int)),
775 signalbase.get(), SLOT(on_capture_state_changed(int)));
778 signal = shared_ptr<views::TraceView::Signal>(
779 new views::TraceView::LogicSignal(*this,
780 device_, signalbase));
781 trace_view->add_signal(signal);
784 case SR_CHANNEL_ANALOG:
787 signalbase = make_shared<data::SignalBase>(channel,
788 data::SignalBase::AnalogChannel);
789 signalbases_.insert(signalbase);
791 shared_ptr<data::Analog> data(new data::Analog());
792 all_signal_data_.insert(data);
793 signalbase->set_data(data);
795 connect(this, SIGNAL(capture_state_changed(int)),
796 signalbase.get(), SLOT(on_capture_state_changed(int)));
799 signal = shared_ptr<views::TraceView::Signal>(
800 new views::TraceView::AnalogSignal(
802 trace_view->add_signal(signal);
818 shared_ptr<data::SignalBase> Session::signalbase_from_channel(
819 shared_ptr<sigrok::Channel> channel) const
821 for (shared_ptr<data::SignalBase> sig : signalbases_) {
823 if (sig->channel() == channel)
826 return shared_ptr<data::SignalBase>();
829 void Session::sample_thread_proc(function<void (const QString)> error_handler)
831 assert(error_handler);
836 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
838 out_of_memory_ = false;
843 error_handler(e.what());
847 set_capture_state(device_->session()->trigger() ?
848 AwaitingTrigger : Running);
851 set_capture_state(Stopped);
853 // Confirm that SR_DF_END was received
854 if (cur_logic_segment_) {
855 qDebug("SR_DF_END was not received.");
859 // Optimize memory usage
860 free_unused_memory();
862 // We now have unsaved data unless we just "captured" from a file
863 shared_ptr<devices::File> file_device =
864 dynamic_pointer_cast<devices::File>(device_);
870 error_handler(tr("Out of memory, acquisition stopped."));
873 void Session::free_unused_memory()
875 for (shared_ptr<data::SignalData> data : all_signal_data_) {
876 const vector< shared_ptr<data::Segment> > segments = data->segments();
878 for (shared_ptr<data::Segment> segment : segments) {
879 segment->free_unused_memory();
884 void Session::feed_in_header()
886 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
889 void Session::feed_in_meta(shared_ptr<Meta> meta)
891 for (auto entry : meta->config()) {
892 switch (entry.first->id()) {
893 case SR_CONF_SAMPLERATE:
894 // We can't rely on the header to always contain the sample rate,
895 // so in case it's supplied via a meta packet, we use it.
896 if (!cur_samplerate_)
897 cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
899 /// @todo handle samplerate changes
902 // Unknown metadata is not an error.
910 void Session::feed_in_trigger()
912 // The channel containing most samples should be most accurate
913 uint64_t sample_count = 0;
916 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
918 uint64_t temp_count = 0;
920 const vector< shared_ptr<pv::data::Segment> > segments =
922 for (const shared_ptr<pv::data::Segment> &s : segments)
923 temp_count += s->get_sample_count();
925 if (temp_count > sample_count)
926 sample_count = temp_count;
930 trigger_event(sample_count / get_samplerate());
933 void Session::feed_in_frame_begin()
935 if (cur_logic_segment_ || !cur_analog_segments_.empty())
939 void Session::feed_in_logic(shared_ptr<Logic> logic)
941 lock_guard<recursive_mutex> lock(data_mutex_);
944 // The only reason logic_data_ would not have been created is
945 // if it was not possible to determine the signals when the
946 // device was created.
950 if (!cur_logic_segment_) {
951 // This could be the first packet after a trigger
952 set_capture_state(Running);
954 // Create a new data segment
955 cur_logic_segment_ = make_shared<data::LogicSegment>(
956 *logic_data_, logic->unit_size(), cur_samplerate_);
957 logic_data_->push_segment(cur_logic_segment_);
959 // @todo Putting this here means that only listeners querying
960 // for logic will be notified. Currently the only user of
961 // frame_began is DecoderStack, but in future we need to signal
962 // this after both analog and logic sweeps have begun.
966 cur_logic_segment_->append_payload(logic);
971 void Session::feed_in_analog(shared_ptr<Analog> analog)
973 lock_guard<recursive_mutex> lock(data_mutex_);
975 const vector<shared_ptr<Channel>> channels = analog->channels();
976 const unsigned int channel_count = channels.size();
977 const size_t sample_count = analog->num_samples() / channel_count;
978 const float *data = static_cast<const float *>(analog->data_pointer());
979 bool sweep_beginning = false;
981 if (signalbases_.empty())
984 for (auto channel : channels) {
985 shared_ptr<data::AnalogSegment> segment;
987 // Try to get the segment of the channel
988 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
989 iterator iter = cur_analog_segments_.find(channel);
990 if (iter != cur_analog_segments_.end())
991 segment = (*iter).second;
993 // If no segment was found, this means we haven't
994 // created one yet. i.e. this is the first packet
995 // in the sweep containing this segment.
996 sweep_beginning = true;
998 // Find the analog data associated with the channel
999 shared_ptr<data::SignalBase> base = signalbase_from_channel(channel);
1002 shared_ptr<data::Analog> data(base->analog_data());
1005 // Create a segment, keep it in the maps of channels
1006 segment = make_shared<data::AnalogSegment>(
1007 *data, cur_samplerate_);
1008 cur_analog_segments_[channel] = segment;
1010 // Push the segment into the analog data.
1011 data->push_segment(segment);
1016 // Append the samples in the segment
1017 segment->append_interleaved_samples(data++, sample_count,
1021 if (sweep_beginning) {
1022 // This could be the first packet after a trigger
1023 set_capture_state(Running);
1029 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
1030 shared_ptr<Packet> packet)
1032 static bool frame_began = false;
1037 assert(device == device_->device());
1040 switch (packet->type()->id()) {
1046 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
1053 case SR_DF_FRAME_BEGIN:
1054 feed_in_frame_begin();
1060 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
1061 } catch (bad_alloc) {
1062 out_of_memory_ = true;
1069 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
1070 } catch (bad_alloc) {
1071 out_of_memory_ = true;
1076 case SR_DF_FRAME_END:
1080 lock_guard<recursive_mutex> lock(data_mutex_);
1081 cur_logic_segment_.reset();
1082 cur_analog_segments_.clear();
1085 frame_began = false;
1095 void Session::on_data_saved()