]> sigrok.org Git - libsigrok.git/blob - bindings/cxx/classes.cpp
C++: Fix shared pointer handling for Device base class.
[libsigrok.git] / bindings / cxx / classes.cpp
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
20 #include "libsigrok/libsigrok.hpp"
21
22 #include <sstream>
23
24 namespace sigrok
25 {
26
27 /** Helper function to translate C errors to C++ exceptions. */
28 static void check(int result)
29 {
30         if (result != SR_OK)
31                 throw Error(result);
32 }
33
34 /** Helper function to obtain valid strings from possibly null input. */
35 static const char *valid_string(const char *input)
36 {
37         if (input != NULL)
38                 return input;
39         else
40                 return "";
41 }
42
43 /** Helper function to convert between map<string, VariantBase> and GHashTable */
44 static GHashTable *map_to_hash_variant(map<string, Glib::VariantBase> input)
45 {
46         auto output = g_hash_table_new_full(
47                 g_variant_hash, g_variant_equal, g_free,
48                 (void (*)(void *))g_variant_unref);
49         for (auto entry : input)
50                 g_hash_table_insert(output,
51                         g_strdup(entry.first.c_str()),
52                         entry.second.gobj_copy());
53     return output;
54 }
55
56 Error::Error(int result) : result(result)
57 {
58 }
59
60 const char *Error::what() const throw()
61 {
62         return sr_strerror(result);
63 }
64
65 Error::~Error() throw()
66 {
67 }
68
69 shared_ptr<Context> Context::create()
70 {
71         return shared_ptr<Context>(new Context(), Context::Deleter());
72 }
73
74 Context::Context() :
75         session(NULL)
76 {
77         check(sr_init(&structure));
78         struct sr_dev_driver **driver_list = sr_driver_list();
79         if (driver_list)
80                 for (int i = 0; driver_list[i]; i++)
81                         drivers[driver_list[i]->name] =
82                                 new Driver(driver_list[i]);
83         const struct sr_input_module **input_list = sr_input_list();
84         if (input_list)
85                 for (int i = 0; input_list[i]; i++)
86                         input_formats[sr_input_id_get(input_list[i])] =
87                                 new InputFormat(input_list[i]);
88         const struct sr_output_module **output_list = sr_output_list();
89         if (output_list)
90                 for (int i = 0; output_list[i]; i++)
91                         output_formats[sr_output_id_get(output_list[i])] =
92                                 new OutputFormat(output_list[i]);
93 }
94
95 string Context::get_package_version()
96 {
97         return sr_package_version_string_get();
98 }
99
100 string Context::get_lib_version()
101 {
102         return sr_lib_version_string_get();
103 }
104
105 map<string, shared_ptr<Driver>> Context::get_drivers()
106 {
107         map<string, shared_ptr<Driver>> result;
108         for (auto entry: drivers)
109         {
110                 auto name = entry.first;
111                 auto driver = entry.second;
112                 result[name] = static_pointer_cast<Driver>(
113                         driver->get_shared_pointer(this));
114         }
115         return result;
116 }
117
118 map<string, shared_ptr<InputFormat>> Context::get_input_formats()
119 {
120         map<string, shared_ptr<InputFormat>> result;
121         for (auto entry: input_formats)
122         {
123                 auto name = entry.first;
124                 auto input_format = entry.second;
125                 result[name] = static_pointer_cast<InputFormat>(
126                         input_format->get_shared_pointer(this));
127         }
128         return result;
129 }
130
131 map<string, shared_ptr<OutputFormat>> Context::get_output_formats()
132 {
133         map<string, shared_ptr<OutputFormat>> result;
134         for (auto entry: output_formats)
135         {
136                 auto name = entry.first;
137                 auto output_format = entry.second;
138                 result[name] = static_pointer_cast<OutputFormat>(
139                         output_format->get_shared_pointer(this));
140         }
141         return result;
142 }
143
144 Context::~Context()
145 {
146         for (auto entry : drivers)
147                 delete entry.second;
148         for (auto entry : input_formats)
149                 delete entry.second;
150         for (auto entry : output_formats)
151                 delete entry.second;
152         check(sr_exit(structure));
153 }
154
155 const LogLevel *Context::get_log_level()
156 {
157         return LogLevel::get(sr_log_loglevel_get());
158 }
159
160 void Context::set_log_level(const LogLevel *level)
161 {
162         check(sr_log_loglevel_set(level->get_id()));
163 }
164
165 string Context::get_log_domain()
166 {
167         return valid_string(sr_log_logdomain_get());
168 }
169
170 void Context::set_log_domain(string value)
171 {
172         check(sr_log_logdomain_set(value.c_str()));
173 }
174
175 static int call_log_callback(void *cb_data, int loglevel, const char *format, va_list args)
176 {
177         va_list args_copy;
178         va_copy(args_copy, args);
179         int length = vsnprintf(NULL, 0, format, args_copy);
180         va_end(args_copy);
181         char *buf = (char *) g_malloc(length + 1);
182         vsprintf(buf, format, args);
183         string message(buf, length);
184         g_free(buf);
185
186         LogCallbackFunction callback = *((LogCallbackFunction *) cb_data);
187
188         try
189         {
190                 callback(LogLevel::get(loglevel), message);
191         }
192         catch (Error e)
193         {
194                 return e.result;
195         }
196
197         return SR_OK;
198 }
199
200 void Context::set_log_callback(LogCallbackFunction callback)
201 {
202         log_callback = callback;
203         check(sr_log_callback_set(call_log_callback, &log_callback));
204
205
206 void Context::set_log_callback_default()
207 {
208         check(sr_log_callback_set_default());
209         log_callback = nullptr;
210
211
212 shared_ptr<Session> Context::create_session()
213 {
214         return shared_ptr<Session>(
215                 new Session(shared_from_this()), Session::Deleter());
216 }
217
218 shared_ptr<Session> Context::load_session(string filename)
219 {
220         return shared_ptr<Session>(
221                 new Session(shared_from_this(), filename), Session::Deleter());
222 }
223
224 shared_ptr<Trigger> Context::create_trigger(string name)
225 {
226         return shared_ptr<Trigger>(
227                 new Trigger(shared_from_this(), name), Trigger::Deleter());
228 }
229
230 shared_ptr<Input> Context::open_file(string filename)
231 {
232         const struct sr_input *input;
233
234         check( sr_input_scan_file(filename.c_str(), &input));
235         return shared_ptr<Input>(
236                 new Input(shared_from_this(), input), Input::Deleter());
237 }
238
239 shared_ptr<Input> Context::open_stream(string header)
240 {
241         const struct sr_input *input;
242
243         auto gstr = g_string_new(header.c_str());
244         auto ret = sr_input_scan_buffer(gstr, &input);
245         g_string_free(gstr, true);
246         check(ret);
247         return shared_ptr<Input>(
248                 new Input(shared_from_this(), input), Input::Deleter());
249 }
250
251 Driver::Driver(struct sr_dev_driver *structure) :
252         StructureWrapper<Context, struct sr_dev_driver>(structure),
253         initialized(false)
254 {
255 }
256
257 Driver::~Driver()
258 {
259         for (auto device : devices)
260                 delete device;
261 }
262
263 string Driver::get_name()
264 {
265         return valid_string(structure->name);
266 }
267
268 string Driver::get_long_name()
269 {
270         return valid_string(structure->longname);
271 }
272
273 vector<shared_ptr<HardwareDevice>> Driver::scan(
274         map<const ConfigKey *, Glib::VariantBase> options)
275 {
276         /* Initialise the driver if not yet done. */
277         if (!initialized)
278         {
279                 check(sr_driver_init(parent->structure, structure));
280                 initialized = true;
281         }
282
283         /* Clear all existing instances. */
284         for (auto device : devices)
285                 delete device;
286         devices.clear();
287
288         /* Translate scan options to GSList of struct sr_config pointers. */
289         GSList *option_list = NULL;
290         for (auto entry : options)
291         {
292                 auto key = entry.first;
293                 auto value = entry.second;
294                 auto config = g_new(struct sr_config, 1);
295                 config->key = key->get_id();
296                 config->data = value.gobj();
297                 option_list = g_slist_append(option_list, config);
298         }
299
300         /* Run scan. */
301         GSList *device_list = sr_driver_scan(structure, option_list);
302
303         /* Free option list. */
304         g_slist_free_full(option_list, g_free);
305
306         /* Create device objects. */
307         for (GSList *device = device_list; device; device = device->next)
308         {
309                 auto sdi = (struct sr_dev_inst *) device->data;
310                 devices.push_back(new HardwareDevice(this, sdi));
311         }
312
313         /* Free GSList returned from scan. */
314         g_slist_free(device_list);
315
316         /* Create list of shared pointers to device instances for return. */
317         vector<shared_ptr<HardwareDevice>> result;
318         for (auto device : devices)
319                 result.push_back(static_pointer_cast<HardwareDevice>(
320                         device->get_shared_pointer(parent)));
321         return result;
322 }
323
324 Configurable::Configurable(
325                 struct sr_dev_driver *driver,
326                 struct sr_dev_inst *sdi,
327                 struct sr_channel_group *cg) :
328         config_driver(driver),
329         config_sdi(sdi),
330         config_channel_group(cg)
331 {
332 }
333
334 Configurable::~Configurable()
335 {
336 }
337
338 Glib::VariantBase Configurable::config_get(const ConfigKey *key)
339 {
340         GVariant *data;
341         check(sr_config_get(
342                 config_driver, config_sdi, config_channel_group,
343                 key->get_id(), &data));
344         return Glib::VariantBase(data);
345 }
346
347 void Configurable::config_set(const ConfigKey *key, Glib::VariantBase value)
348 {
349         check(sr_config_set(
350                 config_sdi, config_channel_group,
351                 key->get_id(), value.gobj()));
352 }
353
354 Glib::VariantContainerBase Configurable::config_list(const ConfigKey *key)
355 {
356         GVariant *data;
357         check(sr_config_list(
358                 config_driver, config_sdi, config_channel_group,
359                 key->get_id(), &data));
360         return Glib::VariantContainerBase(data);
361 }
362
363 Device::Device(struct sr_dev_inst *structure) :
364         Configurable(structure->driver, structure, NULL),
365         structure(structure)
366 {
367         for (GSList *entry = structure->channels; entry; entry = entry->next)
368         {
369                 auto channel = (struct sr_channel *) entry->data;
370                 channels[channel] = new Channel(channel);
371         }
372
373         for (GSList *entry = structure->channel_groups; entry; entry = entry->next)
374         {
375                 auto group = (struct sr_channel_group *) entry->data;
376                 channel_groups[group->name] = new ChannelGroup(this, group);
377         }
378 }
379
380 Device::~Device()
381 {
382         for (auto entry : channels)
383                 delete entry.second;
384         for (auto entry : channel_groups)
385                 delete entry.second;
386 }
387
388 string Device::get_description()
389 {
390         ostringstream s;
391
392         vector<string> parts =
393                 {get_vendor(), get_model(), get_version()};
394
395         for (string part : parts)
396                 if (part.length() > 0)
397                         s << part;
398
399         return s.str();
400 }
401
402 string Device::get_vendor()
403 {
404         return valid_string(structure->vendor);
405 }
406
407 string Device::get_model()
408 {
409         return valid_string(structure->model);
410 }
411
412 string Device::get_version()
413 {
414         return valid_string(structure->version);
415 }
416
417 vector<shared_ptr<Channel>> Device::get_channels()
418 {
419         vector<shared_ptr<Channel>> result;
420         for (auto entry : channels)
421                 result.push_back(static_pointer_cast<Channel>(
422                         entry.second->get_shared_pointer(get_shared_from_this())));
423         return result;
424 }
425
426 shared_ptr<Channel> Device::get_channel(struct sr_channel *ptr)
427 {
428         return static_pointer_cast<Channel>(
429                 channels[ptr]->get_shared_pointer(get_shared_from_this()));
430 }
431
432 map<string, shared_ptr<ChannelGroup>>
433 Device::get_channel_groups()
434 {
435         map<string, shared_ptr<ChannelGroup>> result;
436         for (auto entry: channel_groups)
437         {
438                 auto name = entry.first;
439                 auto channel_group = entry.second;
440                 result[name] = static_pointer_cast<ChannelGroup>(
441                         channel_group->get_shared_pointer(get_shared_from_this()));
442         }
443         return result;
444 }
445
446 void Device::open()
447 {
448         check(sr_dev_open(structure));
449 }
450
451 void Device::close()
452 {
453         check(sr_dev_close(structure));
454 }
455
456 HardwareDevice::HardwareDevice(Driver *driver, struct sr_dev_inst *structure) :
457         StructureWrapper(structure),
458         Device(structure),
459         driver(driver)
460 {
461 }
462
463 HardwareDevice::~HardwareDevice()
464 {
465 }
466
467 shared_ptr<Device> HardwareDevice::get_shared_from_this()
468 {
469         return static_pointer_cast<Device>(
470                 static_pointer_cast<HardwareDevice>(shared_from_this()));
471 }
472
473 shared_ptr<Driver> HardwareDevice::get_driver()
474 {
475         return static_pointer_cast<Driver>(driver->get_shared_pointer(parent));
476 }
477
478 Channel::Channel(struct sr_channel *structure) :
479         StructureWrapper<Device, struct sr_channel>(structure),
480         type(ChannelType::get(structure->type))
481 {
482 }
483
484 Channel::~Channel()
485 {
486 }
487
488 string Channel::get_name()
489 {
490         return valid_string(structure->name);
491 }
492
493 void Channel::set_name(string name)
494 {
495         check(sr_dev_channel_name_set(parent->structure, structure->index, name.c_str()));
496 }
497
498 const ChannelType *Channel::get_type()
499 {
500         return ChannelType::get(structure->type);
501 }
502
503 bool Channel::get_enabled()
504 {
505         return structure->enabled;
506 }
507
508 void Channel::set_enabled(bool value)
509 {
510         check(sr_dev_channel_enable(parent->structure, structure->index, value));
511 }
512
513 unsigned int Channel::get_index()
514 {
515         return structure->index;
516 }
517
518 ChannelGroup::ChannelGroup(Device *device,
519                 struct sr_channel_group *structure) :
520         StructureWrapper<Device, struct sr_channel_group>(structure),
521         Configurable(device->structure->driver, device->structure, structure)
522 {
523         for (GSList *entry = structure->channels; entry; entry = entry->next)
524                 channels.push_back(device->channels[(struct sr_channel *)entry->data]);
525 }
526
527 ChannelGroup::~ChannelGroup()
528 {
529 }
530
531 string ChannelGroup::get_name()
532 {
533         return valid_string(structure->name);
534 }
535
536 vector<shared_ptr<Channel>> ChannelGroup::get_channels()
537 {
538         vector<shared_ptr<Channel>> result;
539         for (auto channel : channels)
540                 result.push_back(static_pointer_cast<Channel>(
541                         channel->get_shared_pointer(parent)));
542         return result;
543 }
544
545 Trigger::Trigger(shared_ptr<Context> context, string name) : 
546         structure(sr_trigger_new(name.c_str())), context(context)
547 {
548         for (auto stage = structure->stages; stage; stage = stage->next)
549                 stages.push_back(new TriggerStage((struct sr_trigger_stage *) stage->data));
550 }
551
552 Trigger::~Trigger()
553 {
554         for (auto stage: stages)
555                 delete stage;
556
557         sr_trigger_free(structure);
558 }
559
560 string Trigger::get_name()
561 {
562         return structure->name;
563 }
564
565 vector<shared_ptr<TriggerStage>> Trigger::get_stages()
566 {
567         vector<shared_ptr<TriggerStage>> result;
568         for (auto stage : stages)
569                 result.push_back(static_pointer_cast<TriggerStage>(
570                         stage->get_shared_pointer(this)));
571         return result;
572 }
573
574 shared_ptr<TriggerStage> Trigger::add_stage()
575 {
576         auto stage = new TriggerStage(sr_trigger_stage_add(structure));
577         stages.push_back(stage);
578         return static_pointer_cast<TriggerStage>(
579                 stage->get_shared_pointer(this));
580 }
581
582 TriggerStage::TriggerStage(struct sr_trigger_stage *structure) : 
583         StructureWrapper<Trigger, struct sr_trigger_stage>(structure)
584 {
585 }
586
587 TriggerStage::~TriggerStage()
588 {
589         for (auto match : matches)
590                 delete match;
591 }
592         
593 int TriggerStage::get_number()
594 {
595         return structure->stage;
596 }
597
598 vector<shared_ptr<TriggerMatch>> TriggerStage::get_matches()
599 {
600         vector<shared_ptr<TriggerMatch>> result;
601         for (auto match : matches)
602                 result.push_back(static_pointer_cast<TriggerMatch>(
603                         match->get_shared_pointer(this)));
604         return result;
605 }
606
607 void TriggerStage::add_match(shared_ptr<Channel> channel, const TriggerMatchType *type, float value)
608 {
609         check(sr_trigger_match_add(structure, channel->structure, type->get_id(), value));
610         matches.push_back(new TriggerMatch(
611                 (struct sr_trigger_match *) g_slist_last(structure->matches)->data, channel));
612 }
613
614 void TriggerStage::add_match(shared_ptr<Channel> channel, const TriggerMatchType *type)
615 {
616         add_match(channel, type, NAN);
617 }
618
619 TriggerMatch::TriggerMatch(struct sr_trigger_match *structure, shared_ptr<Channel> channel) :
620         StructureWrapper<TriggerStage, struct sr_trigger_match>(structure), channel(channel)
621 {
622 }
623
624 TriggerMatch::~TriggerMatch()
625 {
626 }
627
628 shared_ptr<Channel> TriggerMatch::get_channel()
629 {
630         return channel;
631 }
632
633 const TriggerMatchType *TriggerMatch::get_type()
634 {
635         return TriggerMatchType::get(structure->match);
636 }
637
638 float TriggerMatch::get_value()
639 {
640         return structure->value;
641 }
642
643 DatafeedCallbackData::DatafeedCallbackData(Session *session,
644                 DatafeedCallbackFunction callback) :
645         callback(callback), session(session)
646 {
647 }
648
649 void DatafeedCallbackData::run(const struct sr_dev_inst *sdi,
650         const struct sr_datafeed_packet *pkt)
651 {
652         auto device = session->devices[sdi];
653         auto packet = shared_ptr<Packet>(new Packet(device, pkt), Packet::Deleter());
654         callback(device, packet);
655 }
656
657 SourceCallbackData::SourceCallbackData(shared_ptr<EventSource> source) :
658         source(source)
659 {
660 }
661
662 bool SourceCallbackData::run(int revents)
663 {
664         return source->callback((Glib::IOCondition) revents);
665 }
666
667 shared_ptr<EventSource> EventSource::create(int fd, Glib::IOCondition events,
668         int timeout, SourceCallbackFunction callback)
669 {
670         auto result = new EventSource(timeout, callback);
671         result->type = EventSource::SOURCE_FD;
672         result->fd = fd;
673         result->events = events;
674         return shared_ptr<EventSource>(result, EventSource::Deleter());
675 }
676
677 shared_ptr<EventSource> EventSource::create(Glib::PollFD pollfd, int timeout,
678         SourceCallbackFunction callback)
679 {
680         auto result = new EventSource(timeout, callback);
681         result->type = EventSource::SOURCE_POLLFD;
682         result->pollfd = pollfd;
683         return shared_ptr<EventSource>(result, EventSource::Deleter());
684 }
685
686 shared_ptr<EventSource> EventSource::create(Glib::RefPtr<Glib::IOChannel> channel,
687         Glib::IOCondition events, int timeout, SourceCallbackFunction callback)
688 {
689         auto result = new EventSource(timeout, callback);
690         result->type = EventSource::SOURCE_IOCHANNEL;
691         result->channel = channel;
692         result->events = events;
693         return shared_ptr<EventSource>(result, EventSource::Deleter());
694 }
695
696 EventSource::EventSource(int timeout, SourceCallbackFunction callback) :
697         timeout(timeout), callback(callback)
698 {
699 }
700
701 EventSource::~EventSource()
702 {
703 }
704
705 Session::Session(shared_ptr<Context> context) :
706         context(context), saving(false)
707 {
708         check(sr_session_new(&structure));
709         context->session = this;
710 }
711
712 Session::Session(shared_ptr<Context> context, string filename) :
713         context(context), saving(false)
714 {
715         check(sr_session_load(filename.c_str(), &structure));
716         context->session = this;
717 }
718
719 Session::~Session()
720 {
721         check(sr_session_destroy(structure));
722
723         for (auto callback : datafeed_callbacks)
724                 delete callback;
725
726         for (auto entry : source_callbacks)
727                 delete entry.second;
728 }
729
730 void Session::add_device(shared_ptr<Device> device)
731 {
732         check(sr_session_dev_add(structure, device->structure));
733         devices[device->structure] = device;
734 }
735
736 vector<shared_ptr<Device>> Session::get_devices()
737 {
738         GSList *dev_list;
739         check(sr_session_dev_list(structure, &dev_list));
740         vector<shared_ptr<Device>> result;
741         for (GSList *dev = dev_list; dev; dev = dev->next)
742         {
743                 auto sdi = (struct sr_dev_inst *) dev->data;
744                 result.push_back(devices[sdi]);
745         }
746         return result;
747 }
748
749 void Session::remove_devices()
750 {
751         devices.clear();
752         check(sr_session_dev_remove_all(structure));
753 }
754
755 void Session::start()
756 {
757         check(sr_session_start(structure));
758 }
759
760 void Session::run()
761 {
762         check(sr_session_run(structure));
763 }
764
765 void Session::stop()
766 {
767         check(sr_session_stop(structure));
768 }
769
770 void Session::begin_save(string filename)
771 {
772         saving = true;
773         save_initialized = false;
774         save_filename = filename;
775         save_samplerate = 0;
776 }
777
778 void Session::append(shared_ptr<Packet> packet)
779 {
780         if (!saving)
781                 throw Error(SR_ERR);
782
783         switch (packet->structure->type)
784         {
785                 case SR_DF_META:
786                 {
787                         auto meta = (const struct sr_datafeed_meta *)
788                                 packet->structure->payload;
789
790                         for (auto l = meta->config; l; l = l->next)
791                         {
792                                 auto config = (struct sr_config *) l->data;
793                                 if (config->key == SR_CONF_SAMPLERATE)
794                                         save_samplerate = g_variant_get_uint64(config->data);
795                         }
796
797                         break;
798                 }
799                 case SR_DF_LOGIC:
800                 {
801                         if (save_samplerate == 0)
802                         {
803                                 GVariant *samplerate;
804
805                                 check(sr_config_get(packet->device->structure->driver,
806                                         packet->device->structure, NULL, SR_CONF_SAMPLERATE,
807                                         &samplerate));
808
809                                 save_samplerate = g_variant_get_uint64(samplerate);
810
811                                 g_variant_unref(samplerate);
812                         }
813
814                         if (!save_initialized)
815                         {
816                                 vector<shared_ptr<Channel>> save_channels;
817
818                                 for (auto channel : packet->device->get_channels())
819                                         if (channel->structure->enabled &&
820                                                         channel->structure->type == SR_CHANNEL_LOGIC)
821                                                 save_channels.push_back(channel);
822
823                                 auto channels = g_new(char *, save_channels.size());
824
825                                 int i = 0;
826                                 for (auto channel : save_channels)
827                                                 channels[i++] = channel->structure->name;
828                                 channels[i] = NULL;
829
830                                 int ret = sr_session_save_init(structure, save_filename.c_str(),
831                                                 save_samplerate, channels);
832
833                                 g_free(channels);
834
835                                 if (ret != SR_OK)
836                                         throw Error(ret);
837
838                                 save_initialized = true;
839                         }
840
841                         auto logic = (const struct sr_datafeed_logic *)
842                                 packet->structure->payload;
843
844                         check(sr_session_append(structure, save_filename.c_str(),
845                                 (uint8_t *) logic->data, logic->unitsize,
846                                 logic->length / logic->unitsize));
847                 }
848         }
849 }
850
851 void Session::append(void *data, size_t length, unsigned int unit_size)
852 {
853         check(sr_session_append(structure, save_filename.c_str(),
854                 (uint8_t *) data, unit_size, length));
855 }
856
857 static void datafeed_callback(const struct sr_dev_inst *sdi,
858         const struct sr_datafeed_packet *pkt, void *cb_data)
859 {
860         auto callback = static_cast<DatafeedCallbackData *>(cb_data);
861         callback->run(sdi, pkt);
862 }
863         
864 void Session::add_datafeed_callback(DatafeedCallbackFunction callback)
865 {
866         auto cb_data = new DatafeedCallbackData(this, callback);
867         check(sr_session_datafeed_callback_add(structure, datafeed_callback, cb_data));
868         datafeed_callbacks.push_back(cb_data);
869 }
870
871 void Session::remove_datafeed_callbacks(void)
872 {
873         check(sr_session_datafeed_callback_remove_all(structure));
874         for (auto callback : datafeed_callbacks)
875                 delete callback;
876         datafeed_callbacks.clear();
877 }
878
879 static int source_callback(int fd, int revents, void *cb_data)
880 {
881         (void) fd;
882         auto callback = (SourceCallbackData *) cb_data;
883         return callback->run(revents);
884 }
885
886 void Session::add_source(shared_ptr<EventSource> source)
887 {
888         if (source_callbacks.count(source) == 1)
889                 throw Error(SR_ERR_ARG);
890
891         auto cb_data = new SourceCallbackData(source);
892
893         switch (source->type)
894         {
895                 case EventSource::SOURCE_FD:
896                         check(sr_session_source_add(structure, source->fd, source->events,
897                                 source->timeout, source_callback, cb_data));
898                         break;
899                 case EventSource::SOURCE_POLLFD:
900                         check(sr_session_source_add_pollfd(structure,
901                                 source->pollfd.gobj(), source->timeout, source_callback,
902                                 cb_data));
903                         break;
904                 case EventSource::SOURCE_IOCHANNEL:
905                         check(sr_session_source_add_channel(structure,
906                                 source->channel->gobj(), source->events, source->timeout,
907                                 source_callback, cb_data));
908                         break;
909         }
910
911         source_callbacks[source] = cb_data;
912 }
913
914 void Session::remove_source(shared_ptr<EventSource> source)
915 {
916         if (source_callbacks.count(source) == 0)
917                 throw Error(SR_ERR_ARG);
918
919         switch (source->type)
920         {
921                 case EventSource::SOURCE_FD:
922                         check(sr_session_source_remove(structure, source->fd));
923                         break;
924                 case EventSource::SOURCE_POLLFD:
925                         check(sr_session_source_remove_pollfd(structure,
926                                 source->pollfd.gobj()));
927                         break;
928                 case EventSource::SOURCE_IOCHANNEL:
929                         check(sr_session_source_remove_channel(structure,
930                                 source->channel->gobj()));
931                         break;
932         }
933
934         delete source_callbacks[source];
935
936         source_callbacks.erase(source);
937 }
938
939 shared_ptr<Trigger> Session::get_trigger()
940 {
941         return trigger;
942 }
943
944 void Session::set_trigger(shared_ptr<Trigger> trigger)
945 {
946         check(sr_session_trigger_set(structure, trigger->structure));
947         this->trigger = trigger;
948 }
949
950 Packet::Packet(shared_ptr<Device> device,
951         const struct sr_datafeed_packet *structure) :
952         structure(structure),
953         device(device)
954 {
955         switch (structure->type)
956         {
957                 case SR_DF_HEADER:
958                         payload = new Header(
959                                 static_cast<const struct sr_datafeed_header *>(
960                                         structure->payload));
961                         break;
962                 case SR_DF_META:
963                         payload = new Meta(
964                                 static_cast<const struct sr_datafeed_meta *>(
965                                         structure->payload));
966                         break;
967                 case SR_DF_LOGIC:
968                         payload = new Logic(
969                                 static_cast<const struct sr_datafeed_logic *>(
970                                         structure->payload));
971                         break;
972                 case SR_DF_ANALOG:
973                         payload = new Analog(
974                                 static_cast<const struct sr_datafeed_analog *>(
975                                         structure->payload));
976                         break;
977         }
978 }
979
980 Packet::~Packet()
981 {
982         if (payload)
983                 delete payload;
984 }
985
986 const PacketType *Packet::get_type()
987 {
988         return PacketType::get(structure->type);
989 }
990
991 shared_ptr<PacketPayload> Packet::get_payload()
992 {
993         return payload->get_shared_pointer(this);
994 }
995
996 PacketPayload::PacketPayload()
997 {
998 }
999
1000 PacketPayload::~PacketPayload()
1001 {
1002 }
1003
1004 Header::Header(const struct sr_datafeed_header *structure) :
1005         PacketPayload(),
1006         StructureWrapper<Packet, const struct sr_datafeed_header>(structure)
1007 {
1008 }
1009
1010 Header::~Header()
1011 {
1012 }
1013
1014 int Header::get_feed_version()
1015 {
1016         return structure->feed_version;
1017 }
1018
1019 Glib::TimeVal Header::get_start_time()
1020 {
1021         return Glib::TimeVal(
1022                 structure->starttime.tv_sec,
1023                 structure->starttime.tv_usec);
1024 }
1025
1026 Meta::Meta(const struct sr_datafeed_meta *structure) :
1027         PacketPayload(),
1028         StructureWrapper<Packet, const struct sr_datafeed_meta>(structure)
1029 {
1030 }
1031
1032 Meta::~Meta()
1033 {
1034 }
1035
1036 map<const ConfigKey *, Glib::VariantBase> Meta::get_config()
1037 {
1038         map<const ConfigKey *, Glib::VariantBase> result;
1039         for (auto l = structure->config; l; l = l->next)
1040         {
1041                 auto config = (struct sr_config *) l->data;
1042                 result[ConfigKey::get(config->key)] = Glib::VariantBase(config->data);
1043         }
1044         return result;
1045 }
1046
1047 Logic::Logic(const struct sr_datafeed_logic *structure) :
1048         PacketPayload(),
1049         StructureWrapper<Packet, const struct sr_datafeed_logic>(structure)
1050 {
1051 }
1052
1053 Logic::~Logic()
1054 {
1055 }
1056
1057 void *Logic::get_data_pointer()
1058 {
1059         return structure->data;
1060 }
1061
1062 size_t Logic::get_data_length()
1063 {
1064         return structure->length;
1065 }
1066
1067 unsigned int Logic::get_unit_size()
1068 {
1069         return structure->unitsize;
1070 }
1071
1072 Analog::Analog(const struct sr_datafeed_analog *structure) :
1073         PacketPayload(),
1074         StructureWrapper<Packet, const struct sr_datafeed_analog>(structure)
1075 {
1076 }
1077
1078 Analog::~Analog()
1079 {
1080 }
1081
1082 float *Analog::get_data_pointer()
1083 {
1084         return structure->data;
1085 }
1086
1087 unsigned int Analog::get_num_samples()
1088 {
1089         return structure->num_samples;
1090 }
1091
1092 vector<shared_ptr<Channel>> Analog::get_channels()
1093 {
1094         vector<shared_ptr<Channel>> result;
1095         for (auto l = structure->channels; l; l = l->next)
1096                 result.push_back(parent->device->get_channel(
1097                         (struct sr_channel *)l->data));
1098         return result;
1099 }
1100
1101 const Quantity *Analog::get_mq()
1102 {
1103         return Quantity::get(structure->mq);
1104 }
1105
1106 const Unit *Analog::get_unit()
1107 {
1108         return Unit::get(structure->unit);
1109 }
1110
1111 vector<const QuantityFlag *> Analog::get_mq_flags()
1112 {
1113         return QuantityFlag::flags_from_mask(structure->mqflags);
1114 }
1115
1116 InputFormat::InputFormat(const struct sr_input_module *structure) :
1117         StructureWrapper<Context, const struct sr_input_module>(structure)
1118 {
1119 }
1120
1121 InputFormat::~InputFormat()
1122 {
1123 }
1124
1125 string InputFormat::get_name()
1126 {
1127         return valid_string(sr_input_id_get(structure));
1128 }
1129
1130 string InputFormat::get_description()
1131 {
1132         return valid_string(sr_input_description_get(structure));
1133 }
1134
1135 map<string, shared_ptr<Option>> InputFormat::get_options()
1136 {
1137         const struct sr_option **options = sr_input_options_get(structure);
1138         auto option_array = shared_ptr<const struct sr_option *>(
1139                 options, sr_input_options_free);
1140         map<string, shared_ptr<Option>> result;
1141         for (int i = 0; options[i]; i++)
1142                 result[options[i]->id] = shared_ptr<Option>(
1143                         new Option(options[i], option_array), Option::Deleter());
1144         return result;
1145 }
1146
1147 shared_ptr<Input> InputFormat::create_input(
1148         map<string, Glib::VariantBase> options)
1149 {
1150         auto input = sr_input_new(structure, map_to_hash_variant(options));
1151         if (!input)
1152                 throw Error(SR_ERR_ARG);
1153         return shared_ptr<Input>(
1154                 new Input(parent->shared_from_this(), input), Input::Deleter());
1155 }
1156
1157 Input::Input(shared_ptr<Context> context, const struct sr_input *structure) :
1158         structure(structure),
1159         context(context),
1160         device(nullptr)
1161 {
1162 }
1163
1164 shared_ptr<InputDevice> Input::get_device()
1165 {
1166         if (!device)
1167         {
1168                 auto sdi = sr_input_dev_inst_get(structure);
1169                 if (!sdi)
1170                         throw Error(SR_ERR_NA);
1171                 device = new InputDevice(shared_from_this(), sdi);
1172         }
1173
1174         return static_pointer_cast<InputDevice>(
1175                 device->get_shared_pointer(shared_from_this()));
1176 }
1177
1178 void Input::send(string data)
1179 {
1180         auto gstr = g_string_new(data.c_str());
1181         auto ret = sr_input_send(structure, gstr);
1182         g_string_free(gstr, false);
1183         check(ret);
1184 }
1185
1186 Input::~Input()
1187 {
1188         if (device)
1189                 delete device;
1190         check(sr_input_free(structure));
1191 }
1192
1193 InputDevice::InputDevice(shared_ptr<Input> input,
1194                 struct sr_dev_inst *structure) :
1195         StructureWrapper(structure),
1196         Device(structure),
1197         input(input)
1198 {
1199 }
1200
1201 InputDevice::~InputDevice()
1202 {
1203 }
1204
1205 shared_ptr<Device> InputDevice::get_shared_from_this()
1206 {
1207         return static_pointer_cast<Device>(
1208                 static_pointer_cast<InputDevice>(shared_from_this()));
1209 }
1210
1211 Option::Option(const struct sr_option *structure,
1212                 shared_ptr<const struct sr_option *> structure_array) :
1213         structure(structure),
1214         structure_array(structure_array)
1215 {
1216 }
1217
1218 Option::~Option()
1219 {
1220 }
1221
1222 string Option::get_id()
1223 {
1224         return valid_string(structure->id);
1225 }
1226
1227 string Option::get_name()
1228 {
1229         return valid_string(structure->name);
1230 }
1231
1232 string Option::get_description()
1233 {
1234         return valid_string(structure->desc);
1235 }
1236
1237 Glib::VariantBase Option::get_default_value()
1238 {
1239         return Glib::VariantBase(structure->def, true);
1240 }
1241
1242 vector<Glib::VariantBase> Option::get_values()
1243 {
1244         vector<Glib::VariantBase> result;
1245         for (auto l = structure->values; l; l = l->next)
1246                 result.push_back(Glib::VariantBase((GVariant *) l->data, true));
1247         return result;
1248 }
1249
1250 OutputFormat::OutputFormat(const struct sr_output_module *structure) :
1251         StructureWrapper<Context, const struct sr_output_module>(structure)
1252 {
1253 }
1254
1255 OutputFormat::~OutputFormat()
1256 {
1257 }
1258
1259 string OutputFormat::get_name()
1260 {
1261         return valid_string(sr_output_id_get(structure));
1262 }
1263
1264 string OutputFormat::get_description()
1265 {
1266         return valid_string(sr_output_description_get(structure));
1267 }
1268
1269 map<string, shared_ptr<Option>> OutputFormat::get_options()
1270 {
1271         const struct sr_option **options = sr_output_options_get(structure);
1272         auto option_array = shared_ptr<const struct sr_option *>(
1273                 options, sr_output_options_free);
1274         map<string, shared_ptr<Option>> result;
1275         for (int i = 0; options[i]; i++)
1276                 result[options[i]->id] = shared_ptr<Option>(
1277                         new Option(options[i], option_array), Option::Deleter());
1278         return result;
1279 }
1280
1281 shared_ptr<Output> OutputFormat::create_output(
1282         shared_ptr<Device> device, map<string, Glib::VariantBase> options)
1283 {
1284         return shared_ptr<Output>(
1285                 new Output(
1286                         static_pointer_cast<OutputFormat>(shared_from_this()),
1287                                 device, options),
1288                 Output::Deleter());
1289 }
1290
1291 Output::Output(shared_ptr<OutputFormat> format,
1292                 shared_ptr<Device> device, map<string, Glib::VariantBase> options) :
1293         structure(sr_output_new(format->structure,
1294                 map_to_hash_variant(options), device->structure)),
1295         format(format), device(device), options(options)
1296 {
1297 }
1298
1299 Output::~Output()
1300 {
1301         check(sr_output_free(structure));
1302 }
1303
1304 string Output::receive(shared_ptr<Packet> packet)
1305 {
1306         GString *out;
1307         check(sr_output_send(structure, packet->structure, &out));
1308         if (out)
1309         {
1310                 auto result = string(out->str, out->str + out->len);
1311                 g_string_free(out, true);
1312                 return result;
1313         }
1314         else
1315         {
1316                 return string();
1317         }
1318 }
1319
1320 #include "enums.cpp"
1321
1322 }