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