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