]> sigrok.org Git - pulseview.git/blob - pv/sigsession.cpp
SigSession: Added DeviceManager accessor functions
[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 vector< shared_ptr<view::Signal> > SigSession::get_signals() const
243 {
244         lock_guard<mutex> lock(_signals_mutex);
245         return _signals;
246 }
247
248 #ifdef ENABLE_DECODE
249 bool SigSession::add_decoder(srd_decoder *const dec)
250 {
251         map<const srd_channel*, shared_ptr<view::LogicSignal> > channels;
252         shared_ptr<data::DecoderStack> decoder_stack;
253
254         try
255         {
256                 lock_guard<mutex> lock(_signals_mutex);
257
258                 // Create the decoder
259                 decoder_stack = shared_ptr<data::DecoderStack>(
260                         new data::DecoderStack(*this, dec));
261
262                 // Make a list of all the channels
263                 std::vector<const srd_channel*> all_channels;
264                 for(const GSList *i = dec->channels; i; i = i->next)
265                         all_channels.push_back((const srd_channel*)i->data);
266                 for(const GSList *i = dec->opt_channels; i; i = i->next)
267                         all_channels.push_back((const srd_channel*)i->data);
268
269                 // Auto select the initial channels
270                 for (const srd_channel *pdch : all_channels)
271                         for (shared_ptr<view::Signal> s : _signals)
272                         {
273                                 shared_ptr<view::LogicSignal> l =
274                                         dynamic_pointer_cast<view::LogicSignal>(s);
275                                 if (l && QString::fromUtf8(pdch->name).
276                                         toLower().contains(
277                                         l->get_name().toLower()))
278                                         channels[pdch] = l;
279                         }
280
281                 assert(decoder_stack);
282                 assert(!decoder_stack->stack().empty());
283                 assert(decoder_stack->stack().front());
284                 decoder_stack->stack().front()->set_channels(channels);
285
286                 // Create the decode signal
287                 shared_ptr<view::DecodeTrace> d(
288                         new view::DecodeTrace(*this, decoder_stack,
289                                 _decode_traces.size()));
290                 _decode_traces.push_back(d);
291         }
292         catch(std::runtime_error e)
293         {
294                 return false;
295         }
296
297         signals_changed();
298
299         // Do an initial decode
300         decoder_stack->begin_decode();
301
302         return true;
303 }
304
305 vector< shared_ptr<view::DecodeTrace> > SigSession::get_decode_signals() const
306 {
307         lock_guard<mutex> lock(_signals_mutex);
308         return _decode_traces;
309 }
310
311 void SigSession::remove_decode_signal(view::DecodeTrace *signal)
312 {
313         for (auto i = _decode_traces.begin(); i != _decode_traces.end(); i++)
314                 if ((*i).get() == signal)
315                 {
316                         _decode_traces.erase(i);
317                         signals_changed();
318                         return;
319                 }
320 }
321 #endif
322
323 void SigSession::set_capture_state(capture_state state)
324 {
325         lock_guard<mutex> lock(_sampling_mutex);
326         const bool changed = _capture_state != state;
327         _capture_state = state;
328         if(changed)
329                 capture_state_changed(state);
330 }
331
332 void SigSession::update_signals(shared_ptr<Device> device)
333 {
334         assert(device);
335         assert(_capture_state == Stopped);
336
337         // Clear the decode traces
338         _decode_traces.clear();
339
340         // Detect what data types we will receive
341         auto channels = device->channels();
342         unsigned int logic_channel_count = std::count_if(
343                 channels.begin(), channels.end(),
344                 [] (shared_ptr<Channel> channel) {
345                         return channel->type() == ChannelType::LOGIC; });
346
347         // Create data containers for the logic data snapshots
348         {
349                 lock_guard<mutex> data_lock(_data_mutex);
350
351                 _logic_data.reset();
352                 if (logic_channel_count != 0) {
353                         _logic_data.reset(new data::Logic(
354                                 logic_channel_count));
355                         assert(_logic_data);
356                 }
357         }
358
359         // Make the Signals list
360         {
361                 lock_guard<mutex> lock(_signals_mutex);
362
363                 _signals.clear();
364
365                 for (auto channel : device->channels()) {
366                         shared_ptr<view::Signal> signal;
367
368                         switch(channel->type()->id()) {
369                         case SR_CHANNEL_LOGIC:
370                                 signal = shared_ptr<view::Signal>(
371                                         new view::LogicSignal(*this, device,
372                                                 channel, _logic_data));
373                                 break;
374
375                         case SR_CHANNEL_ANALOG:
376                         {
377                                 shared_ptr<data::Analog> data(
378                                         new data::Analog());
379                                 signal = shared_ptr<view::Signal>(
380                                         new view::AnalogSignal(
381                                                 *this, channel, data));
382                                 break;
383                         }
384
385                         default:
386                                 assert(0);
387                                 break;
388                         }
389
390                         assert(signal);
391                         _signals.push_back(signal);
392                 }
393
394         }
395
396         signals_changed();
397 }
398
399 shared_ptr<view::Signal> SigSession::signal_from_channel(
400         shared_ptr<Channel> channel) const
401 {
402         lock_guard<mutex> lock(_signals_mutex);
403         for (shared_ptr<view::Signal> sig : _signals) {
404                 assert(sig);
405                 if (sig->channel() == channel)
406                         return sig;
407         }
408         return shared_ptr<view::Signal>();
409 }
410
411 void SigSession::read_sample_rate(shared_ptr<Device> device)
412 {
413         uint64_t sample_rate = VariantBase::cast_dynamic<Variant<guint64>>(
414                 device->config_get(ConfigKey::SAMPLERATE)).get();
415
416         // Set the sample rate of all data
417         const set< shared_ptr<data::SignalData> > data_set = get_data();
418         for (shared_ptr<data::SignalData> data : data_set) {
419                 assert(data);
420                 data->set_samplerate(sample_rate);
421         }
422 }
423
424 void SigSession::sample_thread_proc(shared_ptr<Device> device,
425         function<void (const QString)> error_handler)
426 {
427         assert(device);
428         assert(error_handler);
429
430         read_sample_rate(device);
431
432         try {
433                 _session->start();
434         } catch(Error e) {
435                 error_handler(e.what());
436                 return;
437         }
438
439         set_capture_state(_session->trigger() ?
440                 AwaitingTrigger : Running);
441
442         _session->run();
443         set_capture_state(Stopped);
444
445         // Confirm that SR_DF_END was received
446         if (_cur_logic_snapshot)
447         {
448                 qDebug("SR_DF_END was not received.");
449                 assert(0);
450         }
451 }
452
453 void SigSession::feed_in_header(shared_ptr<Device> device)
454 {
455         read_sample_rate(device);
456 }
457
458 void SigSession::feed_in_meta(shared_ptr<Device> device,
459         shared_ptr<Meta> meta)
460 {
461         (void)device;
462
463         for (auto entry : meta->config()) {
464                 switch (entry.first->id()) {
465                 case SR_CONF_SAMPLERATE:
466                         /// @todo handle samplerate changes
467                         break;
468                 default:
469                         // Unknown metadata is not an error.
470                         break;
471                 }
472         }
473
474         signals_changed();
475 }
476
477 void SigSession::feed_in_frame_begin()
478 {
479         if (_cur_logic_snapshot || !_cur_analog_snapshots.empty())
480                 frame_began();
481 }
482
483 void SigSession::feed_in_logic(shared_ptr<Logic> logic)
484 {
485         lock_guard<mutex> lock(_data_mutex);
486
487         if (!_logic_data)
488         {
489                 qDebug() << "Unexpected logic packet";
490                 return;
491         }
492
493         if (!_cur_logic_snapshot)
494         {
495                 // This could be the first packet after a trigger
496                 set_capture_state(Running);
497
498                 // Get sample limit.
499                 uint64_t sample_limit;
500                 try {
501                         sample_limit = VariantBase::cast_dynamic<Variant<guint64>>(
502                                 _device->config_get(ConfigKey::LIMIT_SAMPLES)).get();
503                 } catch (Error) {
504                         sample_limit = 0;
505                 }
506
507                 // Create a new data snapshot
508                 _cur_logic_snapshot = shared_ptr<data::LogicSnapshot>(
509                         new data::LogicSnapshot(logic, sample_limit));
510                 _logic_data->push_snapshot(_cur_logic_snapshot);
511
512                 // @todo Putting this here means that only listeners querying
513                 // for logic will be notified. Currently the only user of
514                 // frame_began is DecoderStack, but in future we need to signal
515                 // this after both analog and logic sweeps have begun.
516                 frame_began();
517         }
518         else
519         {
520                 // Append to the existing data snapshot
521                 _cur_logic_snapshot->append_payload(logic);
522         }
523
524         data_received();
525 }
526
527 void SigSession::feed_in_analog(shared_ptr<Analog> analog)
528 {
529         lock_guard<mutex> lock(_data_mutex);
530
531         const vector<shared_ptr<Channel>> channels = analog->channels();
532         const unsigned int channel_count = channels.size();
533         const size_t sample_count = analog->num_samples() / channel_count;
534         const float *data = analog->data_pointer();
535         bool sweep_beginning = false;
536
537         for (auto channel : channels)
538         {
539                 shared_ptr<data::AnalogSnapshot> snapshot;
540
541                 // Try to get the snapshot of the channel
542                 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSnapshot> >::
543                         iterator iter = _cur_analog_snapshots.find(channel);
544                 if (iter != _cur_analog_snapshots.end())
545                         snapshot = (*iter).second;
546                 else
547                 {
548                         // If no snapshot was found, this means we havn't
549                         // created one yet. i.e. this is the first packet
550                         // in the sweep containing this snapshot.
551                         sweep_beginning = true;
552
553                         // Get sample limit.
554                         uint64_t sample_limit;
555                         try {
556                                 sample_limit = VariantBase::cast_dynamic<Variant<guint64>>(
557                                         _device->config_get(ConfigKey::LIMIT_SAMPLES)).get();
558                         } catch (Error) {
559                                 sample_limit = 0;
560                         }
561
562                         // Create a snapshot, keep it in the maps of channels
563                         snapshot = shared_ptr<data::AnalogSnapshot>(
564                                 new data::AnalogSnapshot(sample_limit));
565                         _cur_analog_snapshots[channel] = snapshot;
566
567                         // Find the annalog data associated with the channel
568                         shared_ptr<view::AnalogSignal> sig =
569                                 dynamic_pointer_cast<view::AnalogSignal>(
570                                         signal_from_channel(channel));
571                         assert(sig);
572
573                         shared_ptr<data::Analog> data(sig->analog_data());
574                         assert(data);
575
576                         // Push the snapshot into the analog data.
577                         data->push_snapshot(snapshot);
578                 }
579
580                 assert(snapshot);
581
582                 // Append the samples in the snapshot
583                 snapshot->append_interleaved_samples(data++, sample_count,
584                         channel_count);
585         }
586
587         if (sweep_beginning) {
588                 // This could be the first packet after a trigger
589                 set_capture_state(Running);
590         }
591
592         data_received();
593 }
594
595 void SigSession::data_feed_in(shared_ptr<Device> device, shared_ptr<Packet> packet)
596 {
597         assert(device);
598         assert(packet);
599
600         switch (packet->type()->id()) {
601         case SR_DF_HEADER:
602                 feed_in_header(device);
603                 break;
604
605         case SR_DF_META:
606                 feed_in_meta(device, dynamic_pointer_cast<Meta>(packet->payload()));
607                 break;
608
609         case SR_DF_FRAME_BEGIN:
610                 feed_in_frame_begin();
611                 break;
612
613         case SR_DF_LOGIC:
614                 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
615                 break;
616
617         case SR_DF_ANALOG:
618                 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
619                 break;
620
621         case SR_DF_END:
622         {
623                 {
624                         lock_guard<mutex> lock(_data_mutex);
625                         _cur_logic_snapshot.reset();
626                         _cur_analog_snapshots.clear();
627                 }
628                 frame_ended();
629                 break;
630         }
631         default:
632                 break;
633         }
634 }
635
636 } // namespace pv