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