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