]> sigrok.org Git - pulseview.git/blame - pv/sigsession.cpp
RowItem: Derrive from std::enable_shared_from_this
[pulseview.git] / pv / sigsession.cpp
CommitLineData
2953961c 1/*
b3f22de0 2 * This file is part of the PulseView project.
2953961c 3 *
1bc6525b 4 * Copyright (C) 2012-14 Joel Holdsworth <joel@airwebreathe.org.uk>
2953961c
JH
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
269528f5 21#ifdef ENABLE_DECODE
4e5a4405 22#include <libsigrokdecode/libsigrokdecode.h>
269528f5 23#endif
4e5a4405 24
2953961c
JH
25#include "sigsession.h"
26
dc0867ff 27#include "devicemanager.h"
119aff65 28
1b1ec774
JH
29#include "data/analog.h"
30#include "data/analogsnapshot.h"
6e89374a 31#include "data/decoderstack.h"
1b1ec774
JH
32#include "data/logic.h"
33#include "data/logicsnapshot.h"
7491a29f 34#include "data/decode/decoder.h"
82c7f640 35
aba1dd16 36#include "view/analogsignal.h"
b9329558 37#include "view/decodetrace.h"
8d634081 38#include "view/logicsignal.h"
28a4c9c5 39
3b68d03d
JH
40#include <cassert>
41#include <mutex>
e92cd4e4
JH
42#include <stdexcept>
43
728e5ef7
JH
44#include <sys/stat.h>
45
79efbc53
JH
46#include <QDebug>
47
e8d00928
ML
48#include <libsigrok/libsigrok.hpp>
49
aca64cac
JH
50using boost::shared_lock;
51using boost::shared_mutex;
52using boost::unique_lock;
53
f9abf97e 54using std::dynamic_pointer_cast;
d2344534 55using std::function;
3b68d03d 56using std::lock_guard;
d873f4d6 57using std::list;
819f4c25 58using std::map;
aca64cac 59using std::mutex;
02412f0b 60using std::set;
f9abf97e 61using std::shared_ptr;
819f4c25
JH
62using std::string;
63using std::vector;
28a4c9c5 64
e8d00928
ML
65using sigrok::Analog;
66using sigrok::Channel;
67using sigrok::ChannelType;
68using sigrok::ConfigKey;
69using sigrok::DatafeedCallbackFunction;
70using sigrok::Device;
71using sigrok::Error;
72using sigrok::HardwareDevice;
73using sigrok::Header;
74using sigrok::Logic;
75using sigrok::Meta;
76using sigrok::Packet;
77using sigrok::PacketPayload;
78using sigrok::Session;
79using sigrok::SessionDevice;
80
81using Glib::VariantBase;
82using Glib::Variant;
51e77110 83
e8d00928 84namespace pv {
dc0867ff
JH
85SigSession::SigSession(DeviceManager &device_manager) :
86 _device_manager(device_manager),
1f4caa77 87 _session(device_manager.context()->create_session()),
5b7cf66c 88 _capture_state(Stopped)
2953961c 89{
d873f4d6 90 set_default_device();
2953961c
JH
91}
92
93SigSession::~SigSession()
94{
04463625 95 // Stop and join to the thread
5b7cf66c 96 stop_capture();
2953961c
JH
97}
98
4cb0b033
JH
99DeviceManager& SigSession::device_manager()
100{
101 return _device_manager;
102}
103
104const DeviceManager& SigSession::device_manager() const
105{
106 return _device_manager;
107}
108
1f4caa77
JH
109const shared_ptr<sigrok::Session>& SigSession::session() const
110{
111 return _session;
112}
113
d260d425 114shared_ptr<Device> SigSession::device() const
dc0867ff 115{
e8d00928 116 return _device;
dc0867ff
JH
117}
118
e8d00928 119void SigSession::set_device(shared_ptr<Device> device)
d64d1596 120{
82596f46
JH
121 // Ensure we are not capturing before setting the device
122 stop_capture();
123
e8d00928
ML
124 // Are we setting a session device?
125 auto session_device = dynamic_pointer_cast<SessionDevice>(device);
126 // Did we have a session device selected previously?
127 auto prev_session_device = dynamic_pointer_cast<SessionDevice>(_device);
128
129 if (_device) {
1f4caa77 130 _session->remove_datafeed_callbacks();
e8d00928
ML
131 if (!prev_session_device) {
132 _device->close();
1f4caa77 133 _session->remove_devices();
e8d00928 134 }
ae2d1bc5
JH
135 }
136
e8d00928 137 if (session_device)
1f4caa77 138 _session = session_device->parent();
e8d00928
ML
139
140 _device = device;
ae2d1bc5 141 _decode_traces.clear();
85843b14 142
e8d00928
ML
143 if (device) {
144 if (!session_device)
145 {
1f4caa77 146 _session = _device_manager.context()->create_session();
e8d00928 147 device->open();
1f4caa77 148 _session->add_device(device);
e8d00928 149 }
1f4caa77 150 _session->add_datafeed_callback([=]
e8d00928
ML
151 (shared_ptr<Device> device, shared_ptr<Packet> packet) {
152 data_feed_in(device, packet);
153 });
154 update_signals(device);
ae2d1bc5
JH
155 }
156}
85843b14 157
e8d00928 158void SigSession::set_file(const string &name)
ae2d1bc5 159{
1f4caa77
JH
160 _session = _device_manager.context()->load_session(name);
161 _device = _session->devices()[0];
e8d00928 162 _decode_traces.clear();
1f4caa77 163 _session->add_datafeed_callback([=]
e8d00928
ML
164 (shared_ptr<Device> device, shared_ptr<Packet> packet) {
165 data_feed_in(device, packet);
166 });
a4cf020a 167 _device_manager.update_display_name(_device);
e8d00928 168 update_signals(_device);
d64d1596
JH
169}
170
6fd0b639
JH
171void SigSession::set_default_device()
172{
e8d00928
ML
173 shared_ptr<HardwareDevice> default_device;
174 const list< shared_ptr<HardwareDevice> > &devices =
6fd0b639
JH
175 _device_manager.devices();
176
177 if (!devices.empty()) {
178 // Fall back to the first device in the list.
179 default_device = devices.front();
180
181 // Try and find the demo device and select that by default
e8d00928
ML
182 for (shared_ptr<HardwareDevice> dev : devices)
183 if (dev->driver()->name().compare("demo") == 0) {
6fd0b639
JH
184 default_device = dev;
185 break;
186 }
dc0867ff 187
e8d00928
ML
188 set_device(default_device);
189 }
dc0867ff
JH
190}
191
5b7cf66c
JH
192SigSession::capture_state SigSession::get_capture_state() const
193{
949f8050 194 lock_guard<mutex> lock(_sampling_mutex);
5b7cf66c
JH
195 return _capture_state;
196}
197
d99dc9f2 198void SigSession::start_capture(function<void (const QString)> error_handler)
2e2946fe 199{
5b7cf66c
JH
200 stop_capture();
201
d64d1596 202 // Check that a device instance has been selected.
e8d00928 203 if (!_device) {
d64d1596
JH
204 qDebug() << "No device selected";
205 return;
206 }
207
6ac6242b 208 // Check that at least one channel is enabled
e8d00928
ML
209 auto channels = _device->channels();
210 bool enabled = std::any_of(channels.begin(), channels.end(),
211 [](shared_ptr<Channel> channel) { return channel->enabled(); });
9c48fa57 212
e8d00928 213 if (!enabled) {
4871ed92 214 error_handler(tr("No channels enabled."));
9c48fa57
JH
215 return;
216 }
217
218 // Begin the session
3b68d03d 219 _sampling_thread = std::thread(
e8d00928 220 &SigSession::sample_thread_proc, this, _device,
19adbc2c 221 error_handler);
2e2946fe
JH
222}
223
5b7cf66c
JH
224void SigSession::stop_capture()
225{
04463625 226 if (get_capture_state() != Stopped)
1f4caa77 227 _session->stop();
5b7cf66c
JH
228
229 // Check that sampling stopped
6d483b8b
MC
230 if (_sampling_thread.joinable())
231 _sampling_thread.join();
5b7cf66c
JH
232}
233
02412f0b
JH
234set< shared_ptr<data::SignalData> > SigSession::get_data() const
235{
aca64cac 236 shared_lock<shared_mutex> lock(_signals_mutex);
02412f0b 237 set< shared_ptr<data::SignalData> > data;
d9aecf1f 238 for (const shared_ptr<view::Signal> sig : _signals) {
02412f0b
JH
239 assert(sig);
240 data.insert(sig->data());
241 }
242
243 return data;
244}
245
aca64cac 246boost::shared_mutex& SigSession::signals_mutex() const
c3a740dd
JH
247{
248 return _signals_mutex;
249}
250
251const vector< shared_ptr<view::Signal> >& SigSession::signals() const
2e2946fe
JH
252{
253 return _signals;
254}
255
269528f5 256#ifdef ENABLE_DECODE
4e5a4405 257bool SigSession::add_decoder(srd_decoder *const dec)
82c7f640 258{
6ac6242b 259 map<const srd_channel*, shared_ptr<view::LogicSignal> > channels;
7491a29f 260 shared_ptr<data::DecoderStack> decoder_stack;
4e5a4405 261
e92cd4e4 262 try
82c7f640 263 {
aca64cac 264 lock_guard<boost::shared_mutex> lock(_signals_mutex);
e0fc5810 265
4e5a4405 266 // Create the decoder
7491a29f 267 decoder_stack = shared_ptr<data::DecoderStack>(
bdc5c3b0 268 new data::DecoderStack(*this, dec));
4e5a4405 269
6ac6242b
ML
270 // Make a list of all the channels
271 std::vector<const srd_channel*> all_channels;
8bd26d8b 272 for(const GSList *i = dec->channels; i; i = i->next)
6ac6242b 273 all_channels.push_back((const srd_channel*)i->data);
8bd26d8b 274 for(const GSList *i = dec->opt_channels; i; i = i->next)
6ac6242b 275 all_channels.push_back((const srd_channel*)i->data);
d2f46d27 276
6ac6242b
ML
277 // Auto select the initial channels
278 for (const srd_channel *pdch : all_channels)
d9aecf1f 279 for (shared_ptr<view::Signal> s : _signals)
4e5a4405
JH
280 {
281 shared_ptr<view::LogicSignal> l =
282 dynamic_pointer_cast<view::LogicSignal>(s);
8bd26d8b 283 if (l && QString::fromUtf8(pdch->name).
27e8df22 284 toLower().contains(
0a47889b 285 l->name().toLower()))
6ac6242b 286 channels[pdch] = l;
4e5a4405 287 }
4e5a4405 288
7491a29f
JH
289 assert(decoder_stack);
290 assert(!decoder_stack->stack().empty());
291 assert(decoder_stack->stack().front());
6ac6242b 292 decoder_stack->stack().front()->set_channels(channels);
4e5a4405
JH
293
294 // Create the decode signal
b9329558 295 shared_ptr<view::DecodeTrace> d(
7491a29f 296 new view::DecodeTrace(*this, decoder_stack,
06bb4e6a 297 _decode_traces.size()));
82c7f640
JH
298 _decode_traces.push_back(d);
299 }
e92cd4e4
JH
300 catch(std::runtime_error e)
301 {
302 return false;
303 }
304
82c7f640 305 signals_changed();
e92cd4e4 306
7491a29f
JH
307 // Do an initial decode
308 decoder_stack->begin_decode();
309
e92cd4e4 310 return true;
82c7f640
JH
311}
312
b9329558 313vector< shared_ptr<view::DecodeTrace> > SigSession::get_decode_signals() const
38eeddea 314{
aca64cac 315 shared_lock<shared_mutex> lock(_signals_mutex);
38eeddea
JH
316 return _decode_traces;
317}
318
b9329558 319void SigSession::remove_decode_signal(view::DecodeTrace *signal)
c51482b3 320{
f46e495e 321 for (auto i = _decode_traces.begin(); i != _decode_traces.end(); i++)
c51482b3
JH
322 if ((*i).get() == signal)
323 {
324 _decode_traces.erase(i);
325 signals_changed();
326 return;
327 }
328}
269528f5 329#endif
c51482b3 330
6ac96c2e
JH
331void SigSession::set_capture_state(capture_state state)
332{
949f8050 333 lock_guard<mutex> lock(_sampling_mutex);
2b49eeb0 334 const bool changed = _capture_state != state;
6ac96c2e 335 _capture_state = state;
2b49eeb0
JH
336 if(changed)
337 capture_state_changed(state);
6ac96c2e
JH
338}
339
e8d00928 340void SigSession::update_signals(shared_ptr<Device> device)
b087ba7f 341{
e8d00928 342 assert(device);
b087ba7f
JH
343 assert(_capture_state == Stopped);
344
82c7f640
JH
345 // Clear the decode traces
346 _decode_traces.clear();
347
b087ba7f 348 // Detect what data types we will receive
e8d00928
ML
349 auto channels = device->channels();
350 unsigned int logic_channel_count = std::count_if(
351 channels.begin(), channels.end(),
352 [] (shared_ptr<Channel> channel) {
353 return channel->type() == ChannelType::LOGIC; });
b087ba7f 354
bb2cdfff 355 // Create data containers for the logic data snapshots
b087ba7f
JH
356 {
357 lock_guard<mutex> data_lock(_data_mutex);
358
359 _logic_data.reset();
6ac6242b 360 if (logic_channel_count != 0) {
b087ba7f 361 _logic_data.reset(new data::Logic(
6ac6242b 362 logic_channel_count));
b087ba7f
JH
363 assert(_logic_data);
364 }
b087ba7f
JH
365 }
366
367 // Make the Signals list
fbd3e234 368 {
aca64cac 369 unique_lock<shared_mutex> lock(_signals_mutex);
b087ba7f
JH
370
371 _signals.clear();
372
e8d00928 373 for (auto channel : device->channels()) {
39e680c2 374 shared_ptr<view::Signal> signal;
39e680c2 375
e8d00928 376 switch(channel->type()->id()) {
4871ed92 377 case SR_CHANNEL_LOGIC:
39e680c2 378 signal = shared_ptr<view::Signal>(
b86aa8f4
JH
379 new view::LogicSignal(*this, device,
380 channel, _logic_data));
39e680c2
JH
381 break;
382
4871ed92 383 case SR_CHANNEL_ANALOG:
bb2cdfff
JH
384 {
385 shared_ptr<data::Analog> data(
386 new data::Analog());
39e680c2 387 signal = shared_ptr<view::Signal>(
b86aa8f4
JH
388 new view::AnalogSignal(
389 *this, channel, data));
39e680c2 390 break;
bb2cdfff 391 }
39e680c2
JH
392
393 default:
394 assert(0);
395 break;
b087ba7f 396 }
39e680c2
JH
397
398 assert(signal);
399 _signals.push_back(signal);
b087ba7f 400 }
39e680c2 401
fbd3e234 402 }
b087ba7f
JH
403
404 signals_changed();
405}
406
6ac6242b 407shared_ptr<view::Signal> SigSession::signal_from_channel(
e8d00928 408 shared_ptr<Channel> channel) const
3ddcc083 409{
aca64cac 410 lock_guard<boost::shared_mutex> lock(_signals_mutex);
d9aecf1f 411 for (shared_ptr<view::Signal> sig : _signals) {
3ddcc083 412 assert(sig);
6ac6242b 413 if (sig->channel() == channel)
3ddcc083
JH
414 return sig;
415 }
416 return shared_ptr<view::Signal>();
417}
418
e8d00928 419void SigSession::read_sample_rate(shared_ptr<Device> device)
deef291c 420{
e8d00928
ML
421 uint64_t sample_rate = VariantBase::cast_dynamic<Variant<guint64>>(
422 device->config_get(ConfigKey::SAMPLERATE)).get();
deef291c 423
bb2cdfff
JH
424 // Set the sample rate of all data
425 const set< shared_ptr<data::SignalData> > data_set = get_data();
d9aecf1f 426 for (shared_ptr<data::SignalData> data : data_set) {
bb2cdfff
JH
427 assert(data);
428 data->set_samplerate(sample_rate);
429 }
deef291c
JH
430}
431
e8d00928 432void SigSession::sample_thread_proc(shared_ptr<Device> device,
f2edb557 433 function<void (const QString)> error_handler)
274d4f13 434{
e8d00928 435 assert(device);
f2edb557 436 assert(error_handler);
be73bdfa 437
e8d00928 438 read_sample_rate(device);
274d4f13 439
ae2d1bc5 440 try {
1f4caa77 441 _session->start();
e8d00928
ML
442 } catch(Error e) {
443 error_handler(e.what());
eec446e1
JH
444 return;
445 }
446
1f4caa77 447 set_capture_state(_session->trigger() ?
07dcf561 448 AwaitingTrigger : Running);
eec446e1 449
1f4caa77 450 _session->run();
eec446e1 451 set_capture_state(Stopped);
1a2fe44c
JH
452
453 // Confirm that SR_DF_END was received
bb2cdfff
JH
454 if (_cur_logic_snapshot)
455 {
456 qDebug("SR_DF_END was not received.");
457 assert(0);
458 }
eec446e1
JH
459}
460
e8d00928 461void SigSession::feed_in_header(shared_ptr<Device> device)
eec446e1 462{
e8d00928 463 read_sample_rate(device);
be73bdfa
JH
464}
465
e8d00928
ML
466void SigSession::feed_in_meta(shared_ptr<Device> device,
467 shared_ptr<Meta> meta)
be73bdfa 468{
e8d00928 469 (void)device;
94fe58ef 470
e8d00928
ML
471 for (auto entry : meta->config()) {
472 switch (entry.first->id()) {
be73bdfa
JH
473 case SR_CONF_SAMPLERATE:
474 /// @todo handle samplerate changes
be73bdfa
JH
475 break;
476 default:
477 // Unknown metadata is not an error.
478 break;
479 }
aba1dd16 480 }
74043039
JH
481
482 signals_changed();
aba1dd16
JH
483}
484
82f50b10
JH
485void SigSession::feed_in_frame_begin()
486{
487 if (_cur_logic_snapshot || !_cur_analog_snapshots.empty())
488 frame_began();
489}
490
e8d00928 491void SigSession::feed_in_logic(shared_ptr<Logic> logic)
9c112671
JH
492{
493 lock_guard<mutex> lock(_data_mutex);
79efbc53
JH
494
495 if (!_logic_data)
9c112671 496 {
79efbc53
JH
497 qDebug() << "Unexpected logic packet";
498 return;
499 }
be73bdfa 500
79efbc53
JH
501 if (!_cur_logic_snapshot)
502 {
bb2cdfff 503 // This could be the first packet after a trigger
2b49eeb0
JH
504 set_capture_state(Running);
505
e8d00928
ML
506 // Get sample limit.
507 uint64_t sample_limit;
508 try {
509 sample_limit = VariantBase::cast_dynamic<Variant<guint64>>(
510 _device->config_get(ConfigKey::LIMIT_SAMPLES)).get();
511 } catch (Error) {
512 sample_limit = 0;
513 }
514
9c112671 515 // Create a new data snapshot
1b1ec774 516 _cur_logic_snapshot = shared_ptr<data::LogicSnapshot>(
e8d00928 517 new data::LogicSnapshot(logic, sample_limit));
9c112671 518 _logic_data->push_snapshot(_cur_logic_snapshot);
82f50b10
JH
519
520 // @todo Putting this here means that only listeners querying
521 // for logic will be notified. Currently the only user of
522 // frame_began is DecoderStack, but in future we need to signal
523 // this after both analog and logic sweeps have begun.
524 frame_began();
9c112671
JH
525 }
526 else
527 {
528 // Append to the existing data snapshot
529 _cur_logic_snapshot->append_payload(logic);
530 }
531
1f374035 532 data_received();
9c112671
JH
533}
534
e8d00928 535void SigSession::feed_in_analog(shared_ptr<Analog> analog)
aba1dd16
JH
536{
537 lock_guard<mutex> lock(_data_mutex);
79efbc53 538
e8d00928
ML
539 const vector<shared_ptr<Channel>> channels = analog->channels();
540 const unsigned int channel_count = channels.size();
541 const size_t sample_count = analog->num_samples() / channel_count;
542 const float *data = analog->data_pointer();
bb2cdfff 543 bool sweep_beginning = false;
be73bdfa 544
e8d00928 545 for (auto channel : channels)
79efbc53 546 {
bb2cdfff 547 shared_ptr<data::AnalogSnapshot> snapshot;
2b49eeb0 548
6ac6242b 549 // Try to get the snapshot of the channel
e8d00928 550 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSnapshot> >::
6ac6242b 551 iterator iter = _cur_analog_snapshots.find(channel);
bb2cdfff
JH
552 if (iter != _cur_analog_snapshots.end())
553 snapshot = (*iter).second;
554 else
555 {
556 // If no snapshot was found, this means we havn't
557 // created one yet. i.e. this is the first packet
558 // in the sweep containing this snapshot.
559 sweep_beginning = true;
560
e8d00928
ML
561 // Get sample limit.
562 uint64_t sample_limit;
563 try {
564 sample_limit = VariantBase::cast_dynamic<Variant<guint64>>(
565 _device->config_get(ConfigKey::LIMIT_SAMPLES)).get();
566 } catch (Error) {
567 sample_limit = 0;
568 }
569
6ac6242b 570 // Create a snapshot, keep it in the maps of channels
bb2cdfff 571 snapshot = shared_ptr<data::AnalogSnapshot>(
e8d00928 572 new data::AnalogSnapshot(sample_limit));
6ac6242b 573 _cur_analog_snapshots[channel] = snapshot;
bb2cdfff 574
6ac6242b 575 // Find the annalog data associated with the channel
bb2cdfff
JH
576 shared_ptr<view::AnalogSignal> sig =
577 dynamic_pointer_cast<view::AnalogSignal>(
6ac6242b 578 signal_from_channel(channel));
bb2cdfff
JH
579 assert(sig);
580
581 shared_ptr<data::Analog> data(sig->analog_data());
582 assert(data);
583
584 // Push the snapshot into the analog data.
585 data->push_snapshot(snapshot);
586 }
587
588 assert(snapshot);
589
590 // Append the samples in the snapshot
591 snapshot->append_interleaved_samples(data++, sample_count,
6ac6242b 592 channel_count);
aba1dd16 593 }
bb2cdfff
JH
594
595 if (sweep_beginning) {
596 // This could be the first packet after a trigger
597 set_capture_state(Running);
aba1dd16
JH
598 }
599
1f374035 600 data_received();
aba1dd16 601}
9c112671 602
e8d00928 603void SigSession::data_feed_in(shared_ptr<Device> device, shared_ptr<Packet> packet)
b0e1d01d 604{
e8d00928 605 assert(device);
b0e1d01d
JH
606 assert(packet);
607
e8d00928 608 switch (packet->type()->id()) {
b0e1d01d 609 case SR_DF_HEADER:
e8d00928 610 feed_in_header(device);
b0e1d01d
JH
611 break;
612
be73bdfa 613 case SR_DF_META:
e8d00928 614 feed_in_meta(device, dynamic_pointer_cast<Meta>(packet->payload()));
aba1dd16
JH
615 break;
616
82f50b10
JH
617 case SR_DF_FRAME_BEGIN:
618 feed_in_frame_begin();
619 break;
620
2e2946fe 621 case SR_DF_LOGIC:
e8d00928 622 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
2953961c
JH
623 break;
624
aba1dd16 625 case SR_DF_ANALOG:
e8d00928 626 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
aba1dd16
JH
627 break;
628
2953961c 629 case SR_DF_END:
2e2946fe
JH
630 {
631 {
632 lock_guard<mutex> lock(_data_mutex);
633 _cur_logic_snapshot.reset();
bb2cdfff 634 _cur_analog_snapshots.clear();
2e2946fe 635 }
1f374035 636 frame_ended();
2953961c
JH
637 break;
638 }
adb0a983
ML
639 default:
640 break;
2e2946fe 641 }
2953961c
JH
642}
643
51e77110 644} // namespace pv