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 "view/analogsignal.hpp"
49 #include "view/decodetrace.hpp"
50 #include "view/logicsignal.hpp"
51 #include "view/signal.hpp"
52 #include "view/view.hpp"
62 #include <libsigrokcxx/libsigrokcxx.hpp>
64 using boost::shared_lock;
65 using boost::shared_mutex;
66 using boost::unique_lock;
68 using std::dynamic_pointer_cast;
70 using std::lock_guard;
74 using std::recursive_mutex;
76 using std::shared_ptr;
78 using std::unordered_set;
82 using sigrok::Channel;
83 using sigrok::ChannelType;
84 using sigrok::ConfigKey;
85 using sigrok::DatafeedCallbackFunction;
91 using sigrok::PacketPayload;
92 using sigrok::Session;
93 using sigrok::SessionDevice;
95 using Glib::VariantBase;
99 Session::Session(DeviceManager &device_manager) :
100 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 void Session::set_device(shared_ptr<devices::Device> device)
138 // Ensure we are not capturing before setting the device
146 // Remove all stored data
147 for (std::shared_ptr<pv::view::View> view : views_)
148 view->clear_signals();
149 for (const shared_ptr<data::SignalData> d : all_signal_data_)
151 all_signal_data_.clear();
152 signalbases_.clear();
153 cur_logic_segment_.reset();
155 for (auto entry : cur_analog_segments_) {
156 shared_ptr<sigrok::Channel>(entry.first).reset();
157 shared_ptr<data::AnalogSegment>(entry.second).reset();
161 decode_traces_.clear();
165 device_ = std::move(device);
169 } catch (const QString &e) {
175 device_->session()->add_datafeed_callback([=]
176 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
177 data_feed_in(device, packet);
184 void Session::set_default_device()
186 const list< shared_ptr<devices::HardwareDevice> > &devices =
187 device_manager_.devices();
192 // Try and find the demo device and select that by default
193 const auto iter = std::find_if(devices.begin(), devices.end(),
194 [] (const shared_ptr<devices::HardwareDevice> &d) {
195 return d->hardware_device()->driver()->name() ==
197 set_device((iter == devices.end()) ? devices.front() : *iter);
200 Session::capture_state Session::get_capture_state() const
202 lock_guard<mutex> lock(sampling_mutex_);
203 return capture_state_;
206 void Session::start_capture(function<void (const QString)> error_handler)
209 error_handler(tr("No active device set, can't start acquisition."));
215 // Check that at least one channel is enabled
216 const shared_ptr<sigrok::Device> sr_dev = device_->device();
218 const auto channels = sr_dev->channels();
219 if (!std::any_of(channels.begin(), channels.end(),
220 [](shared_ptr<Channel> channel) {
221 return channel->enabled(); })) {
222 error_handler(tr("No channels enabled."));
228 for (const shared_ptr<data::SignalData> d : all_signal_data_)
232 sampling_thread_ = std::thread(
233 &Session::sample_thread_proc, this, error_handler);
236 void Session::stop_capture()
238 if (get_capture_state() != Stopped)
241 // Check that sampling stopped
242 if (sampling_thread_.joinable())
243 sampling_thread_.join();
246 void Session::register_view(std::shared_ptr<pv::view::View> view)
251 void Session::deregister_view(std::shared_ptr<pv::view::View> view)
256 double Session::get_samplerate() const
258 double samplerate = 0.0;
260 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
262 const vector< shared_ptr<pv::data::Segment> > segments =
264 for (const shared_ptr<pv::data::Segment> &s : segments)
265 samplerate = std::max(samplerate, s->samplerate());
267 // If there is no sample rate given we use samples as unit
268 if (samplerate == 0.0)
274 const std::unordered_set< std::shared_ptr<data::SignalBase> >
275 Session::signalbases() const
281 bool Session::add_decoder(srd_decoder *const dec)
283 map<const srd_channel*, shared_ptr<data::SignalBase> > channels;
284 shared_ptr<data::DecoderStack> decoder_stack;
287 // Create the decoder
288 decoder_stack = shared_ptr<data::DecoderStack>(
289 new data::DecoderStack(*this, dec));
291 // Make a list of all the channels
292 std::vector<const srd_channel*> all_channels;
293 for (const GSList *i = dec->channels; i; i = i->next)
294 all_channels.push_back((const srd_channel*)i->data);
295 for (const GSList *i = dec->opt_channels; i; i = i->next)
296 all_channels.push_back((const srd_channel*)i->data);
298 // Auto select the initial channels
299 for (const srd_channel *pdch : all_channels)
300 for (shared_ptr<data::SignalBase> b : signalbases_) {
301 if (b->type() == ChannelType::LOGIC) {
302 if (QString::fromUtf8(pdch->name).toLower().
303 contains(b->name().toLower()))
308 assert(decoder_stack);
309 assert(!decoder_stack->stack().empty());
310 assert(decoder_stack->stack().front());
311 decoder_stack->stack().front()->set_channels(channels);
313 // Create the decode signal
314 shared_ptr<data::SignalBase> signalbase =
315 shared_ptr<data::SignalBase>(new data::SignalBase(nullptr));
317 shared_ptr<view::DecodeTrace> d(
318 new view::DecodeTrace(*this, signalbase, decoder_stack,
319 decode_traces_.size()));
320 decode_traces_.push_back(d);
321 } catch (std::runtime_error e) {
327 // Do an initial decode
328 decoder_stack->begin_decode();
333 vector< shared_ptr<view::DecodeTrace> > Session::get_decode_signals() const
335 return decode_traces_;
338 void Session::remove_decode_signal(view::DecodeTrace *signal)
340 for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
341 if ((*i).get() == signal) {
342 decode_traces_.erase(i);
349 void Session::set_capture_state(capture_state state)
354 lock_guard<mutex> lock(sampling_mutex_);
355 changed = capture_state_ != state;
356 capture_state_ = state;
360 capture_state_changed(state);
363 void Session::update_signals()
366 signalbases_.clear();
368 for (std::shared_ptr<pv::view::View> view : views_)
369 view->clear_signals();
373 lock_guard<recursive_mutex> lock(data_mutex_);
375 const shared_ptr<sigrok::Device> sr_dev = device_->device();
377 signalbases_.clear();
379 for (std::shared_ptr<pv::view::View> view : views_)
380 view->clear_signals();
384 // Detect what data types we will receive
385 auto channels = sr_dev->channels();
386 unsigned int logic_channel_count = std::count_if(
387 channels.begin(), channels.end(),
388 [] (shared_ptr<Channel> channel) {
389 return channel->type() == ChannelType::LOGIC; });
391 // Create data containers for the logic data segments
393 lock_guard<recursive_mutex> data_lock(data_mutex_);
395 if (logic_channel_count == 0) {
397 } else if (!logic_data_ ||
398 logic_data_->num_channels() != logic_channel_count) {
399 logic_data_.reset(new data::Logic(
400 logic_channel_count));
405 // Make the signals list
406 for (std::shared_ptr<pv::view::View> view : views_) {
407 unordered_set< shared_ptr<view::Signal> > prev_sigs(view->signals());
408 view->clear_signals();
410 for (auto channel : sr_dev->channels()) {
411 shared_ptr<data::SignalBase> signalbase;
412 shared_ptr<view::Signal> signal;
414 // Find the channel in the old signals
415 const auto iter = std::find_if(
416 prev_sigs.cbegin(), prev_sigs.cend(),
417 [&](const shared_ptr<view::Signal> &s) {
418 return s->base()->channel() == channel;
420 if (iter != prev_sigs.end()) {
421 // Copy the signal from the old set to the new
424 // Find the signalbase for this channel if possible
426 for (const shared_ptr<data::SignalBase> b : signalbases_)
427 if (b->channel() == channel)
430 switch(channel->type()->id()) {
431 case SR_CHANNEL_LOGIC:
433 signalbase = shared_ptr<data::SignalBase>(
434 new data::SignalBase(channel));
435 signalbases_.insert(signalbase);
437 all_signal_data_.insert(logic_data_);
438 signalbase->set_data(logic_data_);
441 signal = shared_ptr<view::Signal>(
442 new view::LogicSignal(*this,
443 device_, signalbase));
444 view->add_signal(signal);
447 case SR_CHANNEL_ANALOG:
450 signalbase = shared_ptr<data::SignalBase>(
451 new data::SignalBase(channel));
452 signalbases_.insert(signalbase);
454 shared_ptr<data::Analog> data(new data::Analog());
455 all_signal_data_.insert(data);
456 signalbase->set_data(data);
459 signal = shared_ptr<view::Signal>(
460 new view::AnalogSignal(
462 view->add_signal(signal);
477 shared_ptr<data::SignalBase> Session::signalbase_from_channel(
478 shared_ptr<sigrok::Channel> channel) const
480 for (shared_ptr<data::SignalBase> sig : signalbases_) {
482 if (sig->channel() == channel)
485 return shared_ptr<data::SignalBase>();
488 void Session::sample_thread_proc(function<void (const QString)> error_handler)
490 assert(error_handler);
495 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
497 out_of_memory_ = false;
502 error_handler(e.what());
506 set_capture_state(device_->session()->trigger() ?
507 AwaitingTrigger : Running);
510 set_capture_state(Stopped);
512 // Confirm that SR_DF_END was received
513 if (cur_logic_segment_) {
514 qDebug("SR_DF_END was not received.");
519 error_handler(tr("Out of memory, acquisition stopped."));
522 void Session::feed_in_header()
524 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
527 void Session::feed_in_meta(shared_ptr<Meta> meta)
529 for (auto entry : meta->config()) {
530 switch (entry.first->id()) {
531 case SR_CONF_SAMPLERATE:
532 // We can't rely on the header to always contain the sample rate,
533 // so in case it's supplied via a meta packet, we use it.
534 if (!cur_samplerate_)
535 cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
537 /// @todo handle samplerate changes
540 // Unknown metadata is not an error.
548 void Session::feed_in_trigger()
550 // The channel containing most samples should be most accurate
551 uint64_t sample_count = 0;
554 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
556 uint64_t temp_count = 0;
558 const vector< shared_ptr<pv::data::Segment> > segments =
560 for (const shared_ptr<pv::data::Segment> &s : segments)
561 temp_count += s->get_sample_count();
563 if (temp_count > sample_count)
564 sample_count = temp_count;
568 trigger_event(sample_count / get_samplerate());
571 void Session::feed_in_frame_begin()
573 if (cur_logic_segment_ || !cur_analog_segments_.empty())
577 void Session::feed_in_logic(shared_ptr<Logic> logic)
579 lock_guard<recursive_mutex> lock(data_mutex_);
581 const size_t sample_count = logic->data_length() / logic->unit_size();
584 // The only reason logic_data_ would not have been created is
585 // if it was not possible to determine the signals when the
586 // device was created.
590 if (!cur_logic_segment_) {
591 // This could be the first packet after a trigger
592 set_capture_state(Running);
594 // Create a new data segment
595 cur_logic_segment_ = shared_ptr<data::LogicSegment>(
596 new data::LogicSegment(
597 logic, cur_samplerate_, sample_count));
598 logic_data_->push_segment(cur_logic_segment_);
600 // @todo Putting this here means that only listeners querying
601 // for logic will be notified. Currently the only user of
602 // frame_began is DecoderStack, but in future we need to signal
603 // this after both analog and logic sweeps have begun.
606 // Append to the existing data segment
607 cur_logic_segment_->append_payload(logic);
613 void Session::feed_in_analog(shared_ptr<Analog> analog)
615 lock_guard<recursive_mutex> lock(data_mutex_);
617 const vector<shared_ptr<Channel>> channels = analog->channels();
618 const unsigned int channel_count = channels.size();
619 const size_t sample_count = analog->num_samples() / channel_count;
620 const float *data = static_cast<const float *>(analog->data_pointer());
621 bool sweep_beginning = false;
623 if (signalbases_.empty())
626 for (auto channel : channels) {
627 shared_ptr<data::AnalogSegment> segment;
629 // Try to get the segment of the channel
630 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
631 iterator iter = cur_analog_segments_.find(channel);
632 if (iter != cur_analog_segments_.end())
633 segment = (*iter).second;
635 // If no segment was found, this means we haven't
636 // created one yet. i.e. this is the first packet
637 // in the sweep containing this segment.
638 sweep_beginning = true;
640 // Create a segment, keep it in the maps of channels
641 segment = shared_ptr<data::AnalogSegment>(
642 new data::AnalogSegment(
643 cur_samplerate_, sample_count));
644 cur_analog_segments_[channel] = segment;
646 // Find the analog data associated with the channel
647 shared_ptr<data::SignalBase> base = signalbase_from_channel(channel);
650 shared_ptr<data::Analog> data(base->analog_data());
653 // Push the segment into the analog data.
654 data->push_segment(segment);
659 // Append the samples in the segment
660 segment->append_interleaved_samples(data++, sample_count,
664 if (sweep_beginning) {
665 // This could be the first packet after a trigger
666 set_capture_state(Running);
672 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
673 shared_ptr<Packet> packet)
678 assert(device == device_->device());
681 switch (packet->type()->id()) {
687 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
694 case SR_DF_FRAME_BEGIN:
695 feed_in_frame_begin();
700 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
701 } catch (std::bad_alloc) {
702 out_of_memory_ = true;
709 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
710 } catch (std::bad_alloc) {
711 out_of_memory_ = true;
719 lock_guard<recursive_mutex> lock(data_mutex_);
720 cur_logic_segment_.reset();
721 cur_analog_segments_.clear();