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;
64 using std::shared_ptr;
66 using std::unordered_set;
70 using sigrok::Channel;
71 using sigrok::ChannelType;
72 using sigrok::ConfigKey;
73 using sigrok::DatafeedCallbackFunction;
79 using sigrok::PacketPayload;
80 using sigrok::Session;
81 using sigrok::SessionDevice;
83 using Glib::VariantBase;
87 Session::Session(DeviceManager &device_manager) :
88 device_manager_(device_manager),
89 capture_state_(Stopped),
97 // Stop and join to the thread
101 DeviceManager& Session::device_manager()
103 return device_manager_;
106 const DeviceManager& Session::device_manager() const
108 return device_manager_;
111 shared_ptr<sigrok::Session> Session::session() const
114 return shared_ptr<sigrok::Session>();
115 return device_->session();
118 shared_ptr<devices::Device> Session::device() const
123 void Session::set_device(shared_ptr<devices::Device> device)
127 // Ensure we are not capturing before setting the device
130 device_ = std::move(device);
132 device_->session()->add_datafeed_callback([=]
133 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
134 data_feed_in(device, packet);
136 update_signals(device_);
138 decode_traces_.clear();
143 void Session::set_default_device()
145 const list< shared_ptr<devices::HardwareDevice> > &devices =
146 device_manager_.devices();
151 // Try and find the demo device and select that by default
152 const auto iter = std::find_if(devices.begin(), devices.end(),
153 [] (const shared_ptr<devices::HardwareDevice> &d) {
154 return d->hardware_device()->driver()->name() ==
156 set_device((iter == devices.end()) ? devices.front() : *iter);
159 Session::capture_state Session::get_capture_state() const
161 lock_guard<mutex> lock(sampling_mutex_);
162 return capture_state_;
165 void Session::start_capture(function<void (const QString)> error_handler)
169 // Check that at least one channel is enabled
171 const std::shared_ptr<sigrok::Device> device = device_->device();
173 auto channels = device->channels();
174 bool enabled = std::any_of(channels.begin(), channels.end(),
175 [](shared_ptr<Channel> channel) { return channel->enabled(); });
178 error_handler(tr("No channels enabled."));
183 sampling_thread_ = std::thread(
184 &Session::sample_thread_proc, this, device_,
188 void Session::stop_capture()
190 if (get_capture_state() != Stopped)
193 // Check that sampling stopped
194 if (sampling_thread_.joinable())
195 sampling_thread_.join();
198 set< shared_ptr<data::SignalData> > Session::get_data() const
200 shared_lock<shared_mutex> lock(signals_mutex_);
201 set< shared_ptr<data::SignalData> > data;
202 for (const shared_ptr<view::Signal> sig : signals_) {
204 data.insert(sig->data());
210 boost::shared_mutex& Session::signals_mutex() const
212 return signals_mutex_;
215 const unordered_set< shared_ptr<view::Signal> >& Session::signals() const
221 bool Session::add_decoder(srd_decoder *const dec)
223 map<const srd_channel*, shared_ptr<view::LogicSignal> > channels;
224 shared_ptr<data::DecoderStack> decoder_stack;
228 lock_guard<boost::shared_mutex> lock(signals_mutex_);
230 // Create the decoder
231 decoder_stack = shared_ptr<data::DecoderStack>(
232 new data::DecoderStack(*this, dec));
234 // Make a list of all the channels
235 std::vector<const srd_channel*> all_channels;
236 for(const GSList *i = dec->channels; i; i = i->next)
237 all_channels.push_back((const srd_channel*)i->data);
238 for(const GSList *i = dec->opt_channels; i; i = i->next)
239 all_channels.push_back((const srd_channel*)i->data);
241 // Auto select the initial channels
242 for (const srd_channel *pdch : all_channels)
243 for (shared_ptr<view::Signal> s : signals_)
245 shared_ptr<view::LogicSignal> l =
246 dynamic_pointer_cast<view::LogicSignal>(s);
247 if (l && QString::fromUtf8(pdch->name).
249 l->name().toLower()))
253 assert(decoder_stack);
254 assert(!decoder_stack->stack().empty());
255 assert(decoder_stack->stack().front());
256 decoder_stack->stack().front()->set_channels(channels);
258 // Create the decode signal
259 shared_ptr<view::DecodeTrace> d(
260 new view::DecodeTrace(*this, decoder_stack,
261 decode_traces_.size()));
262 decode_traces_.push_back(d);
264 catch(std::runtime_error e)
271 // Do an initial decode
272 decoder_stack->begin_decode();
277 vector< shared_ptr<view::DecodeTrace> > Session::get_decode_signals() const
279 shared_lock<shared_mutex> lock(signals_mutex_);
280 return decode_traces_;
283 void Session::remove_decode_signal(view::DecodeTrace *signal)
285 for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
286 if ((*i).get() == signal)
288 decode_traces_.erase(i);
295 void Session::set_capture_state(capture_state state)
297 lock_guard<mutex> lock(sampling_mutex_);
298 const bool changed = capture_state_ != state;
299 capture_state_ = state;
301 capture_state_changed(state);
304 void Session::update_signals(shared_ptr<devices::Device> device)
307 assert(capture_state_ == Stopped);
309 // Detect what data types we will receive
310 auto channels = device->device()->channels();
311 unsigned int logic_channel_count = std::count_if(
312 channels.begin(), channels.end(),
313 [] (shared_ptr<Channel> channel) {
314 return channel->type() == ChannelType::LOGIC; });
316 // Create data containers for the logic data segments
318 lock_guard<mutex> data_lock(data_mutex_);
320 if (logic_channel_count == 0) {
322 } else if (!logic_data_ ||
323 logic_data_->num_channels() != logic_channel_count) {
324 logic_data_.reset(new data::Logic(
325 logic_channel_count));
330 // Make the Signals list
332 unique_lock<shared_mutex> lock(signals_mutex_);
334 unordered_set< shared_ptr<view::Signal> > prev_sigs(signals_);
337 for (auto channel : device->device()->channels()) {
338 shared_ptr<view::Signal> signal;
340 // Find the channel in the old signals
341 const auto iter = std::find_if(
342 prev_sigs.cbegin(), prev_sigs.cend(),
343 [&](const shared_ptr<view::Signal> &s) {
344 return s->channel() == channel;
346 if (iter != prev_sigs.end()) {
347 // Copy the signal from the old set to the new
349 auto logic_signal = dynamic_pointer_cast<
350 view::LogicSignal>(signal);
352 logic_signal->set_logic_data(
355 // Create a new signal
356 switch(channel->type()->id()) {
357 case SR_CHANNEL_LOGIC:
358 signal = shared_ptr<view::Signal>(
359 new view::LogicSignal(*this,
364 case SR_CHANNEL_ANALOG:
366 shared_ptr<data::Analog> data(
368 signal = shared_ptr<view::Signal>(
369 new view::AnalogSignal(
370 *this, channel, data));
381 signals_.insert(signal);
388 shared_ptr<view::Signal> Session::signal_from_channel(
389 shared_ptr<Channel> channel) const
391 lock_guard<boost::shared_mutex> lock(signals_mutex_);
392 for (shared_ptr<view::Signal> sig : signals_) {
394 if (sig->channel() == channel)
397 return shared_ptr<view::Signal>();
400 void Session::read_sample_rate(shared_ptr<sigrok::Device> device)
403 map< const ConfigKey*, set<sigrok::Capability> > keys;
406 keys = device->config_keys(ConfigKey::DEVICE_OPTIONS);
407 } catch (const Error) {}
409 const auto iter = keys.find(ConfigKey::SAMPLERATE);
410 cur_samplerate_ = (iter != keys.end() &&
411 (*iter).second.find(sigrok::GET) != (*iter).second.end()) ?
412 VariantBase::cast_dynamic<Variant<guint64>>(
413 device->config_get(ConfigKey::SAMPLERATE)).get() : 0;
416 void Session::sample_thread_proc(shared_ptr<devices::Device> device,
417 function<void (const QString)> error_handler)
420 assert(error_handler);
422 const std::shared_ptr<sigrok::Device> sr_dev = device->device();
424 read_sample_rate(sr_dev);
427 device_->session()->start();
429 error_handler(e.what());
433 set_capture_state(device_->session()->trigger() ?
434 AwaitingTrigger : Running);
437 set_capture_state(Stopped);
439 // Confirm that SR_DF_END was received
440 if (cur_logic_segment_)
442 qDebug("SR_DF_END was not received.");
447 void Session::feed_in_header()
449 read_sample_rate(device_->device());
452 void Session::feed_in_meta(shared_ptr<Meta> meta)
454 for (auto entry : meta->config()) {
455 switch (entry.first->id()) {
456 case SR_CONF_SAMPLERATE:
457 /// @todo handle samplerate changes
460 // Unknown metadata is not an error.
468 void Session::feed_in_frame_begin()
470 if (cur_logic_segment_ || !cur_analog_segments_.empty())
474 void Session::feed_in_logic(shared_ptr<Logic> logic)
476 lock_guard<mutex> lock(data_mutex_);
480 qDebug() << "Unexpected logic packet";
484 if (!cur_logic_segment_)
486 // This could be the first packet after a trigger
487 set_capture_state(Running);
491 const std::shared_ptr<sigrok::Device> device =
494 const auto keys = device->config_keys(
495 ConfigKey::DEVICE_OPTIONS);
496 const auto iter = keys.find(ConfigKey::LIMIT_SAMPLES);
497 const uint64_t sample_limit = (iter != keys.end() &&
498 (*iter).second.find(sigrok::GET) !=
499 (*iter).second.end()) ?
500 VariantBase::cast_dynamic<Variant<guint64>>(
501 device->config_get(ConfigKey::LIMIT_SAMPLES)).get() : 0;
503 // Create a new data segment
504 cur_logic_segment_ = shared_ptr<data::LogicSegment>(
505 new data::LogicSegment(
506 logic, cur_samplerate_, sample_limit));
507 logic_data_->push_segment(cur_logic_segment_);
509 // @todo Putting this here means that only listeners querying
510 // for logic will be notified. Currently the only user of
511 // frame_began is DecoderStack, but in future we need to signal
512 // this after both analog and logic sweeps have begun.
517 // Append to the existing data segment
518 cur_logic_segment_->append_payload(logic);
524 void Session::feed_in_analog(shared_ptr<Analog> analog)
526 lock_guard<mutex> lock(data_mutex_);
528 const vector<shared_ptr<Channel>> channels = analog->channels();
529 const unsigned int channel_count = channels.size();
530 const size_t sample_count = analog->num_samples() / channel_count;
531 const float *data = analog->data_pointer();
532 bool sweep_beginning = false;
534 for (auto channel : channels)
536 shared_ptr<data::AnalogSegment> segment;
538 // Try to get the segment of the channel
539 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
540 iterator iter = cur_analog_segments_.find(channel);
541 if (iter != cur_analog_segments_.end())
542 segment = (*iter).second;
545 // If no segment was found, this means we havn't
546 // created one yet. i.e. this is the first packet
547 // in the sweep containing this segment.
548 sweep_beginning = true;
551 uint64_t sample_limit;
554 const std::shared_ptr<sigrok::Device> device =
557 sample_limit = VariantBase::cast_dynamic<Variant<guint64>>(
558 device->config_get(ConfigKey::LIMIT_SAMPLES)).get();
563 // Create a segment, keep it in the maps of channels
564 segment = shared_ptr<data::AnalogSegment>(
565 new data::AnalogSegment(
566 cur_samplerate_, sample_limit));
567 cur_analog_segments_[channel] = segment;
569 // Find the annalog data associated with the channel
570 shared_ptr<view::AnalogSignal> sig =
571 dynamic_pointer_cast<view::AnalogSignal>(
572 signal_from_channel(channel));
575 shared_ptr<data::Analog> data(sig->analog_data());
578 // Push the segment into the analog data.
579 data->push_segment(segment);
584 // Append the samples in the segment
585 segment->append_interleaved_samples(data++, sample_count,
589 if (sweep_beginning) {
590 // This could be the first packet after a trigger
591 set_capture_state(Running);
597 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
598 shared_ptr<Packet> packet)
603 assert(device == device_->device());
606 switch (packet->type()->id()) {
612 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
615 case SR_DF_FRAME_BEGIN:
616 feed_in_frame_begin();
620 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
624 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
630 lock_guard<mutex> lock(data_mutex_);
631 cur_logic_segment_.reset();
632 cur_analog_segments_.clear();