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