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 "devices/hardwaredevice.hpp"
37 #include "devices/sessionfile.hpp"
39 #include "view/analogsignal.hpp"
40 #include "view/decodetrace.hpp"
41 #include "view/logicsignal.hpp"
51 #include <libsigrokcxx/libsigrokcxx.hpp>
53 using boost::shared_lock;
54 using boost::shared_mutex;
55 using boost::unique_lock;
57 using std::dynamic_pointer_cast;
59 using std::lock_guard;
63 using std::recursive_mutex;
65 using std::shared_ptr;
67 using std::unordered_set;
71 using sigrok::Channel;
72 using sigrok::ChannelType;
73 using sigrok::ConfigKey;
74 using sigrok::DatafeedCallbackFunction;
80 using sigrok::PacketPayload;
81 using sigrok::Session;
82 using sigrok::SessionDevice;
84 using Glib::VariantBase;
88 Session::Session(DeviceManager &device_manager) :
89 device_manager_(device_manager),
90 capture_state_(Stopped),
98 // Stop and join to the thread
102 DeviceManager& Session::device_manager()
104 return device_manager_;
107 const DeviceManager& Session::device_manager() const
109 return device_manager_;
112 shared_ptr<sigrok::Session> Session::session() const
115 return shared_ptr<sigrok::Session>();
116 return device_->session();
119 shared_ptr<devices::Device> Session::device() const
124 void Session::set_device(shared_ptr<devices::Device> device)
128 // Ensure we are not capturing before setting the device
131 device_ = std::move(device);
133 device_->session()->add_datafeed_callback([=]
134 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
135 data_feed_in(device, packet);
139 decode_traces_.clear();
144 void Session::set_default_device()
146 const list< shared_ptr<devices::HardwareDevice> > &devices =
147 device_manager_.devices();
152 // Try and find the demo device and select that by default
153 const auto iter = std::find_if(devices.begin(), devices.end(),
154 [] (const shared_ptr<devices::HardwareDevice> &d) {
155 return d->hardware_device()->driver()->name() ==
157 set_device((iter == devices.end()) ? devices.front() : *iter);
160 Session::capture_state Session::get_capture_state() const
162 lock_guard<mutex> lock(sampling_mutex_);
163 return capture_state_;
166 void Session::start_capture(function<void (const QString)> error_handler)
170 // Check that at least one channel is enabled
172 const std::shared_ptr<sigrok::Device> device = device_->device();
174 auto channels = device->channels();
175 bool enabled = std::any_of(channels.begin(), channels.end(),
176 [](shared_ptr<Channel> channel) { return channel->enabled(); });
179 error_handler(tr("No channels enabled."));
184 sampling_thread_ = std::thread(
185 &Session::sample_thread_proc, this, device_,
189 void Session::stop_capture()
191 if (get_capture_state() != Stopped)
194 // Check that sampling stopped
195 if (sampling_thread_.joinable())
196 sampling_thread_.join();
199 set< shared_ptr<data::SignalData> > Session::get_data() const
201 shared_lock<shared_mutex> lock(signals_mutex_);
202 set< shared_ptr<data::SignalData> > data;
203 for (const shared_ptr<view::Signal> sig : signals_) {
205 data.insert(sig->data());
211 boost::shared_mutex& Session::signals_mutex() const
213 return signals_mutex_;
216 const unordered_set< shared_ptr<view::Signal> >& Session::signals() const
222 bool Session::add_decoder(srd_decoder *const dec)
224 map<const srd_channel*, shared_ptr<view::LogicSignal> > channels;
225 shared_ptr<data::DecoderStack> decoder_stack;
229 lock_guard<boost::shared_mutex> lock(signals_mutex_);
231 // Create the decoder
232 decoder_stack = shared_ptr<data::DecoderStack>(
233 new data::DecoderStack(*this, dec));
235 // Make a list of all the channels
236 std::vector<const srd_channel*> all_channels;
237 for(const GSList *i = dec->channels; i; i = i->next)
238 all_channels.push_back((const srd_channel*)i->data);
239 for(const GSList *i = dec->opt_channels; i; i = i->next)
240 all_channels.push_back((const srd_channel*)i->data);
242 // Auto select the initial channels
243 for (const srd_channel *pdch : all_channels)
244 for (shared_ptr<view::Signal> s : signals_)
246 shared_ptr<view::LogicSignal> l =
247 dynamic_pointer_cast<view::LogicSignal>(s);
248 if (l && QString::fromUtf8(pdch->name).
250 l->name().toLower()))
254 assert(decoder_stack);
255 assert(!decoder_stack->stack().empty());
256 assert(decoder_stack->stack().front());
257 decoder_stack->stack().front()->set_channels(channels);
259 // Create the decode signal
260 shared_ptr<view::DecodeTrace> d(
261 new view::DecodeTrace(*this, decoder_stack,
262 decode_traces_.size()));
263 decode_traces_.push_back(d);
265 catch(std::runtime_error e)
272 // Do an initial decode
273 decoder_stack->begin_decode();
278 vector< shared_ptr<view::DecodeTrace> > Session::get_decode_signals() const
280 shared_lock<shared_mutex> lock(signals_mutex_);
281 return decode_traces_;
284 void Session::remove_decode_signal(view::DecodeTrace *signal)
286 for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
287 if ((*i).get() == signal)
289 decode_traces_.erase(i);
296 void Session::set_capture_state(capture_state state)
298 lock_guard<mutex> lock(sampling_mutex_);
299 const bool changed = capture_state_ != state;
300 capture_state_ = state;
302 capture_state_changed(state);
305 void Session::update_signals()
308 assert(capture_state_ == Stopped);
310 const shared_ptr<sigrok::Device> sr_dev = device_->device();
317 // Detect what data types we will receive
318 auto channels = sr_dev->channels();
319 unsigned int logic_channel_count = std::count_if(
320 channels.begin(), channels.end(),
321 [] (shared_ptr<Channel> channel) {
322 return channel->type() == ChannelType::LOGIC; });
324 // Create data containers for the logic data segments
326 lock_guard<recursive_mutex> data_lock(data_mutex_);
328 if (logic_channel_count == 0) {
330 } else if (!logic_data_ ||
331 logic_data_->num_channels() != logic_channel_count) {
332 logic_data_.reset(new data::Logic(
333 logic_channel_count));
338 // Make the Signals list
340 unique_lock<shared_mutex> lock(signals_mutex_);
342 unordered_set< shared_ptr<view::Signal> > prev_sigs(signals_);
345 for (auto channel : sr_dev->channels()) {
346 shared_ptr<view::Signal> signal;
348 // Find the channel in the old signals
349 const auto iter = std::find_if(
350 prev_sigs.cbegin(), prev_sigs.cend(),
351 [&](const shared_ptr<view::Signal> &s) {
352 return s->channel() == channel;
354 if (iter != prev_sigs.end()) {
355 // Copy the signal from the old set to the new
357 auto logic_signal = dynamic_pointer_cast<
358 view::LogicSignal>(signal);
360 logic_signal->set_logic_data(
363 // Create a new signal
364 switch(channel->type()->id()) {
365 case SR_CHANNEL_LOGIC:
366 signal = shared_ptr<view::Signal>(
367 new view::LogicSignal(*this,
372 case SR_CHANNEL_ANALOG:
374 shared_ptr<data::Analog> data(
376 signal = shared_ptr<view::Signal>(
377 new view::AnalogSignal(
378 *this, channel, data));
389 signals_.insert(signal);
396 shared_ptr<view::Signal> Session::signal_from_channel(
397 shared_ptr<Channel> channel) const
399 lock_guard<boost::shared_mutex> lock(signals_mutex_);
400 for (shared_ptr<view::Signal> sig : signals_) {
402 if (sig->channel() == channel)
405 return shared_ptr<view::Signal>();
408 void Session::read_sample_rate(shared_ptr<sigrok::Device> device)
411 map< const ConfigKey*, set<sigrok::Capability> > keys;
414 keys = device->config_keys(ConfigKey::DEVICE_OPTIONS);
415 } catch (const Error) {}
417 const auto iter = keys.find(ConfigKey::SAMPLERATE);
418 cur_samplerate_ = (iter != keys.end() &&
419 (*iter).second.find(sigrok::GET) != (*iter).second.end()) ?
420 VariantBase::cast_dynamic<Variant<guint64>>(
421 device->config_get(ConfigKey::SAMPLERATE)).get() : 0;
424 void Session::sample_thread_proc(shared_ptr<devices::Device> device,
425 function<void (const QString)> error_handler)
428 assert(error_handler);
430 const std::shared_ptr<sigrok::Device> sr_dev = device->device();
432 read_sample_rate(sr_dev);
435 device_->session()->start();
437 error_handler(e.what());
441 set_capture_state(device_->session()->trigger() ?
442 AwaitingTrigger : Running);
445 set_capture_state(Stopped);
447 // Confirm that SR_DF_END was received
448 if (cur_logic_segment_)
450 qDebug("SR_DF_END was not received.");
455 void Session::feed_in_header()
457 read_sample_rate(device_->device());
460 void Session::feed_in_meta(shared_ptr<Meta> meta)
462 for (auto entry : meta->config()) {
463 switch (entry.first->id()) {
464 case SR_CONF_SAMPLERATE:
465 /// @todo handle samplerate changes
468 // Unknown metadata is not an error.
476 void Session::feed_in_frame_begin()
478 if (cur_logic_segment_ || !cur_analog_segments_.empty())
482 void Session::feed_in_logic(shared_ptr<Logic> logic)
484 lock_guard<recursive_mutex> lock(data_mutex_);
488 qDebug() << "Unexpected logic packet";
492 if (!cur_logic_segment_)
494 // This could be the first packet after a trigger
495 set_capture_state(Running);
499 const std::shared_ptr<sigrok::Device> device =
502 const auto keys = device->config_keys(
503 ConfigKey::DEVICE_OPTIONS);
504 const auto iter = keys.find(ConfigKey::LIMIT_SAMPLES);
505 const uint64_t sample_limit = (iter != keys.end() &&
506 (*iter).second.find(sigrok::GET) !=
507 (*iter).second.end()) ?
508 VariantBase::cast_dynamic<Variant<guint64>>(
509 device->config_get(ConfigKey::LIMIT_SAMPLES)).get() : 0;
511 // Create a new data segment
512 cur_logic_segment_ = shared_ptr<data::LogicSegment>(
513 new data::LogicSegment(
514 logic, cur_samplerate_, sample_limit));
515 logic_data_->push_segment(cur_logic_segment_);
517 // @todo Putting this here means that only listeners querying
518 // for logic will be notified. Currently the only user of
519 // frame_began is DecoderStack, but in future we need to signal
520 // this after both analog and logic sweeps have begun.
525 // Append to the existing data segment
526 cur_logic_segment_->append_payload(logic);
532 void Session::feed_in_analog(shared_ptr<Analog> analog)
534 lock_guard<recursive_mutex> lock(data_mutex_);
536 const vector<shared_ptr<Channel>> channels = analog->channels();
537 const unsigned int channel_count = channels.size();
538 const size_t sample_count = analog->num_samples() / channel_count;
539 const float *data = analog->data_pointer();
540 bool sweep_beginning = false;
542 for (auto channel : channels)
544 shared_ptr<data::AnalogSegment> segment;
546 // Try to get the segment of the channel
547 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
548 iterator iter = cur_analog_segments_.find(channel);
549 if (iter != cur_analog_segments_.end())
550 segment = (*iter).second;
553 // If no segment was found, this means we havn't
554 // created one yet. i.e. this is the first packet
555 // in the sweep containing this segment.
556 sweep_beginning = true;
559 uint64_t sample_limit;
562 const std::shared_ptr<sigrok::Device> device =
565 sample_limit = VariantBase::cast_dynamic<Variant<guint64>>(
566 device->config_get(ConfigKey::LIMIT_SAMPLES)).get();
571 // Create a segment, keep it in the maps of channels
572 segment = shared_ptr<data::AnalogSegment>(
573 new data::AnalogSegment(
574 cur_samplerate_, sample_limit));
575 cur_analog_segments_[channel] = segment;
577 // Find the annalog data associated with the channel
578 shared_ptr<view::AnalogSignal> sig =
579 dynamic_pointer_cast<view::AnalogSignal>(
580 signal_from_channel(channel));
583 shared_ptr<data::Analog> data(sig->analog_data());
586 // Push the segment into the analog data.
587 data->push_segment(segment);
592 // Append the samples in the segment
593 segment->append_interleaved_samples(data++, sample_count,
597 if (sweep_beginning) {
598 // This could be the first packet after a trigger
599 set_capture_state(Running);
605 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
606 shared_ptr<Packet> packet)
611 assert(device == device_->device());
614 switch (packet->type()->id()) {
620 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
623 case SR_DF_FRAME_BEGIN:
624 feed_in_frame_begin();
628 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
632 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
638 lock_guard<recursive_mutex> lock(data_mutex_);
639 cur_logic_segment_.reset();
640 cur_analog_segments_.clear();