]> sigrok.org Git - pulseview.git/blame_incremental - pv/sigsession.cpp
Moved SigSession::is_trigger_enabled into DevInst
[pulseview.git] / pv / sigsession.cpp
... / ...
CommitLineData
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
30#include "data/analog.h"
31#include "data/analogsnapshot.h"
32#include "data/decoderstack.h"
33#include "data/logic.h"
34#include "data/logicsnapshot.h"
35#include "data/decode/decoder.h"
36
37#include "view/analogsignal.h"
38#include "view/decodetrace.h"
39#include "view/logicsignal.h"
40
41#include <assert.h>
42
43#include <stdexcept>
44
45#include <boost/foreach.hpp>
46
47#include <sys/stat.h>
48
49#include <QDebug>
50
51using boost::dynamic_pointer_cast;
52using boost::function;
53using boost::lock_guard;
54using boost::mutex;
55using boost::shared_ptr;
56using std::map;
57using std::set;
58using std::string;
59using std::vector;
60
61namespace pv {
62
63// TODO: This should not be necessary
64SigSession* SigSession::_session = NULL;
65
66SigSession::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
74SigSession::~SigSession()
75{
76 using pv::device::Device;
77
78 stop_capture();
79
80 if (_sampling_thread.joinable())
81 _sampling_thread.join();
82
83 _dev_inst->release();
84
85 // TODO: This should not be necessary
86 _session = NULL;
87}
88
89shared_ptr<device::DevInst> SigSession::get_device() const
90{
91 return _dev_inst;
92}
93
94void SigSession::set_device(shared_ptr<device::DevInst> dev_inst)
95{
96 using pv::device::Device;
97
98 // Ensure we are not capturing before setting the device
99 stop_capture();
100
101 if (_dev_inst)
102 _dev_inst->release();
103
104 if (dev_inst)
105 dev_inst->use(this);
106
107 _dev_inst = dev_inst;
108 update_signals(dev_inst);
109}
110
111void SigSession::release_device(device::DevInst *dev_inst)
112{
113 (void)dev_inst;
114 assert(_dev_inst.get() == dev_inst);
115
116 assert(_capture_state == Stopped);
117 _dev_inst = shared_ptr<device::DevInst>();
118}
119
120void SigSession::load_file(const string &name,
121 function<void (const QString)> error_handler)
122{
123 stop_capture();
124
125 if (sr_session_load(name.c_str()) == SR_OK) {
126 GSList *devlist = NULL;
127 sr_session_dev_list(&devlist);
128
129 if (!devlist || !devlist->data ||
130 sr_session_start() != SR_OK) {
131 error_handler(tr("Failed to start session."));
132 return;
133 }
134
135 shared_ptr<device::DevInst> dev_inst(
136 new device::Device((sr_dev_inst*)devlist->data));
137 g_slist_free(devlist);
138
139 _decode_traces.clear();
140 update_signals(dev_inst);
141 read_sample_rate(dev_inst->dev_inst());
142
143 _sampling_thread = boost::thread(
144 &SigSession::load_session_thread_proc, this,
145 error_handler);
146
147 } else {
148 sr_input *in = NULL;
149
150 if (!(in = load_input_file_format(name.c_str(),
151 error_handler)))
152 return;
153
154 _decode_traces.clear();
155 update_signals(shared_ptr<device::DevInst>(
156 new device::Device(in->sdi)));
157 read_sample_rate(in->sdi);
158
159 _sampling_thread = boost::thread(
160 &SigSession::load_input_thread_proc, this,
161 name, in, error_handler);
162 }
163}
164
165SigSession::capture_state SigSession::get_capture_state() const
166{
167 lock_guard<mutex> lock(_sampling_mutex);
168 return _capture_state;
169}
170
171void SigSession::start_capture(function<void (const QString)> error_handler)
172{
173 stop_capture();
174
175 // Check that a device instance has been selected.
176 if (!_dev_inst) {
177 qDebug() << "No device selected";
178 return;
179 }
180
181 assert(_dev_inst->dev_inst());
182
183 // Check that at least one probe is enabled
184 const GSList *l;
185 for (l = _dev_inst->dev_inst()->probes; l; l = l->next) {
186 sr_probe *const probe = (sr_probe*)l->data;
187 assert(probe);
188 if (probe->enabled)
189 break;
190 }
191
192 if (!l) {
193 error_handler(tr("No probes enabled."));
194 return;
195 }
196
197 // Begin the session
198 _sampling_thread = boost::thread(
199 &SigSession::sample_thread_proc, this, _dev_inst,
200 error_handler);
201}
202
203void SigSession::stop_capture()
204{
205 if (get_capture_state() == Stopped)
206 return;
207
208 sr_session_stop();
209
210 // Check that sampling stopped
211 if (_sampling_thread.joinable())
212 _sampling_thread.join();
213}
214
215set< shared_ptr<data::SignalData> > SigSession::get_data() const
216{
217 lock_guard<mutex> lock(_signals_mutex);
218 set< shared_ptr<data::SignalData> > data;
219 BOOST_FOREACH(const shared_ptr<view::Signal> sig, _signals) {
220 assert(sig);
221 data.insert(sig->data());
222 }
223
224 return data;
225}
226
227vector< shared_ptr<view::Signal> > SigSession::get_signals() const
228{
229 lock_guard<mutex> lock(_signals_mutex);
230 return _signals;
231}
232
233#ifdef ENABLE_DECODE
234bool SigSession::add_decoder(srd_decoder *const dec)
235{
236 map<const srd_probe*, shared_ptr<view::LogicSignal> > probes;
237 shared_ptr<data::DecoderStack> decoder_stack;
238
239 try
240 {
241 lock_guard<mutex> lock(_signals_mutex);
242
243 // Create the decoder
244 decoder_stack = shared_ptr<data::DecoderStack>(
245 new data::DecoderStack(dec));
246
247 // Make a list of all the probes
248 std::vector<const srd_probe*> all_probes;
249 for(const GSList *i = dec->probes; i; i = i->next)
250 all_probes.push_back((const srd_probe*)i->data);
251 for(const GSList *i = dec->opt_probes; i; i = i->next)
252 all_probes.push_back((const srd_probe*)i->data);
253
254 // Auto select the initial probes
255 BOOST_FOREACH(const srd_probe *probe, all_probes)
256 BOOST_FOREACH(shared_ptr<view::Signal> s, _signals)
257 {
258 shared_ptr<view::LogicSignal> l =
259 dynamic_pointer_cast<view::LogicSignal>(s);
260 if (l && QString::fromUtf8(probe->name).
261 toLower().contains(
262 l->get_name().toLower()))
263 probes[probe] = l;
264 }
265
266 assert(decoder_stack);
267 assert(!decoder_stack->stack().empty());
268 assert(decoder_stack->stack().front());
269 decoder_stack->stack().front()->set_probes(probes);
270
271 // Create the decode signal
272 shared_ptr<view::DecodeTrace> d(
273 new view::DecodeTrace(*this, decoder_stack,
274 _decode_traces.size()));
275 _decode_traces.push_back(d);
276 }
277 catch(std::runtime_error e)
278 {
279 return false;
280 }
281
282 signals_changed();
283
284 // Do an initial decode
285 decoder_stack->begin_decode();
286
287 return true;
288}
289
290vector< shared_ptr<view::DecodeTrace> > SigSession::get_decode_signals() const
291{
292 lock_guard<mutex> lock(_signals_mutex);
293 return _decode_traces;
294}
295
296void SigSession::remove_decode_signal(view::DecodeTrace *signal)
297{
298 for (vector< shared_ptr<view::DecodeTrace> >::iterator i =
299 _decode_traces.begin();
300 i != _decode_traces.end();
301 i++)
302 if ((*i).get() == signal)
303 {
304 _decode_traces.erase(i);
305 signals_changed();
306 return;
307 }
308}
309#endif
310
311void SigSession::set_capture_state(capture_state state)
312{
313 lock_guard<mutex> lock(_sampling_mutex);
314 const bool changed = _capture_state != state;
315 _capture_state = state;
316 if(changed)
317 capture_state_changed(state);
318}
319
320/**
321 * Attempts to autodetect the format. Failing that
322 * @param filename The filename of the input file.
323 * @return A pointer to the 'struct sr_input_format' that should be used,
324 * or NULL if no input format was selected or auto-detected.
325 */
326sr_input_format* SigSession::determine_input_file_format(
327 const string &filename)
328{
329 int i;
330
331 /* If there are no input formats, return NULL right away. */
332 sr_input_format *const *const inputs = sr_input_list();
333 if (!inputs) {
334 g_critical("No supported input formats available.");
335 return NULL;
336 }
337
338 /* Otherwise, try to find an input module that can handle this file. */
339 for (i = 0; inputs[i]; i++) {
340 if (inputs[i]->format_match(filename.c_str()))
341 break;
342 }
343
344 /* Return NULL if no input module wanted to touch this. */
345 if (!inputs[i]) {
346 g_critical("Error: no matching input module found.");
347 return NULL;
348 }
349
350 return inputs[i];
351}
352
353sr_input* SigSession::load_input_file_format(const string &filename,
354 function<void (const QString)> error_handler,
355 sr_input_format *format)
356{
357 struct stat st;
358 sr_input *in;
359
360 if (!format && !(format =
361 determine_input_file_format(filename.c_str()))) {
362 /* The exact cause was already logged. */
363 return NULL;
364 }
365
366 if (stat(filename.c_str(), &st) == -1) {
367 error_handler(tr("Failed to load file"));
368 return NULL;
369 }
370
371 /* Initialize the input module. */
372 if (!(in = new sr_input)) {
373 qDebug("Failed to allocate input module.\n");
374 return NULL;
375 }
376
377 in->format = format;
378 in->param = NULL;
379 if (in->format->init &&
380 in->format->init(in, filename.c_str()) != SR_OK) {
381 qDebug("Input format init failed.\n");
382 return NULL;
383 }
384
385 sr_session_new();
386
387 if (sr_session_dev_add(in->sdi) != SR_OK) {
388 qDebug("Failed to use device.\n");
389 sr_session_destroy();
390 return NULL;
391 }
392
393 return in;
394}
395
396void SigSession::update_signals(shared_ptr<device::DevInst> dev_inst)
397{
398 assert(dev_inst);
399 assert(_capture_state == Stopped);
400
401 unsigned int logic_probe_count = 0;
402
403 // Clear the decode traces
404 _decode_traces.clear();
405
406 // Detect what data types we will receive
407 if(dev_inst) {
408 assert(dev_inst->dev_inst());
409 for (const GSList *l = dev_inst->dev_inst()->probes;
410 l; l = l->next) {
411 const sr_probe *const probe = (const sr_probe *)l->data;
412 if (!probe->enabled)
413 continue;
414
415 switch(probe->type) {
416 case SR_PROBE_LOGIC:
417 logic_probe_count++;
418 break;
419 }
420 }
421 }
422
423 // Create data containers for the logic data snapshots
424 {
425 lock_guard<mutex> data_lock(_data_mutex);
426
427 _logic_data.reset();
428 if (logic_probe_count != 0) {
429 _logic_data.reset(new data::Logic(
430 logic_probe_count));
431 assert(_logic_data);
432 }
433 }
434
435 // Make the Signals list
436 do {
437 lock_guard<mutex> lock(_signals_mutex);
438
439 _signals.clear();
440
441 if(!dev_inst)
442 break;
443
444 assert(dev_inst->dev_inst());
445 for (const GSList *l = dev_inst->dev_inst()->probes;
446 l; l = l->next) {
447 shared_ptr<view::Signal> signal;
448 sr_probe *const probe = (sr_probe *)l->data;
449 assert(probe);
450
451 switch(probe->type) {
452 case SR_PROBE_LOGIC:
453 signal = shared_ptr<view::Signal>(
454 new view::LogicSignal(dev_inst,
455 probe, _logic_data));
456 break;
457
458 case SR_PROBE_ANALOG:
459 {
460 shared_ptr<data::Analog> data(
461 new data::Analog());
462 signal = shared_ptr<view::Signal>(
463 new view::AnalogSignal(dev_inst,
464 probe, data));
465 break;
466 }
467
468 default:
469 assert(0);
470 break;
471 }
472
473 assert(signal);
474 _signals.push_back(signal);
475 }
476
477 } while(0);
478
479 signals_changed();
480}
481
482shared_ptr<view::Signal> SigSession::signal_from_probe(
483 const sr_probe *probe) const
484{
485 lock_guard<mutex> lock(_signals_mutex);
486 BOOST_FOREACH(shared_ptr<view::Signal> sig, _signals) {
487 assert(sig);
488 if (sig->probe() == probe)
489 return sig;
490 }
491 return shared_ptr<view::Signal>();
492}
493
494void SigSession::read_sample_rate(const sr_dev_inst *const sdi)
495{
496 GVariant *gvar;
497 uint64_t sample_rate = 0;
498
499 // Read out the sample rate
500 if(sdi->driver)
501 {
502 const int ret = sr_config_get(sdi->driver, sdi, NULL,
503 SR_CONF_SAMPLERATE, &gvar);
504 if (ret != SR_OK) {
505 qDebug("Failed to get samplerate\n");
506 return;
507 }
508
509 sample_rate = g_variant_get_uint64(gvar);
510 g_variant_unref(gvar);
511 }
512
513 // Set the sample rate of all data
514 const set< shared_ptr<data::SignalData> > data_set = get_data();
515 BOOST_FOREACH(shared_ptr<data::SignalData> data, data_set) {
516 assert(data);
517 data->set_samplerate(sample_rate);
518 }
519}
520
521void SigSession::load_session_thread_proc(
522 function<void (const QString)> error_handler)
523{
524 (void)error_handler;
525
526 sr_session_datafeed_callback_add(data_feed_in_proc, NULL);
527
528 set_capture_state(Running);
529
530 sr_session_run();
531
532 sr_session_destroy();
533 set_capture_state(Stopped);
534
535 // Confirm that SR_DF_END was received
536 assert(!_cur_logic_snapshot);
537 assert(_cur_analog_snapshots.empty());
538}
539
540void SigSession::load_input_thread_proc(const string name,
541 sr_input *in, function<void (const QString)> error_handler)
542{
543 (void)error_handler;
544
545 assert(in);
546 assert(in->format);
547
548 sr_session_datafeed_callback_add(data_feed_in_proc, NULL);
549
550 set_capture_state(Running);
551
552 in->format->loadfile(in, name.c_str());
553
554 sr_session_destroy();
555 set_capture_state(Stopped);
556
557 // Confirm that SR_DF_END was received
558 assert(!_cur_logic_snapshot);
559 assert(_cur_analog_snapshots.empty());
560
561 delete in;
562}
563
564void SigSession::sample_thread_proc(shared_ptr<device::DevInst> dev_inst,
565 function<void (const QString)> error_handler)
566{
567 assert(dev_inst);
568 assert(dev_inst->dev_inst());
569 assert(error_handler);
570
571 sr_session_new();
572 sr_session_datafeed_callback_add(data_feed_in_proc, NULL);
573
574 if (sr_session_dev_add(dev_inst->dev_inst()) != SR_OK) {
575 error_handler(tr("Failed to use device."));
576 sr_session_destroy();
577 return;
578 }
579
580 if (sr_session_start() != SR_OK) {
581 error_handler(tr("Failed to start session."));
582 return;
583 }
584
585 set_capture_state(dev_inst->is_trigger_enabled() ?
586 AwaitingTrigger : Running);
587
588 sr_session_run();
589 sr_session_destroy();
590
591 set_capture_state(Stopped);
592
593 // Confirm that SR_DF_END was received
594 if (_cur_logic_snapshot)
595 {
596 qDebug("SR_DF_END was not received.");
597 assert(0);
598 }
599}
600
601void SigSession::feed_in_header(const sr_dev_inst *sdi)
602{
603 read_sample_rate(sdi);
604}
605
606void SigSession::feed_in_meta(const sr_dev_inst *sdi,
607 const sr_datafeed_meta &meta)
608{
609 (void)sdi;
610
611 for (const GSList *l = meta.config; l; l = l->next) {
612 const sr_config *const src = (const sr_config*)l->data;
613 switch (src->key) {
614 case SR_CONF_SAMPLERATE:
615 /// @todo handle samplerate changes
616 /// samplerate = (uint64_t *)src->value;
617 break;
618 default:
619 // Unknown metadata is not an error.
620 break;
621 }
622 }
623
624 signals_changed();
625}
626
627void SigSession::feed_in_logic(const sr_datafeed_logic &logic)
628{
629 lock_guard<mutex> lock(_data_mutex);
630
631 if (!_logic_data)
632 {
633 qDebug() << "Unexpected logic packet";
634 return;
635 }
636
637 if (!_cur_logic_snapshot)
638 {
639 // This could be the first packet after a trigger
640 set_capture_state(Running);
641
642 // Create a new data snapshot
643 _cur_logic_snapshot = shared_ptr<data::LogicSnapshot>(
644 new data::LogicSnapshot(logic, _dev_inst->get_sample_limit()));
645 _logic_data->push_snapshot(_cur_logic_snapshot);
646 }
647 else
648 {
649 // Append to the existing data snapshot
650 _cur_logic_snapshot->append_payload(logic);
651 }
652
653 data_updated();
654}
655
656void SigSession::feed_in_analog(const sr_datafeed_analog &analog)
657{
658 lock_guard<mutex> lock(_data_mutex);
659
660 const unsigned int probe_count = g_slist_length(analog.probes);
661 const size_t sample_count = analog.num_samples / probe_count;
662 const float *data = analog.data;
663 bool sweep_beginning = false;
664
665 for (GSList *p = analog.probes; p; p = p->next)
666 {
667 shared_ptr<data::AnalogSnapshot> snapshot;
668
669 sr_probe *const probe = (sr_probe*)p->data;
670 assert(probe);
671
672 // Try to get the snapshot of the probe
673 const map< const sr_probe*, shared_ptr<data::AnalogSnapshot> >::
674 iterator iter = _cur_analog_snapshots.find(probe);
675 if (iter != _cur_analog_snapshots.end())
676 snapshot = (*iter).second;
677 else
678 {
679 // If no snapshot was found, this means we havn't
680 // created one yet. i.e. this is the first packet
681 // in the sweep containing this snapshot.
682 sweep_beginning = true;
683
684 // Create a snapshot, keep it in the maps of probes
685 snapshot = shared_ptr<data::AnalogSnapshot>(
686 new data::AnalogSnapshot(_dev_inst->get_sample_limit()));
687 _cur_analog_snapshots[probe] = snapshot;
688
689 // Find the annalog data associated with the probe
690 shared_ptr<view::AnalogSignal> sig =
691 dynamic_pointer_cast<view::AnalogSignal>(
692 signal_from_probe(probe));
693 assert(sig);
694
695 shared_ptr<data::Analog> data(sig->analog_data());
696 assert(data);
697
698 // Push the snapshot into the analog data.
699 data->push_snapshot(snapshot);
700 }
701
702 assert(snapshot);
703
704 // Append the samples in the snapshot
705 snapshot->append_interleaved_samples(data++, sample_count,
706 probe_count);
707 }
708
709 if (sweep_beginning) {
710 // This could be the first packet after a trigger
711 set_capture_state(Running);
712 }
713
714 data_updated();
715}
716
717void SigSession::data_feed_in(const struct sr_dev_inst *sdi,
718 const struct sr_datafeed_packet *packet)
719{
720 assert(sdi);
721 assert(packet);
722
723 switch (packet->type) {
724 case SR_DF_HEADER:
725 feed_in_header(sdi);
726 break;
727
728 case SR_DF_META:
729 assert(packet->payload);
730 feed_in_meta(sdi,
731 *(const sr_datafeed_meta*)packet->payload);
732 break;
733
734 case SR_DF_LOGIC:
735 assert(packet->payload);
736 feed_in_logic(*(const sr_datafeed_logic*)packet->payload);
737 break;
738
739 case SR_DF_ANALOG:
740 assert(packet->payload);
741 feed_in_analog(*(const sr_datafeed_analog*)packet->payload);
742 break;
743
744 case SR_DF_END:
745 {
746 {
747 lock_guard<mutex> lock(_data_mutex);
748 _cur_logic_snapshot.reset();
749 _cur_analog_snapshots.clear();
750 }
751 data_updated();
752 break;
753 }
754 }
755}
756
757void SigSession::data_feed_in_proc(const struct sr_dev_inst *sdi,
758 const struct sr_datafeed_packet *packet, void *cb_data)
759{
760 (void) cb_data;
761 assert(_session);
762 _session->data_feed_in(sdi, packet);
763}
764
765} // namespace pv