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 // Windows: Avoid boost/thread namespace pollution (which includes windows.h).
26 #include <boost/thread/locks.hpp>
27 #include <boost/thread/shared_mutex.hpp>
30 #include <libsigrokdecode/libsigrokdecode.h>
33 #include "session.hpp"
35 #include "devicemanager.hpp"
37 #include "data/analog.hpp"
38 #include "data/analogsegment.hpp"
39 #include "data/decoderstack.hpp"
40 #include "data/logic.hpp"
41 #include "data/logicsegment.hpp"
42 #include "data/decode/decoder.hpp"
44 #include "devices/hardwaredevice.hpp"
45 #include "devices/sessionfile.hpp"
47 #include "view/analogsignal.hpp"
48 #include "view/decodetrace.hpp"
49 #include "view/logicsignal.hpp"
59 #include <libsigrokcxx/libsigrokcxx.hpp>
61 using boost::shared_lock;
62 using boost::shared_mutex;
63 using boost::unique_lock;
65 using std::dynamic_pointer_cast;
67 using std::lock_guard;
71 using std::recursive_mutex;
73 using std::shared_ptr;
75 using std::unordered_set;
79 using sigrok::Channel;
80 using sigrok::ChannelType;
81 using sigrok::ConfigKey;
82 using sigrok::DatafeedCallbackFunction;
88 using sigrok::PacketPayload;
89 using sigrok::Session;
90 using sigrok::SessionDevice;
92 using Glib::VariantBase;
96 Session::Session(DeviceManager &device_manager) :
97 device_manager_(device_manager),
98 capture_state_(Stopped),
105 // Stop and join to the thread
109 DeviceManager& Session::device_manager()
111 return device_manager_;
114 const DeviceManager& Session::device_manager() const
116 return device_manager_;
119 shared_ptr<sigrok::Session> Session::session() const
122 return shared_ptr<sigrok::Session>();
123 return device_->session();
126 shared_ptr<devices::Device> Session::device() const
131 void Session::set_device(shared_ptr<devices::Device> device)
135 // Ensure we are not capturing before setting the device
141 device_ = std::move(device);
143 device_->session()->add_datafeed_callback([=]
144 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
145 data_feed_in(device, packet);
149 decode_traces_.clear();
154 void Session::set_default_device()
156 const list< shared_ptr<devices::HardwareDevice> > &devices =
157 device_manager_.devices();
162 // Try and find the demo device and select that by default
163 const auto iter = std::find_if(devices.begin(), devices.end(),
164 [] (const shared_ptr<devices::HardwareDevice> &d) {
165 return d->hardware_device()->driver()->name() ==
167 set_device((iter == devices.end()) ? devices.front() : *iter);
170 Session::capture_state Session::get_capture_state() const
172 lock_guard<mutex> lock(sampling_mutex_);
173 return capture_state_;
176 void Session::start_capture(function<void (const QString)> error_handler)
180 // Check that at least one channel is enabled
182 const shared_ptr<sigrok::Device> sr_dev = device_->device();
184 const auto channels = sr_dev->channels();
185 if (!std::any_of(channels.begin(), channels.end(),
186 [](shared_ptr<Channel> channel) {
187 return channel->enabled(); })) {
188 error_handler(tr("No channels enabled."));
194 for (const shared_ptr<data::SignalData> d : get_data())
198 sampling_thread_ = std::thread(
199 &Session::sample_thread_proc, this, device_,
203 void Session::stop_capture()
205 if (get_capture_state() != Stopped)
208 // Check that sampling stopped
209 if (sampling_thread_.joinable())
210 sampling_thread_.join();
213 set< shared_ptr<data::SignalData> > Session::get_data() const
215 shared_lock<shared_mutex> lock(signals_mutex_);
216 set< shared_ptr<data::SignalData> > data;
217 for (const shared_ptr<view::Signal> sig : signals_) {
219 data.insert(sig->data());
225 const unordered_set< shared_ptr<view::Signal> > Session::signals() const
227 shared_lock<shared_mutex> lock(signals_mutex_);
232 bool Session::add_decoder(srd_decoder *const dec)
234 map<const srd_channel*, shared_ptr<view::LogicSignal> > channels;
235 shared_ptr<data::DecoderStack> decoder_stack;
239 lock_guard<boost::shared_mutex> lock(signals_mutex_);
241 // Create the decoder
242 decoder_stack = shared_ptr<data::DecoderStack>(
243 new data::DecoderStack(*this, dec));
245 // Make a list of all the channels
246 std::vector<const srd_channel*> all_channels;
247 for (const GSList *i = dec->channels; i; i = i->next)
248 all_channels.push_back((const srd_channel*)i->data);
249 for (const GSList *i = dec->opt_channels; i; i = i->next)
250 all_channels.push_back((const srd_channel*)i->data);
252 // Auto select the initial channels
253 for (const srd_channel *pdch : all_channels)
254 for (shared_ptr<view::Signal> s : signals_)
256 shared_ptr<view::LogicSignal> l =
257 dynamic_pointer_cast<view::LogicSignal>(s);
258 if (l && QString::fromUtf8(pdch->name).
260 l->name().toLower()))
264 assert(decoder_stack);
265 assert(!decoder_stack->stack().empty());
266 assert(decoder_stack->stack().front());
267 decoder_stack->stack().front()->set_channels(channels);
269 // Create the decode signal
270 shared_ptr<view::DecodeTrace> d(
271 new view::DecodeTrace(*this, decoder_stack,
272 decode_traces_.size()));
273 decode_traces_.push_back(d);
275 catch(std::runtime_error e)
282 // Do an initial decode
283 decoder_stack->begin_decode();
288 vector< shared_ptr<view::DecodeTrace> > Session::get_decode_signals() const
290 shared_lock<shared_mutex> lock(signals_mutex_);
291 return decode_traces_;
294 void Session::remove_decode_signal(view::DecodeTrace *signal)
296 for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
297 if ((*i).get() == signal)
299 decode_traces_.erase(i);
306 void Session::set_capture_state(capture_state state)
308 lock_guard<mutex> lock(sampling_mutex_);
309 const bool changed = capture_state_ != state;
310 capture_state_ = state;
312 capture_state_changed(state);
315 void Session::update_signals()
319 lock_guard<recursive_mutex> lock(data_mutex_);
321 const shared_ptr<sigrok::Device> sr_dev = device_->device();
328 // Detect what data types we will receive
329 auto channels = sr_dev->channels();
330 unsigned int logic_channel_count = std::count_if(
331 channels.begin(), channels.end(),
332 [] (shared_ptr<Channel> channel) {
333 return channel->type() == ChannelType::LOGIC; });
335 // Create data containers for the logic data segments
337 lock_guard<recursive_mutex> data_lock(data_mutex_);
339 if (logic_channel_count == 0) {
341 } else if (!logic_data_ ||
342 logic_data_->num_channels() != logic_channel_count) {
343 logic_data_.reset(new data::Logic(
344 logic_channel_count));
349 // Make the Signals list
351 unique_lock<shared_mutex> lock(signals_mutex_);
353 unordered_set< shared_ptr<view::Signal> > prev_sigs(signals_);
356 for (auto channel : sr_dev->channels()) {
357 shared_ptr<view::Signal> signal;
359 // Find the channel in the old signals
360 const auto iter = std::find_if(
361 prev_sigs.cbegin(), prev_sigs.cend(),
362 [&](const shared_ptr<view::Signal> &s) {
363 return s->channel() == channel;
365 if (iter != prev_sigs.end()) {
366 // Copy the signal from the old set to the new
368 auto logic_signal = dynamic_pointer_cast<
369 view::LogicSignal>(signal);
371 logic_signal->set_logic_data(
374 // Create a new signal
375 switch(channel->type()->id()) {
376 case SR_CHANNEL_LOGIC:
377 signal = shared_ptr<view::Signal>(
378 new view::LogicSignal(*this,
383 case SR_CHANNEL_ANALOG:
385 shared_ptr<data::Analog> data(
387 signal = shared_ptr<view::Signal>(
388 new view::AnalogSignal(
389 *this, channel, data));
400 signals_.insert(signal);
407 shared_ptr<view::Signal> Session::signal_from_channel(
408 shared_ptr<Channel> channel) const
410 lock_guard<boost::shared_mutex> lock(signals_mutex_);
411 for (shared_ptr<view::Signal> sig : signals_) {
413 if (sig->channel() == channel)
416 return shared_ptr<view::Signal>();
419 void Session::sample_thread_proc(shared_ptr<devices::Device> device,
420 function<void (const QString)> error_handler)
423 assert(error_handler);
427 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
429 out_of_memory_ = false;
434 error_handler(e.what());
438 set_capture_state(device_->session()->trigger() ?
439 AwaitingTrigger : Running);
442 set_capture_state(Stopped);
444 // Confirm that SR_DF_END was received
445 if (cur_logic_segment_)
447 qDebug("SR_DF_END was not received.");
452 error_handler(tr("Out of memory, acquisition stopped."));
455 void Session::feed_in_header()
457 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
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_);
486 const size_t sample_count = logic->data_length() / logic->unit_size();
490 // The only reason logic_data_ would not have been created is
491 // if it was not possible to determine the signals when the
492 // device was created.
496 if (!cur_logic_segment_)
498 // This could be the first packet after a trigger
499 set_capture_state(Running);
501 // Create a new data segment
502 cur_logic_segment_ = shared_ptr<data::LogicSegment>(
503 new data::LogicSegment(
504 logic, cur_samplerate_, sample_count));
505 logic_data_->push_segment(cur_logic_segment_);
507 // @todo Putting this here means that only listeners querying
508 // for logic will be notified. Currently the only user of
509 // frame_began is DecoderStack, but in future we need to signal
510 // this after both analog and logic sweeps have begun.
515 // Append to the existing data segment
516 cur_logic_segment_->append_payload(logic);
522 void Session::feed_in_analog(shared_ptr<Analog> analog)
524 lock_guard<recursive_mutex> lock(data_mutex_);
526 const vector<shared_ptr<Channel>> channels = analog->channels();
527 const unsigned int channel_count = channels.size();
528 const size_t sample_count = analog->num_samples() / channel_count;
529 const float *data = static_cast<const float *>(analog->data_pointer());
530 bool sweep_beginning = false;
532 for (auto channel : channels)
534 shared_ptr<data::AnalogSegment> segment;
536 // Try to get the segment of the channel
537 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
538 iterator iter = cur_analog_segments_.find(channel);
539 if (iter != cur_analog_segments_.end())
540 segment = (*iter).second;
543 // If no segment was found, this means we havn't
544 // created one yet. i.e. this is the first packet
545 // in the sweep containing this segment.
546 sweep_beginning = true;
548 // Create a segment, keep it in the maps of channels
549 segment = shared_ptr<data::AnalogSegment>(
550 new data::AnalogSegment(
551 cur_samplerate_, sample_count));
552 cur_analog_segments_[channel] = segment;
554 // Find the analog data associated with the channel
555 shared_ptr<view::AnalogSignal> sig =
556 dynamic_pointer_cast<view::AnalogSignal>(
557 signal_from_channel(channel));
560 shared_ptr<data::Analog> data(sig->analog_data());
563 // Push the segment into the analog data.
564 data->push_segment(segment);
569 // Append the samples in the segment
570 segment->append_interleaved_samples(data++, sample_count,
574 if (sweep_beginning) {
575 // This could be the first packet after a trigger
576 set_capture_state(Running);
582 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
583 shared_ptr<Packet> packet)
588 assert(device == device_->device());
591 switch (packet->type()->id()) {
597 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
600 case SR_DF_FRAME_BEGIN:
601 feed_in_frame_begin();
606 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
607 } catch (std::bad_alloc) {
608 out_of_memory_ = true;
615 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
616 } catch (std::bad_alloc) {
617 out_of_memory_ = true;
625 lock_guard<recursive_mutex> lock(data_mutex_);
626 cur_logic_segment_.reset();
627 cur_analog_segments_.clear();