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.hpp"
27 #include "devicemanager.hpp"
29 #include "data/analog.hpp"
30 #include "data/analogsnapshot.hpp"
31 #include "data/decoderstack.hpp"
32 #include "data/logic.hpp"
33 #include "data/logicsnapshot.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)
95 // Stop and join to the thread
99 DeviceManager& Session::device_manager()
101 return device_manager_;
104 const DeviceManager& Session::device_manager() const
106 return device_manager_;
109 const shared_ptr<sigrok::Session>& Session::session() const
114 shared_ptr<Device> Session::device() const
119 void Session::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);
160 void Session::set_file(const string &name)
162 session_ = device_manager_.context()->load_session(name);
163 device_ = session_->devices()[0];
164 decode_traces_.clear();
165 session_->add_datafeed_callback([=]
166 (shared_ptr<Device> device, shared_ptr<Packet> packet) {
167 data_feed_in(device, packet);
169 device_manager_.update_display_name(device_);
170 update_signals(device_);
174 void Session::set_default_device()
176 shared_ptr<HardwareDevice> default_device;
177 const list< shared_ptr<HardwareDevice> > &devices =
178 device_manager_.devices();
180 if (!devices.empty()) {
181 // Fall back to the first device in the list.
182 default_device = devices.front();
184 // Try and find the demo device and select that by default
185 for (shared_ptr<HardwareDevice> dev : devices)
186 if (dev->driver()->name().compare("demo") == 0) {
187 default_device = dev;
191 set_device(default_device);
195 Session::capture_state Session::get_capture_state() const
197 lock_guard<mutex> lock(sampling_mutex_);
198 return capture_state_;
201 void Session::start_capture(function<void (const QString)> error_handler)
205 // Check that a device instance has been selected.
207 qDebug() << "No device selected";
211 // Check that at least one channel is enabled
212 auto channels = device_->channels();
213 bool enabled = std::any_of(channels.begin(), channels.end(),
214 [](shared_ptr<Channel> channel) { return channel->enabled(); });
217 error_handler(tr("No channels enabled."));
222 sampling_thread_ = std::thread(
223 &Session::sample_thread_proc, this, device_,
227 void Session::stop_capture()
229 if (get_capture_state() != Stopped)
232 // Check that sampling stopped
233 if (sampling_thread_.joinable())
234 sampling_thread_.join();
237 set< shared_ptr<data::SignalData> > Session::get_data() const
239 shared_lock<shared_mutex> lock(signals_mutex_);
240 set< shared_ptr<data::SignalData> > data;
241 for (const shared_ptr<view::Signal> sig : signals_) {
243 data.insert(sig->data());
249 boost::shared_mutex& Session::signals_mutex() const
251 return signals_mutex_;
254 const vector< shared_ptr<view::Signal> >& Session::signals() const
260 bool Session::add_decoder(srd_decoder *const dec)
262 map<const srd_channel*, shared_ptr<view::LogicSignal> > channels;
263 shared_ptr<data::DecoderStack> decoder_stack;
267 lock_guard<boost::shared_mutex> lock(signals_mutex_);
269 // Create the decoder
270 decoder_stack = shared_ptr<data::DecoderStack>(
271 new data::DecoderStack(*this, dec));
273 // Make a list of all the channels
274 std::vector<const srd_channel*> all_channels;
275 for(const GSList *i = dec->channels; i; i = i->next)
276 all_channels.push_back((const srd_channel*)i->data);
277 for(const GSList *i = dec->opt_channels; i; i = i->next)
278 all_channels.push_back((const srd_channel*)i->data);
280 // Auto select the initial channels
281 for (const srd_channel *pdch : all_channels)
282 for (shared_ptr<view::Signal> s : signals_)
284 shared_ptr<view::LogicSignal> l =
285 dynamic_pointer_cast<view::LogicSignal>(s);
286 if (l && QString::fromUtf8(pdch->name).
288 l->name().toLower()))
292 assert(decoder_stack);
293 assert(!decoder_stack->stack().empty());
294 assert(decoder_stack->stack().front());
295 decoder_stack->stack().front()->set_channels(channels);
297 // Create the decode signal
298 shared_ptr<view::DecodeTrace> d(
299 new view::DecodeTrace(*this, decoder_stack,
300 decode_traces_.size()));
301 decode_traces_.push_back(d);
303 catch(std::runtime_error e)
310 // Do an initial decode
311 decoder_stack->begin_decode();
316 vector< shared_ptr<view::DecodeTrace> > Session::get_decode_signals() const
318 shared_lock<shared_mutex> lock(signals_mutex_);
319 return decode_traces_;
322 void Session::remove_decode_signal(view::DecodeTrace *signal)
324 for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
325 if ((*i).get() == signal)
327 decode_traces_.erase(i);
334 void Session::set_capture_state(capture_state state)
336 lock_guard<mutex> lock(sampling_mutex_);
337 const bool changed = capture_state_ != state;
338 capture_state_ = state;
340 capture_state_changed(state);
343 void Session::update_signals(shared_ptr<Device> device)
346 assert(capture_state_ == Stopped);
348 // Clear the decode traces
349 decode_traces_.clear();
351 // Detect what data types we will receive
352 auto channels = device->channels();
353 unsigned int logic_channel_count = std::count_if(
354 channels.begin(), channels.end(),
355 [] (shared_ptr<Channel> channel) {
356 return channel->type() == ChannelType::LOGIC; });
358 // Create data containers for the logic data snapshots
360 lock_guard<mutex> data_lock(data_mutex_);
363 if (logic_channel_count != 0) {
364 logic_data_.reset(new data::Logic(
365 logic_channel_count));
370 // Make the Signals list
372 unique_lock<shared_mutex> lock(signals_mutex_);
376 for (auto channel : device->channels()) {
377 shared_ptr<view::Signal> signal;
379 switch(channel->type()->id()) {
380 case SR_CHANNEL_LOGIC:
381 signal = shared_ptr<view::Signal>(
382 new view::LogicSignal(*this, device,
383 channel, logic_data_));
386 case SR_CHANNEL_ANALOG:
388 shared_ptr<data::Analog> data(
390 signal = shared_ptr<view::Signal>(
391 new view::AnalogSignal(
392 *this, channel, data));
402 signals_.push_back(signal);
410 shared_ptr<view::Signal> Session::signal_from_channel(
411 shared_ptr<Channel> channel) const
413 lock_guard<boost::shared_mutex> lock(signals_mutex_);
414 for (shared_ptr<view::Signal> sig : signals_) {
416 if (sig->channel() == channel)
419 return shared_ptr<view::Signal>();
422 void Session::read_sample_rate(shared_ptr<Device> device)
424 const auto keys = device_->config_keys(ConfigKey::DEVICE_OPTIONS);
425 const auto iter = keys.find(ConfigKey::SAMPLERATE);
426 const uint64_t sample_rate = (iter != keys.end() &&
427 (*iter).second.find(sigrok::GET) != (*iter).second.end()) ?
428 VariantBase::cast_dynamic<Variant<guint64>>(
429 device->config_get(ConfigKey::SAMPLERATE)).get() : 0;
431 // Set the sample rate of all data
432 const set< shared_ptr<data::SignalData> > data_set = get_data();
433 for (shared_ptr<data::SignalData> data : data_set) {
435 data->set_samplerate(sample_rate);
439 void Session::sample_thread_proc(shared_ptr<Device> device,
440 function<void (const QString)> error_handler)
443 assert(error_handler);
445 read_sample_rate(device);
450 error_handler(e.what());
454 set_capture_state(session_->trigger() ?
455 AwaitingTrigger : Running);
458 set_capture_state(Stopped);
460 // Confirm that SR_DF_END was received
461 if (cur_logic_snapshot_)
463 qDebug("SR_DF_END was not received.");
468 void Session::feed_in_header(shared_ptr<Device> device)
470 read_sample_rate(device);
473 void Session::feed_in_meta(shared_ptr<Device> device,
474 shared_ptr<Meta> meta)
478 for (auto entry : meta->config()) {
479 switch (entry.first->id()) {
480 case SR_CONF_SAMPLERATE:
481 /// @todo handle samplerate changes
484 // Unknown metadata is not an error.
492 void Session::feed_in_frame_begin()
494 if (cur_logic_snapshot_ || !cur_analog_snapshots_.empty())
498 void Session::feed_in_logic(shared_ptr<Logic> logic)
500 lock_guard<mutex> lock(data_mutex_);
504 qDebug() << "Unexpected logic packet";
508 if (!cur_logic_snapshot_)
510 // This could be the first packet after a trigger
511 set_capture_state(Running);
514 const auto keys = device_->config_keys(
515 ConfigKey::DEVICE_OPTIONS);
516 const auto iter = keys.find(ConfigKey::LIMIT_SAMPLES);
517 const uint64_t sample_limit = (iter != keys.end() &&
518 (*iter).second.find(sigrok::GET) !=
519 (*iter).second.end()) ?
520 VariantBase::cast_dynamic<Variant<guint64>>(
521 device_->config_get(ConfigKey::LIMIT_SAMPLES)).get() : 0;
523 // Create a new data snapshot
524 cur_logic_snapshot_ = shared_ptr<data::LogicSnapshot>(
525 new data::LogicSnapshot(logic, sample_limit));
526 logic_data_->push_snapshot(cur_logic_snapshot_);
528 // @todo Putting this here means that only listeners querying
529 // for logic will be notified. Currently the only user of
530 // frame_began is DecoderStack, but in future we need to signal
531 // this after both analog and logic sweeps have begun.
536 // Append to the existing data snapshot
537 cur_logic_snapshot_->append_payload(logic);
543 void Session::feed_in_analog(shared_ptr<Analog> analog)
545 lock_guard<mutex> lock(data_mutex_);
547 const vector<shared_ptr<Channel>> channels = analog->channels();
548 const unsigned int channel_count = channels.size();
549 const size_t sample_count = analog->num_samples() / channel_count;
550 const float *data = analog->data_pointer();
551 bool sweep_beginning = false;
553 for (auto channel : channels)
555 shared_ptr<data::AnalogSnapshot> snapshot;
557 // Try to get the snapshot of the channel
558 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSnapshot> >::
559 iterator iter = cur_analog_snapshots_.find(channel);
560 if (iter != cur_analog_snapshots_.end())
561 snapshot = (*iter).second;
564 // If no snapshot was found, this means we havn't
565 // created one yet. i.e. this is the first packet
566 // in the sweep containing this snapshot.
567 sweep_beginning = true;
570 uint64_t sample_limit;
572 sample_limit = VariantBase::cast_dynamic<Variant<guint64>>(
573 device_->config_get(ConfigKey::LIMIT_SAMPLES)).get();
578 // Create a snapshot, keep it in the maps of channels
579 snapshot = shared_ptr<data::AnalogSnapshot>(
580 new data::AnalogSnapshot(sample_limit));
581 cur_analog_snapshots_[channel] = snapshot;
583 // Find the annalog data associated with the channel
584 shared_ptr<view::AnalogSignal> sig =
585 dynamic_pointer_cast<view::AnalogSignal>(
586 signal_from_channel(channel));
589 shared_ptr<data::Analog> data(sig->analog_data());
592 // Push the snapshot into the analog data.
593 data->push_snapshot(snapshot);
598 // Append the samples in the snapshot
599 snapshot->append_interleaved_samples(data++, sample_count,
603 if (sweep_beginning) {
604 // This could be the first packet after a trigger
605 set_capture_state(Running);
611 void Session::data_feed_in(shared_ptr<Device> device, shared_ptr<Packet> packet)
616 switch (packet->type()->id()) {
618 feed_in_header(device);
622 feed_in_meta(device, dynamic_pointer_cast<Meta>(packet->payload()));
625 case SR_DF_FRAME_BEGIN:
626 feed_in_frame_begin();
630 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
634 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
640 lock_guard<mutex> lock(data_mutex_);
641 cur_logic_snapshot_.reset();
642 cur_analog_snapshots_.clear();