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