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