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();
140 decode_traces_.clear();
145 session_ = device_manager_.context()->create_session();
149 } catch(const sigrok::Error &e) {
150 throw QString(e.what());
153 session_->add_device(device);
157 session_->add_datafeed_callback([=]
158 (shared_ptr<Device> device, shared_ptr<Packet> packet) {
159 data_feed_in(device, packet);
161 update_signals(device);
168 void Session::set_file(const string &name)
170 session_ = device_manager_.context()->load_session(name);
171 device_ = session_->devices()[0];
172 decode_traces_.clear();
173 session_->add_datafeed_callback([=]
174 (shared_ptr<Device> device, shared_ptr<Packet> packet) {
175 data_feed_in(device, packet);
177 device_manager_.update_display_name(device_);
178 update_signals(device_);
182 void Session::set_default_device()
184 shared_ptr<HardwareDevice> default_device;
185 const list< shared_ptr<HardwareDevice> > &devices =
186 device_manager_.devices();
188 if (!devices.empty()) {
189 // Fall back to the first device in the list.
190 default_device = devices.front();
192 // Try and find the demo device and select that by default
193 for (shared_ptr<HardwareDevice> dev : devices)
194 if (dev->driver()->name().compare("demo") == 0) {
195 default_device = dev;
199 set_device(default_device);
203 Session::capture_state Session::get_capture_state() const
205 lock_guard<mutex> lock(sampling_mutex_);
206 return capture_state_;
209 void Session::start_capture(function<void (const QString)> error_handler)
213 // Check that a device instance has been selected.
215 qDebug() << "No device selected";
219 // Check that at least one channel is enabled
220 auto channels = device_->channels();
221 bool enabled = std::any_of(channels.begin(), channels.end(),
222 [](shared_ptr<Channel> channel) { return channel->enabled(); });
225 error_handler(tr("No channels enabled."));
230 sampling_thread_ = std::thread(
231 &Session::sample_thread_proc, this, device_,
235 void Session::stop_capture()
237 if (get_capture_state() != Stopped)
240 // Check that sampling stopped
241 if (sampling_thread_.joinable())
242 sampling_thread_.join();
245 set< shared_ptr<data::SignalData> > Session::get_data() const
247 shared_lock<shared_mutex> lock(signals_mutex_);
248 set< shared_ptr<data::SignalData> > data;
249 for (const shared_ptr<view::Signal> sig : signals_) {
251 data.insert(sig->data());
257 boost::shared_mutex& Session::signals_mutex() const
259 return signals_mutex_;
262 const vector< shared_ptr<view::Signal> >& Session::signals() const
268 bool Session::add_decoder(srd_decoder *const dec)
270 map<const srd_channel*, shared_ptr<view::LogicSignal> > channels;
271 shared_ptr<data::DecoderStack> decoder_stack;
275 lock_guard<boost::shared_mutex> lock(signals_mutex_);
277 // Create the decoder
278 decoder_stack = shared_ptr<data::DecoderStack>(
279 new data::DecoderStack(*this, dec));
281 // Make a list of all the channels
282 std::vector<const srd_channel*> all_channels;
283 for(const GSList *i = dec->channels; i; i = i->next)
284 all_channels.push_back((const srd_channel*)i->data);
285 for(const GSList *i = dec->opt_channels; i; i = i->next)
286 all_channels.push_back((const srd_channel*)i->data);
288 // Auto select the initial channels
289 for (const srd_channel *pdch : all_channels)
290 for (shared_ptr<view::Signal> s : signals_)
292 shared_ptr<view::LogicSignal> l =
293 dynamic_pointer_cast<view::LogicSignal>(s);
294 if (l && QString::fromUtf8(pdch->name).
296 l->name().toLower()))
300 assert(decoder_stack);
301 assert(!decoder_stack->stack().empty());
302 assert(decoder_stack->stack().front());
303 decoder_stack->stack().front()->set_channels(channels);
305 // Create the decode signal
306 shared_ptr<view::DecodeTrace> d(
307 new view::DecodeTrace(*this, decoder_stack,
308 decode_traces_.size()));
309 decode_traces_.push_back(d);
311 catch(std::runtime_error e)
318 // Do an initial decode
319 decoder_stack->begin_decode();
324 vector< shared_ptr<view::DecodeTrace> > Session::get_decode_signals() const
326 shared_lock<shared_mutex> lock(signals_mutex_);
327 return decode_traces_;
330 void Session::remove_decode_signal(view::DecodeTrace *signal)
332 for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
333 if ((*i).get() == signal)
335 decode_traces_.erase(i);
342 void Session::set_capture_state(capture_state state)
344 lock_guard<mutex> lock(sampling_mutex_);
345 const bool changed = capture_state_ != state;
346 capture_state_ = state;
348 capture_state_changed(state);
351 void Session::update_signals(shared_ptr<Device> device)
354 assert(capture_state_ == Stopped);
356 // Clear the decode traces
357 decode_traces_.clear();
359 // Detect what data types we will receive
360 auto channels = device->channels();
361 unsigned int logic_channel_count = std::count_if(
362 channels.begin(), channels.end(),
363 [] (shared_ptr<Channel> channel) {
364 return channel->type() == ChannelType::LOGIC; });
366 // Create data containers for the logic data snapshots
368 lock_guard<mutex> data_lock(data_mutex_);
371 if (logic_channel_count != 0) {
372 logic_data_.reset(new data::Logic(
373 logic_channel_count));
378 // Make the Signals list
380 unique_lock<shared_mutex> lock(signals_mutex_);
384 for (auto channel : device->channels()) {
385 shared_ptr<view::Signal> signal;
387 switch(channel->type()->id()) {
388 case SR_CHANNEL_LOGIC:
389 signal = shared_ptr<view::Signal>(
390 new view::LogicSignal(*this, device,
391 channel, logic_data_));
394 case SR_CHANNEL_ANALOG:
396 shared_ptr<data::Analog> data(
398 signal = shared_ptr<view::Signal>(
399 new view::AnalogSignal(
400 *this, channel, data));
410 signals_.push_back(signal);
418 shared_ptr<view::Signal> Session::signal_from_channel(
419 shared_ptr<Channel> channel) const
421 lock_guard<boost::shared_mutex> lock(signals_mutex_);
422 for (shared_ptr<view::Signal> sig : signals_) {
424 if (sig->channel() == channel)
427 return shared_ptr<view::Signal>();
430 void Session::read_sample_rate(shared_ptr<Device> device)
432 const auto keys = device_->config_keys(ConfigKey::DEVICE_OPTIONS);
433 const auto iter = keys.find(ConfigKey::SAMPLERATE);
434 const uint64_t sample_rate = (iter != keys.end() &&
435 (*iter).second.find(sigrok::GET) != (*iter).second.end()) ?
436 VariantBase::cast_dynamic<Variant<guint64>>(
437 device->config_get(ConfigKey::SAMPLERATE)).get() : 0;
439 // Set the sample rate of all data
440 const set< shared_ptr<data::SignalData> > data_set = get_data();
441 for (shared_ptr<data::SignalData> data : data_set) {
443 data->set_samplerate(sample_rate);
447 void Session::sample_thread_proc(shared_ptr<Device> device,
448 function<void (const QString)> error_handler)
451 assert(error_handler);
453 read_sample_rate(device);
458 error_handler(e.what());
462 set_capture_state(session_->trigger() ?
463 AwaitingTrigger : Running);
466 set_capture_state(Stopped);
468 // Confirm that SR_DF_END was received
469 if (cur_logic_snapshot_)
471 qDebug("SR_DF_END was not received.");
476 void Session::feed_in_header(shared_ptr<Device> device)
478 read_sample_rate(device);
481 void Session::feed_in_meta(shared_ptr<Device> device,
482 shared_ptr<Meta> meta)
486 for (auto entry : meta->config()) {
487 switch (entry.first->id()) {
488 case SR_CONF_SAMPLERATE:
489 /// @todo handle samplerate changes
492 // Unknown metadata is not an error.
500 void Session::feed_in_frame_begin()
502 if (cur_logic_snapshot_ || !cur_analog_snapshots_.empty())
506 void Session::feed_in_logic(shared_ptr<Logic> logic)
508 lock_guard<mutex> lock(data_mutex_);
512 qDebug() << "Unexpected logic packet";
516 if (!cur_logic_snapshot_)
518 // This could be the first packet after a trigger
519 set_capture_state(Running);
522 const auto keys = device_->config_keys(
523 ConfigKey::DEVICE_OPTIONS);
524 const auto iter = keys.find(ConfigKey::LIMIT_SAMPLES);
525 const uint64_t sample_limit = (iter != keys.end() &&
526 (*iter).second.find(sigrok::GET) !=
527 (*iter).second.end()) ?
528 VariantBase::cast_dynamic<Variant<guint64>>(
529 device_->config_get(ConfigKey::LIMIT_SAMPLES)).get() : 0;
531 // Create a new data snapshot
532 cur_logic_snapshot_ = shared_ptr<data::LogicSnapshot>(
533 new data::LogicSnapshot(logic, sample_limit));
534 logic_data_->push_snapshot(cur_logic_snapshot_);
536 // @todo Putting this here means that only listeners querying
537 // for logic will be notified. Currently the only user of
538 // frame_began is DecoderStack, but in future we need to signal
539 // this after both analog and logic sweeps have begun.
544 // Append to the existing data snapshot
545 cur_logic_snapshot_->append_payload(logic);
551 void Session::feed_in_analog(shared_ptr<Analog> analog)
553 lock_guard<mutex> lock(data_mutex_);
555 const vector<shared_ptr<Channel>> channels = analog->channels();
556 const unsigned int channel_count = channels.size();
557 const size_t sample_count = analog->num_samples() / channel_count;
558 const float *data = analog->data_pointer();
559 bool sweep_beginning = false;
561 for (auto channel : channels)
563 shared_ptr<data::AnalogSnapshot> snapshot;
565 // Try to get the snapshot of the channel
566 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSnapshot> >::
567 iterator iter = cur_analog_snapshots_.find(channel);
568 if (iter != cur_analog_snapshots_.end())
569 snapshot = (*iter).second;
572 // If no snapshot was found, this means we havn't
573 // created one yet. i.e. this is the first packet
574 // in the sweep containing this snapshot.
575 sweep_beginning = true;
578 uint64_t sample_limit;
580 sample_limit = VariantBase::cast_dynamic<Variant<guint64>>(
581 device_->config_get(ConfigKey::LIMIT_SAMPLES)).get();
586 // Create a snapshot, keep it in the maps of channels
587 snapshot = shared_ptr<data::AnalogSnapshot>(
588 new data::AnalogSnapshot(sample_limit));
589 cur_analog_snapshots_[channel] = snapshot;
591 // Find the annalog data associated with the channel
592 shared_ptr<view::AnalogSignal> sig =
593 dynamic_pointer_cast<view::AnalogSignal>(
594 signal_from_channel(channel));
597 shared_ptr<data::Analog> data(sig->analog_data());
600 // Push the snapshot into the analog data.
601 data->push_snapshot(snapshot);
606 // Append the samples in the snapshot
607 snapshot->append_interleaved_samples(data++, sample_count,
611 if (sweep_beginning) {
612 // This could be the first packet after a trigger
613 set_capture_state(Running);
619 void Session::data_feed_in(shared_ptr<Device> device, shared_ptr<Packet> packet)
624 switch (packet->type()->id()) {
626 feed_in_header(device);
630 feed_in_meta(device, dynamic_pointer_cast<Meta>(packet->payload()));
633 case SR_DF_FRAME_BEGIN:
634 feed_in_frame_begin();
638 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
642 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
648 lock_guard<mutex> lock(data_mutex_);
649 cur_logic_snapshot_.reset();
650 cur_analog_snapshots_.clear();