]> sigrok.org Git - pulseview.git/blame_incremental - pv/session.cpp
Fix warning for unused Session::sample_thread_proc() parameter
[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#ifdef _WIN32
22// Windows: Avoid boost/thread namespace pollution (which includes windows.h).
23#define NOGDI
24#define NORESOURCE
25#endif
26#include <boost/thread/locks.hpp>
27#include <boost/thread/shared_mutex.hpp>
28
29#ifdef ENABLE_DECODE
30#include <libsigrokdecode/libsigrokdecode.h>
31#endif
32
33#include "session.hpp"
34
35#include "devicemanager.hpp"
36
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"
43
44#include "devices/hardwaredevice.hpp"
45#include "devices/sessionfile.hpp"
46
47#include "view/analogsignal.hpp"
48#include "view/decodetrace.hpp"
49#include "view/logicsignal.hpp"
50
51#include <cassert>
52#include <mutex>
53#include <stdexcept>
54
55#include <sys/stat.h>
56
57#include <QDebug>
58
59#include <libsigrokcxx/libsigrokcxx.hpp>
60
61using boost::shared_lock;
62using boost::shared_mutex;
63using boost::unique_lock;
64
65using std::dynamic_pointer_cast;
66using std::function;
67using std::lock_guard;
68using std::list;
69using std::map;
70using std::mutex;
71using std::recursive_mutex;
72using std::set;
73using std::shared_ptr;
74using std::string;
75using std::unordered_set;
76using std::vector;
77
78using sigrok::Analog;
79using sigrok::Channel;
80using sigrok::ChannelType;
81using sigrok::ConfigKey;
82using sigrok::DatafeedCallbackFunction;
83using sigrok::Error;
84using sigrok::Header;
85using sigrok::Logic;
86using sigrok::Meta;
87using sigrok::Packet;
88using sigrok::PacketPayload;
89using sigrok::Session;
90using sigrok::SessionDevice;
91
92using Glib::VariantBase;
93using Glib::Variant;
94
95namespace pv {
96Session::Session(DeviceManager &device_manager) :
97 device_manager_(device_manager),
98 capture_state_(Stopped),
99 cur_samplerate_(0)
100{
101}
102
103Session::~Session()
104{
105 // Stop and join to the thread
106 stop_capture();
107}
108
109DeviceManager& Session::device_manager()
110{
111 return device_manager_;
112}
113
114const DeviceManager& Session::device_manager() const
115{
116 return device_manager_;
117}
118
119shared_ptr<sigrok::Session> Session::session() const
120{
121 if (!device_)
122 return shared_ptr<sigrok::Session>();
123 return device_->session();
124}
125
126shared_ptr<devices::Device> Session::device() const
127{
128 return device_;
129}
130
131void Session::set_device(shared_ptr<devices::Device> device)
132{
133 assert(device);
134
135 // Ensure we are not capturing before setting the device
136 stop_capture();
137
138 if (device_)
139 device_->close();
140
141 device_.reset();
142
143 // Remove all stored data
144 signals_.clear();
145 {
146 shared_lock<shared_mutex> lock(signals_mutex_);
147 for (const shared_ptr<data::SignalData> d : all_signal_data_)
148 d->clear();
149 }
150 all_signal_data_.clear();
151 cur_logic_segment_.reset();
152
153 for (auto entry : cur_analog_segments_) {
154 shared_ptr<sigrok::Channel>(entry.first).reset();
155 shared_ptr<data::AnalogSegment>(entry.second).reset();
156 }
157
158 logic_data_.reset();
159 decode_traces_.clear();
160
161 signals_changed();
162
163 device_ = std::move(device);
164 device_->open();
165 device_->session()->add_datafeed_callback([=]
166 (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
167 data_feed_in(device, packet);
168 });
169
170 update_signals();
171 device_selected();
172}
173
174void Session::set_default_device()
175{
176 const list< shared_ptr<devices::HardwareDevice> > &devices =
177 device_manager_.devices();
178
179 if (devices.empty())
180 return;
181
182 // Try and find the demo device and select that by default
183 const auto iter = std::find_if(devices.begin(), devices.end(),
184 [] (const shared_ptr<devices::HardwareDevice> &d) {
185 return d->hardware_device()->driver()->name() ==
186 "demo"; });
187 set_device((iter == devices.end()) ? devices.front() : *iter);
188}
189
190Session::capture_state Session::get_capture_state() const
191{
192 lock_guard<mutex> lock(sampling_mutex_);
193 return capture_state_;
194}
195
196void Session::start_capture(function<void (const QString)> error_handler)
197{
198 if (!device_) {
199 error_handler(tr("No active device set, can't start acquisition."));
200 return;
201 }
202
203 stop_capture();
204
205 // Check that at least one channel is enabled
206 const shared_ptr<sigrok::Device> sr_dev = device_->device();
207 if (sr_dev) {
208 const auto channels = sr_dev->channels();
209 if (!std::any_of(channels.begin(), channels.end(),
210 [](shared_ptr<Channel> channel) {
211 return channel->enabled(); })) {
212 error_handler(tr("No channels enabled."));
213 return;
214 }
215 }
216
217 // Clear signal data
218 {
219 shared_lock<shared_mutex> lock(signals_mutex_);
220 for (const shared_ptr<data::SignalData> d : all_signal_data_)
221 d->clear();
222 }
223
224 // Begin the session
225 sampling_thread_ = std::thread(
226 &Session::sample_thread_proc, this, error_handler);
227}
228
229void Session::stop_capture()
230{
231 if (get_capture_state() != Stopped)
232 device_->stop();
233
234 // Check that sampling stopped
235 if (sampling_thread_.joinable())
236 sampling_thread_.join();
237}
238
239double Session::get_samplerate() const
240{
241 double samplerate = 0.0;
242
243 {
244 shared_lock<shared_mutex> lock(signals_mutex_);
245 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
246 assert(d);
247 const vector< shared_ptr<pv::data::Segment> > segments =
248 d->segments();
249 for (const shared_ptr<pv::data::Segment> &s : segments)
250 samplerate = std::max(samplerate, s->samplerate());
251 }
252 }
253 // If there is no sample rate given we use samples as unit
254 if (samplerate == 0.0)
255 samplerate = 1.0;
256
257 return samplerate;
258}
259
260const unordered_set< shared_ptr<view::Signal> > Session::signals() const
261{
262 shared_lock<shared_mutex> lock(signals_mutex_);
263 return signals_;
264}
265
266#ifdef ENABLE_DECODE
267bool Session::add_decoder(srd_decoder *const dec)
268{
269 map<const srd_channel*, shared_ptr<view::LogicSignal> > channels;
270 shared_ptr<data::DecoderStack> decoder_stack;
271
272 try {
273 lock_guard<boost::shared_mutex> lock(signals_mutex_);
274
275 // Create the decoder
276 decoder_stack = shared_ptr<data::DecoderStack>(
277 new data::DecoderStack(*this, dec));
278
279 // Make a list of all the channels
280 std::vector<const srd_channel*> all_channels;
281 for (const GSList *i = dec->channels; i; i = i->next)
282 all_channels.push_back((const srd_channel*)i->data);
283 for (const GSList *i = dec->opt_channels; i; i = i->next)
284 all_channels.push_back((const srd_channel*)i->data);
285
286 // Auto select the initial channels
287 for (const srd_channel *pdch : all_channels)
288 for (shared_ptr<view::Signal> s : signals_) {
289 shared_ptr<view::LogicSignal> l =
290 dynamic_pointer_cast<view::LogicSignal>(s);
291 if (l && QString::fromUtf8(pdch->name).
292 toLower().contains(
293 l->name().toLower()))
294 channels[pdch] = l;
295 }
296
297 assert(decoder_stack);
298 assert(!decoder_stack->stack().empty());
299 assert(decoder_stack->stack().front());
300 decoder_stack->stack().front()->set_channels(channels);
301
302 // Create the decode signal
303 shared_ptr<view::DecodeTrace> d(
304 new view::DecodeTrace(*this, decoder_stack,
305 decode_traces_.size()));
306 decode_traces_.push_back(d);
307 } catch (std::runtime_error e) {
308 return false;
309 }
310
311 signals_changed();
312
313 // Do an initial decode
314 decoder_stack->begin_decode();
315
316 return true;
317}
318
319vector< shared_ptr<view::DecodeTrace> > Session::get_decode_signals() const
320{
321 shared_lock<shared_mutex> lock(signals_mutex_);
322 return decode_traces_;
323}
324
325void Session::remove_decode_signal(view::DecodeTrace *signal)
326{
327 for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
328 if ((*i).get() == signal) {
329 decode_traces_.erase(i);
330 signals_changed();
331 return;
332 }
333}
334#endif
335
336void Session::set_capture_state(capture_state state)
337{
338 bool changed;
339
340 {
341 lock_guard<mutex> lock(sampling_mutex_);
342 changed = capture_state_ != state;
343 capture_state_ = state;
344 }
345
346 if (changed)
347 capture_state_changed(state);
348}
349
350void Session::update_signals()
351{
352 if (!device_) {
353 signals_.clear();
354 logic_data_.reset();
355 return;
356 }
357
358 lock_guard<recursive_mutex> lock(data_mutex_);
359
360 const shared_ptr<sigrok::Device> sr_dev = device_->device();
361 if (!sr_dev) {
362 signals_.clear();
363 logic_data_.reset();
364 return;
365 }
366
367 // Detect what data types we will receive
368 auto channels = sr_dev->channels();
369 unsigned int logic_channel_count = std::count_if(
370 channels.begin(), channels.end(),
371 [] (shared_ptr<Channel> channel) {
372 return channel->type() == ChannelType::LOGIC; });
373
374 // Create data containers for the logic data segments
375 {
376 lock_guard<recursive_mutex> data_lock(data_mutex_);
377
378 if (logic_channel_count == 0) {
379 logic_data_.reset();
380 } else if (!logic_data_ ||
381 logic_data_->num_channels() != logic_channel_count) {
382 logic_data_.reset(new data::Logic(
383 logic_channel_count));
384 assert(logic_data_);
385 }
386 }
387
388 // Make the Signals list
389 {
390 unique_lock<shared_mutex> lock(signals_mutex_);
391
392 unordered_set< shared_ptr<view::Signal> > prev_sigs(signals_);
393 signals_.clear();
394
395 for (auto channel : sr_dev->channels()) {
396 shared_ptr<view::Signal> signal;
397
398 // Find the channel in the old signals
399 const auto iter = std::find_if(
400 prev_sigs.cbegin(), prev_sigs.cend(),
401 [&](const shared_ptr<view::Signal> &s) {
402 return s->channel() == channel;
403 });
404 if (iter != prev_sigs.end()) {
405 // Copy the signal from the old set to the new
406 signal = *iter;
407 auto logic_signal = dynamic_pointer_cast<
408 view::LogicSignal>(signal);
409 if (logic_signal)
410 logic_signal->set_logic_data(
411 logic_data_);
412 } else {
413 // Create a new signal
414 switch(channel->type()->id()) {
415 case SR_CHANNEL_LOGIC:
416 signal = shared_ptr<view::Signal>(
417 new view::LogicSignal(*this,
418 device_, channel,
419 logic_data_));
420 all_signal_data_.insert(logic_data_);
421 break;
422
423 case SR_CHANNEL_ANALOG:
424 {
425 shared_ptr<data::Analog> data(
426 new data::Analog());
427 signal = shared_ptr<view::Signal>(
428 new view::AnalogSignal(
429 *this, channel, data));
430 all_signal_data_.insert(data);
431 break;
432 }
433
434 default:
435 assert(0);
436 break;
437 }
438 }
439
440 assert(signal);
441 signals_.insert(signal);
442 }
443 }
444
445 signals_changed();
446}
447
448shared_ptr<view::Signal> Session::signal_from_channel(
449 shared_ptr<Channel> channel) const
450{
451 lock_guard<boost::shared_mutex> lock(signals_mutex_);
452 for (shared_ptr<view::Signal> sig : signals_) {
453 assert(sig);
454 if (sig->channel() == channel)
455 return sig;
456 }
457 return shared_ptr<view::Signal>();
458}
459
460void Session::sample_thread_proc(function<void (const QString)> error_handler)
461{
462 assert(error_handler);
463
464 if (!device_)
465 return;
466
467 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
468
469 out_of_memory_ = false;
470
471 try {
472 device_->start();
473 } catch (Error e) {
474 error_handler(e.what());
475 return;
476 }
477
478 set_capture_state(device_->session()->trigger() ?
479 AwaitingTrigger : Running);
480
481 device_->run();
482 set_capture_state(Stopped);
483
484 // Confirm that SR_DF_END was received
485 if (cur_logic_segment_) {
486 qDebug("SR_DF_END was not received.");
487 assert(0);
488 }
489
490 if (out_of_memory_)
491 error_handler(tr("Out of memory, acquisition stopped."));
492}
493
494void Session::feed_in_header()
495{
496 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
497}
498
499void Session::feed_in_meta(shared_ptr<Meta> meta)
500{
501 for (auto entry : meta->config()) {
502 switch (entry.first->id()) {
503 case SR_CONF_SAMPLERATE:
504 // We can't rely on the header to always contain the sample rate,
505 // so in case it's supplied via a meta packet, we use it.
506 if (!cur_samplerate_)
507 cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
508
509 /// @todo handle samplerate changes
510 break;
511 default:
512 // Unknown metadata is not an error.
513 break;
514 }
515 }
516
517 signals_changed();
518}
519
520void Session::feed_in_trigger()
521{
522 // The channel containing most samples should be most accurate
523 uint64_t sample_count = 0;
524
525 {
526 shared_lock<shared_mutex> lock(signals_mutex_);
527 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
528 assert(d);
529 uint64_t temp_count = 0;
530
531 const vector< shared_ptr<pv::data::Segment> > segments =
532 d->segments();
533 for (const shared_ptr<pv::data::Segment> &s : segments)
534 temp_count += s->get_sample_count();
535
536 if (temp_count > sample_count)
537 sample_count = temp_count;
538 }
539 }
540
541 trigger_event(sample_count / get_samplerate());
542}
543
544void Session::feed_in_frame_begin()
545{
546 if (cur_logic_segment_ || !cur_analog_segments_.empty())
547 frame_began();
548}
549
550void Session::feed_in_logic(shared_ptr<Logic> logic)
551{
552 lock_guard<recursive_mutex> lock(data_mutex_);
553
554 const size_t sample_count = logic->data_length() / logic->unit_size();
555
556 if (!logic_data_) {
557 // The only reason logic_data_ would not have been created is
558 // if it was not possible to determine the signals when the
559 // device was created.
560 update_signals();
561 }
562
563 if (!cur_logic_segment_) {
564 // This could be the first packet after a trigger
565 set_capture_state(Running);
566
567 // Create a new data segment
568 cur_logic_segment_ = shared_ptr<data::LogicSegment>(
569 new data::LogicSegment(
570 logic, cur_samplerate_, sample_count));
571 logic_data_->push_segment(cur_logic_segment_);
572
573 // @todo Putting this here means that only listeners querying
574 // for logic will be notified. Currently the only user of
575 // frame_began is DecoderStack, but in future we need to signal
576 // this after both analog and logic sweeps have begun.
577 frame_began();
578 } else {
579 // Append to the existing data segment
580 cur_logic_segment_->append_payload(logic);
581 }
582
583 data_received();
584}
585
586void Session::feed_in_analog(shared_ptr<Analog> analog)
587{
588 lock_guard<recursive_mutex> lock(data_mutex_);
589
590 const vector<shared_ptr<Channel>> channels = analog->channels();
591 const unsigned int channel_count = channels.size();
592 const size_t sample_count = analog->num_samples() / channel_count;
593 const float *data = static_cast<const float *>(analog->data_pointer());
594 bool sweep_beginning = false;
595
596 if (signals_.empty())
597 update_signals();
598
599 for (auto channel : channels) {
600 shared_ptr<data::AnalogSegment> segment;
601
602 // Try to get the segment of the channel
603 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
604 iterator iter = cur_analog_segments_.find(channel);
605 if (iter != cur_analog_segments_.end())
606 segment = (*iter).second;
607 else {
608 // If no segment was found, this means we haven't
609 // created one yet. i.e. this is the first packet
610 // in the sweep containing this segment.
611 sweep_beginning = true;
612
613 // Create a segment, keep it in the maps of channels
614 segment = shared_ptr<data::AnalogSegment>(
615 new data::AnalogSegment(
616 cur_samplerate_, sample_count));
617 cur_analog_segments_[channel] = segment;
618
619 // Find the analog data associated with the channel
620 shared_ptr<view::AnalogSignal> sig =
621 dynamic_pointer_cast<view::AnalogSignal>(
622 signal_from_channel(channel));
623 assert(sig);
624
625 shared_ptr<data::Analog> data(sig->analog_data());
626 assert(data);
627
628 // Push the segment into the analog data.
629 data->push_segment(segment);
630 }
631
632 assert(segment);
633
634 // Append the samples in the segment
635 segment->append_interleaved_samples(data++, sample_count,
636 channel_count);
637 }
638
639 if (sweep_beginning) {
640 // This could be the first packet after a trigger
641 set_capture_state(Running);
642 }
643
644 data_received();
645}
646
647void Session::data_feed_in(shared_ptr<sigrok::Device> device,
648 shared_ptr<Packet> packet)
649{
650 (void)device;
651
652 assert(device);
653 assert(device == device_->device());
654 assert(packet);
655
656 switch (packet->type()->id()) {
657 case SR_DF_HEADER:
658 feed_in_header();
659 break;
660
661 case SR_DF_META:
662 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
663 break;
664
665 case SR_DF_TRIGGER:
666 feed_in_trigger();
667 break;
668
669 case SR_DF_FRAME_BEGIN:
670 feed_in_frame_begin();
671 break;
672
673 case SR_DF_LOGIC:
674 try {
675 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
676 } catch (std::bad_alloc) {
677 out_of_memory_ = true;
678 device_->stop();
679 }
680 break;
681
682 case SR_DF_ANALOG:
683 try {
684 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
685 } catch (std::bad_alloc) {
686 out_of_memory_ = true;
687 device_->stop();
688 }
689 break;
690
691 case SR_DF_END:
692 {
693 {
694 lock_guard<recursive_mutex> lock(data_mutex_);
695 cur_logic_segment_.reset();
696 cur_analog_segments_.clear();
697 }
698 frame_ended();
699 break;
700 }
701 default:
702 break;
703 }
704}
705
706} // namespace pv