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