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