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