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 "sigsession.h"
27 #include "devicemanager.h"
29 #include "data/analog.h"
30 #include "data/analogsnapshot.h"
31 #include "data/decoderstack.h"
32 #include "data/logic.h"
33 #include "data/logicsnapshot.h"
34 #include "data/decode/decoder.h"
36 #include "view/analogsignal.h"
37 #include "view/decodetrace.h"
38 #include "view/logicsignal.h"
48 #include <libsigrok/libsigrok.hpp>
50 using std::dynamic_pointer_cast;
52 using std::lock_guard;
57 using std::shared_ptr;
62 using sigrok::Channel;
63 using sigrok::ChannelType;
64 using sigrok::ConfigKey;
65 using sigrok::DatafeedCallbackFunction;
68 using sigrok::HardwareDevice;
73 using sigrok::PacketPayload;
74 using sigrok::Session;
75 using sigrok::SessionDevice;
77 using Glib::VariantBase;
81 SigSession::SigSession(DeviceManager &device_manager) :
82 _device_manager(device_manager),
83 _session(device_manager.context()->create_session()),
84 _capture_state(Stopped)
89 SigSession::~SigSession()
91 // Stop and join to the thread
95 DeviceManager& SigSession::device_manager()
97 return _device_manager;
100 const DeviceManager& SigSession::device_manager() const
102 return _device_manager;
105 const shared_ptr<sigrok::Session>& SigSession::session() const
110 shared_ptr<Device> SigSession::device() const
115 void SigSession::set_device(shared_ptr<Device> device)
117 // Ensure we are not capturing before setting the device
120 // Are we setting a session device?
121 auto session_device = dynamic_pointer_cast<SessionDevice>(device);
122 // Did we have a session device selected previously?
123 auto prev_session_device = dynamic_pointer_cast<SessionDevice>(_device);
126 _session->remove_datafeed_callbacks();
127 if (!prev_session_device) {
129 _session->remove_devices();
134 _session = session_device->parent();
137 _decode_traces.clear();
142 _session = _device_manager.context()->create_session();
144 _session->add_device(device);
146 _session->add_datafeed_callback([=]
147 (shared_ptr<Device> device, shared_ptr<Packet> packet) {
148 data_feed_in(device, packet);
150 update_signals(device);
154 void SigSession::set_file(const string &name)
156 _session = _device_manager.context()->load_session(name);
157 _device = _session->devices()[0];
158 _decode_traces.clear();
159 _session->add_datafeed_callback([=]
160 (shared_ptr<Device> device, shared_ptr<Packet> packet) {
161 data_feed_in(device, packet);
163 _device_manager.update_display_name(_device);
164 update_signals(_device);
167 void SigSession::set_default_device()
169 shared_ptr<HardwareDevice> default_device;
170 const list< shared_ptr<HardwareDevice> > &devices =
171 _device_manager.devices();
173 if (!devices.empty()) {
174 // Fall back to the first device in the list.
175 default_device = devices.front();
177 // Try and find the demo device and select that by default
178 for (shared_ptr<HardwareDevice> dev : devices)
179 if (dev->driver()->name().compare("demo") == 0) {
180 default_device = dev;
184 set_device(default_device);
188 SigSession::capture_state SigSession::get_capture_state() const
190 lock_guard<mutex> lock(_sampling_mutex);
191 return _capture_state;
194 void SigSession::start_capture(function<void (const QString)> error_handler)
198 // Check that a device instance has been selected.
200 qDebug() << "No device selected";
204 // Check that at least one channel is enabled
205 auto channels = _device->channels();
206 bool enabled = std::any_of(channels.begin(), channels.end(),
207 [](shared_ptr<Channel> channel) { return channel->enabled(); });
210 error_handler(tr("No channels enabled."));
215 _sampling_thread = std::thread(
216 &SigSession::sample_thread_proc, this, _device,
220 void SigSession::stop_capture()
222 if (get_capture_state() != Stopped)
225 // Check that sampling stopped
226 if (_sampling_thread.joinable())
227 _sampling_thread.join();
230 set< shared_ptr<data::SignalData> > SigSession::get_data() const
232 lock_guard<mutex> lock(_signals_mutex);
233 set< shared_ptr<data::SignalData> > data;
234 for (const shared_ptr<view::Signal> sig : _signals) {
236 data.insert(sig->data());
242 vector< shared_ptr<view::Signal> > SigSession::get_signals() const
244 lock_guard<mutex> lock(_signals_mutex);
249 bool SigSession::add_decoder(srd_decoder *const dec)
251 map<const srd_channel*, shared_ptr<view::LogicSignal> > channels;
252 shared_ptr<data::DecoderStack> decoder_stack;
256 lock_guard<mutex> lock(_signals_mutex);
258 // Create the decoder
259 decoder_stack = shared_ptr<data::DecoderStack>(
260 new data::DecoderStack(*this, dec));
262 // Make a list of all the channels
263 std::vector<const srd_channel*> all_channels;
264 for(const GSList *i = dec->channels; i; i = i->next)
265 all_channels.push_back((const srd_channel*)i->data);
266 for(const GSList *i = dec->opt_channels; i; i = i->next)
267 all_channels.push_back((const srd_channel*)i->data);
269 // Auto select the initial channels
270 for (const srd_channel *pdch : all_channels)
271 for (shared_ptr<view::Signal> s : _signals)
273 shared_ptr<view::LogicSignal> l =
274 dynamic_pointer_cast<view::LogicSignal>(s);
275 if (l && QString::fromUtf8(pdch->name).
277 l->name().toLower()))
281 assert(decoder_stack);
282 assert(!decoder_stack->stack().empty());
283 assert(decoder_stack->stack().front());
284 decoder_stack->stack().front()->set_channels(channels);
286 // Create the decode signal
287 shared_ptr<view::DecodeTrace> d(
288 new view::DecodeTrace(*this, decoder_stack,
289 _decode_traces.size()));
290 _decode_traces.push_back(d);
292 catch(std::runtime_error e)
299 // Do an initial decode
300 decoder_stack->begin_decode();
305 vector< shared_ptr<view::DecodeTrace> > SigSession::get_decode_signals() const
307 lock_guard<mutex> lock(_signals_mutex);
308 return _decode_traces;
311 void SigSession::remove_decode_signal(view::DecodeTrace *signal)
313 for (auto i = _decode_traces.begin(); i != _decode_traces.end(); i++)
314 if ((*i).get() == signal)
316 _decode_traces.erase(i);
323 void SigSession::set_capture_state(capture_state state)
325 lock_guard<mutex> lock(_sampling_mutex);
326 const bool changed = _capture_state != state;
327 _capture_state = state;
329 capture_state_changed(state);
332 void SigSession::update_signals(shared_ptr<Device> device)
335 assert(_capture_state == Stopped);
337 // Clear the decode traces
338 _decode_traces.clear();
340 // Detect what data types we will receive
341 auto channels = device->channels();
342 unsigned int logic_channel_count = std::count_if(
343 channels.begin(), channels.end(),
344 [] (shared_ptr<Channel> channel) {
345 return channel->type() == ChannelType::LOGIC; });
347 // Create data containers for the logic data snapshots
349 lock_guard<mutex> data_lock(_data_mutex);
352 if (logic_channel_count != 0) {
353 _logic_data.reset(new data::Logic(
354 logic_channel_count));
359 // Make the Signals list
361 lock_guard<mutex> lock(_signals_mutex);
365 for (auto channel : device->channels()) {
366 shared_ptr<view::Signal> signal;
368 switch(channel->type()->id()) {
369 case SR_CHANNEL_LOGIC:
370 signal = shared_ptr<view::Signal>(
371 new view::LogicSignal(*this, device,
372 channel, _logic_data));
375 case SR_CHANNEL_ANALOG:
377 shared_ptr<data::Analog> data(
379 signal = shared_ptr<view::Signal>(
380 new view::AnalogSignal(
381 *this, channel, data));
391 _signals.push_back(signal);
399 shared_ptr<view::Signal> SigSession::signal_from_channel(
400 shared_ptr<Channel> channel) const
402 lock_guard<mutex> lock(_signals_mutex);
403 for (shared_ptr<view::Signal> sig : _signals) {
405 if (sig->channel() == channel)
408 return shared_ptr<view::Signal>();
411 void SigSession::read_sample_rate(shared_ptr<Device> device)
413 uint64_t sample_rate = VariantBase::cast_dynamic<Variant<guint64>>(
414 device->config_get(ConfigKey::SAMPLERATE)).get();
416 // Set the sample rate of all data
417 const set< shared_ptr<data::SignalData> > data_set = get_data();
418 for (shared_ptr<data::SignalData> data : data_set) {
420 data->set_samplerate(sample_rate);
424 void SigSession::sample_thread_proc(shared_ptr<Device> device,
425 function<void (const QString)> error_handler)
428 assert(error_handler);
430 read_sample_rate(device);
435 error_handler(e.what());
439 set_capture_state(_session->trigger() ?
440 AwaitingTrigger : Running);
443 set_capture_state(Stopped);
445 // Confirm that SR_DF_END was received
446 if (_cur_logic_snapshot)
448 qDebug("SR_DF_END was not received.");
453 void SigSession::feed_in_header(shared_ptr<Device> device)
455 read_sample_rate(device);
458 void SigSession::feed_in_meta(shared_ptr<Device> device,
459 shared_ptr<Meta> meta)
463 for (auto entry : meta->config()) {
464 switch (entry.first->id()) {
465 case SR_CONF_SAMPLERATE:
466 /// @todo handle samplerate changes
469 // Unknown metadata is not an error.
477 void SigSession::feed_in_frame_begin()
479 if (_cur_logic_snapshot || !_cur_analog_snapshots.empty())
483 void SigSession::feed_in_logic(shared_ptr<Logic> logic)
485 lock_guard<mutex> lock(_data_mutex);
489 qDebug() << "Unexpected logic packet";
493 if (!_cur_logic_snapshot)
495 // This could be the first packet after a trigger
496 set_capture_state(Running);
499 uint64_t sample_limit;
501 sample_limit = VariantBase::cast_dynamic<Variant<guint64>>(
502 _device->config_get(ConfigKey::LIMIT_SAMPLES)).get();
507 // Create a new data snapshot
508 _cur_logic_snapshot = shared_ptr<data::LogicSnapshot>(
509 new data::LogicSnapshot(logic, sample_limit));
510 _logic_data->push_snapshot(_cur_logic_snapshot);
512 // @todo Putting this here means that only listeners querying
513 // for logic will be notified. Currently the only user of
514 // frame_began is DecoderStack, but in future we need to signal
515 // this after both analog and logic sweeps have begun.
520 // Append to the existing data snapshot
521 _cur_logic_snapshot->append_payload(logic);
527 void SigSession::feed_in_analog(shared_ptr<Analog> analog)
529 lock_guard<mutex> lock(_data_mutex);
531 const vector<shared_ptr<Channel>> channels = analog->channels();
532 const unsigned int channel_count = channels.size();
533 const size_t sample_count = analog->num_samples() / channel_count;
534 const float *data = analog->data_pointer();
535 bool sweep_beginning = false;
537 for (auto channel : channels)
539 shared_ptr<data::AnalogSnapshot> snapshot;
541 // Try to get the snapshot of the channel
542 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSnapshot> >::
543 iterator iter = _cur_analog_snapshots.find(channel);
544 if (iter != _cur_analog_snapshots.end())
545 snapshot = (*iter).second;
548 // If no snapshot was found, this means we havn't
549 // created one yet. i.e. this is the first packet
550 // in the sweep containing this snapshot.
551 sweep_beginning = true;
554 uint64_t sample_limit;
556 sample_limit = VariantBase::cast_dynamic<Variant<guint64>>(
557 _device->config_get(ConfigKey::LIMIT_SAMPLES)).get();
562 // Create a snapshot, keep it in the maps of channels
563 snapshot = shared_ptr<data::AnalogSnapshot>(
564 new data::AnalogSnapshot(sample_limit));
565 _cur_analog_snapshots[channel] = snapshot;
567 // Find the annalog data associated with the channel
568 shared_ptr<view::AnalogSignal> sig =
569 dynamic_pointer_cast<view::AnalogSignal>(
570 signal_from_channel(channel));
573 shared_ptr<data::Analog> data(sig->analog_data());
576 // Push the snapshot into the analog data.
577 data->push_snapshot(snapshot);
582 // Append the samples in the snapshot
583 snapshot->append_interleaved_samples(data++, sample_count,
587 if (sweep_beginning) {
588 // This could be the first packet after a trigger
589 set_capture_state(Running);
595 void SigSession::data_feed_in(shared_ptr<Device> device, shared_ptr<Packet> packet)
600 switch (packet->type()->id()) {
602 feed_in_header(device);
606 feed_in_meta(device, dynamic_pointer_cast<Meta>(packet->payload()));
609 case SR_DF_FRAME_BEGIN:
610 feed_in_frame_begin();
614 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
618 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
624 lock_guard<mutex> lock(_data_mutex);
625 _cur_logic_snapshot.reset();
626 _cur_analog_snapshots.clear();