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