sdbus-c++ 2.4.0
High-level C++ D-Bus library based on systemd D-Bus implementation
Loading...
Searching...
No Matches
ConvenienceApiClasses.inl
Go to the documentation of this file.
1
26
27#ifndef SDBUS_CPP_CONVENIENCEAPICLASSES_INL_
28#define SDBUS_CPP_CONVENIENCEAPICLASSES_INL_
29
30#include <sdbus-c++/Error.h>
31#include <sdbus-c++/IObject.h> // NOLINT(misc-header-include-cycle)
32#include <sdbus-c++/IProxy.h> // NOLINT(misc-header-include-cycle)
33#include <sdbus-c++/Message.h>
36#include <sdbus-c++/Types.h>
37
38#include <algorithm>
39#include <cassert>
40#include <exception>
41#include <map>
42#include <optional>
43#include <string>
44#include <tuple>
45#include <type_traits>
46#include <vector>
47
48namespace sdbus {
49
50 /*** ------------- ***/
51 /*** VTableAdder ***/
52 /*** ------------- ***/
53
54 inline VTableAdder::VTableAdder(IObject& object, std::vector<VTableItem> vtable)
55 : object_(object)
56 , vtable_(std::move(vtable))
57 {
58 }
59
60 inline void VTableAdder::forInterface(InterfaceName interfaceName)
61 {
62 object_.addVTable(std::move(interfaceName), std::move(vtable_));
63 }
64
65 inline void VTableAdder::forInterface(std::string interfaceName)
66 {
67 forInterface(InterfaceName{std::move(interfaceName)});
68 }
69
70 [[nodiscard]] inline Slot VTableAdder::forInterface(InterfaceName interfaceName, return_slot_t)
71 {
72 return object_.addVTable(std::move(interfaceName), std::move(vtable_), return_slot);
73 }
74
75 [[nodiscard]] inline Slot VTableAdder::forInterface(std::string interfaceName, return_slot_t)
76 {
77 return forInterface(InterfaceName{std::move(interfaceName)}, return_slot);
78 }
79
80 /*** ------------- ***/
81 /*** SignalEmitter ***/
82 /*** ------------- ***/
83
84 inline SignalEmitter::SignalEmitter(IObject& object, const SignalName& signalName)
85 : SignalEmitter(object, signalName.c_str())
86 {
87 }
88
89 inline SignalEmitter::SignalEmitter(IObject& object, const char* signalName)
90 : object_(object)
91 , signalName_(signalName)
92 , exceptions_(std::uncaught_exceptions())
93 {
94 }
95
96 inline SignalEmitter::~SignalEmitter() noexcept(false) // since C++11, destructors must
97 { // explicitly be allowed to throw
98 // Don't emit the signal if SignalEmitter threw an exception in one of its methods
99 if (std::uncaught_exceptions() != exceptions_)
100 return;
101
102 // emitSignal() can throw. But as the SignalEmitter shall always be used as an unnamed,
103 // temporary object, i.e. not as a stack-allocated object, the double-exception situation
104 // shall never happen. I.e. it should not happen that this destructor is directly called
105 // in the stack-unwinding process of another flying exception (which would lead to immediate
106 // termination). It can be called indirectly in the destructor of another object, but that's
107 // fine and safe provided that the caller catches exceptions thrown from here.
108 // Therefore, we can allow emitSignal() to throw even if we are in the destructor.
109 // Bottomline is, to be on the safe side, the caller must take care of catching and reacting
110 // to the exception thrown from here if the caller is a destructor itself.
111 object_.emitSignal(signal_);
112 }
113
114 inline SignalEmitter& SignalEmitter::onInterface(const InterfaceName& interfaceName)
115 {
116 return onInterface(interfaceName.c_str());
117 }
118
119 inline SignalEmitter& SignalEmitter::onInterface(const std::string& interfaceName)
120 {
121 return onInterface(interfaceName.c_str());
122 }
123
124 inline SignalEmitter& SignalEmitter::onInterface(const char* interfaceName)
125 {
126 signal_ = object_.createSignal(interfaceName, signalName_);
127
128 return *this;
129 }
130
131 template <typename... Args>
132 inline void SignalEmitter::withArguments(Args&&... args)
133 {
134 assert(signal_.isValid()); // onInterface() must be placed/called prior to withArguments()
135
136 detail::serialize_pack(signal_, std::forward<Args>(args)...);
137 }
138
139 /*** ------------- ***/
140 /*** MethodInvoker ***/
141 /*** ------------- ***/
142
143 inline MethodInvoker::MethodInvoker(IProxy& proxy, const MethodName& methodName)
144 : MethodInvoker(proxy, methodName.c_str())
145 {
146 }
147
148 inline MethodInvoker::MethodInvoker(IProxy& proxy, const char* methodName)
149 : proxy_(proxy)
150 , methodName_(methodName)
151 , exceptions_(std::uncaught_exceptions())
152 {
153 }
154
155 inline MethodInvoker::~MethodInvoker() noexcept(false) // since C++11, destructors must
156 { // explicitly be allowed to throw
157 // Don't call the method if it has been called already or if MethodInvoker
158 // threw an exception in one of its methods
159 if (methodCalled_ || std::uncaught_exceptions() != exceptions_)
160 return;
161
162 // callMethod() can throw. But as the MethodInvoker shall always be used as an unnamed,
163 // temporary object, i.e. not as a stack-allocated object, the double-exception situation
164 // shall never happen. I.e. it should not happen that this destructor is directly called
165 // in the stack-unwinding process of another flying exception (which would lead to immediate
166 // termination). It can be called indirectly in the destructor of another object, but that's
167 // fine and safe provided that the caller catches exceptions thrown from here.
168 // Therefore, we can allow callMethod() to throw even if we are in the destructor.
169 // Bottomline is, to be on the safe side, the caller must take care of catching and reacting
170 // to the exception thrown from here if the caller is a destructor itself.
171 proxy_.callMethod(method_, timeout_);
172 }
173
174 inline MethodInvoker& MethodInvoker::onInterface(const InterfaceName& interfaceName)
175 {
176 return onInterface(interfaceName.c_str());
177 }
178
179 inline MethodInvoker& MethodInvoker::onInterface(const std::string& interfaceName)
180 {
181 return onInterface(interfaceName.c_str());
182 }
183
184 inline MethodInvoker& MethodInvoker::onInterface(const char* interfaceName)
185 {
186 method_ = proxy_.createMethodCall(interfaceName, methodName_);
187
188 return *this;
189 }
190
191 inline MethodInvoker& MethodInvoker::withTimeout(uint64_t usec)
192 {
193 timeout_ = usec;
194
195 return *this;
196 }
197
198 template <typename Rep, typename Period>
199 inline MethodInvoker& MethodInvoker::withTimeout(const std::chrono::duration<Rep, Period>& timeout)
200 {
201 auto microsecs = std::chrono::duration_cast<std::chrono::microseconds>(timeout);
202 return withTimeout(microsecs.count());
203 }
204
205 template <typename... Args>
206 inline MethodInvoker& MethodInvoker::withArguments(Args&&... args)
207 {
208 assert(method_.isValid()); // onInterface() must be placed/called prior to this function
209
210 detail::serialize_pack(method_, std::forward<Args>(args)...);
211
212 return *this;
213 }
214
215 template <typename... Args>
216 inline void MethodInvoker::storeResultsTo(Args&... args)
217 {
218 assert(method_.isValid()); // onInterface() must be placed/called prior to this function
219
220 auto reply = proxy_.callMethod(method_, timeout_);
221 methodCalled_ = true;
222
223 detail::deserialize_pack(reply, args...);
224 }
225
226 inline void MethodInvoker::dontExpectReply()
227 {
228 assert(method_.isValid()); // onInterface() must be placed/called prior to this function
229
230 method_.dontExpectReply();
231 }
232
233 /*** ------------------ ***/
234 /*** AsyncMethodInvoker ***/
235 /*** ------------------ ***/
236
237 inline AsyncMethodInvoker::AsyncMethodInvoker(IProxy& proxy, const MethodName& methodName)
238 : AsyncMethodInvoker(proxy, methodName.c_str())
239 {
240 }
241
242 inline AsyncMethodInvoker::AsyncMethodInvoker(IProxy& proxy, const char* methodName)
243 : proxy_(proxy)
244 , methodName_(methodName)
245 {
246 }
247
248 inline AsyncMethodInvoker& AsyncMethodInvoker::onInterface(const InterfaceName& interfaceName)
249 {
250 return onInterface(interfaceName.c_str());
251 }
252
253 inline AsyncMethodInvoker& AsyncMethodInvoker::onInterface(const std::string& interfaceName)
254 {
255 return onInterface(interfaceName.c_str());
256 }
257
258 inline AsyncMethodInvoker& AsyncMethodInvoker::onInterface(const char* interfaceName)
259 {
260 method_ = proxy_.createMethodCall(interfaceName, methodName_);
261
262 return *this;
263 }
264
265 inline AsyncMethodInvoker& AsyncMethodInvoker::withTimeout(uint64_t usec)
266 {
267 timeout_ = usec;
268
269 return *this;
270 }
271
272 template <typename Rep, typename Period>
273 inline AsyncMethodInvoker& AsyncMethodInvoker::withTimeout(const std::chrono::duration<Rep, Period>& timeout)
274 {
275 auto microsecs = std::chrono::duration_cast<std::chrono::microseconds>(timeout);
276 return withTimeout(microsecs.count());
277 }
278
279 template <typename... Args>
280 inline AsyncMethodInvoker& AsyncMethodInvoker::withArguments(Args&&... args)
281 {
282 assert(method_.isValid()); // onInterface() must be placed/called prior to this function
283
284 detail::serialize_pack(method_, std::forward<Args>(args)...);
285
286 return *this;
287 }
288
289 template <typename Function>
290 PendingAsyncCall AsyncMethodInvoker::uponReplyInvoke(Function&& callback)
291 {
292 assert(method_.isValid()); // onInterface() must be placed/called prior to this function
293
294 return proxy_.callMethodAsync(method_, makeAsyncReplyHandler(std::forward<Function>(callback)), timeout_);
295 }
296
297 template <typename Function>
298 [[nodiscard]] Slot AsyncMethodInvoker::uponReplyInvoke(Function&& callback, return_slot_t)
299 {
300 assert(method_.isValid()); // onInterface() must be placed/called prior to this function
301
302 return proxy_.callMethodAsync( method_
303 , makeAsyncReplyHandler(std::forward<Function>(callback))
304 , timeout_
305 , return_slot );
306 }
307
308 template <typename Function>
309 inline async_reply_handler AsyncMethodInvoker::makeAsyncReplyHandler(Function&& callback)
310 {
311 return [callback = std::forward<Function>(callback)](MethodReply reply, std::optional<Error> error)
312 {
313 // Create a tuple of callback input arguments' types, which will be used
314 // as a storage for the argument values deserialized from the message.
315 tuple_of_function_input_arg_types_t<Function> args;
316
317 // Deserialize input arguments from the message into the tuple (if no error occurred).
318 if (!error)
319 {
320 try
321 {
322 reply >> args;
323 }
324 catch (const Error& err)
325 {
326 // Pass message deserialization exceptions to the client via callback error parameter,
327 // instead of propagating them up the message loop call stack.
328 sdbus::apply(callback, err, args);
329 return;
330 }
331 }
332
333 // Invoke callback with input arguments from the tuple.
334 sdbus::apply(callback, std::move(error), args);
335 };
336 }
337
338 template <typename... Args>
339 std::future<future_return_t<Args...>> AsyncMethodInvoker::getResultAsFuture()
340 {
341 auto promise = std::make_shared<std::promise<future_return_t<Args...>>>();
342 auto future = promise->get_future();
343
344 uponReplyInvoke([promise = std::move(promise)](std::optional<Error> error, Args... args)
345 {
346 if (!error)
347 if constexpr (!std::is_void_v<future_return_t<Args...>>)
348 promise->set_value({std::move(args)...});
349 else
350 promise->set_value();
351 else
352 promise->set_exception(std::make_exception_ptr(*std::move(error)));
353 });
354
355 // Will be std::future<void> for no D-Bus method return value
356 // or std::future<T> for single D-Bus method return value
357 // or std::future<std::tuple<...>> for multiple method return values
358 return future;
359 }
360
361 template <typename... Args>
362 Awaitable<awaitable_return_t<Args...>> AsyncMethodInvoker::getResultAsAwaitable()
363 {
364 // awaitable_return_t<Args...> will be void for no D-Bus method return value
365 // or T for single D-Bus method return value
366 // or std::tuple<...> for multiple method return values
367 auto data = std::make_shared<AwaitableData<awaitable_return_t<Args...>>>();
368
369 uponReplyInvoke([data](std::optional<Error> error, Args... args)
370 {
371 if (!error)
372 if constexpr (!std::is_void_v<awaitable_return_t<Args...>>)
373 data->result = {std::move(args)...};
374 else
375 data->result = std::monostate{};
376 else
377 data->result = std::make_exception_ptr(*std::move(error));
378
379 auto previous = data->status.exchange(AwaitableState::Completed, std::memory_order_acq_rel);
380 if (previous == AwaitableState::Waiting)
381 data->resumeCoroutine();
382 });
383
384 return Awaitable(data);
385 }
386
387 /*** ---------------- ***/
388 /*** SignalSubscriber ***/
389 /*** ---------------- ***/
390
391 inline SignalSubscriber::SignalSubscriber(IProxy& proxy, const SignalName& signalName)
392 : SignalSubscriber(proxy, signalName.c_str())
393 {
394 }
395
396 inline SignalSubscriber::SignalSubscriber(IProxy& proxy, const char* signalName)
397 : proxy_(proxy)
398 , signalName_(signalName)
399 {
400 }
401
402 inline SignalSubscriber& SignalSubscriber::onInterface(const InterfaceName& interfaceName)
403 {
404 return onInterface(interfaceName.c_str());
405 }
406
407 inline SignalSubscriber& SignalSubscriber::onInterface(const std::string& interfaceName)
408 {
409 return onInterface(interfaceName.c_str());
410 }
411
412 inline SignalSubscriber& SignalSubscriber::onInterface(const char* interfaceName)
413 {
414 interfaceName_ = std::move(interfaceName);
415
416 return *this;
417 }
418
419 template <typename Function>
420 inline void SignalSubscriber::call(Function&& callback)
421 {
422 assert(interfaceName_ != nullptr); // onInterface() must be placed/called prior to this function
423
424 proxy_.registerSignalHandler( interfaceName_
425 , signalName_
426 , makeSignalHandler(std::forward<Function>(callback)) );
427 }
428
429 template <typename Function>
430 [[nodiscard]] inline Slot SignalSubscriber::call(Function&& callback, return_slot_t)
431 {
432 assert(interfaceName_ != nullptr); // onInterface() must be placed/called prior to this function
433
434 return proxy_.registerSignalHandler( interfaceName_
435 , signalName_
436 , makeSignalHandler(std::forward<Function>(callback))
437 , return_slot );
438 }
439
440 template <typename Function>
441 inline signal_handler SignalSubscriber::makeSignalHandler(Function&& callback)
442 {
443 return [callback = std::forward<Function>(callback)](Signal signal)
444 {
445 // Create a tuple of callback input arguments' types, which will be used
446 // as a storage for the argument values deserialized from the signal message.
447 tuple_of_function_input_arg_types_t<Function> signalArgs;
448
449 // The signal handler can take pure signal parameters only, or an additional `std::optional<Error>` as its first
450 // parameter. In the former case, if the deserialization fails (e.g. due to signature mismatch),
451 // the failure is ignored (and signal simply dropped). In the latter case, the deserialization failure
452 // will be communicated to the client's signal handler as a valid Error object inside the std::optional parameter.
453 if constexpr (has_error_param_v<Function>)
454 {
455 // Deserialize input arguments from the signal message into the tuple
456 try
457 {
458 signal >> signalArgs;
459 }
460 catch (const Error& err)
461 {
462 // Pass message deserialization exceptions to the client via callback error parameter,
463 // instead of propagating them up the message loop call stack.
464 sdbus::apply(callback, err, signalArgs);
465 return;
466 }
467
468 // Invoke callback with no error and input arguments from the tuple.
469 sdbus::apply(callback, std::nullopt, signalArgs);
470 }
471 else
472 {
473 // Deserialize input arguments from the signal message into the tuple
474 signal >> signalArgs;
475
476 // Invoke callback with input arguments from the tuple.
477 sdbus::apply(callback, signalArgs);
478 }
479 };
480 }
481
482 /*** ------------------------ ***/
483 /*** PropertyChangeSubscriber ***/
484 /*** ------------------------ ***/
485
486 inline PropertyChangeSubscriber::PropertyChangeSubscriber(IProxy& proxy, PropertyName propertyName)
487 : proxy_(proxy)
488 , propertyName_(std::move(propertyName))
489 {
490 }
491
492 inline PropertyChangeSubscriber& PropertyChangeSubscriber::onInterface(InterfaceName interfaceName)
493 {
494 interfaceName_ = std::move(interfaceName);
495
496 return *this;
497 }
498
499 inline PropertyChangeSubscriber& PropertyChangeSubscriber::onInterface(std::string_view interfaceName)
500 {
501 return onInterface(InterfaceName{std::string{interfaceName}});
502 }
503
504 template <typename Function>
505 inline void PropertyChangeSubscriber::call(Function&& callback)
506 {
507 assert(!interfaceName_.empty()); // onInterface() must be placed/called prior to this function
508
509 proxy_.registerSignalHandler( DBUS_PROPERTIES_INTERFACE_NAME
510 , PROPERTIES_CHANGED_SIGNAL_NAME
511 , makeSignalHandler(std::forward<Function>(callback)) );
512 }
513
514 template <typename Function>
515 [[nodiscard]] inline Slot PropertyChangeSubscriber::call(Function&& callback, return_slot_t)
516 {
517 assert(!interfaceName_.empty()); // onInterface() must be placed/called prior to this function
518
519 return proxy_.registerSignalHandler( DBUS_PROPERTIES_INTERFACE_NAME
520 , PROPERTIES_CHANGED_SIGNAL_NAME
521 , makeSignalHandler(std::forward<Function>(callback))
522 , return_slot );
523 }
524
525 template <typename Function>
526 inline signal_handler PropertyChangeSubscriber::makeSignalHandler(Function&& callback)
527 {
528 using callback_args_t = tuple_of_function_input_arg_types_t<Function>;
529 static_assert( std::tuple_size_v<callback_args_t> == 1
530 , "Property change callback must take exactly one property value parameter (plus optional error parameter)" );
531 using property_arg_t = std::tuple_element_t<0, callback_args_t>;
532 static_assert( is_optional_v<property_arg_t>
533 , "Property value parameter of property change callback must be std::optional<T>" );
534 using property_value_t = typename property_arg_t::value_type;
535
536 return [ callback = std::forward<Function>(callback)
537 , interfaceName = std::move(interfaceName_)
538 , propertyName = std::move(propertyName_) ](Signal signal)
539 {
540 std::optional<property_value_t> value;
541 bool affected{};
542
543 // Like with signal handlers, the callback can take an additional `std::optional<Error>` as its first
544 // parameter. In such a case, deserialization failures (e.g. due to property type mismatch) are passed to
545 // the callback. Otherwise, they are propagated up the message loop call stack.
546 if constexpr (has_error_param_v<Function>)
547 {
548 try
549 {
550 affected = readPropertyChange(signal, interfaceName, propertyName, value);
551 }
552 catch (const Error& err)
553 {
554 callback(err, std::optional<property_value_t>{});
555 return;
556 }
557
558 if (affected)
559 callback(std::nullopt, std::move(value));
560 }
561 else
562 {
563 affected = readPropertyChange(signal, interfaceName, propertyName, value);
564
565 if (affected)
566 callback(std::move(value));
567 }
568 };
569 }
570
571 template <typename Value>
572 inline bool PropertyChangeSubscriber::readPropertyChange( Signal& signal
573 , const InterfaceName& interfaceName
574 , const PropertyName& propertyName
575 , std::optional<Value>& value )
576 {
577 std::string changedInterfaceName;
578 std::map<std::string, Variant> changedProperties;
579 std::vector<std::string> invalidatedProperties;
580 signal >> changedInterfaceName >> changedProperties >> invalidatedProperties;
581
582 if (changedInterfaceName != interfaceName)
583 return false;
584
585 if (auto it = changedProperties.find(propertyName); it != changedProperties.end())
586 {
587 value = it->second.get<Value>();
588 return true;
589 }
590
591 // Invalidated property comes without value
592 return std::find(invalidatedProperties.begin(), invalidatedProperties.end(), propertyName) != invalidatedProperties.end();
593 }
594
595 /*** -------------- ***/
596 /*** PropertyGetter ***/
597 /*** -------------- ***/
598
599 inline PropertyGetter::PropertyGetter(IProxy& proxy, std::string_view propertyName)
600 : proxy_(proxy)
601 , propertyName_(std::move(propertyName))
602 {
603 }
604
605 inline Variant PropertyGetter::onInterface(std::string_view interfaceName)
606 {
607 Variant var;
608 proxy_.callMethod("Get")
609 .onInterface(DBUS_PROPERTIES_INTERFACE_NAME)
610 .withArguments(interfaceName, propertyName_)
611 .storeResultsTo(var);
612 return var;
613 }
614
615 /*** ------------------- ***/
616 /*** AsyncPropertyGetter ***/
617 /*** ------------------- ***/
618
619 inline AsyncPropertyGetter::AsyncPropertyGetter(IProxy& proxy, std::string_view propertyName)
620 : proxy_(proxy)
621 , propertyName_(std::move(propertyName))
622 {
623 }
624
625 inline AsyncPropertyGetter& AsyncPropertyGetter::onInterface(std::string_view interfaceName)
626 {
627 interfaceName_ = std::move(interfaceName);
628
629 return *this;
630 }
631
632 template <typename Function>
633 auto AsyncPropertyGetter::makeReplyHandler(Function&& callback)
634 {
635 static_assert( has_error_param_v<Function>
636 , "Property get callback function must accept std::optional<Error> as its first parameter" );
637 // Function traits strip the std::optional<Error> first param (see TypeTraits.h),
638 // so the only remaining argument is the property value parameter.
639 static_assert( function_argument_count_v<Function> == 1
640 , "Property get callback function must accept std::optional<Error> and property value" );
641 using value_t = std::decay_t<function_argument_t<Function, 0>>;
642
643 if constexpr (std::is_same_v<value_t, Variant>)
644 return std::forward<Function>(callback);
645 else
646 return [callback = std::forward<Function>(callback)](std::optional<Error> error, Variant value)
647 {
648 if (error)
649 {
650 callback(std::move(error), value_t{});
651 return;
652 }
653
654 value_t typedValue{};
655 try
656 {
657 typedValue = value.get<value_t>();
658 }
659 catch (const Error& err)
660 {
661 // Pass type mismatch errors to the client via callback error parameter,
662 // the same way AsyncMethodInvoker handles reply deserialization errors.
663 callback(err, value_t{});
664 return;
665 }
666
667 callback(std::nullopt, std::move(typedValue));
668 };
669 }
670
671 template <typename Function>
672 PendingAsyncCall AsyncPropertyGetter::uponReplyInvoke(Function&& callback)
673 {
674 assert(!interfaceName_.empty()); // onInterface() must be placed/called prior to this function
675
676 return proxy_.callMethodAsync("Get")
677 .onInterface(DBUS_PROPERTIES_INTERFACE_NAME)
678 .withArguments(interfaceName_, propertyName_)
679 .uponReplyInvoke(makeReplyHandler(std::forward<Function>(callback)));
680 }
681
682 template <typename Function>
683 [[nodiscard]] Slot AsyncPropertyGetter::uponReplyInvoke(Function&& callback, return_slot_t)
684 {
685 assert(!interfaceName_.empty()); // onInterface() must be placed/called prior to this function
686
687 return proxy_.callMethodAsync("Get")
688 .onInterface(DBUS_PROPERTIES_INTERFACE_NAME)
689 .withArguments(interfaceName_, propertyName_)
690 .uponReplyInvoke(makeReplyHandler(std::forward<Function>(callback)), return_slot);
691 }
692
693 inline std::future<Variant> AsyncPropertyGetter::getResultAsFuture()
694 {
695 assert(!interfaceName_.empty()); // onInterface() must be placed/called prior to this function
696
697 return proxy_.callMethodAsync("Get")
698 .onInterface(DBUS_PROPERTIES_INTERFACE_NAME)
699 .withArguments(interfaceName_, propertyName_)
700 .getResultAsFuture<Variant>();
701 }
702
703 inline Awaitable<Variant> AsyncPropertyGetter::getResultAsAwaitable()
704 {
705 assert(!interfaceName_.empty()); // onInterface() must be placed/called prior to this function
706
707 return proxy_.callMethodAsync("Get")
708 .onInterface(DBUS_PROPERTIES_INTERFACE_NAME)
709 .withArguments(interfaceName_, propertyName_)
710 .getResultAsAwaitable<Variant>();
711 }
712
713 /*** -------------- ***/
714 /*** PropertySetter ***/
715 /*** -------------- ***/
716
717 inline PropertySetter::PropertySetter(IProxy& proxy, std::string_view propertyName)
718 : proxy_(proxy)
719 , propertyName_(std::move(propertyName))
720 {
721 }
722
723 inline PropertySetter& PropertySetter::onInterface(std::string_view interfaceName)
724 {
725 interfaceName_ = std::move(interfaceName);
726
727 return *this;
728 }
729
730 inline PropertySetter& PropertySetter::withTimeout(uint64_t usec)
731 {
732 timeout_ = usec;
733
734 return *this;
735 }
736
737 template <typename Rep, typename Period>
738 inline PropertySetter& PropertySetter::withTimeout(const std::chrono::duration<Rep, Period>& timeout)
739 {
740 auto microsecs = std::chrono::duration_cast<std::chrono::microseconds>(timeout);
741 return withTimeout(microsecs.count());
742 }
743
744 template <typename Value>
745 inline void PropertySetter::toValue(const Value& value)
746 {
747 PropertySetter::toValue(Variant{value});
748 }
749
750 template <typename Value>
751 inline void PropertySetter::toValue(const Value& value, dont_expect_reply_t)
752 {
753 PropertySetter::toValue(Variant{value}, dont_expect_reply);
754 }
755
756 inline void PropertySetter::toValue(const Variant& value)
757 {
758 assert(!interfaceName_.empty()); // onInterface() must be placed/called prior to this function
759
760 proxy_.callMethod("Set")
761 .onInterface(DBUS_PROPERTIES_INTERFACE_NAME)
762 .withTimeout(timeout_)
763 .withArguments(interfaceName_, propertyName_, value);
764 }
765
766 inline void PropertySetter::toValue(const Variant& value, dont_expect_reply_t)
767 {
768 assert(!interfaceName_.empty()); // onInterface() must be placed/called prior to this function
769
770 proxy_.callMethod("Set")
771 .onInterface(DBUS_PROPERTIES_INTERFACE_NAME)
772 .withTimeout(timeout_)
773 .withArguments(interfaceName_, propertyName_, value)
774 .dontExpectReply();
775 }
776
777 /*** ------------------- ***/
778 /*** AsyncPropertySetter ***/
779 /*** ------------------- ***/
780
781 inline AsyncPropertySetter::AsyncPropertySetter(IProxy& proxy, std::string_view propertyName)
782 : proxy_(proxy)
783 , propertyName_(propertyName)
784 {
785 }
786
787 inline AsyncPropertySetter& AsyncPropertySetter::onInterface(std::string_view interfaceName)
788 {
789 interfaceName_ = std::move(interfaceName);
790
791 return *this;
792 }
793
794 inline AsyncPropertySetter& AsyncPropertySetter::withTimeout(uint64_t usec)
795 {
796 timeout_ = usec;
797
798 return *this;
799 }
800
801 template <typename Rep, typename Period>
802 inline AsyncPropertySetter& AsyncPropertySetter::withTimeout(const std::chrono::duration<Rep, Period>& timeout)
803 {
804 auto microsecs = std::chrono::duration_cast<std::chrono::microseconds>(timeout);
805 return withTimeout(microsecs.count());
806 }
807
808 template <typename Value>
809 inline AsyncPropertySetter& AsyncPropertySetter::toValue(Value&& value)
810 {
811 return AsyncPropertySetter::toValue(Variant{std::forward<Value>(value)});
812 }
813
814 inline AsyncPropertySetter& AsyncPropertySetter::toValue(Variant value)
815 {
816 value_ = std::move(value);
817
818 return *this;
819 }
820
821 template <typename Function>
822 PendingAsyncCall AsyncPropertySetter::uponReplyInvoke(Function&& callback)
823 {
824 static_assert( std::is_invocable_r_v<void, Function, std::optional<Error>>
825 , "Property set callback function must accept std::optional<Error> only" );
826
827 assert(!interfaceName_.empty()); // onInterface() must be placed/called prior to this function
828
829 return proxy_.callMethodAsync("Set")
830 .onInterface(DBUS_PROPERTIES_INTERFACE_NAME)
831 .withTimeout(timeout_)
832 .withArguments(interfaceName_, propertyName_, std::move(value_))
833 .uponReplyInvoke(std::forward<Function>(callback));
834 }
835
836 template <typename Function>
837 [[nodiscard]] Slot AsyncPropertySetter::uponReplyInvoke(Function&& callback, return_slot_t)
838 {
839 static_assert( std::is_invocable_r_v<void, Function, std::optional<Error>>
840 , "Property set callback function must accept std::optional<Error> only" );
841
842 assert(!interfaceName_.empty()); // onInterface() must be placed/called prior to this function
843
844 return proxy_.callMethodAsync("Set")
845 .onInterface(DBUS_PROPERTIES_INTERFACE_NAME)
846 .withTimeout(timeout_)
847 .withArguments(interfaceName_, propertyName_, std::move(value_))
848 .uponReplyInvoke(std::forward<Function>(callback), return_slot);
849 }
850
851 inline std::future<void> AsyncPropertySetter::getResultAsFuture()
852 {
853 assert(!interfaceName_.empty()); // onInterface() must be placed/called prior to this function
854
855 return proxy_.callMethodAsync("Set")
856 .onInterface(DBUS_PROPERTIES_INTERFACE_NAME)
857 .withTimeout(timeout_)
858 .withArguments(interfaceName_, propertyName_, std::move(value_))
859 .getResultAsFuture<>();
860 }
861
862 inline Awaitable<void> AsyncPropertySetter::getResultAsAwaitable()
863 {
864 assert(!interfaceName_.empty()); // onInterface() must be placed/called prior to this function
865
866 return proxy_.callMethodAsync("Set")
867 .onInterface(DBUS_PROPERTIES_INTERFACE_NAME)
868 .withTimeout(timeout_)
869 .withArguments(interfaceName_, propertyName_, std::move(value_))
870 .getResultAsAwaitable<>();
871 }
872
873 /*** ------------------- ***/
874 /*** AllPropertiesGetter ***/
875 /*** ------------------- ***/
876
877 inline AllPropertiesGetter::AllPropertiesGetter(IProxy& proxy)
878 : proxy_(proxy)
879 {
880 }
881
882 inline std::map<PropertyName, Variant> AllPropertiesGetter::onInterface(std::string_view interfaceName)
883 {
884 std::map<PropertyName, Variant> props;
885 proxy_.callMethod("GetAll")
886 .onInterface(DBUS_PROPERTIES_INTERFACE_NAME)
887 .withArguments(std::move(interfaceName))
888 .storeResultsTo(props);
889 return props;
890 }
891
892 /*** ------------------------ ***/
893 /*** AsyncAllPropertiesGetter ***/
894 /*** ------------------------ ***/
895
896 inline AsyncAllPropertiesGetter::AsyncAllPropertiesGetter(IProxy& proxy)
897 : proxy_(proxy)
898 {
899 }
900
901 inline AsyncAllPropertiesGetter& AsyncAllPropertiesGetter::onInterface(std::string_view interfaceName)
902 {
903 interfaceName_ = std::move(interfaceName);
904
905 return *this;
906 }
907
908 template <typename Function>
909 PendingAsyncCall AsyncAllPropertiesGetter::uponReplyInvoke(Function&& callback)
910 {
911 static_assert( std::is_invocable_r_v<void, Function, std::optional<Error>, std::map<PropertyName, Variant>>
912 , "All properties get callback function must accept std::optional<Error> and a map of property names to their values" );
913
914 assert(!interfaceName_.empty()); // onInterface() must be placed/called prior to this function
915
916 return proxy_.callMethodAsync("GetAll")
917 .onInterface(DBUS_PROPERTIES_INTERFACE_NAME)
918 .withArguments(interfaceName_)
919 .uponReplyInvoke(std::forward<Function>(callback));
920 }
921
922 template <typename Function>
923 [[nodiscard]] Slot AsyncAllPropertiesGetter::uponReplyInvoke(Function&& callback, return_slot_t)
924 {
925 static_assert( std::is_invocable_r_v<void, Function, std::optional<Error>, std::map<PropertyName, Variant>>
926 , "All properties get callback function must accept std::optional<Error> and a map of property names to their values" );
927
928 assert(!interfaceName_.empty()); // onInterface() must be placed/called prior to this function
929
930 return proxy_.callMethodAsync("GetAll")
931 .onInterface(DBUS_PROPERTIES_INTERFACE_NAME)
932 .withArguments(interfaceName_)
933 .uponReplyInvoke(std::forward<Function>(callback), return_slot);
934 }
935
936 inline std::future<std::map<PropertyName, Variant>> AsyncAllPropertiesGetter::getResultAsFuture()
937 {
938 assert(!interfaceName_.empty()); // onInterface() must be placed/called prior to this function
939
940 return proxy_.callMethodAsync("GetAll")
941 .onInterface(DBUS_PROPERTIES_INTERFACE_NAME)
942 .withArguments(interfaceName_)
943 .getResultAsFuture<std::map<PropertyName, Variant>>();
944 }
945
946 inline Awaitable<std::map<PropertyName, Variant>> AsyncAllPropertiesGetter::getResultAsAwaitable()
947 {
948 assert(!interfaceName_.empty()); // onInterface() must be placed/called prior to this function
949
950 return proxy_.callMethodAsync("GetAll")
951 .onInterface(DBUS_PROPERTIES_INTERFACE_NAME)
952 .withArguments(interfaceName_)
953 .getResultAsAwaitable<std::map<PropertyName, Variant>>();
954 }
955
956} // namespace sdbus
957
958#endif /* SDBUS_CPP_CONVENIENCEAPICLASSES_INL_ */
Definition IObject.h:63