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 "view/analogsignal.hpp"
37 #include "view/decodetrace.hpp"
38 #include "view/logicsignal.hpp"
48 #include <libsigrokcxx/libsigrokcxx.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;
63 using std::unordered_set;
67 using sigrok::Channel;
68 using sigrok::ChannelType;
69 using sigrok::ConfigKey;
70 using sigrok::DatafeedCallbackFunction;
73 using sigrok::HardwareDevice;
78 using sigrok::PacketPayload;
79 using sigrok::Session;
80 using sigrok::SessionDevice;
82 using Glib::VariantBase;
86 Session::Session(DeviceManager &device_manager) :
87 device_manager_(device_manager),
88 session_(device_manager.context()->create_session()),
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 const shared_ptr<sigrok::Session>& Session::session() const
116 shared_ptr<Device> Session::device() const
121 void Session::set_device(shared_ptr<Device> device)
123 // Ensure we are not capturing before setting the device
126 // Are we setting a session device?
127 const auto session_device =
128 dynamic_pointer_cast<SessionDevice>(device);
130 // Did we have a session device selected previously?
131 const auto prev_session_device =
132 dynamic_pointer_cast<SessionDevice>(device_);
135 session_->remove_datafeed_callbacks();
136 if (!prev_session_device) {
138 session_->remove_devices();
143 session_ = session_device->parent();
145 decode_traces_.clear();
150 session_ = device_manager_.context()->create_session();
154 } catch(const sigrok::Error &e) {
155 throw QString(e.what());
158 session_->add_device(device);
162 session_->add_datafeed_callback([=]
163 (shared_ptr<Device> device, shared_ptr<Packet> packet) {
164 data_feed_in(device, packet);
166 device_manager_.update_display_name(device);
167 update_signals(device);
174 void Session::set_session_file(const string &name)
176 const shared_ptr<sigrok::Session> session =
177 device_manager_.context()->load_session(name);
178 set_device(session->devices()[0]);
181 void Session::set_default_device()
183 shared_ptr<HardwareDevice> default_device;
184 const list< shared_ptr<HardwareDevice> > &devices =
185 device_manager_.devices();
187 if (!devices.empty()) {
188 // Fall back to the first device in the list.
189 default_device = devices.front();
191 // Try and find the demo device and select that by default
192 for (shared_ptr<HardwareDevice> dev : devices)
193 if (dev->driver()->name().compare("demo") == 0) {
194 default_device = dev;
198 set_device(default_device);
202 Session::capture_state Session::get_capture_state() const
204 lock_guard<mutex> lock(sampling_mutex_);
205 return capture_state_;
208 void Session::start_capture(function<void (const QString)> error_handler)
212 // Check that a device instance has been selected.
214 qDebug() << "No device selected";
218 // Check that at least one channel is enabled
219 auto channels = device_->channels();
220 bool enabled = std::any_of(channels.begin(), channels.end(),
221 [](shared_ptr<Channel> channel) { return channel->enabled(); });
224 error_handler(tr("No channels enabled."));
229 sampling_thread_ = std::thread(
230 &Session::sample_thread_proc, this, device_,
234 void Session::stop_capture()
236 if (get_capture_state() != Stopped)
239 // Check that sampling stopped
240 if (sampling_thread_.joinable())
241 sampling_thread_.join();
244 set< shared_ptr<data::SignalData> > Session::get_data() const
246 shared_lock<shared_mutex> lock(signals_mutex_);
247 set< shared_ptr<data::SignalData> > data;
248 for (const shared_ptr<view::Signal> sig : signals_) {
250 data.insert(sig->data());
256 boost::shared_mutex& Session::signals_mutex() const
258 return signals_mutex_;
261 const unordered_set< shared_ptr<view::Signal> >& Session::signals() const
267 bool Session::add_decoder(srd_decoder *const dec)
269 map<const srd_channel*, shared_ptr<view::LogicSignal> > channels;
270 shared_ptr<data::DecoderStack> decoder_stack;
274 lock_guard<boost::shared_mutex> lock(signals_mutex_);
276 // Create the decoder
277 decoder_stack = shared_ptr<data::DecoderStack>(
278 new data::DecoderStack(*this, dec));
280 // Make a list of all the channels
281 std::vector<const srd_channel*> all_channels;
282 for(const GSList *i = dec->channels; i; i = i->next)
283 all_channels.push_back((const srd_channel*)i->data);
284 for(const GSList *i = dec->opt_channels; i; i = i->next)
285 all_channels.push_back((const srd_channel*)i->data);
287 // Auto select the initial channels
288 for (const srd_channel *pdch : all_channels)
289 for (shared_ptr<view::Signal> s : signals_)
291 shared_ptr<view::LogicSignal> l =
292 dynamic_pointer_cast<view::LogicSignal>(s);
293 if (l && QString::fromUtf8(pdch->name).
295 l->name().toLower()))
299 assert(decoder_stack);
300 assert(!decoder_stack->stack().empty());
301 assert(decoder_stack->stack().front());
302 decoder_stack->stack().front()->set_channels(channels);
304 // Create the decode signal
305 shared_ptr<view::DecodeTrace> d(
306 new view::DecodeTrace(*this, decoder_stack,
307 decode_traces_.size()));
308 decode_traces_.push_back(d);
310 catch(std::runtime_error e)
317 // Do an initial decode
318 decoder_stack->begin_decode();
323 vector< shared_ptr<view::DecodeTrace> > Session::get_decode_signals() const
325 shared_lock<shared_mutex> lock(signals_mutex_);
326 return decode_traces_;
329 void Session::remove_decode_signal(view::DecodeTrace *signal)
331 for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
332 if ((*i).get() == signal)
334 decode_traces_.erase(i);
341 void Session::set_capture_state(capture_state state)
343 lock_guard<mutex> lock(sampling_mutex_);
344 const bool changed = capture_state_ != state;
345 capture_state_ = state;
347 capture_state_changed(state);
350 void Session::update_signals(shared_ptr<Device> device)
353 assert(capture_state_ == Stopped);
355 // Clear the decode traces
356 decode_traces_.clear();
358 // Detect what data types we will receive
359 auto channels = device->channels();
360 unsigned int logic_channel_count = std::count_if(
361 channels.begin(), channels.end(),
362 [] (shared_ptr<Channel> channel) {
363 return channel->type() == ChannelType::LOGIC; });
365 // Create data containers for the logic data segments
367 lock_guard<mutex> data_lock(data_mutex_);
370 if (logic_channel_count != 0) {
371 logic_data_.reset(new data::Logic(
372 logic_channel_count));
377 // Make the Signals list
379 unique_lock<shared_mutex> lock(signals_mutex_);
383 for (auto channel : device->channels()) {
384 shared_ptr<view::Signal> signal;
386 switch(channel->type()->id()) {
387 case SR_CHANNEL_LOGIC:
388 signal = shared_ptr<view::Signal>(
389 new view::LogicSignal(*this, device,
390 channel, logic_data_));
393 case SR_CHANNEL_ANALOG:
395 shared_ptr<data::Analog> data(
397 signal = shared_ptr<view::Signal>(
398 new view::AnalogSignal(
399 *this, channel, data));
409 signals_.insert(signal);
417 shared_ptr<view::Signal> Session::signal_from_channel(
418 shared_ptr<Channel> channel) const
420 lock_guard<boost::shared_mutex> lock(signals_mutex_);
421 for (shared_ptr<view::Signal> sig : signals_) {
423 if (sig->channel() == channel)
426 return shared_ptr<view::Signal>();
429 void Session::read_sample_rate(shared_ptr<Device> device)
431 const auto keys = device_->config_keys(ConfigKey::DEVICE_OPTIONS);
432 const auto iter = keys.find(ConfigKey::SAMPLERATE);
433 cur_samplerate_ = (iter != keys.end() &&
434 (*iter).second.find(sigrok::GET) != (*iter).second.end()) ?
435 VariantBase::cast_dynamic<Variant<guint64>>(
436 device->config_get(ConfigKey::SAMPLERATE)).get() : 0;
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_segment_)
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_segment_ || !cur_analog_segments_.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_segment_)
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 segment
524 cur_logic_segment_ = shared_ptr<data::LogicSegment>(
525 new data::LogicSegment(
526 logic, cur_samplerate_, sample_limit));
527 logic_data_->push_segment(cur_logic_segment_);
529 // @todo Putting this here means that only listeners querying
530 // for logic will be notified. Currently the only user of
531 // frame_began is DecoderStack, but in future we need to signal
532 // this after both analog and logic sweeps have begun.
537 // Append to the existing data segment
538 cur_logic_segment_->append_payload(logic);
544 void Session::feed_in_analog(shared_ptr<Analog> analog)
546 lock_guard<mutex> lock(data_mutex_);
548 const vector<shared_ptr<Channel>> channels = analog->channels();
549 const unsigned int channel_count = channels.size();
550 const size_t sample_count = analog->num_samples() / channel_count;
551 const float *data = analog->data_pointer();
552 bool sweep_beginning = false;
554 for (auto channel : channels)
556 shared_ptr<data::AnalogSegment> segment;
558 // Try to get the segment of the channel
559 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
560 iterator iter = cur_analog_segments_.find(channel);
561 if (iter != cur_analog_segments_.end())
562 segment = (*iter).second;
565 // If no segment was found, this means we havn't
566 // created one yet. i.e. this is the first packet
567 // in the sweep containing this segment.
568 sweep_beginning = true;
571 uint64_t sample_limit;
573 sample_limit = VariantBase::cast_dynamic<Variant<guint64>>(
574 device_->config_get(ConfigKey::LIMIT_SAMPLES)).get();
579 // Create a segment, keep it in the maps of channels
580 segment = shared_ptr<data::AnalogSegment>(
581 new data::AnalogSegment(
582 cur_samplerate_, sample_limit));
583 cur_analog_segments_[channel] = segment;
585 // Find the annalog data associated with the channel
586 shared_ptr<view::AnalogSignal> sig =
587 dynamic_pointer_cast<view::AnalogSignal>(
588 signal_from_channel(channel));
591 shared_ptr<data::Analog> data(sig->analog_data());
594 // Push the segment into the analog data.
595 data->push_segment(segment);
600 // Append the samples in the segment
601 segment->append_interleaved_samples(data++, sample_count,
605 if (sweep_beginning) {
606 // This could be the first packet after a trigger
607 set_capture_state(Running);
613 void Session::data_feed_in(shared_ptr<Device> device, shared_ptr<Packet> packet)
618 switch (packet->type()->id()) {
620 feed_in_header(device);
624 feed_in_meta(device, dynamic_pointer_cast<Meta>(packet->payload()));
627 case SR_DF_FRAME_BEGIN:
628 feed_in_frame_begin();
632 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
636 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
642 lock_guard<mutex> lock(data_mutex_);
643 cur_logic_segment_.reset();
644 cur_analog_segments_.clear();