]> sigrok.org Git - pulseview.git/blob - pv/session.cpp
22e0428d94abf26a5421c540377dc9e55c6ddccf
[pulseview.git] / pv / session.cpp
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
53 using boost::shared_lock;
54 using boost::shared_mutex;
55 using boost::unique_lock;
56
57 using std::dynamic_pointer_cast;
58 using std::function;
59 using std::lock_guard;
60 using std::list;
61 using std::map;
62 using std::mutex;
63 using std::recursive_mutex;
64 using std::set;
65 using std::shared_ptr;
66 using std::string;
67 using std::unordered_set;
68 using std::vector;
69
70 using sigrok::Analog;
71 using sigrok::Channel;
72 using sigrok::ChannelType;
73 using sigrok::ConfigKey;
74 using sigrok::DatafeedCallbackFunction;
75 using sigrok::Error;
76 using sigrok::Header;
77 using sigrok::Logic;
78 using sigrok::Meta;
79 using sigrok::Packet;
80 using sigrok::PacketPayload;
81 using sigrok::Session;
82 using sigrok::SessionDevice;
83
84 using Glib::VariantBase;
85 using Glib::Variant;
86
87 namespace pv {
88 Session::Session(DeviceManager &device_manager) :
89         device_manager_(device_manager),
90         capture_state_(Stopped),
91         cur_samplerate_(0)
92 {
93 }
94
95 Session::~Session()
96 {
97         // Stop and join to the thread
98         stop_capture();
99 }
100
101 DeviceManager& Session::device_manager()
102 {
103         return device_manager_;
104 }
105
106 const DeviceManager& Session::device_manager() const
107 {
108         return device_manager_;
109 }
110
111 shared_ptr<sigrok::Session> Session::session() const
112 {
113         if (!device_)
114                 return shared_ptr<sigrok::Session>();
115         return device_->session();
116 }
117
118 shared_ptr<devices::Device> Session::device() const
119 {
120         return device_;
121 }
122
123 void 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
143 void 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
159 Session::capture_state Session::get_capture_state() const
160 {
161         lock_guard<mutex> lock(sampling_mutex_);
162         return capture_state_;
163 }
164
165 void 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         for (const shared_ptr<data::SignalData> d : get_data())
184                 d->clear();
185
186         // Begin the session
187         sampling_thread_ = std::thread(
188                 &Session::sample_thread_proc, this, device_,
189                         error_handler);
190 }
191
192 void Session::stop_capture()
193 {
194         if (get_capture_state() != Stopped)
195                 device_->stop();
196
197         // Check that sampling stopped
198         if (sampling_thread_.joinable())
199                 sampling_thread_.join();
200 }
201
202 set< shared_ptr<data::SignalData> > Session::get_data() const
203 {
204         shared_lock<shared_mutex> lock(signals_mutex_);
205         set< shared_ptr<data::SignalData> > data;
206         for (const shared_ptr<view::Signal> sig : signals_) {
207                 assert(sig);
208                 data.insert(sig->data());
209         }
210
211         return data;
212 }
213
214 boost::shared_mutex& Session::signals_mutex() const
215 {
216         return signals_mutex_;
217 }
218
219 const unordered_set< shared_ptr<view::Signal> >& Session::signals() const
220 {
221         return signals_;
222 }
223
224 #ifdef ENABLE_DECODE
225 bool Session::add_decoder(srd_decoder *const dec)
226 {
227         map<const srd_channel*, shared_ptr<view::LogicSignal> > channels;
228         shared_ptr<data::DecoderStack> decoder_stack;
229
230         try
231         {
232                 lock_guard<boost::shared_mutex> lock(signals_mutex_);
233
234                 // Create the decoder
235                 decoder_stack = shared_ptr<data::DecoderStack>(
236                         new data::DecoderStack(*this, dec));
237
238                 // Make a list of all the channels
239                 std::vector<const srd_channel*> all_channels;
240                 for (const GSList *i = dec->channels; i; i = i->next)
241                         all_channels.push_back((const srd_channel*)i->data);
242                 for (const GSList *i = dec->opt_channels; i; i = i->next)
243                         all_channels.push_back((const srd_channel*)i->data);
244
245                 // Auto select the initial channels
246                 for (const srd_channel *pdch : all_channels)
247                         for (shared_ptr<view::Signal> s : signals_)
248                         {
249                                 shared_ptr<view::LogicSignal> l =
250                                         dynamic_pointer_cast<view::LogicSignal>(s);
251                                 if (l && QString::fromUtf8(pdch->name).
252                                         toLower().contains(
253                                         l->name().toLower()))
254                                         channels[pdch] = l;
255                         }
256
257                 assert(decoder_stack);
258                 assert(!decoder_stack->stack().empty());
259                 assert(decoder_stack->stack().front());
260                 decoder_stack->stack().front()->set_channels(channels);
261
262                 // Create the decode signal
263                 shared_ptr<view::DecodeTrace> d(
264                         new view::DecodeTrace(*this, decoder_stack,
265                                 decode_traces_.size()));
266                 decode_traces_.push_back(d);
267         }
268         catch(std::runtime_error e)
269         {
270                 return false;
271         }
272
273         signals_changed();
274
275         // Do an initial decode
276         decoder_stack->begin_decode();
277
278         return true;
279 }
280
281 vector< shared_ptr<view::DecodeTrace> > Session::get_decode_signals() const
282 {
283         shared_lock<shared_mutex> lock(signals_mutex_);
284         return decode_traces_;
285 }
286
287 void Session::remove_decode_signal(view::DecodeTrace *signal)
288 {
289         for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
290                 if ((*i).get() == signal)
291                 {
292                         decode_traces_.erase(i);
293                         signals_changed();
294                         return;
295                 }
296 }
297 #endif
298
299 void Session::set_capture_state(capture_state state)
300 {
301         lock_guard<mutex> lock(sampling_mutex_);
302         const bool changed = capture_state_ != state;
303         capture_state_ = state;
304         if (changed)
305                 capture_state_changed(state);
306 }
307
308 void Session::update_signals()
309 {
310         assert(device_);
311
312         lock_guard<recursive_mutex> lock(data_mutex_);
313
314         const shared_ptr<sigrok::Device> sr_dev = device_->device();
315         if (!sr_dev) {
316                 signals_.clear();
317                 logic_data_.reset();
318                 return;
319         }
320
321         // Detect what data types we will receive
322         auto channels = sr_dev->channels();
323         unsigned int logic_channel_count = std::count_if(
324                 channels.begin(), channels.end(),
325                 [] (shared_ptr<Channel> channel) {
326                         return channel->type() == ChannelType::LOGIC; });
327
328         // Create data containers for the logic data segments
329         {
330                 lock_guard<recursive_mutex> data_lock(data_mutex_);
331
332                 if (logic_channel_count == 0) {
333                         logic_data_.reset();
334                 } else if (!logic_data_ ||
335                         logic_data_->num_channels() != logic_channel_count) {
336                         logic_data_.reset(new data::Logic(
337                                 logic_channel_count));
338                         assert(logic_data_);
339                 }
340         }
341
342         // Make the Signals list
343         {
344                 unique_lock<shared_mutex> lock(signals_mutex_);
345
346                 unordered_set< shared_ptr<view::Signal> > prev_sigs(signals_);
347                 signals_.clear();
348
349                 for (auto channel : sr_dev->channels()) {
350                         shared_ptr<view::Signal> signal;
351
352                         // Find the channel in the old signals
353                         const auto iter = std::find_if(
354                                 prev_sigs.cbegin(), prev_sigs.cend(),
355                                 [&](const shared_ptr<view::Signal> &s) {
356                                         return s->channel() == channel;
357                                 });
358                         if (iter != prev_sigs.end()) {
359                                 // Copy the signal from the old set to the new
360                                 signal = *iter;
361                                 auto logic_signal = dynamic_pointer_cast<
362                                         view::LogicSignal>(signal);
363                                 if (logic_signal)
364                                         logic_signal->set_logic_data(
365                                                 logic_data_);
366                         } else {
367                                 // Create a new signal
368                                 switch(channel->type()->id()) {
369                                 case SR_CHANNEL_LOGIC:
370                                         signal = shared_ptr<view::Signal>(
371                                                 new view::LogicSignal(*this,
372                                                         device_, channel,
373                                                         logic_data_));
374                                         break;
375
376                                 case SR_CHANNEL_ANALOG:
377                                 {
378                                         shared_ptr<data::Analog> data(
379                                                 new data::Analog());
380                                         signal = shared_ptr<view::Signal>(
381                                                 new view::AnalogSignal(
382                                                         *this, channel, data));
383                                         break;
384                                 }
385
386                                 default:
387                                         assert(0);
388                                         break;
389                                 }
390                         }
391
392                         assert(signal);
393                         signals_.insert(signal);
394                 }
395         }
396
397         signals_changed();
398 }
399
400 shared_ptr<view::Signal> Session::signal_from_channel(
401         shared_ptr<Channel> channel) const
402 {
403         lock_guard<boost::shared_mutex> lock(signals_mutex_);
404         for (shared_ptr<view::Signal> sig : signals_) {
405                 assert(sig);
406                 if (sig->channel() == channel)
407                         return sig;
408         }
409         return shared_ptr<view::Signal>();
410 }
411
412 void Session::sample_thread_proc(shared_ptr<devices::Device> device,
413         function<void (const QString)> error_handler)
414 {
415         assert(device);
416         assert(error_handler);
417
418         (void)device;
419
420         cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
421
422         out_of_memory_ = false;
423
424         try {
425                 device_->start();
426         } catch(Error e) {
427                 error_handler(e.what());
428                 return;
429         }
430
431         set_capture_state(device_->session()->trigger() ?
432                 AwaitingTrigger : Running);
433
434         device_->run();
435         set_capture_state(Stopped);
436
437         // Confirm that SR_DF_END was received
438         if (cur_logic_segment_)
439         {
440                 qDebug("SR_DF_END was not received.");
441                 assert(0);
442         }
443
444         if (out_of_memory_)
445                 error_handler(tr("Out of memory, acquisition stopped."));
446 }
447
448 void Session::feed_in_header()
449 {
450         cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
451 }
452
453 void Session::feed_in_meta(shared_ptr<Meta> meta)
454 {
455         for (auto entry : meta->config()) {
456                 switch (entry.first->id()) {
457                 case SR_CONF_SAMPLERATE:
458                         /// @todo handle samplerate changes
459                         break;
460                 default:
461                         // Unknown metadata is not an error.
462                         break;
463                 }
464         }
465
466         signals_changed();
467 }
468
469 void Session::feed_in_frame_begin()
470 {
471         if (cur_logic_segment_ || !cur_analog_segments_.empty())
472                 frame_began();
473 }
474
475 void Session::feed_in_logic(shared_ptr<Logic> logic)
476 {
477         lock_guard<recursive_mutex> lock(data_mutex_);
478
479         const size_t sample_count = logic->data_length() / logic->unit_size();
480
481         if (!logic_data_)
482         {
483                 // The only reason logic_data_ would not have been created is
484                 // if it was not possible to determine the signals when the
485                 // device was created.
486                 update_signals();
487         }
488
489         if (!cur_logic_segment_)
490         {
491                 // This could be the first packet after a trigger
492                 set_capture_state(Running);
493
494                 // Create a new data segment
495                 cur_logic_segment_ = shared_ptr<data::LogicSegment>(
496                         new data::LogicSegment(
497                                 logic, cur_samplerate_, sample_count));
498                 logic_data_->push_segment(cur_logic_segment_);
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 segment
509                 cur_logic_segment_->append_payload(logic);
510         }
511
512         data_received();
513 }
514
515 void Session::feed_in_analog(shared_ptr<Analog> analog)
516 {
517         lock_guard<recursive_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::AnalogSegment> segment;
528
529                 // Try to get the segment of the channel
530                 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
531                         iterator iter = cur_analog_segments_.find(channel);
532                 if (iter != cur_analog_segments_.end())
533                         segment = (*iter).second;
534                 else
535                 {
536                         // If no segment was found, this means we havn't
537                         // created one yet. i.e. this is the first packet
538                         // in the sweep containing this segment.
539                         sweep_beginning = true;
540
541                         // Create a segment, keep it in the maps of channels
542                         segment = shared_ptr<data::AnalogSegment>(
543                                 new data::AnalogSegment(
544                                         cur_samplerate_, sample_count));
545                         cur_analog_segments_[channel] = segment;
546
547                         // Find the analog data associated with the channel
548                         shared_ptr<view::AnalogSignal> sig =
549                                 dynamic_pointer_cast<view::AnalogSignal>(
550                                         signal_from_channel(channel));
551                         assert(sig);
552
553                         shared_ptr<data::Analog> data(sig->analog_data());
554                         assert(data);
555
556                         // Push the segment into the analog data.
557                         data->push_segment(segment);
558                 }
559
560                 assert(segment);
561
562                 // Append the samples in the segment
563                 segment->append_interleaved_samples(data++, sample_count,
564                         channel_count);
565         }
566
567         if (sweep_beginning) {
568                 // This could be the first packet after a trigger
569                 set_capture_state(Running);
570         }
571
572         data_received();
573 }
574
575 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
576         shared_ptr<Packet> packet)
577 {
578         (void)device;
579
580         assert(device);
581         assert(device == device_->device());
582         assert(packet);
583
584         switch (packet->type()->id()) {
585         case SR_DF_HEADER:
586                 feed_in_header();
587                 break;
588
589         case SR_DF_META:
590                 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
591                 break;
592
593         case SR_DF_FRAME_BEGIN:
594                 feed_in_frame_begin();
595                 break;
596
597         case SR_DF_LOGIC:
598                 try {
599                         feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
600                 } catch (std::bad_alloc) {
601                         out_of_memory_ = true;
602                         device_->stop();
603                 }
604                 break;
605
606         case SR_DF_ANALOG:
607                 try {
608                         feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
609                 } catch (std::bad_alloc) {
610                         out_of_memory_ = true;
611                         device_->stop();
612                 }
613                 break;
614
615         case SR_DF_END:
616         {
617                 {
618                         lock_guard<recursive_mutex> lock(data_mutex_);
619                         cur_logic_segment_.reset();
620                         cur_analog_segments_.clear();
621                 }
622                 frame_ended();
623                 break;
624         }
625         default:
626                 break;
627         }
628 }
629
630 } // namespace pv