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