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