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 #include <libsigrokdecode/libsigrokdecode.h>
25 #include "session.hpp"
27 #include "devicemanager.hpp"
29 #include "data/analog.hpp"
30 #include "data/analogsegment.hpp"
31 #include "data/decoderstack.hpp"
32 #include "data/logic.hpp"
33 #include "data/logicsegment.hpp"
34 #include "data/decode/decoder.hpp"
36 #include "view/analogsignal.hpp"
37 #include "view/decodetrace.hpp"
38 #include "view/logicsignal.hpp"
48 #include <libsigrok/libsigrok.hpp>
50 using boost::shared_lock;
51 using boost::shared_mutex;
52 using boost::unique_lock;
54 using std::dynamic_pointer_cast;
56 using std::lock_guard;
61 using std::shared_ptr;
66 using sigrok::Channel;
67 using sigrok::ChannelType;
68 using sigrok::ConfigKey;
69 using sigrok::DatafeedCallbackFunction;
72 using sigrok::HardwareDevice;
77 using sigrok::PacketPayload;
78 using sigrok::Session;
79 using sigrok::SessionDevice;
81 using Glib::VariantBase;
85 Session::Session(DeviceManager &device_manager) :
86 device_manager_(device_manager),
87 session_(device_manager.context()->create_session()),
88 capture_state_(Stopped),
96 // Stop and join to the thread
100 DeviceManager& Session::device_manager()
102 return device_manager_;
105 const DeviceManager& Session::device_manager() const
107 return device_manager_;
110 const shared_ptr<sigrok::Session>& Session::session() const
115 shared_ptr<Device> Session::device() const
120 void Session::set_device(shared_ptr<Device> device)
122 // Ensure we are not capturing before setting the device
125 // Are we setting a session device?
126 auto session_device = dynamic_pointer_cast<SessionDevice>(device);
127 // Did we have a session device selected previously?
128 auto prev_session_device = dynamic_pointer_cast<SessionDevice>(device_);
131 session_->remove_datafeed_callbacks();
132 if (!prev_session_device) {
134 session_->remove_devices();
139 session_ = session_device->parent();
141 decode_traces_.clear();
146 session_ = device_manager_.context()->create_session();
150 } catch(const sigrok::Error &e) {
151 throw QString(e.what());
154 session_->add_device(device);
158 session_->add_datafeed_callback([=]
159 (shared_ptr<Device> device, shared_ptr<Packet> packet) {
160 data_feed_in(device, packet);
162 update_signals(device);
169 void Session::set_file(const string &name)
171 session_ = device_manager_.context()->load_session(name);
172 device_ = session_->devices()[0];
173 decode_traces_.clear();
174 session_->add_datafeed_callback([=]
175 (shared_ptr<Device> device, shared_ptr<Packet> packet) {
176 data_feed_in(device, packet);
178 device_manager_.update_display_name(device_);
179 update_signals(device_);
183 void Session::set_default_device()
185 shared_ptr<HardwareDevice> default_device;
186 const list< shared_ptr<HardwareDevice> > &devices =
187 device_manager_.devices();
189 if (!devices.empty()) {
190 // Fall back to the first device in the list.
191 default_device = devices.front();
193 // Try and find the demo device and select that by default
194 for (shared_ptr<HardwareDevice> dev : devices)
195 if (dev->driver()->name().compare("demo") == 0) {
196 default_device = dev;
200 set_device(default_device);
204 Session::capture_state Session::get_capture_state() const
206 lock_guard<mutex> lock(sampling_mutex_);
207 return capture_state_;
210 void Session::start_capture(function<void (const QString)> error_handler)
214 // Check that a device instance has been selected.
216 qDebug() << "No device selected";
220 // Check that at least one channel is enabled
221 auto channels = device_->channels();
222 bool enabled = std::any_of(channels.begin(), channels.end(),
223 [](shared_ptr<Channel> channel) { return channel->enabled(); });
226 error_handler(tr("No channels enabled."));
231 sampling_thread_ = std::thread(
232 &Session::sample_thread_proc, this, device_,
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 set< shared_ptr<data::SignalData> > Session::get_data() const
248 shared_lock<shared_mutex> lock(signals_mutex_);
249 set< shared_ptr<data::SignalData> > data;
250 for (const shared_ptr<view::Signal> sig : signals_) {
252 data.insert(sig->data());
258 boost::shared_mutex& Session::signals_mutex() const
260 return signals_mutex_;
263 const vector< shared_ptr<view::Signal> >& Session::signals() const
269 bool Session::add_decoder(srd_decoder *const dec)
271 map<const srd_channel*, shared_ptr<view::LogicSignal> > channels;
272 shared_ptr<data::DecoderStack> decoder_stack;
276 lock_guard<boost::shared_mutex> lock(signals_mutex_);
278 // Create the decoder
279 decoder_stack = shared_ptr<data::DecoderStack>(
280 new data::DecoderStack(*this, dec));
282 // Make a list of all the channels
283 std::vector<const srd_channel*> all_channels;
284 for(const GSList *i = dec->channels; i; i = i->next)
285 all_channels.push_back((const srd_channel*)i->data);
286 for(const GSList *i = dec->opt_channels; i; i = i->next)
287 all_channels.push_back((const srd_channel*)i->data);
289 // Auto select the initial channels
290 for (const srd_channel *pdch : all_channels)
291 for (shared_ptr<view::Signal> s : signals_)
293 shared_ptr<view::LogicSignal> l =
294 dynamic_pointer_cast<view::LogicSignal>(s);
295 if (l && QString::fromUtf8(pdch->name).
297 l->name().toLower()))
301 assert(decoder_stack);
302 assert(!decoder_stack->stack().empty());
303 assert(decoder_stack->stack().front());
304 decoder_stack->stack().front()->set_channels(channels);
306 // Create the decode signal
307 shared_ptr<view::DecodeTrace> d(
308 new view::DecodeTrace(*this, decoder_stack,
309 decode_traces_.size()));
310 decode_traces_.push_back(d);
312 catch(std::runtime_error e)
319 // Do an initial decode
320 decoder_stack->begin_decode();
325 vector< shared_ptr<view::DecodeTrace> > Session::get_decode_signals() const
327 shared_lock<shared_mutex> lock(signals_mutex_);
328 return decode_traces_;
331 void Session::remove_decode_signal(view::DecodeTrace *signal)
333 for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
334 if ((*i).get() == signal)
336 decode_traces_.erase(i);
343 void Session::set_capture_state(capture_state state)
345 lock_guard<mutex> lock(sampling_mutex_);
346 const bool changed = capture_state_ != state;
347 capture_state_ = state;
349 capture_state_changed(state);
352 void Session::update_signals(shared_ptr<Device> device)
355 assert(capture_state_ == Stopped);
357 // Clear the decode traces
358 decode_traces_.clear();
360 // Detect what data types we will receive
361 auto channels = device->channels();
362 unsigned int logic_channel_count = std::count_if(
363 channels.begin(), channels.end(),
364 [] (shared_ptr<Channel> channel) {
365 return channel->type() == ChannelType::LOGIC; });
367 // Create data containers for the logic data segments
369 lock_guard<mutex> data_lock(data_mutex_);
372 if (logic_channel_count != 0) {
373 logic_data_.reset(new data::Logic(
374 logic_channel_count));
379 // Make the Signals list
381 unique_lock<shared_mutex> lock(signals_mutex_);
385 for (auto channel : device->channels()) {
386 shared_ptr<view::Signal> signal;
388 switch(channel->type()->id()) {
389 case SR_CHANNEL_LOGIC:
390 signal = shared_ptr<view::Signal>(
391 new view::LogicSignal(*this, device,
392 channel, logic_data_));
395 case SR_CHANNEL_ANALOG:
397 shared_ptr<data::Analog> data(
399 signal = shared_ptr<view::Signal>(
400 new view::AnalogSignal(
401 *this, channel, data));
411 signals_.push_back(signal);
419 shared_ptr<view::Signal> Session::signal_from_channel(
420 shared_ptr<Channel> channel) const
422 lock_guard<boost::shared_mutex> lock(signals_mutex_);
423 for (shared_ptr<view::Signal> sig : signals_) {
425 if (sig->channel() == channel)
428 return shared_ptr<view::Signal>();
431 void Session::read_sample_rate(shared_ptr<Device> device)
433 const auto keys = device_->config_keys(ConfigKey::DEVICE_OPTIONS);
434 const auto iter = keys.find(ConfigKey::SAMPLERATE);
435 cur_samplerate_ = (iter != keys.end() &&
436 (*iter).second.find(sigrok::GET) != (*iter).second.end()) ?
437 VariantBase::cast_dynamic<Variant<guint64>>(
438 device->config_get(ConfigKey::SAMPLERATE)).get() : 0;
441 void Session::sample_thread_proc(shared_ptr<Device> device,
442 function<void (const QString)> error_handler)
445 assert(error_handler);
447 read_sample_rate(device);
452 error_handler(e.what());
456 set_capture_state(session_->trigger() ?
457 AwaitingTrigger : Running);
460 set_capture_state(Stopped);
462 // Confirm that SR_DF_END was received
463 if (cur_logic_segment_)
465 qDebug("SR_DF_END was not received.");
470 void Session::feed_in_header(shared_ptr<Device> device)
472 read_sample_rate(device);
475 void Session::feed_in_meta(shared_ptr<Device> device,
476 shared_ptr<Meta> meta)
480 for (auto entry : meta->config()) {
481 switch (entry.first->id()) {
482 case SR_CONF_SAMPLERATE:
483 /// @todo handle samplerate changes
486 // Unknown metadata is not an error.
494 void Session::feed_in_frame_begin()
496 if (cur_logic_segment_ || !cur_analog_segments_.empty())
500 void Session::feed_in_logic(shared_ptr<Logic> logic)
502 lock_guard<mutex> lock(data_mutex_);
506 qDebug() << "Unexpected logic packet";
510 if (!cur_logic_segment_)
512 // This could be the first packet after a trigger
513 set_capture_state(Running);
516 const auto keys = device_->config_keys(
517 ConfigKey::DEVICE_OPTIONS);
518 const auto iter = keys.find(ConfigKey::LIMIT_SAMPLES);
519 const uint64_t sample_limit = (iter != keys.end() &&
520 (*iter).second.find(sigrok::GET) !=
521 (*iter).second.end()) ?
522 VariantBase::cast_dynamic<Variant<guint64>>(
523 device_->config_get(ConfigKey::LIMIT_SAMPLES)).get() : 0;
525 // Create a new data segment
526 cur_logic_segment_ = shared_ptr<data::LogicSegment>(
527 new data::LogicSegment(
528 logic, cur_samplerate_, sample_limit));
529 logic_data_->push_segment(cur_logic_segment_);
531 // @todo Putting this here means that only listeners querying
532 // for logic will be notified. Currently the only user of
533 // frame_began is DecoderStack, but in future we need to signal
534 // this after both analog and logic sweeps have begun.
539 // Append to the existing data segment
540 cur_logic_segment_->append_payload(logic);
546 void Session::feed_in_analog(shared_ptr<Analog> analog)
548 lock_guard<mutex> lock(data_mutex_);
550 const vector<shared_ptr<Channel>> channels = analog->channels();
551 const unsigned int channel_count = channels.size();
552 const size_t sample_count = analog->num_samples() / channel_count;
553 const float *data = analog->data_pointer();
554 bool sweep_beginning = false;
556 for (auto channel : channels)
558 shared_ptr<data::AnalogSegment> segment;
560 // Try to get the segment of the channel
561 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
562 iterator iter = cur_analog_segments_.find(channel);
563 if (iter != cur_analog_segments_.end())
564 segment = (*iter).second;
567 // If no segment was found, this means we havn't
568 // created one yet. i.e. this is the first packet
569 // in the sweep containing this segment.
570 sweep_beginning = true;
573 uint64_t sample_limit;
575 sample_limit = VariantBase::cast_dynamic<Variant<guint64>>(
576 device_->config_get(ConfigKey::LIMIT_SAMPLES)).get();
581 // Create a segment, keep it in the maps of channels
582 segment = shared_ptr<data::AnalogSegment>(
583 new data::AnalogSegment(
584 cur_samplerate_, sample_limit));
585 cur_analog_segments_[channel] = segment;
587 // Find the annalog data associated with the channel
588 shared_ptr<view::AnalogSignal> sig =
589 dynamic_pointer_cast<view::AnalogSignal>(
590 signal_from_channel(channel));
593 shared_ptr<data::Analog> data(sig->analog_data());
596 // Push the segment into the analog data.
597 data->push_segment(segment);
602 // Append the samples in the segment
603 segment->append_interleaved_samples(data++, sample_count,
607 if (sweep_beginning) {
608 // This could be the first packet after a trigger
609 set_capture_state(Running);
615 void Session::data_feed_in(shared_ptr<Device> device, shared_ptr<Packet> packet)
620 switch (packet->type()->id()) {
622 feed_in_header(device);
626 feed_in_meta(device, dynamic_pointer_cast<Meta>(packet->payload()));
629 case SR_DF_FRAME_BEGIN:
630 feed_in_frame_begin();
634 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
638 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
644 lock_guard<mutex> lock(data_mutex_);
645 cur_logic_segment_.reset();
646 cur_analog_segments_.clear();