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