]> sigrok.org Git - pulseview.git/blame_incremental - pv/session.cpp
ViewItem: Make select virtual
[pulseview.git] / pv / session.cpp
... / ...
CommitLineData
1/*
2 * This file is part of the PulseView project.
3 *
4 * Copyright (C) 2012-14 Joel Holdsworth <joel@airwebreathe.org.uk>
5 *
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.
10 *
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.
15 *
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
19 */
20
21#include <boost/thread/locks.hpp>
22#include <boost/thread/shared_mutex.hpp>
23
24#ifdef ENABLE_DECODE
25#include <libsigrokdecode/libsigrokdecode.h>
26#endif
27
28#include "session.hpp"
29
30#include "devicemanager.hpp"
31
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"
38
39#include "devices/hardwaredevice.hpp"
40#include "devices/sessionfile.hpp"
41
42#include "view/analogsignal.hpp"
43#include "view/decodetrace.hpp"
44#include "view/logicsignal.hpp"
45
46#include <cassert>
47#include <mutex>
48#include <stdexcept>
49
50#include <sys/stat.h>
51
52#include <QDebug>
53
54#include <libsigrokcxx/libsigrokcxx.hpp>
55
56using boost::shared_lock;
57using boost::shared_mutex;
58using boost::unique_lock;
59
60using std::dynamic_pointer_cast;
61using std::function;
62using std::lock_guard;
63using std::list;
64using std::map;
65using std::mutex;
66using std::recursive_mutex;
67using std::set;
68using std::shared_ptr;
69using std::string;
70using std::unordered_set;
71using std::vector;
72
73using sigrok::Analog;
74using sigrok::Channel;
75using sigrok::ChannelType;
76using sigrok::ConfigKey;
77using sigrok::DatafeedCallbackFunction;
78using sigrok::Error;
79using sigrok::Header;
80using sigrok::Logic;
81using sigrok::Meta;
82using sigrok::Packet;
83using sigrok::PacketPayload;
84using sigrok::Session;
85using sigrok::SessionDevice;
86
87using Glib::VariantBase;
88using Glib::Variant;
89
90namespace pv {
91Session::Session(DeviceManager &device_manager) :
92 device_manager_(device_manager),
93 capture_state_(Stopped),
94 cur_samplerate_(0)
95{
96}
97
98Session::~Session()
99{
100 // Stop and join to the thread
101 stop_capture();
102}
103
104DeviceManager& Session::device_manager()
105{
106 return device_manager_;
107}
108
109const DeviceManager& Session::device_manager() const
110{
111 return device_manager_;
112}
113
114shared_ptr<sigrok::Session> Session::session() const
115{
116 if (!device_)
117 return shared_ptr<sigrok::Session>();
118 return device_->session();
119}
120
121shared_ptr<devices::Device> Session::device() const
122{
123 return device_;
124}
125
126void Session::set_device(shared_ptr<devices::Device> device)
127{
128 assert(device);
129
130 // Ensure we are not capturing before setting the device
131 stop_capture();
132
133 if (device_)
134 device_->close();
135
136 device_ = std::move(device);
137 device_->open();
138 device_->session()->add_datafeed_callback([=]
139 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
140 data_feed_in(device, packet);
141 });
142 update_signals();
143
144 decode_traces_.clear();
145
146 device_selected();
147}
148
149void Session::set_default_device()
150{
151 const list< shared_ptr<devices::HardwareDevice> > &devices =
152 device_manager_.devices();
153
154 if (devices.empty())
155 return;
156
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() ==
161 "demo"; });
162 set_device((iter == devices.end()) ? devices.front() : *iter);
163}
164
165Session::capture_state Session::get_capture_state() const
166{
167 lock_guard<mutex> lock(sampling_mutex_);
168 return capture_state_;
169}
170
171void Session::start_capture(function<void (const QString)> error_handler)
172{
173 stop_capture();
174
175 // Check that at least one channel is enabled
176 assert(device_);
177 const shared_ptr<sigrok::Device> sr_dev = device_->device();
178 if (sr_dev) {
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."));
184 return;
185 }
186 }
187
188 // Clear signal data
189 for (const shared_ptr<data::SignalData> d : get_data())
190 d->clear();
191
192 // Begin the session
193 sampling_thread_ = std::thread(
194 &Session::sample_thread_proc, this, device_,
195 error_handler);
196}
197
198void Session::stop_capture()
199{
200 if (get_capture_state() != Stopped)
201 device_->stop();
202
203 // Check that sampling stopped
204 if (sampling_thread_.joinable())
205 sampling_thread_.join();
206}
207
208set< shared_ptr<data::SignalData> > Session::get_data() const
209{
210 shared_lock<shared_mutex> lock(signals_mutex_);
211 set< shared_ptr<data::SignalData> > data;
212 for (const shared_ptr<view::Signal> sig : signals_) {
213 assert(sig);
214 data.insert(sig->data());
215 }
216
217 return data;
218}
219
220const unordered_set< shared_ptr<view::Signal> > Session::signals() const
221{
222 shared_lock<shared_mutex> lock(signals_mutex_);
223 return signals_;
224}
225
226#ifdef ENABLE_DECODE
227bool Session::add_decoder(srd_decoder *const dec)
228{
229 map<const srd_channel*, shared_ptr<view::LogicSignal> > channels;
230 shared_ptr<data::DecoderStack> decoder_stack;
231
232 try
233 {
234 lock_guard<boost::shared_mutex> lock(signals_mutex_);
235
236 // Create the decoder
237 decoder_stack = shared_ptr<data::DecoderStack>(
238 new data::DecoderStack(*this, dec));
239
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);
246
247 // Auto select the initial channels
248 for (const srd_channel *pdch : all_channels)
249 for (shared_ptr<view::Signal> s : signals_)
250 {
251 shared_ptr<view::LogicSignal> l =
252 dynamic_pointer_cast<view::LogicSignal>(s);
253 if (l && QString::fromUtf8(pdch->name).
254 toLower().contains(
255 l->name().toLower()))
256 channels[pdch] = l;
257 }
258
259 assert(decoder_stack);
260 assert(!decoder_stack->stack().empty());
261 assert(decoder_stack->stack().front());
262 decoder_stack->stack().front()->set_channels(channels);
263
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);
269 }
270 catch(std::runtime_error e)
271 {
272 return false;
273 }
274
275 signals_changed();
276
277 // Do an initial decode
278 decoder_stack->begin_decode();
279
280 return true;
281}
282
283vector< shared_ptr<view::DecodeTrace> > Session::get_decode_signals() const
284{
285 shared_lock<shared_mutex> lock(signals_mutex_);
286 return decode_traces_;
287}
288
289void Session::remove_decode_signal(view::DecodeTrace *signal)
290{
291 for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
292 if ((*i).get() == signal)
293 {
294 decode_traces_.erase(i);
295 signals_changed();
296 return;
297 }
298}
299#endif
300
301void Session::set_capture_state(capture_state state)
302{
303 lock_guard<mutex> lock(sampling_mutex_);
304 const bool changed = capture_state_ != state;
305 capture_state_ = state;
306 if (changed)
307 capture_state_changed(state);
308}
309
310void Session::update_signals()
311{
312 assert(device_);
313
314 lock_guard<recursive_mutex> lock(data_mutex_);
315
316 const shared_ptr<sigrok::Device> sr_dev = device_->device();
317 if (!sr_dev) {
318 signals_.clear();
319 logic_data_.reset();
320 return;
321 }
322
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; });
329
330 // Create data containers for the logic data segments
331 {
332 lock_guard<recursive_mutex> data_lock(data_mutex_);
333
334 if (logic_channel_count == 0) {
335 logic_data_.reset();
336 } else if (!logic_data_ ||
337 logic_data_->num_channels() != logic_channel_count) {
338 logic_data_.reset(new data::Logic(
339 logic_channel_count));
340 assert(logic_data_);
341 }
342 }
343
344 // Make the Signals list
345 {
346 unique_lock<shared_mutex> lock(signals_mutex_);
347
348 unordered_set< shared_ptr<view::Signal> > prev_sigs(signals_);
349 signals_.clear();
350
351 for (auto channel : sr_dev->channels()) {
352 shared_ptr<view::Signal> signal;
353
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;
359 });
360 if (iter != prev_sigs.end()) {
361 // Copy the signal from the old set to the new
362 signal = *iter;
363 auto logic_signal = dynamic_pointer_cast<
364 view::LogicSignal>(signal);
365 if (logic_signal)
366 logic_signal->set_logic_data(
367 logic_data_);
368 } else {
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,
374 device_, channel,
375 logic_data_));
376 break;
377
378 case SR_CHANNEL_ANALOG:
379 {
380 shared_ptr<data::Analog> data(
381 new data::Analog());
382 signal = shared_ptr<view::Signal>(
383 new view::AnalogSignal(
384 *this, channel, data));
385 break;
386 }
387
388 default:
389 assert(0);
390 break;
391 }
392 }
393
394 assert(signal);
395 signals_.insert(signal);
396 }
397 }
398
399 signals_changed();
400}
401
402shared_ptr<view::Signal> Session::signal_from_channel(
403 shared_ptr<Channel> channel) const
404{
405 lock_guard<boost::shared_mutex> lock(signals_mutex_);
406 for (shared_ptr<view::Signal> sig : signals_) {
407 assert(sig);
408 if (sig->channel() == channel)
409 return sig;
410 }
411 return shared_ptr<view::Signal>();
412}
413
414void Session::sample_thread_proc(shared_ptr<devices::Device> device,
415 function<void (const QString)> error_handler)
416{
417 assert(device);
418 assert(error_handler);
419
420 (void)device;
421
422 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
423
424 out_of_memory_ = false;
425
426 try {
427 device_->start();
428 } catch(Error e) {
429 error_handler(e.what());
430 return;
431 }
432
433 set_capture_state(device_->session()->trigger() ?
434 AwaitingTrigger : Running);
435
436 device_->run();
437 set_capture_state(Stopped);
438
439 // Confirm that SR_DF_END was received
440 if (cur_logic_segment_)
441 {
442 qDebug("SR_DF_END was not received.");
443 assert(0);
444 }
445
446 if (out_of_memory_)
447 error_handler(tr("Out of memory, acquisition stopped."));
448}
449
450void Session::feed_in_header()
451{
452 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
453}
454
455void Session::feed_in_meta(shared_ptr<Meta> meta)
456{
457 for (auto entry : meta->config()) {
458 switch (entry.first->id()) {
459 case SR_CONF_SAMPLERATE:
460 /// @todo handle samplerate changes
461 break;
462 default:
463 // Unknown metadata is not an error.
464 break;
465 }
466 }
467
468 signals_changed();
469}
470
471void Session::feed_in_frame_begin()
472{
473 if (cur_logic_segment_ || !cur_analog_segments_.empty())
474 frame_began();
475}
476
477void Session::feed_in_logic(shared_ptr<Logic> logic)
478{
479 lock_guard<recursive_mutex> lock(data_mutex_);
480
481 const size_t sample_count = logic->data_length() / logic->unit_size();
482
483 if (!logic_data_)
484 {
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.
488 update_signals();
489 }
490
491 if (!cur_logic_segment_)
492 {
493 // This could be the first packet after a trigger
494 set_capture_state(Running);
495
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_);
501
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.
506 frame_began();
507 }
508 else
509 {
510 // Append to the existing data segment
511 cur_logic_segment_->append_payload(logic);
512 }
513
514 data_received();
515}
516
517void Session::feed_in_analog(shared_ptr<Analog> analog)
518{
519 lock_guard<recursive_mutex> lock(data_mutex_);
520
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;
526
527 for (auto channel : channels)
528 {
529 shared_ptr<data::AnalogSegment> segment;
530
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;
536 else
537 {
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;
542
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;
548
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));
553 assert(sig);
554
555 shared_ptr<data::Analog> data(sig->analog_data());
556 assert(data);
557
558 // Push the segment into the analog data.
559 data->push_segment(segment);
560 }
561
562 assert(segment);
563
564 // Append the samples in the segment
565 segment->append_interleaved_samples(data++, sample_count,
566 channel_count);
567 }
568
569 if (sweep_beginning) {
570 // This could be the first packet after a trigger
571 set_capture_state(Running);
572 }
573
574 data_received();
575}
576
577void Session::data_feed_in(shared_ptr<sigrok::Device> device,
578 shared_ptr<Packet> packet)
579{
580 (void)device;
581
582 assert(device);
583 assert(device == device_->device());
584 assert(packet);
585
586 switch (packet->type()->id()) {
587 case SR_DF_HEADER:
588 feed_in_header();
589 break;
590
591 case SR_DF_META:
592 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
593 break;
594
595 case SR_DF_FRAME_BEGIN:
596 feed_in_frame_begin();
597 break;
598
599 case SR_DF_LOGIC:
600 try {
601 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
602 } catch (std::bad_alloc) {
603 out_of_memory_ = true;
604 device_->stop();
605 }
606 break;
607
608 case SR_DF_ANALOG:
609 try {
610 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
611 } catch (std::bad_alloc) {
612 out_of_memory_ = true;
613 device_->stop();
614 }
615 break;
616
617 case SR_DF_END:
618 {
619 {
620 lock_guard<recursive_mutex> lock(data_mutex_);
621 cur_logic_segment_.reset();
622 cur_analog_segments_.clear();
623 }
624 frame_ended();
625 break;
626 }
627 default:
628 break;
629 }
630}
631
632} // namespace pv