]> sigrok.org Git - pulseview.git/blame_incremental - pv/session.cpp
Append "-git" to the version string.
[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 // Begin the session
183 sampling_thread_ = std::thread(
184 &Session::sample_thread_proc, this, device_,
185 error_handler);
186}
187
188void Session::stop_capture()
189{
190 if (get_capture_state() != Stopped)
191 device_->stop();
192
193 // Check that sampling stopped
194 if (sampling_thread_.joinable())
195 sampling_thread_.join();
196}
197
198set< shared_ptr<data::SignalData> > Session::get_data() const
199{
200 shared_lock<shared_mutex> lock(signals_mutex_);
201 set< shared_ptr<data::SignalData> > data;
202 for (const shared_ptr<view::Signal> sig : signals_) {
203 assert(sig);
204 data.insert(sig->data());
205 }
206
207 return data;
208}
209
210boost::shared_mutex& Session::signals_mutex() const
211{
212 return signals_mutex_;
213}
214
215const unordered_set< shared_ptr<view::Signal> >& Session::signals() const
216{
217 return signals_;
218}
219
220#ifdef ENABLE_DECODE
221bool Session::add_decoder(srd_decoder *const dec)
222{
223 map<const srd_channel*, shared_ptr<view::LogicSignal> > channels;
224 shared_ptr<data::DecoderStack> decoder_stack;
225
226 try
227 {
228 lock_guard<boost::shared_mutex> lock(signals_mutex_);
229
230 // Create the decoder
231 decoder_stack = shared_ptr<data::DecoderStack>(
232 new data::DecoderStack(*this, dec));
233
234 // Make a list of all the channels
235 std::vector<const srd_channel*> all_channels;
236 for(const GSList *i = dec->channels; i; i = i->next)
237 all_channels.push_back((const srd_channel*)i->data);
238 for(const GSList *i = dec->opt_channels; i; i = i->next)
239 all_channels.push_back((const srd_channel*)i->data);
240
241 // Auto select the initial channels
242 for (const srd_channel *pdch : all_channels)
243 for (shared_ptr<view::Signal> s : signals_)
244 {
245 shared_ptr<view::LogicSignal> l =
246 dynamic_pointer_cast<view::LogicSignal>(s);
247 if (l && QString::fromUtf8(pdch->name).
248 toLower().contains(
249 l->name().toLower()))
250 channels[pdch] = l;
251 }
252
253 assert(decoder_stack);
254 assert(!decoder_stack->stack().empty());
255 assert(decoder_stack->stack().front());
256 decoder_stack->stack().front()->set_channels(channels);
257
258 // Create the decode signal
259 shared_ptr<view::DecodeTrace> d(
260 new view::DecodeTrace(*this, decoder_stack,
261 decode_traces_.size()));
262 decode_traces_.push_back(d);
263 }
264 catch(std::runtime_error e)
265 {
266 return false;
267 }
268
269 signals_changed();
270
271 // Do an initial decode
272 decoder_stack->begin_decode();
273
274 return true;
275}
276
277vector< shared_ptr<view::DecodeTrace> > Session::get_decode_signals() const
278{
279 shared_lock<shared_mutex> lock(signals_mutex_);
280 return decode_traces_;
281}
282
283void Session::remove_decode_signal(view::DecodeTrace *signal)
284{
285 for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
286 if ((*i).get() == signal)
287 {
288 decode_traces_.erase(i);
289 signals_changed();
290 return;
291 }
292}
293#endif
294
295void Session::set_capture_state(capture_state state)
296{
297 lock_guard<mutex> lock(sampling_mutex_);
298 const bool changed = capture_state_ != state;
299 capture_state_ = state;
300 if(changed)
301 capture_state_changed(state);
302}
303
304void Session::update_signals()
305{
306 assert(device_);
307
308 lock_guard<recursive_mutex> lock(data_mutex_);
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 (void)device;
415
416 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
417
418 try {
419 device_->start();
420 } catch(Error e) {
421 error_handler(e.what());
422 return;
423 }
424
425 set_capture_state(device_->session()->trigger() ?
426 AwaitingTrigger : Running);
427
428 device_->run();
429 set_capture_state(Stopped);
430
431 // Confirm that SR_DF_END was received
432 if (cur_logic_segment_)
433 {
434 qDebug("SR_DF_END was not received.");
435 assert(0);
436 }
437}
438
439void Session::feed_in_header()
440{
441 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
442}
443
444void Session::feed_in_meta(shared_ptr<Meta> meta)
445{
446 for (auto entry : meta->config()) {
447 switch (entry.first->id()) {
448 case SR_CONF_SAMPLERATE:
449 /// @todo handle samplerate changes
450 break;
451 default:
452 // Unknown metadata is not an error.
453 break;
454 }
455 }
456
457 signals_changed();
458}
459
460void Session::feed_in_frame_begin()
461{
462 if (cur_logic_segment_ || !cur_analog_segments_.empty())
463 frame_began();
464}
465
466void Session::feed_in_logic(shared_ptr<Logic> logic)
467{
468 lock_guard<recursive_mutex> lock(data_mutex_);
469
470 if (!logic_data_)
471 {
472 // The only reason logic_data_ would not have been created is
473 // if it was not possible to determine the signals when the
474 // device was created.
475 update_signals();
476 }
477
478 if (!cur_logic_segment_)
479 {
480 // This could be the first packet after a trigger
481 set_capture_state(Running);
482
483 // Get sample limit.
484 const uint64_t sample_limit = device_->read_config<uint64_t>(
485 ConfigKey::LIMIT_SAMPLES);
486
487 // Create a new data segment
488 cur_logic_segment_ = shared_ptr<data::LogicSegment>(
489 new data::LogicSegment(
490 logic, cur_samplerate_, sample_limit));
491 logic_data_->push_segment(cur_logic_segment_);
492
493 // @todo Putting this here means that only listeners querying
494 // for logic will be notified. Currently the only user of
495 // frame_began is DecoderStack, but in future we need to signal
496 // this after both analog and logic sweeps have begun.
497 frame_began();
498 }
499 else
500 {
501 // Append to the existing data segment
502 cur_logic_segment_->append_payload(logic);
503 }
504
505 data_received();
506}
507
508void Session::feed_in_analog(shared_ptr<Analog> analog)
509{
510 lock_guard<recursive_mutex> lock(data_mutex_);
511
512 const vector<shared_ptr<Channel>> channels = analog->channels();
513 const unsigned int channel_count = channels.size();
514 const size_t sample_count = analog->num_samples() / channel_count;
515 const float *data = analog->data_pointer();
516 bool sweep_beginning = false;
517
518 for (auto channel : channels)
519 {
520 shared_ptr<data::AnalogSegment> segment;
521
522 // Try to get the segment of the channel
523 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
524 iterator iter = cur_analog_segments_.find(channel);
525 if (iter != cur_analog_segments_.end())
526 segment = (*iter).second;
527 else
528 {
529 // If no segment was found, this means we havn't
530 // created one yet. i.e. this is the first packet
531 // in the sweep containing this segment.
532 sweep_beginning = true;
533
534 // Get sample limit.
535 uint64_t sample_limit;
536 try {
537 assert(device_);
538 const std::shared_ptr<sigrok::Device> device =
539 device_->device();
540 assert(device);
541 sample_limit = VariantBase::cast_dynamic<Variant<guint64>>(
542 device->config_get(ConfigKey::LIMIT_SAMPLES)).get();
543 } catch (Error) {
544 sample_limit = 0;
545 }
546
547 // Create a segment, keep it in the maps of channels
548 segment = shared_ptr<data::AnalogSegment>(
549 new data::AnalogSegment(
550 cur_samplerate_, sample_limit));
551 cur_analog_segments_[channel] = segment;
552
553 // Find the annalog data associated with the channel
554 shared_ptr<view::AnalogSignal> sig =
555 dynamic_pointer_cast<view::AnalogSignal>(
556 signal_from_channel(channel));
557 assert(sig);
558
559 shared_ptr<data::Analog> data(sig->analog_data());
560 assert(data);
561
562 // Push the segment into the analog data.
563 data->push_segment(segment);
564 }
565
566 assert(segment);
567
568 // Append the samples in the segment
569 segment->append_interleaved_samples(data++, sample_count,
570 channel_count);
571 }
572
573 if (sweep_beginning) {
574 // This could be the first packet after a trigger
575 set_capture_state(Running);
576 }
577
578 data_received();
579}
580
581void Session::data_feed_in(shared_ptr<sigrok::Device> device,
582 shared_ptr<Packet> packet)
583{
584 (void)device;
585
586 assert(device);
587 assert(device == device_->device());
588 assert(packet);
589
590 switch (packet->type()->id()) {
591 case SR_DF_HEADER:
592 feed_in_header();
593 break;
594
595 case SR_DF_META:
596 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
597 break;
598
599 case SR_DF_FRAME_BEGIN:
600 feed_in_frame_begin();
601 break;
602
603 case SR_DF_LOGIC:
604 feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
605 break;
606
607 case SR_DF_ANALOG:
608 feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
609 break;
610
611 case SR_DF_END:
612 {
613 {
614 lock_guard<recursive_mutex> lock(data_mutex_);
615 cur_logic_segment_.reset();
616 cur_analog_segments_.clear();
617 }
618 frame_ended();
619 break;
620 }
621 default:
622 break;
623 }
624}
625
626} // namespace pv