]> sigrok.org Git - libsigrok.git/blame - bindings/cxx/include/libsigrok/libsigrok.hpp
C++: Centralise code for preparing shared pointers.
[libsigrok.git] / bindings / cxx / include / libsigrok / libsigrok.hpp
CommitLineData
c23c8659
ML
1/*
2 * This file is part of the libsigrok project.
3 *
4 * Copyright (C) 2013-2014 Martin Ling <martin-sigrok@earth.li>
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 3 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, see <http://www.gnu.org/licenses/>.
18 */
19
07443fd2
ML
20/**
21
22@mainpage API Reference
23
24Introduction
25------------
26
27The sigrok++ API provides an object-oriented C++ interface to the functionality
28in libsigrok, including automatic memory and resource management.
29
30It is built on top of the public libsigrok C API, and is designed to be used as
31a standalone alternative API. Programs should not mix usage of the C and C++
32APIs; the C++ interface code needs to have full control of all C API calls for
33resources to be managed correctly.
34
35Memory management
36-----------------
37
38All runtime objects created through the C++ API are passed and accessed via
39shared pointers, using the C++11 std::shared_ptr implementation. This means
40that a reference count is kept for each object.
41
42Shared pointers can be copied and assigned in a user's program, automatically
43updating their reference count and deleting objects when they are no longer in
44use. The C++ interface code also keeps track of internal dependencies between
45libsigrok resources, and ensures that objects are not prematurely deleted when
46their resources are in use by other objects.
47
48This means that management of sigrok++ objects and their underlying libsigrok
49resources can be treated as fully automatic. As long as all shared pointers to
50objects are deleted or reassigned when no longer in use, all underlying
51resources will be released at the right time.
52
53Getting started
54---------------
55
56Usage of the C++ API needs to begin with a call to sigrok::Context::create().
57This will create the global libsigrok context and returns a shared pointer to
58the sigrok::Context object. Methods on this object provide access to the
59hardware drivers, input and output formats supported by the library, as well
60as means of creating other objects such as sessions and triggers.
61
62Error handling
63--------------
64
65When any libsigrok C API call returns an error, a sigrok::Error exception is
66raised, which provides access to the error code and description.
67
68*/
69
c23c8659
ML
70#ifndef LIBSIGROK_HPP
71#define LIBSIGROK_HPP
72
73#include "libsigrok/libsigrok.h"
74#include <glibmm-2.4/glibmm.h>
75
76#include <stdexcept>
77#include <memory>
78#include <vector>
79#include <map>
80
81namespace sigrok
82{
83
84using namespace std;
85
86/* Forward declarations */
87class SR_API Error;
88class SR_API Context;
89class SR_API Driver;
90class SR_API Device;
91class SR_API HardwareDevice;
92class SR_API Channel;
93class SR_API EventSource;
94class SR_API Session;
95class SR_API ConfigKey;
96class SR_API InputFormat;
97class SR_API OutputFormat;
98class SR_API LogLevel;
99class SR_API ChannelGroup;
100class SR_API Trigger;
101class SR_API TriggerStage;
102class SR_API TriggerMatch;
103class SR_API TriggerMatchType;
104class SR_API ChannelType;
105class SR_API Packet;
106class SR_API PacketPayload;
107class SR_API PacketType;
108class SR_API Quantity;
109class SR_API Unit;
110class SR_API QuantityFlag;
111class SR_API InputFileDevice;
112class SR_API Output;
113class SR_API DataType;
114
115/** Exception thrown when an error code is returned by any libsigrok call. */
116class SR_API Error: public exception
117{
118public:
119 Error(int result);
120 ~Error() throw();
121 const int result;
122 const char *what() const throw();
123};
124
07443fd2 125/* Base template for most classes which wrap a struct type from libsigrok. */
c23c8659
ML
126template <class Parent, typename Struct> class SR_API StructureWrapper :
127 public enable_shared_from_this<StructureWrapper<Parent, Struct> >
128{
7649683c 129protected:
07443fd2 130 /* Parent object which owns this child object's underlying structure.
c23c8659
ML
131
132 This shared pointer will be null when this child is unused, but
133 will be assigned to point to the parent before any shared pointer
134 to this child is handed out to the user.
135
136 When the reference count of this child falls to zero, this shared
137 pointer to its parent is reset by a custom deleter on the child's
138 shared pointer.
139
140 This strategy ensures that the destructors for both the child and
141 the parent are called at the correct time, i.e. only when all
142 references to both the parent and all its children are gone. */
143 shared_ptr<Parent> parent;
7649683c
ML
144
145public:
146 shared_ptr<StructureWrapper<Parent, Struct> >
147 get_shared_pointer(Parent *parent)
148 {
149 this->parent = static_pointer_cast<Parent>(parent->shared_from_this());
150 return shared_ptr<StructureWrapper<Parent, Struct> >(
151 this, reset_parent);
152 }
153 shared_ptr<StructureWrapper<Parent, Struct> >
154 get_shared_pointer(shared_ptr<Parent> parent)
155 {
156 this->parent = parent;
157 return shared_ptr<StructureWrapper<Parent, Struct> >(
158 this, reset_parent);
159 }
c23c8659 160protected:
7649683c
ML
161 static void reset_parent(StructureWrapper<Parent, Struct> *object)
162 {
163 object->parent.reset();
164 }
165
c23c8659
ML
166 Struct *structure;
167
168 StructureWrapper<Parent, Struct>(Struct *structure) :
169 structure(structure)
170 {
171 }
172};
173
174/** Type of log callback */
175typedef function<void(const LogLevel *, string message)> LogCallbackFunction;
176
07443fd2 177/** The global libsigrok context */
c23c8659
ML
178class SR_API Context : public enable_shared_from_this<Context>
179{
180public:
181 /** Create new context */
182 static shared_ptr<Context> create();
183 /** libsigrok package version. */
184 string get_package_version();
185 /** libsigrok library version. */
186 string get_lib_version();
187 /** Available hardware drivers, indexed by name. */
188 map<string, shared_ptr<Driver> > get_drivers();
189 /** Available input formats, indexed by name. */
190 map<string, shared_ptr<InputFormat> > get_input_formats();
191 /** Available output formats, indexed by name. */
192 map<string, shared_ptr<OutputFormat> > get_output_formats();
193 /** Current log level. */
194 const LogLevel *get_log_level();
195 /** Set the log level. */
196 void set_log_level(const LogLevel *level);
197 /** Current log domain. */
198 string get_log_domain();
199 /** Set the log domain. */
200 void set_log_domain(string value);
201 /** Set the log callback. */
202 void set_log_callback(LogCallbackFunction callback);
203 /** Set the log callback to the default handler. */
204 void set_log_callback_default();
205 /** Create a new session. */
206 shared_ptr<Session> create_session();
207 /** Load a saved session. */
208 shared_ptr<Session> load_session(string filename);
209 /** Create a new trigger. */
210 shared_ptr<Trigger> create_trigger(string name);
211protected:
212 struct sr_context *structure;
213 map<string, Driver *> drivers;
214 map<string, InputFormat *> input_formats;
215 map<string, OutputFormat *> output_formats;
216 Session *session;
217 LogCallbackFunction log_callback;
218 Context();
219 ~Context();
220 /** Deleter needed to allow shared_ptr use with protected destructor. */
221 class Deleter
222 {
223 public:
224 void operator()(Context *context) { delete context; }
225 };
226 friend class Deleter;
227 friend class Session;
228 friend class Driver;
229};
230
07443fd2 231/** A hardware driver provided by the library */
c23c8659
ML
232class SR_API Driver : public StructureWrapper<Context, struct sr_dev_driver>
233{
234public:
235 /** Name of this driver. */
236 string get_name();
237 /** Long name for this driver. */
238 string get_long_name();
239 /** Scan for devices and return a list of devices found. */
240 vector<shared_ptr<HardwareDevice> > scan(
241 map<const ConfigKey *, Glib::VariantBase> options = {});
242protected:
243 bool initialized;
244 vector<HardwareDevice *> devices;
245 Driver(struct sr_dev_driver *structure);
246 ~Driver();
247 friend class Context;
248 friend class HardwareDevice;
249 friend class ChannelGroup;
250};
251
252/** An object that can be configured. */
253class SR_API Configurable
254{
255public:
256 /** Read configuration for the given key. */
257 Glib::VariantBase config_get(const ConfigKey *key);
258 /** Set configuration for the given key to a specified value. */
259 void config_set(const ConfigKey *key, Glib::VariantBase value);
260 /** Enumerate available values for the given configuration key. */
261 Glib::VariantBase config_list(const ConfigKey *key);
262protected:
263 Configurable(
264 struct sr_dev_driver *driver,
265 struct sr_dev_inst *sdi,
266 struct sr_channel_group *channel_group);
267 virtual ~Configurable();
268 struct sr_dev_driver *config_driver;
269 struct sr_dev_inst *config_sdi;
270 struct sr_channel_group *config_channel_group;
271};
272
07443fd2 273/** A generic device, either hardware or virtual */
c23c8659
ML
274class SR_API Device :
275 public Configurable,
276 public StructureWrapper<Context, struct sr_dev_inst>
277{
278public:
279 /** Vendor name for this device. */
280 string get_vendor();
281 /** Model name for this device. */
282 string get_model();
283 /** Version string for this device. */
284 string get_version();
285 /** List of the channels available on this device. */
286 vector<shared_ptr<Channel> > get_channels();
287 /** Open device. */
288 void open();
289 /** Close device. */
290 void close();
291protected:
292 Device(struct sr_dev_inst *structure);
293 ~Device();
294 vector<Channel *> channels;
295 /** Deleter needed to allow shared_ptr use with protected destructor. */
296 class Deleter
297 {
298 public:
299 void operator()(Device *device) { delete device; }
300 };
301 friend class Deleter;
302 friend class Session;
303 friend class Channel;
304 friend class ChannelGroup;
305 friend class Output;
306};
307
07443fd2 308/** A real hardware device, connected via a driver */
c23c8659
ML
309class SR_API HardwareDevice : public Device
310{
311public:
312 /** Driver providing this device. */
313 shared_ptr<Driver> get_driver();
314 /** Channel groups available on this device, indexed by name. */
315 map<string, shared_ptr<ChannelGroup> > get_channel_groups();
316protected:
317 HardwareDevice(Driver *driver, struct sr_dev_inst *structure);
318 ~HardwareDevice();
319 Driver *driver;
320 map<string, ChannelGroup *> channel_groups;
321 friend class Driver;
322 friend class ChannelGroup;
323};
324
07443fd2 325/** A channel on a device */
c23c8659
ML
326class SR_API Channel : public StructureWrapper<Device, struct sr_channel>
327{
328public:
329 /** Current name of this channel. */
330 string get_name();
331 /** Set the name of this channel. */
332 void set_name(string name);
333 /** Type of this channel. */
334 const ChannelType *get_type();
335 /** Enabled status of this channel. */
336 bool get_enabled();
337 /** Set the enabled status of this channel. */
338 void set_enabled(bool value);
339protected:
340 Channel(struct sr_channel *structure);
341 ~Channel();
342 const ChannelType * const type;
343 friend class Device;
344 friend class ChannelGroup;
345 friend class Session;
346 friend class TriggerStage;
347};
348
07443fd2 349/** A group of channels on a device, which share some configuration */
c23c8659
ML
350class SR_API ChannelGroup :
351 public StructureWrapper<HardwareDevice, struct sr_channel_group>,
352 public Configurable
353{
354public:
355 /** Name of this channel group. */
356 string get_name();
357 /** List of the channels in this group. */
358 vector<shared_ptr<Channel> > get_channels();
359protected:
360 ChannelGroup(HardwareDevice *device, struct sr_channel_group *structure);
361 ~ChannelGroup();
362 vector<Channel *> channels;
363 friend class HardwareDevice;
364};
365
07443fd2 366/** A trigger configuration */
c23c8659
ML
367class SR_API Trigger : public enable_shared_from_this<Trigger>
368{
369public:
370 string get_name();
371 vector<shared_ptr<TriggerStage> > get_stages();
372 shared_ptr<TriggerStage> add_stage();
373protected:
374 Trigger(shared_ptr<Context> context, string name);
375 ~Trigger();
376 struct sr_trigger *structure;
377 shared_ptr<Context> context;
378 vector<TriggerStage *> stages;
379 /** Deleter needed to allow shared_ptr use with protected destructor. */
380 class Deleter
381 {
382 public:
383 void operator()(Trigger *trigger) { delete trigger; }
384 };
385 friend class Context;
6fa0eb86 386 friend class Session;
c23c8659
ML
387};
388
07443fd2 389/** A stage in a trigger configuration */
c23c8659
ML
390class SR_API TriggerStage : public StructureWrapper<Trigger, struct sr_trigger_stage>
391{
392public:
393 int get_number();
394 vector<shared_ptr<TriggerMatch> > get_matches();
395 void add_match(shared_ptr<Channel> channel, const TriggerMatchType *type);
396 void add_match(shared_ptr<Channel> channel, const TriggerMatchType *type, float value);
397protected:
398 vector<TriggerMatch *> matches;
399 TriggerStage(struct sr_trigger_stage *structure);
400 ~TriggerStage();
401 friend class Trigger;
402};
403
07443fd2 404/** A match condition in a trigger configuration */
c23c8659
ML
405class SR_API TriggerMatch : public StructureWrapper<TriggerStage, struct sr_trigger_match>
406{
407public:
408 shared_ptr<Channel> get_channel();
409 const TriggerMatchType *get_type();
410 float get_value();
411protected:
412 TriggerMatch(struct sr_trigger_match *structure, shared_ptr<Channel> channel);
413 ~TriggerMatch();
414 shared_ptr<Channel> channel;
415 friend class TriggerStage;
416};
417
418/** Type of datafeed callback */
419typedef function<void(shared_ptr<Device>, shared_ptr<Packet>)>
420 DatafeedCallbackFunction;
421
07443fd2 422/* Data required for C callback function to call a C++ datafeed callback */
c23c8659
ML
423class SR_PRIV DatafeedCallbackData
424{
425public:
426 void run(const struct sr_dev_inst *sdi,
427 const struct sr_datafeed_packet *pkt);
428protected:
429 DatafeedCallbackFunction callback;
430 DatafeedCallbackData(Session *session,
431 DatafeedCallbackFunction callback);
432 Session *session;
433 friend class Session;
434};
435
436/** Type of source callback */
437typedef function<bool(Glib::IOCondition)>
438 SourceCallbackFunction;
439
07443fd2 440/* Data required for C callback function to call a C++ source callback */
c23c8659
ML
441class SR_PRIV SourceCallbackData
442{
443public:
444 bool run(int revents);
445protected:
446 SourceCallbackData(shared_ptr<EventSource> source);
447 shared_ptr<EventSource> source;
448 friend class Session;
449};
450
07443fd2 451/** An I/O event source */
c23c8659
ML
452class SR_API EventSource
453{
454public:
455 /** Create an event source from a file descriptor. */
456 static shared_ptr<EventSource> create(int fd, Glib::IOCondition events,
457 int timeout, SourceCallbackFunction callback);
458 /** Create an event source from a Glib::PollFD */
459 static shared_ptr<EventSource> create(Glib::PollFD pollfd, int timeout,
460 SourceCallbackFunction callback);
461 /** Create an event source from a Glib::IOChannel */
462 static shared_ptr<EventSource> create(
463 Glib::RefPtr<Glib::IOChannel> channel, Glib::IOCondition events,
464 int timeout, SourceCallbackFunction callback);
465protected:
466 EventSource(int timeout, SourceCallbackFunction callback);
467 ~EventSource();
468 enum source_type {
469 SOURCE_FD,
470 SOURCE_POLLFD,
471 SOURCE_IOCHANNEL
472 } type;
473 int fd;
474 Glib::PollFD pollfd;
475 Glib::RefPtr<Glib::IOChannel> channel;
476 Glib::IOCondition events;
477 int timeout;
478 SourceCallbackFunction callback;
479 /** Deleter needed to allow shared_ptr use with protected destructor. */
480 class Deleter
481 {
482 public:
483 void operator()(EventSource *source) { delete source; }
484 };
485 friend class Deleter;
486 friend class Session;
487 friend class SourceCallbackData;
488};
489
07443fd2 490/** A sigrok session */
c23c8659
ML
491class SR_API Session
492{
493public:
494 /** Add a device to this session. */
495 void add_device(shared_ptr<Device> device);
496 /** List devices attached to this session. */
497 vector<shared_ptr<Device> > get_devices();
498 /** Remove all devices from this session. */
499 void remove_devices();
500 /** Add a datafeed callback to this session. */
501 void add_datafeed_callback(DatafeedCallbackFunction callback);
502 /** Remove all datafeed callbacks from this session. */
503 void remove_datafeed_callbacks();
504 /** Add an event source. */
505 void add_source(shared_ptr<EventSource> source);
506 /** Remove an event source. */
507 void remove_source(shared_ptr<EventSource> source);
508 /** Start the session. */
509 void start();
510 /** Run the session event loop. */
511 void run();
512 /** Stop the session. */
513 void stop();
514 /** Begin saving session to a file. */
515 void begin_save(string filename);
516 /** Append a packet to the session file being saved. */
517 void append(shared_ptr<Device> device, shared_ptr<Packet> packet);
6fa0eb86
ML
518 /** Get current trigger setting. */
519 shared_ptr<Trigger> get_trigger();
520 /** Set trigger setting. */
521 void set_trigger(shared_ptr<Trigger> trigger);
c23c8659
ML
522protected:
523 Session(shared_ptr<Context> context);
524 Session(shared_ptr<Context> context, string filename);
525 ~Session();
526 struct sr_session *structure;
527 const shared_ptr<Context> context;
528 map<const struct sr_dev_inst *, shared_ptr<Device> > devices;
529 vector<DatafeedCallbackData *> datafeed_callbacks;
530 map<shared_ptr<EventSource>, SourceCallbackData *> source_callbacks;
531 bool saving;
532 bool save_initialized;
533 string save_filename;
534 uint64_t save_samplerate;
6fa0eb86 535 shared_ptr<Trigger> trigger;
c23c8659
ML
536 /** Deleter needed to allow shared_ptr use with protected destructor. */
537 class Deleter
538 {
539 public:
540 void operator()(Session *session) { delete session; }
541 };
542 friend class Deleter;
543 friend class Context;
544 friend class DatafeedCallbackData;
545};
546
07443fd2 547/** A packet on the session datafeed */
c23c8659
ML
548class SR_API Packet
549{
550public:
90ba83f2
ML
551 /** Type of this packet. */
552 const PacketType *get_type();
c23c8659
ML
553 /** Payload of this packet. */
554 PacketPayload *get_payload();
555protected:
556 Packet(const struct sr_datafeed_packet *structure);
557 ~Packet();
558 const struct sr_datafeed_packet *structure;
559 PacketPayload *payload;
560 /** Deleter needed to allow shared_ptr use with protected destructor. */
561 class Deleter
562 {
563 public:
564 void operator()(Packet *packet) { delete packet; }
565 };
566 friend class Deleter;
567 friend class Session;
568 friend class Output;
569 friend class DatafeedCallbackData;
570};
571
07443fd2 572/** Abstract base class for datafeed packet payloads */
c23c8659
ML
573class SR_API PacketPayload
574{
575protected:
576 PacketPayload();
577 virtual ~PacketPayload() = 0;
578 virtual void *get_data() = 0;
579 virtual size_t get_data_size() = 0;
580 friend class Packet;
581 friend class Output;
582};
583
07443fd2 584/** Payload of a datafeed packet with logic data */
c23c8659
ML
585class SR_API Logic : public PacketPayload
586{
587protected:
588 Logic(const struct sr_datafeed_logic *structure);
589 ~Logic();
590 const struct sr_datafeed_logic *structure;
591 vector<uint8_t> data;
592 void *get_data();
593 size_t get_data_size();
594 friend class Packet;
595};
596
07443fd2 597/** Payload of a datafeed packet with analog data */
c23c8659
ML
598class SR_API Analog : public PacketPayload
599{
600public:
601 /** Number of samples in this packet. */
602 unsigned int get_num_samples();
603 /** Measured quantity of the samples in this packet. */
604 const Quantity *get_mq();
605 /** Unit of the samples in this packet. */
606 const Unit *get_unit();
607 /** Measurement flags associated with the samples in this packet. */
608 vector<const QuantityFlag *> get_mq_flags();
609protected:
610 Analog(const struct sr_datafeed_analog *structure);
611 ~Analog();
612 const struct sr_datafeed_analog *structure;
613 void *get_data();
614 size_t get_data_size();
615 friend class Packet;
616};
617
07443fd2 618/** An input format supported by the library */
c23c8659
ML
619class SR_API InputFormat :
620 public StructureWrapper<Context, struct sr_input_format>
621{
622public:
623 /** Name of this input format. */
624 string get_name();
625 /** Description of this input format. */
626 string get_description();
627 /** Check whether a given file matches this input format. */
628 bool format_match(string filename);
629 /** Open a file using this input format. */
630 shared_ptr<InputFileDevice> open_file(string filename,
631 map<string, string> options = {});
632protected:
633 InputFormat(struct sr_input_format *structure);
634 ~InputFormat();
635 friend class Context;
636 friend class InputFileDevice;
637};
638
07443fd2 639/** A virtual device associated with an input file */
c23c8659
ML
640class SR_API InputFileDevice : public Device
641{
642public:
643 /** Load data from file. */
644 void load();
645protected:
646 InputFileDevice(shared_ptr<InputFormat> format,
647 struct sr_input *input, string filename);
648 ~InputFileDevice();
649 struct sr_input *input;
650 shared_ptr<InputFormat> format;
651 string filename;
652 /** Deleter needed to allow shared_ptr use with protected destructor. */
653 class Deleter
654 {
655 public:
656 void operator()(InputFileDevice *device) { delete device; }
657 };
658 friend class Deleter;
659 friend class InputFormat;
660};
661
07443fd2 662/** An output format supported by the library */
c23c8659
ML
663class SR_API OutputFormat :
664 public StructureWrapper<Context, struct sr_output_format>
665{
666public:
667 /** Name of this output format. */
668 string get_name();
669 /** Description of this output format. */
670 string get_description();
671 /** Create an output using this format. */
672 shared_ptr<Output> create_output(shared_ptr<Device> device, map<string, string> options = {});
673protected:
674 OutputFormat(struct sr_output_format *structure);
675 ~OutputFormat();
676 friend class Context;
677 friend class Output;
678};
679
07443fd2 680/** An output instance (an output format applied to a device) */
c23c8659
ML
681class SR_API Output
682{
683public:
684 /** Update output with data from the given packet. */
685 string receive(shared_ptr<Packet> packet);
686protected:
687 Output(shared_ptr<OutputFormat> format, shared_ptr<Device> device);
688 Output(shared_ptr<OutputFormat> format,
689 shared_ptr<Device> device, map<string, string> options);
690 ~Output();
691 struct sr_output *structure;
692 const shared_ptr<OutputFormat> format;
693 const shared_ptr<Device> device;
694 const map<string, string> options;
695 /** Deleter needed to allow shared_ptr use with protected destructor. */
696 class Deleter
697 {
698 public:
699 void operator()(Output *output) { delete output; }
700 };
701 friend class Deleter;
702 friend class OutputFormat;
703};
704
705/** Base class for objects which wrap an enumeration value from libsigrok */
706template <typename T> class SR_API EnumValue
707{
708public:
709 /** The enum constant associated with this value. */
710 T get_id() const { return id; }
711 /** The name associated with this value. */
712 string get_name() const { return name; }
713protected:
714 EnumValue(T id, const char name[]) : id(id), name(name) {}
715 ~EnumValue() {}
716 const T id;
717 const string name;
718};
719
720#include "enums.hpp"
721
722}
723
724#endif // LIBSIGROK_HPP