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),
103 capture_state_(Stopped),
110 // Stop and join to the thread
114 DeviceManager& Session::device_manager()
116 return device_manager_;
119 const DeviceManager& Session::device_manager() const
121 return device_manager_;
124 shared_ptr<sigrok::Session> Session::session() const
127 return shared_ptr<sigrok::Session>();
128 return device_->session();
131 shared_ptr<devices::Device> Session::device() const
136 QString Session::name() const
141 void Session::set_name(QString name)
143 if (default_name_.isEmpty())
144 default_name_ = name;
151 std::shared_ptr<pv::view::View> Session::main_view() const
156 void Session::set_main_bar(std::shared_ptr<pv::toolbars::MainBar> main_bar)
158 main_bar_ = main_bar;
161 shared_ptr<pv::toolbars::MainBar> Session::main_bar() const
166 void Session::save_settings(QSettings &settings) const
168 map<string, string> dev_info;
169 list<string> key_list;
173 shared_ptr<devices::HardwareDevice> hw_device =
174 dynamic_pointer_cast< devices::HardwareDevice >(device_);
177 settings.setValue("device_type", "hardware");
178 settings.beginGroup("device");
180 key_list.push_back("vendor");
181 key_list.push_back("model");
182 key_list.push_back("version");
183 key_list.push_back("serial_num");
184 key_list.push_back("connection_id");
186 dev_info = device_manager_.get_device_info(device_);
188 for (string key : key_list) {
189 if (dev_info.count(key))
190 settings.setValue(QString::fromUtf8(key.c_str()),
191 QString::fromUtf8(dev_info.at(key).c_str()));
193 settings.remove(QString::fromUtf8(key.c_str()));
199 shared_ptr<devices::SessionFile> sessionfile_device =
200 dynamic_pointer_cast< devices::SessionFile >(device_);
202 if (sessionfile_device) {
203 settings.setValue("device_type", "sessionfile");
204 settings.beginGroup("device");
205 settings.setValue("filename", QString::fromStdString(
206 sessionfile_device->full_name()));
210 // Save channels and decoders
211 for (shared_ptr<data::SignalBase> base : signalbases_) {
213 if (base->is_decode_signal()) {
214 shared_ptr<pv::data::DecoderStack> decoder_stack =
215 base->decoder_stack();
216 std::shared_ptr<data::decode::Decoder> top_decoder =
217 decoder_stack->stack().front();
219 settings.beginGroup("decoder_stack" + QString::number(stacks++));
220 settings.setValue("id", top_decoder->decoder()->id);
221 settings.setValue("name", top_decoder->decoder()->name);
226 settings.beginGroup(base->internal_name());
227 base->save_settings(settings);
232 settings.setValue("decoder_stacks", stacks);
236 void Session::restore_settings(QSettings &settings)
238 shared_ptr<devices::Device> device;
240 QString device_type = settings.value("device_type").toString();
242 if (device_type == "hardware") {
243 map<string, string> dev_info;
244 list<string> key_list;
246 // Re-select last used device if possible but only if it's not demo
247 settings.beginGroup("device");
248 key_list.push_back("vendor");
249 key_list.push_back("model");
250 key_list.push_back("version");
251 key_list.push_back("serial_num");
252 key_list.push_back("connection_id");
254 for (string key : key_list) {
255 const QString k = QString::fromStdString(key);
256 if (!settings.contains(k))
259 const string value = settings.value(k).toString().toStdString();
261 dev_info.insert(std::make_pair(key, value));
264 if (dev_info.count("model") > 0)
265 device = device_manager_.find_device_from_info(dev_info);
273 if (device_type == "sessionfile") {
274 settings.beginGroup("device");
275 QString filename = settings.value("filename").toString();
278 if (QFileInfo(filename).isReadable()) {
279 device = std::make_shared<devices::SessionFile>(device_manager_.context(),
280 filename.toStdString());
284 // TODO Perform error handling
285 start_capture([](QString infoMessage) { (void)infoMessage; });
291 for (shared_ptr<data::SignalBase> base : signalbases_) {
292 settings.beginGroup(base->internal_name());
293 base->restore_settings(settings);
299 int stacks = settings.value("decoder_stacks").toInt();
301 for (int i = 0; i < stacks; i++) {
302 settings.beginGroup("decoder_stack" + QString::number(i++));
304 QString id = settings.value("id").toString();
305 add_decoder(srd_decoder_get_by_id(id.toStdString().c_str()));
313 void Session::set_device(shared_ptr<devices::Device> device)
317 // Ensure we are not capturing before setting the device
325 // Revert name back to default name (e.g. "Untitled-1") as the data is gone
326 name_ = default_name_;
329 // Remove all stored data
330 for (std::shared_ptr<pv::view::View> view : views_) {
331 view->clear_signals();
333 view->clear_decode_traces();
336 for (const shared_ptr<data::SignalData> d : all_signal_data_)
338 all_signal_data_.clear();
339 signalbases_.clear();
340 cur_logic_segment_.reset();
342 for (auto entry : cur_analog_segments_) {
343 shared_ptr<sigrok::Channel>(entry.first).reset();
344 shared_ptr<data::AnalogSegment>(entry.second).reset();
351 device_ = std::move(device);
355 } catch (const QString &e) {
361 device_->session()->add_datafeed_callback([=]
362 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
363 data_feed_in(device, packet);
370 void Session::set_default_device()
372 const list< shared_ptr<devices::HardwareDevice> > &devices =
373 device_manager_.devices();
378 // Try and find the demo device and select that by default
379 const auto iter = std::find_if(devices.begin(), devices.end(),
380 [] (const shared_ptr<devices::HardwareDevice> &d) {
381 return d->hardware_device()->driver()->name() ==
383 set_device((iter == devices.end()) ? devices.front() : *iter);
386 Session::capture_state Session::get_capture_state() const
388 lock_guard<mutex> lock(sampling_mutex_);
389 return capture_state_;
392 void Session::start_capture(function<void (const QString)> error_handler)
395 error_handler(tr("No active device set, can't start acquisition."));
401 // Check that at least one channel is enabled
402 const shared_ptr<sigrok::Device> sr_dev = device_->device();
404 const auto channels = sr_dev->channels();
405 if (!std::any_of(channels.begin(), channels.end(),
406 [](shared_ptr<Channel> channel) {
407 return channel->enabled(); })) {
408 error_handler(tr("No channels enabled."));
414 for (const shared_ptr<data::SignalData> d : all_signal_data_)
417 // Revert name back to default name (e.g. "Untitled-1") as the data is gone
418 name_ = default_name_;
422 sampling_thread_ = std::thread(
423 &Session::sample_thread_proc, this, error_handler);
426 void Session::stop_capture()
428 if (get_capture_state() != Stopped)
431 // Check that sampling stopped
432 if (sampling_thread_.joinable())
433 sampling_thread_.join();
436 void Session::register_view(std::shared_ptr<pv::view::View> view)
438 if (views_.empty()) {
445 void Session::deregister_view(std::shared_ptr<pv::view::View> view)
449 if (views_.empty()) {
452 // Without a view there can be no main bar
457 bool Session::has_view(std::shared_ptr<pv::view::View> view)
459 return views_.find(view) != views_.end();
462 double Session::get_samplerate() const
464 double samplerate = 0.0;
466 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
468 const vector< shared_ptr<pv::data::Segment> > segments =
470 for (const shared_ptr<pv::data::Segment> &s : segments)
471 samplerate = std::max(samplerate, s->samplerate());
473 // If there is no sample rate given we use samples as unit
474 if (samplerate == 0.0)
480 const std::unordered_set< std::shared_ptr<data::SignalBase> >
481 Session::signalbases() const
487 bool Session::add_decoder(srd_decoder *const dec)
489 map<const srd_channel*, shared_ptr<data::SignalBase> > channels;
490 shared_ptr<data::DecoderStack> decoder_stack;
493 // Create the decoder
494 decoder_stack = shared_ptr<data::DecoderStack>(
495 new data::DecoderStack(*this, dec));
497 // Make a list of all the channels
498 std::vector<const srd_channel*> all_channels;
499 for (const GSList *i = dec->channels; i; i = i->next)
500 all_channels.push_back((const srd_channel*)i->data);
501 for (const GSList *i = dec->opt_channels; i; i = i->next)
502 all_channels.push_back((const srd_channel*)i->data);
504 // Auto select the initial channels
505 for (const srd_channel *pdch : all_channels)
506 for (shared_ptr<data::SignalBase> b : signalbases_) {
507 if (b->type() == ChannelType::LOGIC) {
508 if (QString::fromUtf8(pdch->name).toLower().
509 contains(b->name().toLower()))
514 assert(decoder_stack);
515 assert(!decoder_stack->stack().empty());
516 assert(decoder_stack->stack().front());
517 decoder_stack->stack().front()->set_channels(channels);
519 // Create the decode signal
520 shared_ptr<data::SignalBase> signalbase =
521 shared_ptr<data::SignalBase>(new data::SignalBase(nullptr));
523 signalbase->set_decoder_stack(decoder_stack);
524 signalbases_.insert(signalbase);
526 for (std::shared_ptr<pv::view::View> view : views_)
527 view->add_decode_trace(signalbase);
528 } catch (std::runtime_error e) {
534 // Do an initial decode
535 decoder_stack->begin_decode();
540 void Session::remove_decode_signal(shared_ptr<data::SignalBase> signalbase)
542 for (std::shared_ptr<pv::view::View> view : views_)
543 view->remove_decode_trace(signalbase);
547 void Session::set_capture_state(capture_state state)
552 lock_guard<mutex> lock(sampling_mutex_);
553 changed = capture_state_ != state;
554 capture_state_ = state;
558 capture_state_changed(state);
561 void Session::update_signals()
564 signalbases_.clear();
566 for (std::shared_ptr<pv::view::View> view : views_) {
567 view->clear_signals();
569 view->clear_decode_traces();
575 lock_guard<recursive_mutex> lock(data_mutex_);
577 const shared_ptr<sigrok::Device> sr_dev = device_->device();
579 signalbases_.clear();
581 for (std::shared_ptr<pv::view::View> view : views_) {
582 view->clear_signals();
584 view->clear_decode_traces();
590 // Detect what data types we will receive
591 auto channels = sr_dev->channels();
592 unsigned int logic_channel_count = std::count_if(
593 channels.begin(), channels.end(),
594 [] (shared_ptr<Channel> channel) {
595 return channel->type() == ChannelType::LOGIC; });
597 // Create data containers for the logic data segments
599 lock_guard<recursive_mutex> data_lock(data_mutex_);
601 if (logic_channel_count == 0) {
603 } else if (!logic_data_ ||
604 logic_data_->num_channels() != logic_channel_count) {
605 logic_data_.reset(new data::Logic(
606 logic_channel_count));
611 // Make the signals list
612 for (std::shared_ptr<pv::view::View> view : views_) {
613 unordered_set< shared_ptr<view::Signal> > prev_sigs(view->signals());
614 view->clear_signals();
616 for (auto channel : sr_dev->channels()) {
617 shared_ptr<data::SignalBase> signalbase;
618 shared_ptr<view::Signal> signal;
620 // Find the channel in the old signals
621 const auto iter = std::find_if(
622 prev_sigs.cbegin(), prev_sigs.cend(),
623 [&](const shared_ptr<view::Signal> &s) {
624 return s->base()->channel() == channel;
626 if (iter != prev_sigs.end()) {
627 // Copy the signal from the old set to the new
630 // Find the signalbase for this channel if possible
632 for (const shared_ptr<data::SignalBase> b : signalbases_)
633 if (b->channel() == channel)
636 switch(channel->type()->id()) {
637 case SR_CHANNEL_LOGIC:
639 signalbase = shared_ptr<data::SignalBase>(
640 new data::SignalBase(channel));
641 signalbases_.insert(signalbase);
643 all_signal_data_.insert(logic_data_);
644 signalbase->set_data(logic_data_);
647 signal = shared_ptr<view::Signal>(
648 new view::LogicSignal(*this,
649 device_, signalbase));
650 view->add_signal(signal);
653 case SR_CHANNEL_ANALOG:
656 signalbase = shared_ptr<data::SignalBase>(
657 new data::SignalBase(channel));
658 signalbases_.insert(signalbase);
660 shared_ptr<data::Analog> data(new data::Analog());
661 all_signal_data_.insert(data);
662 signalbase->set_data(data);
665 signal = shared_ptr<view::Signal>(
666 new view::AnalogSignal(
668 view->add_signal(signal);
683 shared_ptr<data::SignalBase> Session::signalbase_from_channel(
684 shared_ptr<sigrok::Channel> channel) const
686 for (shared_ptr<data::SignalBase> sig : signalbases_) {
688 if (sig->channel() == channel)
691 return shared_ptr<data::SignalBase>();
694 void Session::sample_thread_proc(function<void (const QString)> error_handler)
696 assert(error_handler);
701 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
703 out_of_memory_ = false;
708 error_handler(e.what());
712 set_capture_state(device_->session()->trigger() ?
713 AwaitingTrigger : Running);
716 set_capture_state(Stopped);
718 // Confirm that SR_DF_END was received
719 if (cur_logic_segment_) {
720 qDebug("SR_DF_END was not received.");
725 error_handler(tr("Out of memory, acquisition stopped."));
728 void Session::feed_in_header()
730 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
733 void Session::feed_in_meta(shared_ptr<Meta> meta)
735 for (auto entry : meta->config()) {
736 switch (entry.first->id()) {
737 case SR_CONF_SAMPLERATE:
738 // We can't rely on the header to always contain the sample rate,
739 // so in case it's supplied via a meta packet, we use it.
740 if (!cur_samplerate_)
741 cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
743 /// @todo handle samplerate changes
746 // Unknown metadata is not an error.
754 void Session::feed_in_trigger()
756 // The channel containing most samples should be most accurate
757 uint64_t sample_count = 0;
760 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
762 uint64_t temp_count = 0;
764 const vector< shared_ptr<pv::data::Segment> > segments =
766 for (const shared_ptr<pv::data::Segment> &s : segments)
767 temp_count += s->get_sample_count();
769 if (temp_count > sample_count)
770 sample_count = temp_count;
774 trigger_event(sample_count / get_samplerate());
777 void Session::feed_in_frame_begin()
779 if (cur_logic_segment_ || !cur_analog_segments_.empty())
783 void Session::feed_in_logic(shared_ptr<Logic> logic)
785 lock_guard<recursive_mutex> lock(data_mutex_);
787 const size_t sample_count = logic->data_length() / logic->unit_size();
790 // The only reason logic_data_ would not have been created is
791 // if it was not possible to determine the signals when the
792 // device was created.
796 if (!cur_logic_segment_) {
797 // This could be the first packet after a trigger
798 set_capture_state(Running);
800 // Create a new data segment
801 cur_logic_segment_ = shared_ptr<data::LogicSegment>(
802 new data::LogicSegment(
803 logic, cur_samplerate_, sample_count));
804 logic_data_->push_segment(cur_logic_segment_);
806 // @todo Putting this here means that only listeners querying
807 // for logic will be notified. Currently the only user of
808 // frame_began is DecoderStack, but in future we need to signal
809 // this after both analog and logic sweeps have begun.
812 // Append to the existing data segment
813 cur_logic_segment_->append_payload(logic);
819 void Session::feed_in_analog(shared_ptr<Analog> analog)
821 lock_guard<recursive_mutex> lock(data_mutex_);
823 const vector<shared_ptr<Channel>> channels = analog->channels();
824 const unsigned int channel_count = channels.size();
825 const size_t sample_count = analog->num_samples() / channel_count;
826 const float *data = static_cast<const float *>(analog->data_pointer());
827 bool sweep_beginning = false;
829 if (signalbases_.empty())
832 for (auto channel : channels) {
833 shared_ptr<data::AnalogSegment> segment;
835 // Try to get the segment of the channel
836 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
837 iterator iter = cur_analog_segments_.find(channel);
838 if (iter != cur_analog_segments_.end())
839 segment = (*iter).second;
841 // If no segment was found, this means we haven't
842 // created one yet. i.e. this is the first packet
843 // in the sweep containing this segment.
844 sweep_beginning = true;
846 // Create a segment, keep it in the maps of channels
847 segment = shared_ptr<data::AnalogSegment>(
848 new data::AnalogSegment(
849 cur_samplerate_, sample_count));
850 cur_analog_segments_[channel] = segment;
852 // Find the analog data associated with the channel
853 shared_ptr<data::SignalBase> base = signalbase_from_channel(channel);
856 shared_ptr<data::Analog> data(base->analog_data());
859 // Push the segment into the analog data.
860 data->push_segment(segment);
865 // Append the samples in the segment
866 segment->append_interleaved_samples(data++, sample_count,
870 if (sweep_beginning) {
871 // This could be the first packet after a trigger
872 set_capture_state(Running);
878 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
879 shared_ptr<Packet> packet)
884 assert(device == device_->device());
887 switch (packet->type()->id()) {
893 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
900 case SR_DF_FRAME_BEGIN:
901 feed_in_frame_begin();
906 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
907 } catch (std::bad_alloc) {
908 out_of_memory_ = true;
915 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
916 } catch (std::bad_alloc) {
917 out_of_memory_ = true;
925 lock_guard<recursive_mutex> lock(data_mutex_);
926 cur_logic_segment_.reset();
927 cur_analog_segments_.clear();