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 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 SigSession::SigSession(DeviceManager &device_manager) :
86 device_manager_(device_manager),
87 session_(device_manager.context()->create_session()),
88 capture_state_(Stopped)
93 SigSession::~SigSession()
95 // Stop and join to the thread
99 DeviceManager& SigSession::device_manager()
101 return device_manager_;
104 const DeviceManager& SigSession::device_manager() const
106 return device_manager_;
109 const shared_ptr<sigrok::Session>& SigSession::session() const
114 shared_ptr<Device> SigSession::device() const
119 void SigSession::set_device(shared_ptr<Device> device)
121 // Ensure we are not capturing before setting the device
124 // Are we setting a session device?
125 auto session_device = dynamic_pointer_cast<SessionDevice>(device);
126 // Did we have a session device selected previously?
127 auto prev_session_device = dynamic_pointer_cast<SessionDevice>(device_);
130 session_->remove_datafeed_callbacks();
131 if (!prev_session_device) {
133 session_->remove_devices();
138 session_ = session_device->parent();
141 decode_traces_.clear();
146 session_ = device_manager_.context()->create_session();
148 session_->add_device(device);
150 session_->add_datafeed_callback([=]
151 (shared_ptr<Device> device, shared_ptr<Packet> packet) {
152 data_feed_in(device, packet);
154 update_signals(device);
158 void SigSession::set_file(const string &name)
160 session_ = device_manager_.context()->load_session(name);
161 device_ = session_->devices()[0];
162 decode_traces_.clear();
163 session_->add_datafeed_callback([=]
164 (shared_ptr<Device> device, shared_ptr<Packet> packet) {
165 data_feed_in(device, packet);
167 device_manager_.update_display_name(device_);
168 update_signals(device_);
171 void SigSession::set_default_device()
173 shared_ptr<HardwareDevice> default_device;
174 const list< shared_ptr<HardwareDevice> > &devices =
175 device_manager_.devices();
177 if (!devices.empty()) {
178 // Fall back to the first device in the list.
179 default_device = devices.front();
181 // Try and find the demo device and select that by default
182 for (shared_ptr<HardwareDevice> dev : devices)
183 if (dev->driver()->name().compare("demo") == 0) {
184 default_device = dev;
188 set_device(default_device);
192 SigSession::capture_state SigSession::get_capture_state() const
194 lock_guard<mutex> lock(sampling_mutex_);
195 return capture_state_;
198 void SigSession::start_capture(function<void (const QString)> error_handler)
202 // Check that a device instance has been selected.
204 qDebug() << "No device selected";
208 // Check that at least one channel is enabled
209 auto channels = device_->channels();
210 bool enabled = std::any_of(channels.begin(), channels.end(),
211 [](shared_ptr<Channel> channel) { return channel->enabled(); });
214 error_handler(tr("No channels enabled."));
219 sampling_thread_ = std::thread(
220 &SigSession::sample_thread_proc, this, device_,
224 void SigSession::stop_capture()
226 if (get_capture_state() != Stopped)
229 // Check that sampling stopped
230 if (sampling_thread_.joinable())
231 sampling_thread_.join();
234 set< shared_ptr<data::SignalData> > SigSession::get_data() const
236 shared_lock<shared_mutex> lock(signals_mutex_);
237 set< shared_ptr<data::SignalData> > data;
238 for (const shared_ptr<view::Signal> sig : signals_) {
240 data.insert(sig->data());
246 boost::shared_mutex& SigSession::signals_mutex() const
248 return signals_mutex_;
251 const vector< shared_ptr<view::Signal> >& SigSession::signals() const
257 bool SigSession::add_decoder(srd_decoder *const dec)
259 map<const srd_channel*, shared_ptr<view::LogicSignal> > channels;
260 shared_ptr<data::DecoderStack> decoder_stack;
264 lock_guard<boost::shared_mutex> lock(signals_mutex_);
266 // Create the decoder
267 decoder_stack = shared_ptr<data::DecoderStack>(
268 new data::DecoderStack(*this, dec));
270 // Make a list of all the channels
271 std::vector<const srd_channel*> all_channels;
272 for(const GSList *i = dec->channels; i; i = i->next)
273 all_channels.push_back((const srd_channel*)i->data);
274 for(const GSList *i = dec->opt_channels; i; i = i->next)
275 all_channels.push_back((const srd_channel*)i->data);
277 // Auto select the initial channels
278 for (const srd_channel *pdch : all_channels)
279 for (shared_ptr<view::Signal> s : signals_)
281 shared_ptr<view::LogicSignal> l =
282 dynamic_pointer_cast<view::LogicSignal>(s);
283 if (l && QString::fromUtf8(pdch->name).
285 l->name().toLower()))
289 assert(decoder_stack);
290 assert(!decoder_stack->stack().empty());
291 assert(decoder_stack->stack().front());
292 decoder_stack->stack().front()->set_channels(channels);
294 // Create the decode signal
295 shared_ptr<view::DecodeTrace> d(
296 new view::DecodeTrace(*this, decoder_stack,
297 decode_traces_.size()));
298 decode_traces_.push_back(d);
300 catch(std::runtime_error e)
307 // Do an initial decode
308 decoder_stack->begin_decode();
313 vector< shared_ptr<view::DecodeTrace> > SigSession::get_decode_signals() const
315 shared_lock<shared_mutex> lock(signals_mutex_);
316 return decode_traces_;
319 void SigSession::remove_decode_signal(view::DecodeTrace *signal)
321 for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
322 if ((*i).get() == signal)
324 decode_traces_.erase(i);
331 void SigSession::set_capture_state(capture_state state)
333 lock_guard<mutex> lock(sampling_mutex_);
334 const bool changed = capture_state_ != state;
335 capture_state_ = state;
337 capture_state_changed(state);
340 void SigSession::update_signals(shared_ptr<Device> device)
343 assert(capture_state_ == Stopped);
345 // Clear the decode traces
346 decode_traces_.clear();
348 // Detect what data types we will receive
349 auto channels = device->channels();
350 unsigned int logic_channel_count = std::count_if(
351 channels.begin(), channels.end(),
352 [] (shared_ptr<Channel> channel) {
353 return channel->type() == ChannelType::LOGIC; });
355 // Create data containers for the logic data snapshots
357 lock_guard<mutex> data_lock(data_mutex_);
360 if (logic_channel_count != 0) {
361 logic_data_.reset(new data::Logic(
362 logic_channel_count));
367 // Make the Signals list
369 unique_lock<shared_mutex> lock(signals_mutex_);
373 for (auto channel : device->channels()) {
374 shared_ptr<view::Signal> signal;
376 switch(channel->type()->id()) {
377 case SR_CHANNEL_LOGIC:
378 signal = shared_ptr<view::Signal>(
379 new view::LogicSignal(*this, device,
380 channel, logic_data_));
383 case SR_CHANNEL_ANALOG:
385 shared_ptr<data::Analog> data(
387 signal = shared_ptr<view::Signal>(
388 new view::AnalogSignal(
389 *this, channel, data));
399 signals_.push_back(signal);
407 shared_ptr<view::Signal> SigSession::signal_from_channel(
408 shared_ptr<Channel> channel) const
410 lock_guard<boost::shared_mutex> lock(signals_mutex_);
411 for (shared_ptr<view::Signal> sig : signals_) {
413 if (sig->channel() == channel)
416 return shared_ptr<view::Signal>();
419 void SigSession::read_sample_rate(shared_ptr<Device> device)
421 uint64_t sample_rate = VariantBase::cast_dynamic<Variant<guint64>>(
422 device->config_get(ConfigKey::SAMPLERATE)).get();
424 // Set the sample rate of all data
425 const set< shared_ptr<data::SignalData> > data_set = get_data();
426 for (shared_ptr<data::SignalData> data : data_set) {
428 data->set_samplerate(sample_rate);
432 void SigSession::sample_thread_proc(shared_ptr<Device> device,
433 function<void (const QString)> error_handler)
436 assert(error_handler);
438 read_sample_rate(device);
443 error_handler(e.what());
447 set_capture_state(session_->trigger() ?
448 AwaitingTrigger : Running);
451 set_capture_state(Stopped);
453 // Confirm that SR_DF_END was received
454 if (cur_logic_snapshot_)
456 qDebug("SR_DF_END was not received.");
461 void SigSession::feed_in_header(shared_ptr<Device> device)
463 read_sample_rate(device);
466 void SigSession::feed_in_meta(shared_ptr<Device> device,
467 shared_ptr<Meta> meta)
471 for (auto entry : meta->config()) {
472 switch (entry.first->id()) {
473 case SR_CONF_SAMPLERATE:
474 /// @todo handle samplerate changes
477 // Unknown metadata is not an error.
485 void SigSession::feed_in_frame_begin()
487 if (cur_logic_snapshot_ || !cur_analog_snapshots_.empty())
491 void SigSession::feed_in_logic(shared_ptr<Logic> logic)
493 lock_guard<mutex> lock(data_mutex_);
497 qDebug() << "Unexpected logic packet";
501 if (!cur_logic_snapshot_)
503 // This could be the first packet after a trigger
504 set_capture_state(Running);
507 uint64_t sample_limit;
509 sample_limit = VariantBase::cast_dynamic<Variant<guint64>>(
510 device_->config_get(ConfigKey::LIMIT_SAMPLES)).get();
515 // Create a new data snapshot
516 cur_logic_snapshot_ = shared_ptr<data::LogicSnapshot>(
517 new data::LogicSnapshot(logic, sample_limit));
518 logic_data_->push_snapshot(cur_logic_snapshot_);
520 // @todo Putting this here means that only listeners querying
521 // for logic will be notified. Currently the only user of
522 // frame_began is DecoderStack, but in future we need to signal
523 // this after both analog and logic sweeps have begun.
528 // Append to the existing data snapshot
529 cur_logic_snapshot_->append_payload(logic);
535 void SigSession::feed_in_analog(shared_ptr<Analog> analog)
537 lock_guard<mutex> lock(data_mutex_);
539 const vector<shared_ptr<Channel>> channels = analog->channels();
540 const unsigned int channel_count = channels.size();
541 const size_t sample_count = analog->num_samples() / channel_count;
542 const float *data = analog->data_pointer();
543 bool sweep_beginning = false;
545 for (auto channel : channels)
547 shared_ptr<data::AnalogSnapshot> snapshot;
549 // Try to get the snapshot of the channel
550 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSnapshot> >::
551 iterator iter = cur_analog_snapshots_.find(channel);
552 if (iter != cur_analog_snapshots_.end())
553 snapshot = (*iter).second;
556 // If no snapshot was found, this means we havn't
557 // created one yet. i.e. this is the first packet
558 // in the sweep containing this snapshot.
559 sweep_beginning = true;
562 uint64_t sample_limit;
564 sample_limit = VariantBase::cast_dynamic<Variant<guint64>>(
565 device_->config_get(ConfigKey::LIMIT_SAMPLES)).get();
570 // Create a snapshot, keep it in the maps of channels
571 snapshot = shared_ptr<data::AnalogSnapshot>(
572 new data::AnalogSnapshot(sample_limit));
573 cur_analog_snapshots_[channel] = snapshot;
575 // Find the annalog data associated with the channel
576 shared_ptr<view::AnalogSignal> sig =
577 dynamic_pointer_cast<view::AnalogSignal>(
578 signal_from_channel(channel));
581 shared_ptr<data::Analog> data(sig->analog_data());
584 // Push the snapshot into the analog data.
585 data->push_snapshot(snapshot);
590 // Append the samples in the snapshot
591 snapshot->append_interleaved_samples(data++, sample_count,
595 if (sweep_beginning) {
596 // This could be the first packet after a trigger
597 set_capture_state(Running);
603 void SigSession::data_feed_in(shared_ptr<Device> device, shared_ptr<Packet> packet)
608 switch (packet->type()->id()) {
610 feed_in_header(device);
614 feed_in_meta(device, dynamic_pointer_cast<Meta>(packet->payload()));
617 case SR_DF_FRAME_BEGIN:
618 feed_in_frame_begin();
622 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
626 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
632 lock_guard<mutex> lock(data_mutex_);
633 cur_logic_snapshot_.reset();
634 cur_analog_snapshots_.clear();