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>
30 #include <libsigrokdecode/libsigrokdecode.h>
33 #include "session.hpp"
35 #include "devicemanager.hpp"
37 #include "data/analog.hpp"
38 #include "data/analogsegment.hpp"
39 #include "data/decoderstack.hpp"
40 #include "data/logic.hpp"
41 #include "data/logicsegment.hpp"
42 #include "data/signalbase.hpp"
43 #include "data/decode/decoder.hpp"
45 #include "devices/hardwaredevice.hpp"
46 #include "devices/sessionfile.hpp"
48 #include "toolbars/mainbar.hpp"
50 #include "view/analogsignal.hpp"
51 #include "view/decodetrace.hpp"
52 #include "view/logicsignal.hpp"
53 #include "view/signal.hpp"
54 #include "view/view.hpp"
64 #include <libsigrokcxx/libsigrokcxx.hpp>
66 using boost::shared_lock;
67 using boost::shared_mutex;
68 using boost::unique_lock;
70 using std::dynamic_pointer_cast;
72 using std::lock_guard;
76 using std::recursive_mutex;
78 using std::shared_ptr;
80 using std::unordered_set;
84 using sigrok::Channel;
85 using sigrok::ChannelType;
86 using sigrok::ConfigKey;
87 using sigrok::DatafeedCallbackFunction;
93 using sigrok::PacketPayload;
94 using sigrok::Session;
95 using sigrok::SessionDevice;
97 using Glib::VariantBase;
101 Session::Session(DeviceManager &device_manager, QString name) :
102 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 std::shared_ptr<pv::view::View> Session::main_view() const
157 void Session::set_main_bar(std::shared_ptr<pv::toolbars::MainBar> main_bar)
159 main_bar_ = main_bar;
162 shared_ptr<pv::toolbars::MainBar> Session::main_bar() const
167 void Session::save_settings(QSettings &settings) const
169 map<string, string> dev_info;
170 list<string> key_list;
173 settings.beginGroup("Device");
174 key_list.push_back("vendor");
175 key_list.push_back("model");
176 key_list.push_back("version");
177 key_list.push_back("serial_num");
178 key_list.push_back("connection_id");
180 dev_info = device_manager_.get_device_info(device_);
182 for (string key : key_list) {
183 if (dev_info.count(key))
184 settings.setValue(QString::fromUtf8(key.c_str()),
185 QString::fromUtf8(dev_info.at(key).c_str()));
187 settings.remove(QString::fromUtf8(key.c_str()));
190 // TODO Save channel settings and decoders
196 void Session::restore_settings(QSettings &settings)
198 map<string, string> dev_info;
199 list<string> key_list;
200 shared_ptr<devices::HardwareDevice> device;
202 // Re-select last used device if possible but only if it's not demo
203 settings.beginGroup("Device");
204 key_list.push_back("vendor");
205 key_list.push_back("model");
206 key_list.push_back("version");
207 key_list.push_back("serial_num");
208 key_list.push_back("connection_id");
210 for (string key : key_list) {
211 const QString k = QString::fromStdString(key);
212 if (!settings.contains(k))
215 const string value = settings.value(k).toString().toStdString();
217 dev_info.insert(std::make_pair(key, value));
220 if (dev_info.count("model") > 0)
221 device = device_manager_.find_device_from_info(dev_info);
226 // TODO Restore channel settings and decoders
232 void Session::set_device(shared_ptr<devices::Device> device)
236 // Ensure we are not capturing before setting the device
244 // Revert name back to default name (e.g. "Untitled-1") as the data is gone
245 name_ = default_name_;
248 // Remove all stored data
249 for (std::shared_ptr<pv::view::View> view : views_) {
250 view->clear_signals();
252 view->clear_decode_traces();
255 for (const shared_ptr<data::SignalData> d : all_signal_data_)
257 all_signal_data_.clear();
258 signalbases_.clear();
259 cur_logic_segment_.reset();
261 for (auto entry : cur_analog_segments_) {
262 shared_ptr<sigrok::Channel>(entry.first).reset();
263 shared_ptr<data::AnalogSegment>(entry.second).reset();
270 device_ = std::move(device);
274 } catch (const QString &e) {
280 device_->session()->add_datafeed_callback([=]
281 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
282 data_feed_in(device, packet);
289 void Session::set_default_device()
291 const list< shared_ptr<devices::HardwareDevice> > &devices =
292 device_manager_.devices();
297 // Try and find the demo device and select that by default
298 const auto iter = std::find_if(devices.begin(), devices.end(),
299 [] (const shared_ptr<devices::HardwareDevice> &d) {
300 return d->hardware_device()->driver()->name() ==
302 set_device((iter == devices.end()) ? devices.front() : *iter);
305 Session::capture_state Session::get_capture_state() const
307 lock_guard<mutex> lock(sampling_mutex_);
308 return capture_state_;
311 void Session::start_capture(function<void (const QString)> error_handler)
314 error_handler(tr("No active device set, can't start acquisition."));
320 // Check that at least one channel is enabled
321 const shared_ptr<sigrok::Device> sr_dev = device_->device();
323 const auto channels = sr_dev->channels();
324 if (!std::any_of(channels.begin(), channels.end(),
325 [](shared_ptr<Channel> channel) {
326 return channel->enabled(); })) {
327 error_handler(tr("No channels enabled."));
333 for (const shared_ptr<data::SignalData> d : all_signal_data_)
336 // Revert name back to default name (e.g. "Untitled-1") as the data is gone
337 name_ = default_name_;
341 sampling_thread_ = std::thread(
342 &Session::sample_thread_proc, this, error_handler);
345 void Session::stop_capture()
347 if (get_capture_state() != Stopped)
350 // Check that sampling stopped
351 if (sampling_thread_.joinable())
352 sampling_thread_.join();
355 void Session::register_view(std::shared_ptr<pv::view::View> view)
357 if (views_.empty()) {
364 void Session::deregister_view(std::shared_ptr<pv::view::View> view)
368 if (views_.empty()) {
371 // Without a view there can be no main bar
376 bool Session::has_view(std::shared_ptr<pv::view::View> view)
378 return views_.find(view) != views_.end();
381 double Session::get_samplerate() const
383 double samplerate = 0.0;
385 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
387 const vector< shared_ptr<pv::data::Segment> > segments =
389 for (const shared_ptr<pv::data::Segment> &s : segments)
390 samplerate = std::max(samplerate, s->samplerate());
392 // If there is no sample rate given we use samples as unit
393 if (samplerate == 0.0)
399 const std::unordered_set< std::shared_ptr<data::SignalBase> >
400 Session::signalbases() const
406 bool Session::add_decoder(srd_decoder *const dec)
408 map<const srd_channel*, shared_ptr<data::SignalBase> > channels;
409 shared_ptr<data::DecoderStack> decoder_stack;
412 // Create the decoder
413 decoder_stack = shared_ptr<data::DecoderStack>(
414 new data::DecoderStack(*this, dec));
416 // Make a list of all the channels
417 std::vector<const srd_channel*> all_channels;
418 for (const GSList *i = dec->channels; i; i = i->next)
419 all_channels.push_back((const srd_channel*)i->data);
420 for (const GSList *i = dec->opt_channels; i; i = i->next)
421 all_channels.push_back((const srd_channel*)i->data);
423 // Auto select the initial channels
424 for (const srd_channel *pdch : all_channels)
425 for (shared_ptr<data::SignalBase> b : signalbases_) {
426 if (b->type() == ChannelType::LOGIC) {
427 if (QString::fromUtf8(pdch->name).toLower().
428 contains(b->name().toLower()))
433 assert(decoder_stack);
434 assert(!decoder_stack->stack().empty());
435 assert(decoder_stack->stack().front());
436 decoder_stack->stack().front()->set_channels(channels);
438 // Create the decode signal
439 shared_ptr<data::SignalBase> signalbase =
440 shared_ptr<data::SignalBase>(new data::SignalBase(nullptr));
442 signalbase->set_decoder_stack(decoder_stack);
444 for (std::shared_ptr<pv::view::View> view : views_)
445 view->add_decode_trace(signalbase);
446 } catch (std::runtime_error e) {
452 // Do an initial decode
453 decoder_stack->begin_decode();
458 void Session::remove_decode_signal(shared_ptr<data::SignalBase> signalbase)
460 for (std::shared_ptr<pv::view::View> view : views_)
461 view->remove_decode_trace(signalbase);
465 void Session::set_capture_state(capture_state state)
470 lock_guard<mutex> lock(sampling_mutex_);
471 changed = capture_state_ != state;
472 capture_state_ = state;
476 capture_state_changed(state);
479 void Session::update_signals()
482 signalbases_.clear();
484 for (std::shared_ptr<pv::view::View> view : views_) {
485 view->clear_signals();
487 view->clear_decode_traces();
493 lock_guard<recursive_mutex> lock(data_mutex_);
495 const shared_ptr<sigrok::Device> sr_dev = device_->device();
497 signalbases_.clear();
499 for (std::shared_ptr<pv::view::View> view : views_) {
500 view->clear_signals();
502 view->clear_decode_traces();
508 // Detect what data types we will receive
509 auto channels = sr_dev->channels();
510 unsigned int logic_channel_count = std::count_if(
511 channels.begin(), channels.end(),
512 [] (shared_ptr<Channel> channel) {
513 return channel->type() == ChannelType::LOGIC; });
515 // Create data containers for the logic data segments
517 lock_guard<recursive_mutex> data_lock(data_mutex_);
519 if (logic_channel_count == 0) {
521 } else if (!logic_data_ ||
522 logic_data_->num_channels() != logic_channel_count) {
523 logic_data_.reset(new data::Logic(
524 logic_channel_count));
529 // Make the signals list
530 for (std::shared_ptr<pv::view::View> view : views_) {
531 unordered_set< shared_ptr<view::Signal> > prev_sigs(view->signals());
532 view->clear_signals();
534 for (auto channel : sr_dev->channels()) {
535 shared_ptr<data::SignalBase> signalbase;
536 shared_ptr<view::Signal> signal;
538 // Find the channel in the old signals
539 const auto iter = std::find_if(
540 prev_sigs.cbegin(), prev_sigs.cend(),
541 [&](const shared_ptr<view::Signal> &s) {
542 return s->base()->channel() == channel;
544 if (iter != prev_sigs.end()) {
545 // Copy the signal from the old set to the new
548 // Find the signalbase for this channel if possible
550 for (const shared_ptr<data::SignalBase> b : signalbases_)
551 if (b->channel() == channel)
554 switch(channel->type()->id()) {
555 case SR_CHANNEL_LOGIC:
557 signalbase = shared_ptr<data::SignalBase>(
558 new data::SignalBase(channel));
559 signalbases_.insert(signalbase);
561 all_signal_data_.insert(logic_data_);
562 signalbase->set_data(logic_data_);
565 signal = shared_ptr<view::Signal>(
566 new view::LogicSignal(*this,
567 device_, signalbase));
568 view->add_signal(signal);
571 case SR_CHANNEL_ANALOG:
574 signalbase = shared_ptr<data::SignalBase>(
575 new data::SignalBase(channel));
576 signalbases_.insert(signalbase);
578 shared_ptr<data::Analog> data(new data::Analog());
579 all_signal_data_.insert(data);
580 signalbase->set_data(data);
583 signal = shared_ptr<view::Signal>(
584 new view::AnalogSignal(
586 view->add_signal(signal);
601 shared_ptr<data::SignalBase> Session::signalbase_from_channel(
602 shared_ptr<sigrok::Channel> channel) const
604 for (shared_ptr<data::SignalBase> sig : signalbases_) {
606 if (sig->channel() == channel)
609 return shared_ptr<data::SignalBase>();
612 void Session::sample_thread_proc(function<void (const QString)> error_handler)
614 assert(error_handler);
619 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
621 out_of_memory_ = false;
626 error_handler(e.what());
630 set_capture_state(device_->session()->trigger() ?
631 AwaitingTrigger : Running);
634 set_capture_state(Stopped);
636 // Confirm that SR_DF_END was received
637 if (cur_logic_segment_) {
638 qDebug("SR_DF_END was not received.");
643 error_handler(tr("Out of memory, acquisition stopped."));
646 void Session::feed_in_header()
648 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
651 void Session::feed_in_meta(shared_ptr<Meta> meta)
653 for (auto entry : meta->config()) {
654 switch (entry.first->id()) {
655 case SR_CONF_SAMPLERATE:
656 // We can't rely on the header to always contain the sample rate,
657 // so in case it's supplied via a meta packet, we use it.
658 if (!cur_samplerate_)
659 cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
661 /// @todo handle samplerate changes
664 // Unknown metadata is not an error.
672 void Session::feed_in_trigger()
674 // The channel containing most samples should be most accurate
675 uint64_t sample_count = 0;
678 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
680 uint64_t temp_count = 0;
682 const vector< shared_ptr<pv::data::Segment> > segments =
684 for (const shared_ptr<pv::data::Segment> &s : segments)
685 temp_count += s->get_sample_count();
687 if (temp_count > sample_count)
688 sample_count = temp_count;
692 trigger_event(sample_count / get_samplerate());
695 void Session::feed_in_frame_begin()
697 if (cur_logic_segment_ || !cur_analog_segments_.empty())
701 void Session::feed_in_logic(shared_ptr<Logic> logic)
703 lock_guard<recursive_mutex> lock(data_mutex_);
705 const size_t sample_count = logic->data_length() / logic->unit_size();
708 // The only reason logic_data_ would not have been created is
709 // if it was not possible to determine the signals when the
710 // device was created.
714 if (!cur_logic_segment_) {
715 // This could be the first packet after a trigger
716 set_capture_state(Running);
718 // Create a new data segment
719 cur_logic_segment_ = shared_ptr<data::LogicSegment>(
720 new data::LogicSegment(
721 logic, cur_samplerate_, sample_count));
722 logic_data_->push_segment(cur_logic_segment_);
724 // @todo Putting this here means that only listeners querying
725 // for logic will be notified. Currently the only user of
726 // frame_began is DecoderStack, but in future we need to signal
727 // this after both analog and logic sweeps have begun.
730 // Append to the existing data segment
731 cur_logic_segment_->append_payload(logic);
737 void Session::feed_in_analog(shared_ptr<Analog> analog)
739 lock_guard<recursive_mutex> lock(data_mutex_);
741 const vector<shared_ptr<Channel>> channels = analog->channels();
742 const unsigned int channel_count = channels.size();
743 const size_t sample_count = analog->num_samples() / channel_count;
744 const float *data = static_cast<const float *>(analog->data_pointer());
745 bool sweep_beginning = false;
747 if (signalbases_.empty())
750 for (auto channel : channels) {
751 shared_ptr<data::AnalogSegment> segment;
753 // Try to get the segment of the channel
754 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
755 iterator iter = cur_analog_segments_.find(channel);
756 if (iter != cur_analog_segments_.end())
757 segment = (*iter).second;
759 // If no segment was found, this means we haven't
760 // created one yet. i.e. this is the first packet
761 // in the sweep containing this segment.
762 sweep_beginning = true;
764 // Create a segment, keep it in the maps of channels
765 segment = shared_ptr<data::AnalogSegment>(
766 new data::AnalogSegment(
767 cur_samplerate_, sample_count));
768 cur_analog_segments_[channel] = segment;
770 // Find the analog data associated with the channel
771 shared_ptr<data::SignalBase> base = signalbase_from_channel(channel);
774 shared_ptr<data::Analog> data(base->analog_data());
777 // Push the segment into the analog data.
778 data->push_segment(segment);
783 // Append the samples in the segment
784 segment->append_interleaved_samples(data++, sample_count,
788 if (sweep_beginning) {
789 // This could be the first packet after a trigger
790 set_capture_state(Running);
796 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
797 shared_ptr<Packet> packet)
802 assert(device == device_->device());
805 switch (packet->type()->id()) {
811 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
818 case SR_DF_FRAME_BEGIN:
819 feed_in_frame_begin();
824 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
825 } catch (std::bad_alloc) {
826 out_of_memory_ = true;
833 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
834 } catch (std::bad_alloc) {
835 out_of_memory_ = true;
843 lock_guard<recursive_mutex> lock(data_mutex_);
844 cur_logic_segment_.reset();
845 cur_analog_segments_.clear();