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