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
21 #include <boost/thread/locks.hpp>
22 #include <boost/thread/shared_mutex.hpp>
25 #include <libsigrokdecode/libsigrokdecode.h>
28 #include "session.hpp"
30 #include "devicemanager.hpp"
32 #include "data/analog.hpp"
33 #include "data/analogsegment.hpp"
34 #include "data/decoderstack.hpp"
35 #include "data/logic.hpp"
36 #include "data/logicsegment.hpp"
37 #include "data/decode/decoder.hpp"
39 #include "devices/hardwaredevice.hpp"
40 #include "devices/sessionfile.hpp"
42 #include "view/analogsignal.hpp"
43 #include "view/decodetrace.hpp"
44 #include "view/logicsignal.hpp"
54 #include <libsigrokcxx/libsigrokcxx.hpp>
56 using boost::shared_lock;
57 using boost::shared_mutex;
58 using boost::unique_lock;
60 using std::dynamic_pointer_cast;
62 using std::lock_guard;
66 using std::recursive_mutex;
68 using std::shared_ptr;
70 using std::unordered_set;
74 using sigrok::Channel;
75 using sigrok::ChannelType;
76 using sigrok::ConfigKey;
77 using sigrok::DatafeedCallbackFunction;
83 using sigrok::PacketPayload;
84 using sigrok::Session;
85 using sigrok::SessionDevice;
87 using Glib::VariantBase;
91 Session::Session(DeviceManager &device_manager) :
92 device_manager_(device_manager),
93 capture_state_(Stopped),
100 // Stop and join to the thread
104 DeviceManager& Session::device_manager()
106 return device_manager_;
109 const DeviceManager& Session::device_manager() const
111 return device_manager_;
114 shared_ptr<sigrok::Session> Session::session() const
117 return shared_ptr<sigrok::Session>();
118 return device_->session();
121 shared_ptr<devices::Device> Session::device() const
126 void Session::set_device(shared_ptr<devices::Device> device)
130 // Ensure we are not capturing before setting the device
136 device_ = std::move(device);
138 device_->session()->add_datafeed_callback([=]
139 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
140 data_feed_in(device, packet);
144 decode_traces_.clear();
149 void Session::set_default_device()
151 const list< shared_ptr<devices::HardwareDevice> > &devices =
152 device_manager_.devices();
157 // Try and find the demo device and select that by default
158 const auto iter = std::find_if(devices.begin(), devices.end(),
159 [] (const shared_ptr<devices::HardwareDevice> &d) {
160 return d->hardware_device()->driver()->name() ==
162 set_device((iter == devices.end()) ? devices.front() : *iter);
165 Session::capture_state Session::get_capture_state() const
167 lock_guard<mutex> lock(sampling_mutex_);
168 return capture_state_;
171 void Session::start_capture(function<void (const QString)> error_handler)
175 // Check that at least one channel is enabled
177 const shared_ptr<sigrok::Device> sr_dev = device_->device();
179 const auto channels = sr_dev->channels();
180 if (!std::any_of(channels.begin(), channels.end(),
181 [](shared_ptr<Channel> channel) {
182 return channel->enabled(); })) {
183 error_handler(tr("No channels enabled."));
189 for (const shared_ptr<data::SignalData> d : get_data())
193 sampling_thread_ = std::thread(
194 &Session::sample_thread_proc, this, device_,
198 void Session::stop_capture()
200 if (get_capture_state() != Stopped)
203 // Check that sampling stopped
204 if (sampling_thread_.joinable())
205 sampling_thread_.join();
208 set< shared_ptr<data::SignalData> > Session::get_data() const
210 shared_lock<shared_mutex> lock(signals_mutex_);
211 set< shared_ptr<data::SignalData> > data;
212 for (const shared_ptr<view::Signal> sig : signals_) {
214 data.insert(sig->data());
220 const unordered_set< shared_ptr<view::Signal> > Session::signals() const
222 shared_lock<shared_mutex> lock(signals_mutex_);
227 bool Session::add_decoder(srd_decoder *const dec)
229 map<const srd_channel*, shared_ptr<view::LogicSignal> > channels;
230 shared_ptr<data::DecoderStack> decoder_stack;
234 lock_guard<boost::shared_mutex> lock(signals_mutex_);
236 // Create the decoder
237 decoder_stack = shared_ptr<data::DecoderStack>(
238 new data::DecoderStack(*this, dec));
240 // Make a list of all the channels
241 std::vector<const srd_channel*> all_channels;
242 for (const GSList *i = dec->channels; i; i = i->next)
243 all_channels.push_back((const srd_channel*)i->data);
244 for (const GSList *i = dec->opt_channels; i; i = i->next)
245 all_channels.push_back((const srd_channel*)i->data);
247 // Auto select the initial channels
248 for (const srd_channel *pdch : all_channels)
249 for (shared_ptr<view::Signal> s : signals_)
251 shared_ptr<view::LogicSignal> l =
252 dynamic_pointer_cast<view::LogicSignal>(s);
253 if (l && QString::fromUtf8(pdch->name).
255 l->name().toLower()))
259 assert(decoder_stack);
260 assert(!decoder_stack->stack().empty());
261 assert(decoder_stack->stack().front());
262 decoder_stack->stack().front()->set_channels(channels);
264 // Create the decode signal
265 shared_ptr<view::DecodeTrace> d(
266 new view::DecodeTrace(*this, decoder_stack,
267 decode_traces_.size()));
268 decode_traces_.push_back(d);
270 catch(std::runtime_error e)
277 // Do an initial decode
278 decoder_stack->begin_decode();
283 vector< shared_ptr<view::DecodeTrace> > Session::get_decode_signals() const
285 shared_lock<shared_mutex> lock(signals_mutex_);
286 return decode_traces_;
289 void Session::remove_decode_signal(view::DecodeTrace *signal)
291 for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
292 if ((*i).get() == signal)
294 decode_traces_.erase(i);
301 void Session::set_capture_state(capture_state state)
303 lock_guard<mutex> lock(sampling_mutex_);
304 const bool changed = capture_state_ != state;
305 capture_state_ = state;
307 capture_state_changed(state);
310 void Session::update_signals()
314 lock_guard<recursive_mutex> lock(data_mutex_);
316 const shared_ptr<sigrok::Device> sr_dev = device_->device();
323 // Detect what data types we will receive
324 auto channels = sr_dev->channels();
325 unsigned int logic_channel_count = std::count_if(
326 channels.begin(), channels.end(),
327 [] (shared_ptr<Channel> channel) {
328 return channel->type() == ChannelType::LOGIC; });
330 // Create data containers for the logic data segments
332 lock_guard<recursive_mutex> data_lock(data_mutex_);
334 if (logic_channel_count == 0) {
336 } else if (!logic_data_ ||
337 logic_data_->num_channels() != logic_channel_count) {
338 logic_data_.reset(new data::Logic(
339 logic_channel_count));
344 // Make the Signals list
346 unique_lock<shared_mutex> lock(signals_mutex_);
348 unordered_set< shared_ptr<view::Signal> > prev_sigs(signals_);
351 for (auto channel : sr_dev->channels()) {
352 shared_ptr<view::Signal> signal;
354 // Find the channel in the old signals
355 const auto iter = std::find_if(
356 prev_sigs.cbegin(), prev_sigs.cend(),
357 [&](const shared_ptr<view::Signal> &s) {
358 return s->channel() == channel;
360 if (iter != prev_sigs.end()) {
361 // Copy the signal from the old set to the new
363 auto logic_signal = dynamic_pointer_cast<
364 view::LogicSignal>(signal);
366 logic_signal->set_logic_data(
369 // Create a new signal
370 switch(channel->type()->id()) {
371 case SR_CHANNEL_LOGIC:
372 signal = shared_ptr<view::Signal>(
373 new view::LogicSignal(*this,
378 case SR_CHANNEL_ANALOG:
380 shared_ptr<data::Analog> data(
382 signal = shared_ptr<view::Signal>(
383 new view::AnalogSignal(
384 *this, channel, data));
395 signals_.insert(signal);
402 shared_ptr<view::Signal> Session::signal_from_channel(
403 shared_ptr<Channel> channel) const
405 lock_guard<boost::shared_mutex> lock(signals_mutex_);
406 for (shared_ptr<view::Signal> sig : signals_) {
408 if (sig->channel() == channel)
411 return shared_ptr<view::Signal>();
414 void Session::sample_thread_proc(shared_ptr<devices::Device> device,
415 function<void (const QString)> error_handler)
418 assert(error_handler);
422 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
424 out_of_memory_ = false;
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 error_handler(tr("Out of memory, acquisition stopped."));
450 void Session::feed_in_header()
452 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
455 void Session::feed_in_meta(shared_ptr<Meta> meta)
457 for (auto entry : meta->config()) {
458 switch (entry.first->id()) {
459 case SR_CONF_SAMPLERATE:
460 /// @todo handle samplerate changes
463 // Unknown metadata is not an error.
471 void Session::feed_in_frame_begin()
473 if (cur_logic_segment_ || !cur_analog_segments_.empty())
477 void Session::feed_in_logic(shared_ptr<Logic> logic)
479 lock_guard<recursive_mutex> lock(data_mutex_);
481 const size_t sample_count = logic->data_length() / logic->unit_size();
485 // The only reason logic_data_ would not have been created is
486 // if it was not possible to determine the signals when the
487 // device was created.
491 if (!cur_logic_segment_)
493 // This could be the first packet after a trigger
494 set_capture_state(Running);
496 // Create a new data segment
497 cur_logic_segment_ = shared_ptr<data::LogicSegment>(
498 new data::LogicSegment(
499 logic, cur_samplerate_, sample_count));
500 logic_data_->push_segment(cur_logic_segment_);
502 // @todo Putting this here means that only listeners querying
503 // for logic will be notified. Currently the only user of
504 // frame_began is DecoderStack, but in future we need to signal
505 // this after both analog and logic sweeps have begun.
510 // Append to the existing data segment
511 cur_logic_segment_->append_payload(logic);
517 void Session::feed_in_analog(shared_ptr<Analog> analog)
519 lock_guard<recursive_mutex> lock(data_mutex_);
521 const vector<shared_ptr<Channel>> channels = analog->channels();
522 const unsigned int channel_count = channels.size();
523 const size_t sample_count = analog->num_samples() / channel_count;
524 const float *data = analog->data_pointer();
525 bool sweep_beginning = false;
527 for (auto channel : channels)
529 shared_ptr<data::AnalogSegment> segment;
531 // Try to get the segment of the channel
532 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
533 iterator iter = cur_analog_segments_.find(channel);
534 if (iter != cur_analog_segments_.end())
535 segment = (*iter).second;
538 // If no segment was found, this means we havn't
539 // created one yet. i.e. this is the first packet
540 // in the sweep containing this segment.
541 sweep_beginning = true;
543 // Create a segment, keep it in the maps of channels
544 segment = shared_ptr<data::AnalogSegment>(
545 new data::AnalogSegment(
546 cur_samplerate_, sample_count));
547 cur_analog_segments_[channel] = segment;
549 // Find the analog data associated with the channel
550 shared_ptr<view::AnalogSignal> sig =
551 dynamic_pointer_cast<view::AnalogSignal>(
552 signal_from_channel(channel));
555 shared_ptr<data::Analog> data(sig->analog_data());
558 // Push the segment into the analog data.
559 data->push_segment(segment);
564 // Append the samples in the segment
565 segment->append_interleaved_samples(data++, sample_count,
569 if (sweep_beginning) {
570 // This could be the first packet after a trigger
571 set_capture_state(Running);
577 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
578 shared_ptr<Packet> packet)
583 assert(device == device_->device());
586 switch (packet->type()->id()) {
592 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
595 case SR_DF_FRAME_BEGIN:
596 feed_in_frame_begin();
601 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
602 } catch (std::bad_alloc) {
603 out_of_memory_ = true;
610 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
611 } catch (std::bad_alloc) {
612 out_of_memory_ = true;
620 lock_guard<recursive_mutex> lock(data_mutex_);
621 cur_logic_segment_.reset();
622 cur_analog_segments_.clear();