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/decode/decoder.hpp"
44 #include "devices/hardwaredevice.hpp"
45 #include "devices/sessionfile.hpp"
47 #include "view/analogsignal.hpp"
48 #include "view/decodetrace.hpp"
49 #include "view/logicsignal.hpp"
59 #include <libsigrokcxx/libsigrokcxx.hpp>
61 using boost::shared_lock;
62 using boost::shared_mutex;
63 using boost::unique_lock;
65 using std::dynamic_pointer_cast;
67 using std::lock_guard;
71 using std::recursive_mutex;
73 using std::shared_ptr;
75 using std::unordered_set;
79 using sigrok::Channel;
80 using sigrok::ChannelType;
81 using sigrok::ConfigKey;
82 using sigrok::DatafeedCallbackFunction;
88 using sigrok::PacketPayload;
89 using sigrok::Session;
90 using sigrok::SessionDevice;
92 using Glib::VariantBase;
96 Session::Session(DeviceManager &device_manager) :
97 device_manager_(device_manager),
98 capture_state_(Stopped),
105 // Stop and join to the thread
109 DeviceManager& Session::device_manager()
111 return device_manager_;
114 const DeviceManager& Session::device_manager() const
116 return device_manager_;
119 shared_ptr<sigrok::Session> Session::session() const
122 return shared_ptr<sigrok::Session>();
123 return device_->session();
126 shared_ptr<devices::Device> Session::device() const
131 void Session::set_device(shared_ptr<devices::Device> device)
135 // Ensure we are not capturing before setting the device
143 // Remove all stored data
146 shared_lock<shared_mutex> lock(signals_mutex_);
147 for (const shared_ptr<data::SignalData> d : all_signal_data_)
150 all_signal_data_.clear();
151 cur_logic_segment_.reset();
153 for (auto entry : cur_analog_segments_) {
154 shared_ptr<sigrok::Channel>(entry.first).reset();
155 shared_ptr<data::AnalogSegment>(entry.second).reset();
159 decode_traces_.clear();
163 device_ = std::move(device);
167 } catch (const QString &e) {
173 device_->session()->add_datafeed_callback([=]
174 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
175 data_feed_in(device, packet);
182 void Session::set_default_device()
184 const list< shared_ptr<devices::HardwareDevice> > &devices =
185 device_manager_.devices();
190 // Try and find the demo device and select that by default
191 const auto iter = std::find_if(devices.begin(), devices.end(),
192 [] (const shared_ptr<devices::HardwareDevice> &d) {
193 return d->hardware_device()->driver()->name() ==
195 set_device((iter == devices.end()) ? devices.front() : *iter);
198 Session::capture_state Session::get_capture_state() const
200 lock_guard<mutex> lock(sampling_mutex_);
201 return capture_state_;
204 void Session::start_capture(function<void (const QString)> error_handler)
207 error_handler(tr("No active device set, can't start acquisition."));
213 // Check that at least one channel is enabled
214 const shared_ptr<sigrok::Device> sr_dev = device_->device();
216 const auto channels = sr_dev->channels();
217 if (!std::any_of(channels.begin(), channels.end(),
218 [](shared_ptr<Channel> channel) {
219 return channel->enabled(); })) {
220 error_handler(tr("No channels enabled."));
227 shared_lock<shared_mutex> lock(signals_mutex_);
228 for (const shared_ptr<data::SignalData> d : all_signal_data_)
233 sampling_thread_ = std::thread(
234 &Session::sample_thread_proc, this, error_handler);
237 void Session::stop_capture()
239 if (get_capture_state() != Stopped)
242 // Check that sampling stopped
243 if (sampling_thread_.joinable())
244 sampling_thread_.join();
247 double Session::get_samplerate() const
249 double samplerate = 0.0;
252 shared_lock<shared_mutex> lock(signals_mutex_);
253 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
255 const vector< shared_ptr<pv::data::Segment> > segments =
257 for (const shared_ptr<pv::data::Segment> &s : segments)
258 samplerate = std::max(samplerate, s->samplerate());
261 // If there is no sample rate given we use samples as unit
262 if (samplerate == 0.0)
268 const unordered_set< shared_ptr<view::Signal> > Session::signals() const
270 shared_lock<shared_mutex> lock(signals_mutex_);
275 bool Session::add_decoder(srd_decoder *const dec)
277 map<const srd_channel*, shared_ptr<view::LogicSignal> > channels;
278 shared_ptr<data::DecoderStack> decoder_stack;
281 lock_guard<boost::shared_mutex> lock(signals_mutex_);
283 // Create the decoder
284 decoder_stack = shared_ptr<data::DecoderStack>(
285 new data::DecoderStack(*this, dec));
287 // Make a list of all the channels
288 std::vector<const srd_channel*> all_channels;
289 for (const GSList *i = dec->channels; i; i = i->next)
290 all_channels.push_back((const srd_channel*)i->data);
291 for (const GSList *i = dec->opt_channels; i; i = i->next)
292 all_channels.push_back((const srd_channel*)i->data);
294 // Auto select the initial channels
295 for (const srd_channel *pdch : all_channels)
296 for (shared_ptr<view::Signal> s : signals_) {
297 shared_ptr<view::LogicSignal> l =
298 dynamic_pointer_cast<view::LogicSignal>(s);
299 if (l && QString::fromUtf8(pdch->name).
301 l->name().toLower()))
305 assert(decoder_stack);
306 assert(!decoder_stack->stack().empty());
307 assert(decoder_stack->stack().front());
308 decoder_stack->stack().front()->set_channels(channels);
310 // Create the decode signal
311 shared_ptr<view::DecodeTrace> d(
312 new view::DecodeTrace(*this, decoder_stack,
313 decode_traces_.size()));
314 decode_traces_.push_back(d);
315 } catch (std::runtime_error e) {
321 // Do an initial decode
322 decoder_stack->begin_decode();
327 vector< shared_ptr<view::DecodeTrace> > Session::get_decode_signals() const
329 shared_lock<shared_mutex> lock(signals_mutex_);
330 return decode_traces_;
333 void Session::remove_decode_signal(view::DecodeTrace *signal)
335 for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
336 if ((*i).get() == signal) {
337 decode_traces_.erase(i);
344 void Session::set_capture_state(capture_state state)
349 lock_guard<mutex> lock(sampling_mutex_);
350 changed = capture_state_ != state;
351 capture_state_ = state;
355 capture_state_changed(state);
358 void Session::update_signals()
366 lock_guard<recursive_mutex> lock(data_mutex_);
368 const shared_ptr<sigrok::Device> sr_dev = device_->device();
375 // Detect what data types we will receive
376 auto channels = sr_dev->channels();
377 unsigned int logic_channel_count = std::count_if(
378 channels.begin(), channels.end(),
379 [] (shared_ptr<Channel> channel) {
380 return channel->type() == ChannelType::LOGIC; });
382 // Create data containers for the logic data segments
384 lock_guard<recursive_mutex> data_lock(data_mutex_);
386 if (logic_channel_count == 0) {
388 } else if (!logic_data_ ||
389 logic_data_->num_channels() != logic_channel_count) {
390 logic_data_.reset(new data::Logic(
391 logic_channel_count));
396 // Make the Signals list
398 unique_lock<shared_mutex> lock(signals_mutex_);
400 unordered_set< shared_ptr<view::Signal> > prev_sigs(signals_);
403 for (auto channel : sr_dev->channels()) {
404 shared_ptr<view::Signal> signal;
406 // Find the channel in the old signals
407 const auto iter = std::find_if(
408 prev_sigs.cbegin(), prev_sigs.cend(),
409 [&](const shared_ptr<view::Signal> &s) {
410 return s->channel() == channel;
412 if (iter != prev_sigs.end()) {
413 // Copy the signal from the old set to the new
415 auto logic_signal = dynamic_pointer_cast<
416 view::LogicSignal>(signal);
418 logic_signal->set_logic_data(
421 // Create a new signal
422 switch(channel->type()->id()) {
423 case SR_CHANNEL_LOGIC:
424 signal = shared_ptr<view::Signal>(
425 new view::LogicSignal(*this,
428 all_signal_data_.insert(logic_data_);
431 case SR_CHANNEL_ANALOG:
433 shared_ptr<data::Analog> data(
435 signal = shared_ptr<view::Signal>(
436 new view::AnalogSignal(
437 *this, channel, data));
438 all_signal_data_.insert(data);
449 signals_.insert(signal);
456 shared_ptr<view::Signal> Session::signal_from_channel(
457 shared_ptr<Channel> channel) const
459 lock_guard<boost::shared_mutex> lock(signals_mutex_);
460 for (shared_ptr<view::Signal> sig : signals_) {
462 if (sig->channel() == channel)
465 return shared_ptr<view::Signal>();
468 void Session::sample_thread_proc(function<void (const QString)> error_handler)
470 assert(error_handler);
475 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
477 out_of_memory_ = false;
482 error_handler(e.what());
486 set_capture_state(device_->session()->trigger() ?
487 AwaitingTrigger : Running);
490 set_capture_state(Stopped);
492 // Confirm that SR_DF_END was received
493 if (cur_logic_segment_) {
494 qDebug("SR_DF_END was not received.");
499 error_handler(tr("Out of memory, acquisition stopped."));
502 void Session::feed_in_header()
504 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
507 void Session::feed_in_meta(shared_ptr<Meta> meta)
509 for (auto entry : meta->config()) {
510 switch (entry.first->id()) {
511 case SR_CONF_SAMPLERATE:
512 // We can't rely on the header to always contain the sample rate,
513 // so in case it's supplied via a meta packet, we use it.
514 if (!cur_samplerate_)
515 cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
517 /// @todo handle samplerate changes
520 // Unknown metadata is not an error.
528 void Session::feed_in_trigger()
530 // The channel containing most samples should be most accurate
531 uint64_t sample_count = 0;
534 shared_lock<shared_mutex> lock(signals_mutex_);
535 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
537 uint64_t temp_count = 0;
539 const vector< shared_ptr<pv::data::Segment> > segments =
541 for (const shared_ptr<pv::data::Segment> &s : segments)
542 temp_count += s->get_sample_count();
544 if (temp_count > sample_count)
545 sample_count = temp_count;
549 trigger_event(sample_count / get_samplerate());
552 void Session::feed_in_frame_begin()
554 if (cur_logic_segment_ || !cur_analog_segments_.empty())
558 void Session::feed_in_logic(shared_ptr<Logic> logic)
560 lock_guard<recursive_mutex> lock(data_mutex_);
562 const size_t sample_count = logic->data_length() / logic->unit_size();
565 // The only reason logic_data_ would not have been created is
566 // if it was not possible to determine the signals when the
567 // device was created.
571 if (!cur_logic_segment_) {
572 // This could be the first packet after a trigger
573 set_capture_state(Running);
575 // Create a new data segment
576 cur_logic_segment_ = shared_ptr<data::LogicSegment>(
577 new data::LogicSegment(
578 logic, cur_samplerate_, sample_count));
579 logic_data_->push_segment(cur_logic_segment_);
581 // @todo Putting this here means that only listeners querying
582 // for logic will be notified. Currently the only user of
583 // frame_began is DecoderStack, but in future we need to signal
584 // this after both analog and logic sweeps have begun.
587 // Append to the existing data segment
588 cur_logic_segment_->append_payload(logic);
594 void Session::feed_in_analog(shared_ptr<Analog> analog)
596 lock_guard<recursive_mutex> lock(data_mutex_);
598 const vector<shared_ptr<Channel>> channels = analog->channels();
599 const unsigned int channel_count = channels.size();
600 const size_t sample_count = analog->num_samples() / channel_count;
601 const float *data = static_cast<const float *>(analog->data_pointer());
602 bool sweep_beginning = false;
604 if (signals_.empty())
607 for (auto channel : channels) {
608 shared_ptr<data::AnalogSegment> segment;
610 // Try to get the segment of the channel
611 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
612 iterator iter = cur_analog_segments_.find(channel);
613 if (iter != cur_analog_segments_.end())
614 segment = (*iter).second;
616 // If no segment was found, this means we haven't
617 // created one yet. i.e. this is the first packet
618 // in the sweep containing this segment.
619 sweep_beginning = true;
621 // Create a segment, keep it in the maps of channels
622 segment = shared_ptr<data::AnalogSegment>(
623 new data::AnalogSegment(
624 cur_samplerate_, sample_count));
625 cur_analog_segments_[channel] = segment;
627 // Find the analog data associated with the channel
628 shared_ptr<view::AnalogSignal> sig =
629 dynamic_pointer_cast<view::AnalogSignal>(
630 signal_from_channel(channel));
633 shared_ptr<data::Analog> data(sig->analog_data());
636 // Push the segment into the analog data.
637 data->push_segment(segment);
642 // Append the samples in the segment
643 segment->append_interleaved_samples(data++, sample_count,
647 if (sweep_beginning) {
648 // This could be the first packet after a trigger
649 set_capture_state(Running);
655 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
656 shared_ptr<Packet> packet)
661 assert(device == device_->device());
664 switch (packet->type()->id()) {
670 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
677 case SR_DF_FRAME_BEGIN:
678 feed_in_frame_begin();
683 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
684 } catch (std::bad_alloc) {
685 out_of_memory_ = true;
692 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
693 } catch (std::bad_alloc) {
694 out_of_memory_ = true;
702 lock_guard<recursive_mutex> lock(data_mutex_);
703 cur_logic_segment_.reset();
704 cur_analog_segments_.clear();