]> sigrok.org Git - pulseview.git/blob - pv/sigsession.cpp
Moved session creation into DevInst objects
[pulseview.git] / pv / sigsession.cpp
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 #include "device/file.h"
30
31 #include "data/analog.h"
32 #include "data/analogsnapshot.h"
33 #include "data/decoderstack.h"
34 #include "data/logic.h"
35 #include "data/logicsnapshot.h"
36 #include "data/decode/decoder.h"
37
38 #include "view/analogsignal.h"
39 #include "view/decodetrace.h"
40 #include "view/logicsignal.h"
41
42 #include <assert.h>
43
44 #include <stdexcept>
45
46 #include <boost/foreach.hpp>
47
48 #include <sys/stat.h>
49
50 #include <QDebug>
51
52 using boost::dynamic_pointer_cast;
53 using boost::function;
54 using boost::lock_guard;
55 using boost::mutex;
56 using boost::shared_ptr;
57 using std::map;
58 using std::set;
59 using std::string;
60 using std::vector;
61
62 namespace pv {
63
64 // TODO: This should not be necessary
65 SigSession* SigSession::_session = NULL;
66
67 SigSession::SigSession(DeviceManager &device_manager) :
68         _device_manager(device_manager),
69         _capture_state(Stopped)
70 {
71         // TODO: This should not be necessary
72         _session = this;
73 }
74
75 SigSession::~SigSession()
76 {
77         using pv::device::Device;
78
79         stop_capture();
80
81         if (_sampling_thread.joinable())
82                 _sampling_thread.join();
83
84         _dev_inst->release();
85
86         // TODO: This should not be necessary
87         _session = NULL;
88 }
89
90 shared_ptr<device::DevInst> SigSession::get_device() const
91 {
92         return _dev_inst;
93 }
94
95 void SigSession::set_device(
96         shared_ptr<device::DevInst> dev_inst) throw(QString)
97 {
98         using pv::device::Device;
99
100         // Ensure we are not capturing before setting the device
101         stop_capture();
102
103         if (_dev_inst) {
104                 sr_session_datafeed_callback_remove_all();
105                 _dev_inst->release();
106         }
107
108         _dev_inst = dev_inst;
109         _decode_traces.clear();
110
111         if (dev_inst) {
112                 dev_inst->use(this);
113                 sr_session_datafeed_callback_add(data_feed_in_proc, NULL);
114                 update_signals(dev_inst);
115         }
116 }
117
118 void SigSession::set_file(const string &name) throw(QString)
119 {
120         // Deslect the old device, because file type detection in File::create
121         // destorys the old session inside libsigrok.
122         set_device(shared_ptr<device::DevInst>());
123         set_device(shared_ptr<device::DevInst>(device::File::create(name)));
124 }
125
126 void SigSession::release_device(device::DevInst *dev_inst)
127 {
128         (void)dev_inst;
129         assert(_dev_inst.get() == dev_inst);
130
131         assert(_capture_state == Stopped);
132         _dev_inst = shared_ptr<device::DevInst>();
133 }
134
135 SigSession::capture_state SigSession::get_capture_state() const
136 {
137         lock_guard<mutex> lock(_sampling_mutex);
138         return _capture_state;
139 }
140
141 void SigSession::start_capture(function<void (const QString)> error_handler)
142 {
143         stop_capture();
144
145         // Check that a device instance has been selected.
146         if (!_dev_inst) {
147                 qDebug() << "No device selected";
148                 return;
149         }
150
151         assert(_dev_inst->dev_inst());
152
153         // Check that at least one probe is enabled
154         const GSList *l;
155         for (l = _dev_inst->dev_inst()->probes; l; l = l->next) {
156                 sr_probe *const probe = (sr_probe*)l->data;
157                 assert(probe);
158                 if (probe->enabled)
159                         break;
160         }
161
162         if (!l) {
163                 error_handler(tr("No probes enabled."));
164                 return;
165         }
166
167         // Begin the session
168         _sampling_thread = boost::thread(
169                 &SigSession::sample_thread_proc, this, _dev_inst,
170                         error_handler);
171 }
172
173 void SigSession::stop_capture()
174 {
175         if (get_capture_state() == Stopped)
176                 return;
177
178         sr_session_stop();
179
180         // Check that sampling stopped
181         if (_sampling_thread.joinable())
182                 _sampling_thread.join();
183 }
184
185 set< shared_ptr<data::SignalData> > SigSession::get_data() const
186 {
187         lock_guard<mutex> lock(_signals_mutex);
188         set< shared_ptr<data::SignalData> > data;
189         BOOST_FOREACH(const shared_ptr<view::Signal> sig, _signals) {
190                 assert(sig);
191                 data.insert(sig->data());
192         }
193
194         return data;
195 }
196
197 vector< shared_ptr<view::Signal> > SigSession::get_signals() const
198 {
199         lock_guard<mutex> lock(_signals_mutex);
200         return _signals;
201 }
202
203 #ifdef ENABLE_DECODE
204 bool SigSession::add_decoder(srd_decoder *const dec)
205 {
206         map<const srd_probe*, shared_ptr<view::LogicSignal> > probes;
207         shared_ptr<data::DecoderStack> decoder_stack;
208
209         try
210         {
211                 lock_guard<mutex> lock(_signals_mutex);
212
213                 // Create the decoder
214                 decoder_stack = shared_ptr<data::DecoderStack>(
215                         new data::DecoderStack(dec));
216
217                 // Make a list of all the probes
218                 std::vector<const srd_probe*> all_probes;
219                 for(const GSList *i = dec->probes; i; i = i->next)
220                         all_probes.push_back((const srd_probe*)i->data);
221                 for(const GSList *i = dec->opt_probes; i; i = i->next)
222                         all_probes.push_back((const srd_probe*)i->data);
223
224                 // Auto select the initial probes
225                 BOOST_FOREACH(const srd_probe *probe, all_probes)
226                         BOOST_FOREACH(shared_ptr<view::Signal> s, _signals)
227                         {
228                                 shared_ptr<view::LogicSignal> l =
229                                         dynamic_pointer_cast<view::LogicSignal>(s);
230                                 if (l && QString::fromUtf8(probe->name).
231                                         toLower().contains(
232                                         l->get_name().toLower()))
233                                         probes[probe] = l;
234                         }
235
236                 assert(decoder_stack);
237                 assert(!decoder_stack->stack().empty());
238                 assert(decoder_stack->stack().front());
239                 decoder_stack->stack().front()->set_probes(probes);
240
241                 // Create the decode signal
242                 shared_ptr<view::DecodeTrace> d(
243                         new view::DecodeTrace(*this, decoder_stack,
244                                 _decode_traces.size()));
245                 _decode_traces.push_back(d);
246         }
247         catch(std::runtime_error e)
248         {
249                 return false;
250         }
251
252         signals_changed();
253
254         // Do an initial decode
255         decoder_stack->begin_decode();
256
257         return true;
258 }
259
260 vector< shared_ptr<view::DecodeTrace> > SigSession::get_decode_signals() const
261 {
262         lock_guard<mutex> lock(_signals_mutex);
263         return _decode_traces;
264 }
265
266 void SigSession::remove_decode_signal(view::DecodeTrace *signal)
267 {
268         for (vector< shared_ptr<view::DecodeTrace> >::iterator i =
269                 _decode_traces.begin();
270                 i != _decode_traces.end();
271                 i++)
272                 if ((*i).get() == signal)
273                 {
274                         _decode_traces.erase(i);
275                         signals_changed();
276                         return;
277                 }
278 }
279 #endif
280
281 void SigSession::set_capture_state(capture_state state)
282 {
283         lock_guard<mutex> lock(_sampling_mutex);
284         const bool changed = _capture_state != state;
285         _capture_state = state;
286         if(changed)
287                 capture_state_changed(state);
288 }
289
290 void SigSession::update_signals(shared_ptr<device::DevInst> dev_inst)
291 {
292         assert(dev_inst);
293         assert(_capture_state == Stopped);
294
295         unsigned int logic_probe_count = 0;
296
297         // Clear the decode traces
298         _decode_traces.clear();
299
300         // Detect what data types we will receive
301         if(dev_inst) {
302                 assert(dev_inst->dev_inst());
303                 for (const GSList *l = dev_inst->dev_inst()->probes;
304                         l; l = l->next) {
305                         const sr_probe *const probe = (const sr_probe *)l->data;
306                         if (!probe->enabled)
307                                 continue;
308
309                         switch(probe->type) {
310                         case SR_PROBE_LOGIC:
311                                 logic_probe_count++;
312                                 break;
313                         }
314                 }
315         }
316
317         // Create data containers for the logic data snapshots
318         {
319                 lock_guard<mutex> data_lock(_data_mutex);
320
321                 _logic_data.reset();
322                 if (logic_probe_count != 0) {
323                         _logic_data.reset(new data::Logic(
324                                 logic_probe_count));
325                         assert(_logic_data);
326                 }
327         }
328
329         // Make the Signals list
330         do {
331                 lock_guard<mutex> lock(_signals_mutex);
332
333                 _signals.clear();
334
335                 if(!dev_inst)
336                         break;
337
338                 assert(dev_inst->dev_inst());
339                 for (const GSList *l = dev_inst->dev_inst()->probes;
340                         l; l = l->next) {
341                         shared_ptr<view::Signal> signal;
342                         sr_probe *const probe = (sr_probe *)l->data;
343                         assert(probe);
344
345                         switch(probe->type) {
346                         case SR_PROBE_LOGIC:
347                                 signal = shared_ptr<view::Signal>(
348                                         new view::LogicSignal(dev_inst,
349                                                 probe, _logic_data));
350                                 break;
351
352                         case SR_PROBE_ANALOG:
353                         {
354                                 shared_ptr<data::Analog> data(
355                                         new data::Analog());
356                                 signal = shared_ptr<view::Signal>(
357                                         new view::AnalogSignal(dev_inst,
358                                                 probe, data));
359                                 break;
360                         }
361
362                         default:
363                                 assert(0);
364                                 break;
365                         }
366
367                         assert(signal);
368                         _signals.push_back(signal);
369                 }
370
371         } while(0);
372
373         signals_changed();
374 }
375
376 shared_ptr<view::Signal> SigSession::signal_from_probe(
377         const sr_probe *probe) const
378 {
379         lock_guard<mutex> lock(_signals_mutex);
380         BOOST_FOREACH(shared_ptr<view::Signal> sig, _signals) {
381                 assert(sig);
382                 if (sig->probe() == probe)
383                         return sig;
384         }
385         return shared_ptr<view::Signal>();
386 }
387
388 void SigSession::read_sample_rate(const sr_dev_inst *const sdi)
389 {
390         GVariant *gvar;
391         uint64_t sample_rate = 0;
392
393         // Read out the sample rate
394         if(sdi->driver)
395         {
396                 const int ret = sr_config_get(sdi->driver, sdi, NULL,
397                         SR_CONF_SAMPLERATE, &gvar);
398                 if (ret != SR_OK) {
399                         qDebug("Failed to get samplerate\n");
400                         return;
401                 }
402
403                 sample_rate = g_variant_get_uint64(gvar);
404                 g_variant_unref(gvar);
405         }
406
407         // Set the sample rate of all data
408         const set< shared_ptr<data::SignalData> > data_set = get_data();
409         BOOST_FOREACH(shared_ptr<data::SignalData> data, data_set) {
410                 assert(data);
411                 data->set_samplerate(sample_rate);
412         }
413 }
414
415 void SigSession::sample_thread_proc(shared_ptr<device::DevInst> dev_inst,
416         function<void (const QString)> error_handler)
417 {
418         assert(dev_inst);
419         assert(dev_inst->dev_inst());
420         assert(error_handler);
421
422         read_sample_rate(dev_inst->dev_inst());
423
424         try {
425                 dev_inst->start();
426         } catch(const QString e) {
427                 error_handler(e);
428                 return;
429         }
430
431         set_capture_state(dev_inst->is_trigger_enabled() ?
432                 AwaitingTrigger : Running);
433
434         dev_inst->run();
435         set_capture_state(Stopped);
436
437         // Confirm that SR_DF_END was received
438         if (_cur_logic_snapshot)
439         {
440                 qDebug("SR_DF_END was not received.");
441                 assert(0);
442         }
443 }
444
445 void SigSession::feed_in_header(const sr_dev_inst *sdi)
446 {
447         read_sample_rate(sdi);
448 }
449
450 void SigSession::feed_in_meta(const sr_dev_inst *sdi,
451         const sr_datafeed_meta &meta)
452 {
453         (void)sdi;
454
455         for (const GSList *l = meta.config; l; l = l->next) {
456                 const sr_config *const src = (const sr_config*)l->data;
457                 switch (src->key) {
458                 case SR_CONF_SAMPLERATE:
459                         /// @todo handle samplerate changes
460                         /// samplerate = (uint64_t *)src->value;
461                         break;
462                 default:
463                         // Unknown metadata is not an error.
464                         break;
465                 }
466         }
467
468         signals_changed();
469 }
470
471 void SigSession::feed_in_logic(const sr_datafeed_logic &logic)
472 {
473         lock_guard<mutex> lock(_data_mutex);
474
475         if (!_logic_data)
476         {
477                 qDebug() << "Unexpected logic packet";
478                 return;
479         }
480
481         if (!_cur_logic_snapshot)
482         {
483                 // This could be the first packet after a trigger
484                 set_capture_state(Running);
485
486                 // Create a new data snapshot
487                 _cur_logic_snapshot = shared_ptr<data::LogicSnapshot>(
488                         new data::LogicSnapshot(logic, _dev_inst->get_sample_limit()));
489                 _logic_data->push_snapshot(_cur_logic_snapshot);
490         }
491         else
492         {
493                 // Append to the existing data snapshot
494                 _cur_logic_snapshot->append_payload(logic);
495         }
496
497         data_updated();
498 }
499
500 void SigSession::feed_in_analog(const sr_datafeed_analog &analog)
501 {
502         lock_guard<mutex> lock(_data_mutex);
503
504         const unsigned int probe_count = g_slist_length(analog.probes);
505         const size_t sample_count = analog.num_samples / probe_count;
506         const float *data = analog.data;
507         bool sweep_beginning = false;
508
509         for (GSList *p = analog.probes; p; p = p->next)
510         {
511                 shared_ptr<data::AnalogSnapshot> snapshot;
512
513                 sr_probe *const probe = (sr_probe*)p->data;
514                 assert(probe);
515
516                 // Try to get the snapshot of the probe
517                 const map< const sr_probe*, shared_ptr<data::AnalogSnapshot> >::
518                         iterator iter = _cur_analog_snapshots.find(probe);
519                 if (iter != _cur_analog_snapshots.end())
520                         snapshot = (*iter).second;
521                 else
522                 {
523                         // If no snapshot was found, this means we havn't
524                         // created one yet. i.e. this is the first packet
525                         // in the sweep containing this snapshot.
526                         sweep_beginning = true;
527
528                         // Create a snapshot, keep it in the maps of probes
529                         snapshot = shared_ptr<data::AnalogSnapshot>(
530                                 new data::AnalogSnapshot(_dev_inst->get_sample_limit()));
531                         _cur_analog_snapshots[probe] = snapshot;
532
533                         // Find the annalog data associated with the probe
534                         shared_ptr<view::AnalogSignal> sig =
535                                 dynamic_pointer_cast<view::AnalogSignal>(
536                                         signal_from_probe(probe));
537                         assert(sig);
538
539                         shared_ptr<data::Analog> data(sig->analog_data());
540                         assert(data);
541
542                         // Push the snapshot into the analog data.
543                         data->push_snapshot(snapshot);
544                 }
545
546                 assert(snapshot);
547
548                 // Append the samples in the snapshot
549                 snapshot->append_interleaved_samples(data++, sample_count,
550                         probe_count);
551         }
552
553         if (sweep_beginning) {
554                 // This could be the first packet after a trigger
555                 set_capture_state(Running);
556         }
557
558         data_updated();
559 }
560
561 void SigSession::data_feed_in(const struct sr_dev_inst *sdi,
562         const struct sr_datafeed_packet *packet)
563 {
564         assert(sdi);
565         assert(packet);
566
567         switch (packet->type) {
568         case SR_DF_HEADER:
569                 feed_in_header(sdi);
570                 break;
571
572         case SR_DF_META:
573                 assert(packet->payload);
574                 feed_in_meta(sdi,
575                         *(const sr_datafeed_meta*)packet->payload);
576                 break;
577
578         case SR_DF_LOGIC:
579                 assert(packet->payload);
580                 feed_in_logic(*(const sr_datafeed_logic*)packet->payload);
581                 break;
582
583         case SR_DF_ANALOG:
584                 assert(packet->payload);
585                 feed_in_analog(*(const sr_datafeed_analog*)packet->payload);
586                 break;
587
588         case SR_DF_END:
589         {
590                 {
591                         lock_guard<mutex> lock(_data_mutex);
592                         _cur_logic_snapshot.reset();
593                         _cur_analog_snapshots.clear();
594                 }
595                 data_updated();
596                 break;
597         }
598         }
599 }
600
601 void SigSession::data_feed_in_proc(const struct sr_dev_inst *sdi,
602         const struct sr_datafeed_packet *packet, void *cb_data)
603 {
604         (void) cb_data;
605         assert(_session);
606         _session->data_feed_in(sdi, packet);
607 }
608
609 } // namespace pv