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