From 9ec7d6b8551291b961e3fdb0be849e4fa9f6a8a2 Mon Sep 17 00:00:00 2001 From: Lars Toenning Date: Sat, 26 Mar 2022 11:29:25 +0100 Subject: [PATCH] swift cleanup --- src/AIModel/AIManager.hxx | 5 +- src/AIModel/AISwiftAircraft.cpp | 2 +- src/AIModel/AISwiftAircraft.h | 4 +- src/Network/Swift/SwiftAircraftManager.cpp | 40 +- src/Network/Swift/SwiftAircraftManager.h | 25 +- src/Network/Swift/dbuscallbacks.h | 64 +-- src/Network/Swift/dbusconnection.cpp | 330 +++++++------- src/Network/Swift/dbusconnection.h | 134 +++--- src/Network/Swift/dbusdispatcher.cpp | 401 ++++++++--------- src/Network/Swift/dbusdispatcher.h | 142 +++--- src/Network/Swift/dbuserror.cpp | 16 +- src/Network/Swift/dbuserror.h | 56 ++- src/Network/Swift/dbusmessage.cpp | 480 ++++++++++----------- src/Network/Swift/dbusmessage.h | 135 +++--- src/Network/Swift/dbusobject.cpp | 166 ++++--- src/Network/Swift/dbusobject.h | 145 ++++--- src/Network/Swift/dbusserver.cpp | 146 ++++--- src/Network/Swift/dbusserver.h | 108 +++-- src/Network/Swift/plugin.cpp | 15 +- src/Network/Swift/plugin.h | 59 ++- src/Network/Swift/service.cpp | 445 +++++++++---------- src/Network/Swift/service.h | 12 +- src/Network/Swift/swift_connection.cxx | 5 - src/Network/Swift/traffic.cpp | 106 +++-- src/Network/Swift/traffic.h | 13 +- 25 files changed, 1496 insertions(+), 1558 deletions(-) diff --git a/src/AIModel/AIManager.hxx b/src/AIModel/AIManager.hxx index d74160df0..3e114c38c 100644 --- a/src/AIModel/AIManager.hxx +++ b/src/AIModel/AIManager.hxx @@ -25,8 +25,11 @@ #include #include -#include +#include +#include +#include #include +#include class FGAIBase; class FGAIThermal; diff --git a/src/AIModel/AISwiftAircraft.cpp b/src/AIModel/AISwiftAircraft.cpp index 1a588844f..0fb0212fa 100755 --- a/src/AIModel/AISwiftAircraft.cpp +++ b/src/AIModel/AISwiftAircraft.cpp @@ -33,7 +33,7 @@ FGAISwiftAircraft::FGAISwiftAircraft(const std::string& callsign, const std::str _searchOrder = ModelSearchOrder::PREFER_AI; } -void FGAISwiftAircraft::updatePosition(SGGeod& position, SGVec3& orientation, double groundspeed, bool initPos) +void FGAISwiftAircraft::updatePosition(const SGGeod &position, const SGVec3 &orientation, double groundspeed, bool initPos) { m_initPos = initPos; _setLatitude(position.getLatitudeDeg()); diff --git a/src/AIModel/AISwiftAircraft.h b/src/AIModel/AISwiftAircraft.h index a689bd6e4..3a10d28a0 100644 --- a/src/AIModel/AISwiftAircraft.h +++ b/src/AIModel/AISwiftAircraft.h @@ -25,8 +25,6 @@ #include "AIBaseAircraft.hxx" -using charPtr = const char*; - struct AircraftTransponder { AircraftTransponder(std::string callsign, int code, bool modeC, bool ident) @@ -76,7 +74,7 @@ public: string_view getTypeString() const override { return "swift"; } void update(double dt) override; - void updatePosition(SGGeod& position, SGVec3& orientation, double groundspeed, bool initPos); + void updatePosition(const SGGeod &position, const SGVec3 &orientation, double groundspeed, bool initPos); double getGroundElevation(const SGGeod& pos) const; void initProps(); void setPlaneSurface(const AircraftSurfaces& surfaces); diff --git a/src/Network/Swift/SwiftAircraftManager.cpp b/src/Network/Swift/SwiftAircraftManager.cpp index e32fd67ce..15c33b550 100644 --- a/src/Network/Swift/SwiftAircraftManager.cpp +++ b/src/Network/Swift/SwiftAircraftManager.cpp @@ -49,15 +49,12 @@ bool FGSwiftAircraftManager::addPlane(const std::string& callsign, const std::st return true; } -void FGSwiftAircraftManager::updatePlanes(std::vector callsigns, std::vector positions, std::vector orientations, std::vector groundspeeds, std::vector onGrounds) +void FGSwiftAircraftManager::updatePlanes(const std::vector& callsigns, const std::vector& positions, const std::vector& orientations, const std::vector& groundspeeds, const std::vector& onGrounds) { - - for (long unsigned int i = 0; i < callsigns.size(); i++) - { + for (long unsigned int i = 0; i < callsigns.size(); i++) { auto it = aircraftByCallsign.find(callsigns.at(i)); - if(it != aircraftByCallsign.end()) - { - it->second->updatePosition(positions.at(i), orientations.at(i), groundspeeds.at(i),true); + if (it != aircraftByCallsign.end()) { + it->second->updatePosition(positions.at(i), orientations.at(i), groundspeeds.at(i), true); } } } @@ -73,9 +70,9 @@ void FGSwiftAircraftManager::getRemoteAircraftData(std::vector& cal elevationsM.clear(); verticalOffsets.clear(); - for (const auto & requestedCallsign : requestedCallsigns) { + for (const auto& requestedCallsign : requestedCallsigns) { const auto it = aircraftByCallsign.find(requestedCallsign); - if(it == aircraftByCallsign.end()) { continue; } + if (it == aircraftByCallsign.end()) { continue; } const FGAISwiftAircraft* aircraft = it->second; assert(aircraft); @@ -93,14 +90,13 @@ void FGSwiftAircraftManager::getRemoteAircraftData(std::vector& cal longitudesDeg.push_back(lonDeg); elevationsM.push_back(groundElevation); verticalOffsets.push_back(0); - } + } } void FGSwiftAircraftManager::removePlane(const std::string& callsign) { auto it = aircraftByCallsign.find(callsign); - if(it != aircraftByCallsign.end()) - { + if (it != aircraftByCallsign.end()) { it->second->setDie(true); aircraftByCallsign.erase(it); } @@ -108,18 +104,16 @@ void FGSwiftAircraftManager::removePlane(const std::string& callsign) void FGSwiftAircraftManager::removeAllPlanes() { - for(auto it = aircraftByCallsign.begin(); it!= aircraftByCallsign.end();) - { + for (auto it = aircraftByCallsign.begin(); it != aircraftByCallsign.end();) { it->second->setDie(true); it = aircraftByCallsign.erase(it); } } -double FGSwiftAircraftManager::getElevationAtPosition(const std::string &callsign, const SGGeod& pos) const +double FGSwiftAircraftManager::getElevationAtPosition(const std::string& callsign, const SGGeod& pos) const { auto it = aircraftByCallsign.find(callsign); - if(it != aircraftByCallsign.end()) - { + if (it != aircraftByCallsign.end()) { return it->second->getGroundElevation(pos); } // Aircraft not found in list @@ -128,11 +122,9 @@ double FGSwiftAircraftManager::getElevationAtPosition(const std::string &callsig void FGSwiftAircraftManager::setPlanesTransponders(const std::vector& transponders) { - for (const auto & transponder : transponders) - { + for (const auto& transponder : transponders) { auto it = aircraftByCallsign.find(transponder.callsign); - if(it != aircraftByCallsign.end()) - { + if (it != aircraftByCallsign.end()) { it->second->setPlaneTransponder(transponder); } } @@ -140,11 +132,9 @@ void FGSwiftAircraftManager::setPlanesTransponders(const std::vector& surfaces) { - for (const auto & surface : surfaces) - { + for (const auto& surface : surfaces) { auto it = aircraftByCallsign.find(surface.callsign); - if(it != aircraftByCallsign.end()) - { + if (it != aircraftByCallsign.end()) { it->second->setPlaneSurface(surface); } } diff --git a/src/Network/Swift/SwiftAircraftManager.h b/src/Network/Swift/SwiftAircraftManager.h index 92dbfb19c..8b9430cd4 100644 --- a/src/Network/Swift/SwiftAircraftManager.h +++ b/src/Network/Swift/SwiftAircraftManager.h @@ -1,5 +1,5 @@ // SwiftAircraftManager.h - Manger class for aircraft generated for swift -// +// // Copyright (C) 2019 - swift Project Community / Contributors (http://swift-project.org/) // Adapted to Flightgear by Lars Toenning // @@ -17,12 +17,12 @@ // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -#include -#include #include +#include +#include -#include #include +#include #ifndef FGSWIFTAIRCRAFTMANAGER_H #define FGSWIFTAIRCRAFTMANAGER_H @@ -34,20 +34,19 @@ class FGSwiftAircraftManager public: FGSwiftAircraftManager(); ~FGSwiftAircraftManager(); - bool addPlane(const std::string& callsign, const std::string& modelString); - void updatePlanes(std::vector callsigns, std::vector positions, std::vector orientations, std::vector groundspeeds, std::vector onGrounds); - void getRemoteAircraftData(std::vector& callsigns, std::vector& latitudesDeg, std::vector& longitudesDeg, - std::vector& elevationsM, std::vector& verticalOffsets) const; - void removePlane(const std::string& callsign); - void removeAllPlanes(); + bool addPlane(const std::string& callsign, const std::string& modelString); + void updatePlanes(const std::vector& callsigns, const std::vector& positions, const std::vector& orientations, const std::vector& groundspeeds, const std::vector& onGrounds); + void getRemoteAircraftData(std::vector& callsigns, std::vector& latitudesDeg, std::vector& longitudesDeg, + std::vector& elevationsM, std::vector& verticalOffsets) const; + void removePlane(const std::string& callsign); + void removeAllPlanes(); void setPlanesTransponders(const std::vector& transponders); - double getElevationAtPosition(const std::string &callsign, const SGGeod& pos) const; - bool isInitialized() const; + double getElevationAtPosition(const std::string& callsign, const SGGeod& pos) const; + bool isInitialized() const; void setPlanesSurfaces(const std::vector& surfaces); private: std::unordered_map aircraftByCallsign; bool m_initialized = false; - }; #endif \ No newline at end of file diff --git a/src/Network/Swift/dbuscallbacks.h b/src/Network/Swift/dbuscallbacks.h index 5d3f1de6b..697576f57 100644 --- a/src/Network/Swift/dbuscallbacks.h +++ b/src/Network/Swift/dbuscallbacks.h @@ -1,5 +1,5 @@ -// dbuscallbacks.h -// +// dbuscallbacks.h +// // Copyright (C) 2019 - swift Project Community / Contributors (http://swift-project.org/) // Adapted to Flightgear by Lars Toenning // @@ -23,42 +23,42 @@ #include #include -namespace FGSwiftBus +namespace FGSwiftBus { +//! \cond PRIVATE +template +class DBusAsyncCallbacks { - //! \cond PRIVATE - template - class DBusAsyncCallbacks +public: + DBusAsyncCallbacks() = default; + DBusAsyncCallbacks(const std::function& add, + const std::function& remove, + const std::function& toggled) + : m_addHandler(add), m_removeHandler(remove), m_toggledHandler(toggled) { - public: - DBusAsyncCallbacks() = default; - DBusAsyncCallbacks(const std::function &add, - const std::function &remove, - const std::function &toggled) - : m_addHandler(add), m_removeHandler(remove), m_toggledHandler(toggled) - { } + } - static dbus_bool_t add(T *watch, void *refcon) - { - return static_cast(refcon)->m_addHandler(watch); - } + static dbus_bool_t add(T* watch, void* refcon) + { + return static_cast(refcon)->m_addHandler(watch); + } - static void remove(T *watch, void *refcon) - { - return static_cast(refcon)->m_removeHandler(watch); - } + static void remove(T* watch, void* refcon) + { + return static_cast(refcon)->m_removeHandler(watch); + } - static void toggled(T *watch, void *refcon) - { - return static_cast(refcon)->m_toggledHandler(watch); - } + static void toggled(T* watch, void* refcon) + { + return static_cast(refcon)->m_toggledHandler(watch); + } - private: - std::function m_addHandler; - std::function m_removeHandler; - std::function m_toggledHandler; - }; - //! \endcond +private: + std::function m_addHandler; + std::function m_removeHandler; + std::function m_toggledHandler; +}; +//! \endcond -} +} // namespace FGSwiftBus #endif // guard diff --git a/src/Network/Swift/dbusconnection.cpp b/src/Network/Swift/dbusconnection.cpp index 91fbd1062..c6f2af680 100644 --- a/src/Network/Swift/dbusconnection.cpp +++ b/src/Network/Swift/dbusconnection.cpp @@ -1,7 +1,5 @@ -#include - -// dbusconnection.cpp -// +// dbusconnection.cpp +// // Copyright (C) 2019 - swift Project Community / Contributors (http://swift-project.org/) // Adapted to Flightgear by Lars Toenning // @@ -26,170 +24,164 @@ #include #include -namespace FGSwiftBus +namespace FGSwiftBus { + +CDBusConnection::CDBusConnection() { - - CDBusConnection::CDBusConnection() - { - dbus_threads_init_default(); - } - - CDBusConnection::CDBusConnection(DBusConnection *connection) - { - m_connection.reset(connection); - dbus_connection_ref(connection); - // Don't exit application, if the connection is disconnected - dbus_connection_set_exit_on_disconnect(connection, false); - dbus_connection_add_filter(connection, filterDisconnectedFunction, this, nullptr); - } - - CDBusConnection::~CDBusConnection() - { - close(); - if (m_connection) { dispatch(); } // dispatch is virtual, but safe to call in dtor, as it's declared final - if (m_dispatcher) { m_dispatcher->remove(this); } - } - - bool CDBusConnection::connect(BusType type) - { - assert(type == SessionBus); - DBusError error; - dbus_error_init(&error); - - DBusBusType dbusBusType; - switch (type) - { - case SessionBus: dbusBusType = DBUS_BUS_SESSION; break; - } - - m_connection.reset(dbus_bus_get_private(dbusBusType, &error)); - if (dbus_error_is_set(&error)) - { - m_lastError = CDBusError(&error); - return false; - } - - // Don't exit application, if the connection is disconnected - dbus_connection_set_exit_on_disconnect(m_connection.get(), false); - return true; - } - - void CDBusConnection::setDispatcher(CDBusDispatcher *dispatcher) - { - assert(dispatcher); - - m_dispatcher = dispatcher; - - m_dispatcher->add(this); - - dbus_connection_set_watch_functions( - m_connection.get(), - dispatcher->m_watchCallbacks.add, - dispatcher->m_watchCallbacks.remove, - dispatcher->m_watchCallbacks.toggled, - &dispatcher->m_watchCallbacks, nullptr); - - dbus_connection_set_timeout_functions( - m_connection.get(), - dispatcher->m_timeoutCallbacks.add, - dispatcher->m_timeoutCallbacks.remove, - dispatcher->m_timeoutCallbacks.toggled, - &dispatcher->m_timeoutCallbacks, nullptr); - } - - void CDBusConnection::requestName(const std::string &name) - { - DBusError error; - dbus_error_init(&error); - dbus_bus_request_name(m_connection.get(), name.c_str(), 0, &error); - } - - bool CDBusConnection::isConnected() const - { - return m_connection && dbus_connection_get_is_connected(m_connection.get()); - } - - void CDBusConnection::registerDisconnectedCallback(CDBusObject *obj, DisconnectedCallback func) - { - m_disconnectedCallbacks[obj] = func; - } - - void CDBusConnection::unregisterDisconnectedCallback(CDBusObject *obj) - { - auto it = m_disconnectedCallbacks.find(obj); - if (it == m_disconnectedCallbacks.end()) { return; } - m_disconnectedCallbacks.erase(it); - } - - void CDBusConnection::registerObjectPath(CDBusObject *object, const std::string &interfaceName, const std::string &objectPath, const DBusObjectPathVTable &dbusObjectPathVTable) - { - (void) interfaceName; - if (!m_connection) { return; } - - dbus_connection_try_register_object_path(m_connection.get(), objectPath.c_str(), &dbusObjectPathVTable, object, nullptr); - } - - void CDBusConnection::sendMessage(const CDBusMessage &message) - { - if (!isConnected()) { return; } - dbus_uint32_t serial = message.getSerial(); - dbus_connection_send(m_connection.get(), message.m_message, &serial); - } - - void CDBusConnection::close() - { - if (m_connection) { dbus_connection_close(m_connection.get()); } - } - - void CDBusConnection::dispatch() - { - dbus_connection_ref(m_connection.get()); - if (dbus_connection_get_dispatch_status(m_connection.get()) == DBUS_DISPATCH_DATA_REMAINS) - { - while (dbus_connection_dispatch(m_connection.get()) == DBUS_DISPATCH_DATA_REMAINS); - } - dbus_connection_unref(m_connection.get()); - } - - void CDBusConnection::setDispatchStatus(DBusConnection *connection, DBusDispatchStatus status) - { - if (dbus_connection_get_is_connected(connection) == FALSE) { return; } - - switch (status) - { - case DBUS_DISPATCH_DATA_REMAINS: - //m_dispatcher->add(this); - break; - case DBUS_DISPATCH_COMPLETE: - case DBUS_DISPATCH_NEED_MEMORY: - break; - } - } - - void CDBusConnection::setDispatchStatus(DBusConnection *connection, DBusDispatchStatus status, void *data) - { - auto *obj = static_cast(data); - obj->setDispatchStatus(connection, status); - } - - DBusHandlerResult CDBusConnection::filterDisconnectedFunction(DBusConnection *connection, DBusMessage *message, void *data) - { - (void)connection; // unused - - auto *obj = static_cast(data); - - DBusError err; - dbus_error_init(&err); - - if (dbus_message_is_signal (message, DBUS_INTERFACE_LOCAL, "Disconnected")) - { - for (auto it = obj->m_disconnectedCallbacks.begin(); it != obj->m_disconnectedCallbacks.end(); ++it) - { - it->second(); - } - return DBUS_HANDLER_RESULT_HANDLED; - } - return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; - } - + dbus_threads_init_default(); } + +CDBusConnection::CDBusConnection(DBusConnection* connection) +{ + m_connection.reset(connection); + dbus_connection_ref(connection); + // Don't exit application, if the connection is disconnected + dbus_connection_set_exit_on_disconnect(connection, false); + dbus_connection_add_filter(connection, filterDisconnectedFunction, this, nullptr); +} + +CDBusConnection::~CDBusConnection() +{ + close(); + if (m_connection) { dispatch(); } // dispatch is virtual, but safe to call in dtor, as it's declared final + if (m_dispatcher) { m_dispatcher->remove(this); } +} + +bool CDBusConnection::connect(BusType type) +{ + assert(type == SessionBus); + DBusError error; + dbus_error_init(&error); + + DBusBusType dbusBusType; + switch (type) { + case SessionBus: dbusBusType = DBUS_BUS_SESSION; break; + } + + m_connection.reset(dbus_bus_get_private(dbusBusType, &error)); + if (dbus_error_is_set(&error)) { + m_lastError = CDBusError(&error); + return false; + } + + // Don't exit application, if the connection is disconnected + dbus_connection_set_exit_on_disconnect(m_connection.get(), false); + return true; +} + +void CDBusConnection::setDispatcher(CDBusDispatcher* dispatcher) +{ + assert(dispatcher); + + m_dispatcher = dispatcher; + + m_dispatcher->add(this); + + dbus_connection_set_watch_functions( + m_connection.get(), + dispatcher->m_watchCallbacks.add, + dispatcher->m_watchCallbacks.remove, + dispatcher->m_watchCallbacks.toggled, + &dispatcher->m_watchCallbacks, nullptr); + + dbus_connection_set_timeout_functions( + m_connection.get(), + dispatcher->m_timeoutCallbacks.add, + dispatcher->m_timeoutCallbacks.remove, + dispatcher->m_timeoutCallbacks.toggled, + &dispatcher->m_timeoutCallbacks, nullptr); +} + +void CDBusConnection::requestName(const std::string& name) +{ + DBusError error; + dbus_error_init(&error); + dbus_bus_request_name(m_connection.get(), name.c_str(), 0, &error); +} + +bool CDBusConnection::isConnected() const +{ + return m_connection && dbus_connection_get_is_connected(m_connection.get()); +} + +void CDBusConnection::registerDisconnectedCallback(CDBusObject* obj, DisconnectedCallback func) +{ + m_disconnectedCallbacks[obj] = func; +} + +void CDBusConnection::unregisterDisconnectedCallback(CDBusObject* obj) +{ + auto it = m_disconnectedCallbacks.find(obj); + if (it == m_disconnectedCallbacks.end()) { return; } + m_disconnectedCallbacks.erase(it); +} + +void CDBusConnection::registerObjectPath(CDBusObject* object, const std::string& interfaceName, const std::string& objectPath, const DBusObjectPathVTable& dbusObjectPathVTable) +{ + (void)interfaceName; + if (!m_connection) { return; } + + dbus_connection_try_register_object_path(m_connection.get(), objectPath.c_str(), &dbusObjectPathVTable, object, nullptr); +} + +void CDBusConnection::sendMessage(const CDBusMessage& message) +{ + if (!isConnected()) { return; } + dbus_uint32_t serial = message.getSerial(); + dbus_connection_send(m_connection.get(), message.m_message, &serial); +} + +void CDBusConnection::close() +{ + if (m_connection) { dbus_connection_close(m_connection.get()); } +} + +void CDBusConnection::dispatch() +{ + dbus_connection_ref(m_connection.get()); + if (dbus_connection_get_dispatch_status(m_connection.get()) == DBUS_DISPATCH_DATA_REMAINS) { + while (dbus_connection_dispatch(m_connection.get()) == DBUS_DISPATCH_DATA_REMAINS) + ; + } + dbus_connection_unref(m_connection.get()); +} + +void CDBusConnection::setDispatchStatus(DBusConnection* connection, DBusDispatchStatus status) +{ + if (dbus_connection_get_is_connected(connection) == FALSE) { return; } + + switch (status) { + case DBUS_DISPATCH_DATA_REMAINS: + //m_dispatcher->add(this); + break; + case DBUS_DISPATCH_COMPLETE: + case DBUS_DISPATCH_NEED_MEMORY: + break; + } +} + +void CDBusConnection::setDispatchStatus(DBusConnection* connection, DBusDispatchStatus status, void* data) +{ + auto* obj = static_cast(data); + obj->setDispatchStatus(connection, status); +} + +DBusHandlerResult CDBusConnection::filterDisconnectedFunction(DBusConnection* connection, DBusMessage* message, void* data) +{ + (void)connection; // unused + + auto* obj = static_cast(data); + + DBusError err; + dbus_error_init(&err); + + if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) { + for (auto it = obj->m_disconnectedCallbacks.begin(); it != obj->m_disconnectedCallbacks.end(); ++it) { + it->second(); + } + return DBUS_HANDLER_RESULT_HANDLED; + } + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; +} + +} // namespace FGSwiftBus diff --git a/src/Network/Swift/dbusconnection.h b/src/Network/Swift/dbusconnection.h index fdf737b23..656472fd3 100644 --- a/src/Network/Swift/dbusconnection.h +++ b/src/Network/Swift/dbusconnection.h @@ -1,5 +1,5 @@ // dbusconnection.h -// +// // Copyright (C) 2019 - swift Project Community / Contributors (http://swift-project.org/) // Adapted to Flightgear by Lars Toenning // @@ -20,100 +20,98 @@ #ifndef BLACKSIM_FGSWIFTBUS_DBUSCONNECTION_H #define BLACKSIM_FGSWIFTBUS_DBUSCONNECTION_H -#include "dbusmessage.h" -#include "dbuserror.h" #include "dbuscallbacks.h" #include "dbusdispatcher.h" +#include "dbuserror.h" +#include "dbusmessage.h" -#include #include +#include +#include #include #include -#include -namespace FGSwiftBus +namespace FGSwiftBus { + +class CDBusObject; + +//! DBus connection +class CDBusConnection : public IDispatchable { +public: + //! Bus type + enum BusType { SessionBus }; - class CDBusObject; + //! Disconnect Callback + using DisconnectedCallback = std::function; - //! DBus connection - class CDBusConnection : public IDispatchable - { - public: - //! Bus type - enum BusType { SessionBus }; + //! Default constructor + CDBusConnection(); - //! Disconnect Callback - using DisconnectedCallback = std::function; + //! Constructor + CDBusConnection(DBusConnection* connection); - //! Default constructor - CDBusConnection(); + //! Destructor + ~CDBusConnection() override; - //! Constructor - CDBusConnection(DBusConnection *connection); + // The ones below are not implemented yet. + // If you need them, make sure that connection reference count is correct + CDBusConnection(const CDBusConnection&) = delete; + CDBusConnection& operator=(const CDBusConnection&) = delete; - //! Destructor - ~CDBusConnection() override; + //! Connect to bus + bool connect(BusType type); - // The ones below are not implemented yet. - // If you need them, make sure that connection reference count is correct - CDBusConnection(const CDBusConnection &) = delete; - CDBusConnection &operator=(const CDBusConnection &) = delete; + //! Set dispatcher + void setDispatcher(CDBusDispatcher* dispatcher); - //! Connect to bus - bool connect(BusType type); + //! Request name to the bus + void requestName(const std::string& name); - //! Set dispatcher - void setDispatcher(CDBusDispatcher *dispatcher); + //! Is connected? + bool isConnected() const; - //! Request name to the bus - void requestName(const std::string &name); + //! Register a disconnected callback + void registerDisconnectedCallback(CDBusObject* obj, DisconnectedCallback func); - //! Is connected? - bool isConnected() const; + //! Register a disconnected callback + void unregisterDisconnectedCallback(CDBusObject* obj); - //! Register a disconnected callback - void registerDisconnectedCallback(CDBusObject *obj, DisconnectedCallback func); + //! Register DBus object with interfaceName and objectPath. + //! \param object + //! \param interfaceName + //! \param objectPath + //! \param dbusObjectPathVTable Virtual table handling DBus messages + void registerObjectPath(CDBusObject* object, const std::string& interfaceName, const std::string& objectPath, const DBusObjectPathVTable& dbusObjectPathVTable); - //! Register a disconnected callback - void unregisterDisconnectedCallback(CDBusObject *obj); + //! Send message to bus + void sendMessage(const CDBusMessage& message); - //! Register DBus object with interfaceName and objectPath. - //! \param object - //! \param interfaceName - //! \param objectPath - //! \param dbusObjectPathVTable Virtual table handling DBus messages - void registerObjectPath(CDBusObject *object, const std::string &interfaceName, const std::string &objectPath, const DBusObjectPathVTable &dbusObjectPathVTable); + //! Close connection + void close(); - //! Send message to bus - void sendMessage(const CDBusMessage &message); + //! Get the last error + CDBusError lastError() const { return m_lastError; } - //! Close connection - void close(); +protected: + // cppcheck-suppress virtualCallInConstructor + virtual void dispatch() override final; - //! Get the last error - CDBusError lastError() const { return m_lastError; } +private: + void setDispatchStatus(DBusConnection* connection, DBusDispatchStatus status); + static void setDispatchStatus(DBusConnection* connection, DBusDispatchStatus status, void* data); + static DBusHandlerResult filterDisconnectedFunction(DBusConnection* connection, DBusMessage* message, void* data); - protected: - // cppcheck-suppress virtualCallInConstructor - virtual void dispatch() override final; - - private: - void setDispatchStatus(DBusConnection *connection, DBusDispatchStatus status); - static void setDispatchStatus(DBusConnection *connection, DBusDispatchStatus status, void *data); - static DBusHandlerResult filterDisconnectedFunction(DBusConnection *connection, DBusMessage *message, void *data); - - struct DBusConnectionDeleter - { - void operator()(DBusConnection *obj) const { dbus_connection_unref(obj); } - }; - - CDBusDispatcher *m_dispatcher = nullptr; - std::unique_ptr m_connection; - CDBusError m_lastError; - std::unordered_map m_disconnectedCallbacks; + struct DBusConnectionDeleter { + void operator()(DBusConnection* obj) const { dbus_connection_unref(obj); } }; -} + CDBusDispatcher* m_dispatcher = nullptr; + std::unique_ptr m_connection; + CDBusError m_lastError; + std::unordered_map m_disconnectedCallbacks; +}; + +} // namespace FGSwiftBus #endif // guard diff --git a/src/Network/Swift/dbusdispatcher.cpp b/src/Network/Swift/dbusdispatcher.cpp index 8a00b9312..704daeee3 100644 --- a/src/Network/Swift/dbusdispatcher.cpp +++ b/src/Network/Swift/dbusdispatcher.cpp @@ -22,233 +22,234 @@ #include namespace { // anonymosu namespace - + template -std::unique_ptr our_make_unique(Args&&... args) { +std::unique_ptr our_make_unique(Args&&... args) +{ return std::unique_ptr(new T(std::forward(args)...)); } } // end of anonymous namespace -namespace FGSwiftBus +namespace FGSwiftBus { + +//! Functor struct deleteing an event +struct EventDeleter { + //! Delete functor + void operator()(event* obj) const + { + event_del(obj); + event_free(obj); + } +}; + +//! DBus watch handler +class WatchHandler { - - //! Functor struct deleteing an event - struct EventDeleter +public: + //! Constructor + WatchHandler(event_base* base, DBusWatch* watch) + : m_base(base), m_watch(watch) { - //! Delete functor - void operator()(event *obj) const - { - event_del(obj); - event_free(obj); - } - }; + const unsigned int flags = dbus_watch_get_flags(watch); + short monitoredEvents = EV_PERSIST; - //! DBus watch handler - class WatchHandler - { - public: - //! Constructor - WatchHandler(event_base *base, DBusWatch *watch) - : m_base(base), m_watch(watch) - { - const unsigned int flags = dbus_watch_get_flags(watch); - short monitoredEvents = EV_PERSIST; + if (flags & DBUS_WATCH_READABLE) { monitoredEvents |= EV_READ; } + if (flags & DBUS_WATCH_WRITABLE) { monitoredEvents |= EV_WRITE; } - if (flags & DBUS_WATCH_READABLE) { monitoredEvents |= EV_READ; } - if (flags & DBUS_WATCH_WRITABLE) { monitoredEvents |= EV_WRITE; } - - const int fd = dbus_watch_get_unix_fd(watch); - m_event.reset(event_new(m_base, fd, monitoredEvents, callback, this)); - event_add(m_event.get(), nullptr); - } - - //! Get DBus watch - DBusWatch *getWatch() { return m_watch; } - - //! Get DBus watch - const DBusWatch *getWatch() const { return m_watch; } - - private: - //! Event callback - static void callback(evutil_socket_t fd, short event, void *data) - { - (void) fd; // Not really unused, but GCC/Clang still complain about it. - auto *watchHandler = static_cast(data); - - unsigned int flags = 0; - if (event & EV_READ) { flags |= DBUS_WATCH_READABLE; } - if (event & EV_WRITE) { flags |= DBUS_WATCH_WRITABLE; } - dbus_watch_handle(watchHandler->m_watch, flags); - } - - event_base *m_base = nullptr; - std::unique_ptr m_event; - DBusWatch *m_watch = nullptr; - }; - - //! DBus timeout handler - class TimeoutHandler - { - public: - //! Constructor - TimeoutHandler(event_base *base, DBusTimeout *timeout) - : m_base(base), m_timeout(timeout) - { - timeval timer; - const int interval = dbus_timeout_get_interval(timeout); - timer.tv_sec = interval / 1000; - timer.tv_usec = (interval % 1000) * 1000; - - m_event.reset(evtimer_new(m_base, callback, this)); - evtimer_add(m_event.get(), &timer); - } - - //! Get DBus timeout - const DBusTimeout *getTimeout() const { return m_timeout; } - - private: - //! Event callback - static void callback(evutil_socket_t fd, short event, void *data) - { - (void) fd; // unused - (void) event; // unused - auto *timeoutHandler = static_cast(data); - dbus_timeout_handle(timeoutHandler->m_timeout); - } - - event_base *m_base = nullptr; - std::unique_ptr m_event; - DBusTimeout *m_timeout = nullptr; - }; - - //! Generic Timer - class Timer - { - public: - Timer() = default; - //! Constructor - Timer(event_base *base, const timeval &timeout, const std::function &func) - : m_base(base), m_func(func) - { - m_event.reset(evtimer_new(m_base, callback, this)); - evtimer_add(m_event.get(), &timeout); - } - - private: - //! Event callback - static void callback(evutil_socket_t fd, short event, void *data) - { - (void) fd; // unused - (void) event; // unused - auto *timer = static_cast(data); - timer->m_func(); - delete timer; - } - - event_base *m_base = nullptr; - std::unique_ptr m_event; - std::function m_func; - }; - - CDBusDispatcher::CDBusDispatcher() : - m_eventBase(event_base_new()) - { - using namespace std::placeholders; - m_watchCallbacks = WatchCallbacks(std::bind(&CDBusDispatcher::dbusAddWatch, this, _1), - std::bind(&CDBusDispatcher::dbusRemoveWatch, this, _1), - std::bind(&CDBusDispatcher::dbusWatchToggled, this, _1)); - - m_timeoutCallbacks = TimeoutCallbacks(std::bind(&CDBusDispatcher::dbusAddTimeout, this, _1), - std::bind(&CDBusDispatcher::dbusRemoveTimeout, this, _1), - std::bind(&CDBusDispatcher::dbusTimeoutToggled, this, _1)); + const int fd = dbus_watch_get_unix_fd(watch); + m_event.reset(event_new(m_base, fd, monitoredEvents, callback, this)); + event_add(m_event.get(), nullptr); } - CDBusDispatcher::~CDBusDispatcher() + //! Get DBus watch + DBusWatch* getWatch() { return m_watch; } + + //! Get DBus watch + const DBusWatch* getWatch() const { return m_watch; } + +private: + //! Event callback + static void callback(evutil_socket_t fd, short event, void* data) { + (void)fd; // Not really unused, but GCC/Clang still complain about it. + auto* watchHandler = static_cast(data); + + unsigned int flags = 0; + if (event & EV_READ) { flags |= DBUS_WATCH_READABLE; } + if (event & EV_WRITE) { flags |= DBUS_WATCH_WRITABLE; } + dbus_watch_handle(watchHandler->m_watch, flags); } - void CDBusDispatcher::add(IDispatchable *dispatchable) + event_base* m_base = nullptr; + std::unique_ptr m_event; + DBusWatch* m_watch = nullptr; +}; + +//! DBus timeout handler +class TimeoutHandler +{ +public: + //! Constructor + TimeoutHandler(event_base* base, DBusTimeout* timeout) + : m_base(base), m_timeout(timeout) { - m_dispatchList.push_back(dispatchable); + timeval timer; + const int interval = dbus_timeout_get_interval(timeout); + timer.tv_sec = interval / 1000; + timer.tv_usec = (interval % 1000) * 1000; + + m_event.reset(evtimer_new(m_base, callback, this)); + evtimer_add(m_event.get(), &timer); } - void CDBusDispatcher::remove(IDispatchable *dispatchable) + //! Get DBus timeout + const DBusTimeout* getTimeout() const { return m_timeout; } + +private: + //! Event callback + static void callback(evutil_socket_t fd, short event, void* data) { - auto it = std::find(m_dispatchList.begin(), m_dispatchList.end(), dispatchable); - if (it != m_dispatchList.end()) { m_dispatchList.erase(it); } + (void)fd; // unused + (void)event; // unused + auto* timeoutHandler = static_cast(data); + dbus_timeout_handle(timeoutHandler->m_timeout); } - void CDBusDispatcher::waitAndRun() + event_base* m_base = nullptr; + std::unique_ptr m_event; + DBusTimeout* m_timeout = nullptr; +}; + +//! Generic Timer +class Timer +{ +public: + Timer() = default; + //! Constructor + Timer(event_base* base, const timeval& timeout, const std::function& func) + : m_base(base), m_func(func) { - if (!m_eventBase) { return; } - event_base_dispatch(m_eventBase.get()); + m_event.reset(evtimer_new(m_base, callback, this)); + evtimer_add(m_event.get(), &timeout); } - void CDBusDispatcher::runOnce() +private: + //! Event callback + static void callback(evutil_socket_t fd, short event, void* data) { - if (!m_eventBase) { return; } - event_base_loop(m_eventBase.get(), EVLOOP_NONBLOCK); - dispatch(); + (void)fd; // unused + (void)event; // unused + auto* timer = static_cast(data); + timer->m_func(); + delete timer; } - void CDBusDispatcher::dispatch() - { - if (m_dispatchList.empty()) { return; } + event_base* m_base = nullptr; + std::unique_ptr m_event; + std::function m_func; +}; - for (IDispatchable *dispatchable : m_dispatchList) - { - dispatchable->dispatch(); - } - } - - dbus_bool_t CDBusDispatcher::dbusAddWatch(DBusWatch *watch) - { - if (dbus_watch_get_enabled(watch) == FALSE) { return true; } - - int fd = dbus_watch_get_unix_fd(watch); - m_watchers.emplace(fd, our_make_unique(m_eventBase.get(), watch)); - return true; - } - - void CDBusDispatcher::dbusRemoveWatch(DBusWatch *watch) - { - for (auto it = m_watchers.begin(); it != m_watchers.end();) - { - if (it->second->getWatch() == watch) { it = m_watchers.erase(it); } - else { ++it; } - } - } - - void CDBusDispatcher::dbusWatchToggled(DBusWatch *watch) - { - if (dbus_watch_get_enabled(watch) == TRUE) { dbusAddWatch(watch); } - else { dbusRemoveWatch(watch); } - } - - dbus_bool_t CDBusDispatcher::dbusAddTimeout(DBusTimeout *timeout) - { - if (dbus_timeout_get_enabled(timeout) == FALSE) { return TRUE; } - m_timeouts.emplace_back(new TimeoutHandler(m_eventBase.get(), timeout)); - return true; - } - - void CDBusDispatcher::dbusRemoveTimeout(DBusTimeout *timeout) - { - auto predicate = [timeout](const std::unique_ptr &ptr) - { - return ptr->getTimeout() == timeout; - }; - - m_timeouts.erase(std::remove_if(m_timeouts.begin(), m_timeouts.end(), predicate), m_timeouts.end()); - } - - void CDBusDispatcher::dbusTimeoutToggled(DBusTimeout *timeout) - { - if (dbus_timeout_get_enabled(timeout) == TRUE) - dbusAddTimeout(timeout); - else - dbusRemoveTimeout(timeout); - } +CDBusDispatcher::CDBusDispatcher() : m_eventBase(event_base_new()) +{ + using namespace std::placeholders; + m_watchCallbacks = WatchCallbacks(std::bind(&CDBusDispatcher::dbusAddWatch, this, _1), + std::bind(&CDBusDispatcher::dbusRemoveWatch, this, _1), + std::bind(&CDBusDispatcher::dbusWatchToggled, this, _1)); + m_timeoutCallbacks = TimeoutCallbacks(std::bind(&CDBusDispatcher::dbusAddTimeout, this, _1), + std::bind(&CDBusDispatcher::dbusRemoveTimeout, this, _1), + std::bind(&CDBusDispatcher::dbusTimeoutToggled, this, _1)); } + +CDBusDispatcher::~CDBusDispatcher() +{ +} + +void CDBusDispatcher::add(IDispatchable* dispatchable) +{ + m_dispatchList.push_back(dispatchable); +} + +void CDBusDispatcher::remove(IDispatchable* dispatchable) +{ + auto it = std::find(m_dispatchList.begin(), m_dispatchList.end(), dispatchable); + if (it != m_dispatchList.end()) { m_dispatchList.erase(it); } +} + +void CDBusDispatcher::waitAndRun() +{ + if (!m_eventBase) { return; } + event_base_dispatch(m_eventBase.get()); +} + +void CDBusDispatcher::runOnce() +{ + if (!m_eventBase) { return; } + event_base_loop(m_eventBase.get(), EVLOOP_NONBLOCK); + dispatch(); +} + +void CDBusDispatcher::dispatch() +{ + if (m_dispatchList.empty()) { return; } + + for (IDispatchable* dispatchable : m_dispatchList) { + dispatchable->dispatch(); + } +} + +dbus_bool_t CDBusDispatcher::dbusAddWatch(DBusWatch* watch) +{ + if (dbus_watch_get_enabled(watch) == FALSE) { return true; } + + int fd = dbus_watch_get_unix_fd(watch); + m_watchers.emplace(fd, our_make_unique(m_eventBase.get(), watch)); + return true; +} + +void CDBusDispatcher::dbusRemoveWatch(DBusWatch* watch) +{ + for (auto it = m_watchers.begin(); it != m_watchers.end();) { + if (it->second->getWatch() == watch) { + it = m_watchers.erase(it); + } else { + ++it; + } + } +} + +void CDBusDispatcher::dbusWatchToggled(DBusWatch* watch) +{ + if (dbus_watch_get_enabled(watch) == TRUE) { + dbusAddWatch(watch); + } else { + dbusRemoveWatch(watch); + } +} + +dbus_bool_t CDBusDispatcher::dbusAddTimeout(DBusTimeout* timeout) +{ + if (dbus_timeout_get_enabled(timeout) == FALSE) { return TRUE; } + m_timeouts.emplace_back(new TimeoutHandler(m_eventBase.get(), timeout)); + return true; +} + +void CDBusDispatcher::dbusRemoveTimeout(DBusTimeout* timeout) +{ + auto predicate = [timeout](const std::unique_ptr& ptr) { + return ptr->getTimeout() == timeout; + }; + + m_timeouts.erase(std::remove_if(m_timeouts.begin(), m_timeouts.end(), predicate), m_timeouts.end()); +} + +void CDBusDispatcher::dbusTimeoutToggled(DBusTimeout* timeout) +{ + if (dbus_timeout_get_enabled(timeout) == TRUE) + dbusAddTimeout(timeout); + else + dbusRemoveTimeout(timeout); +} + +} // namespace FGSwiftBus diff --git a/src/Network/Swift/dbusdispatcher.h b/src/Network/Swift/dbusdispatcher.h index 4412f0ad5..5ec7f66ab 100644 --- a/src/Network/Swift/dbusdispatcher.h +++ b/src/Network/Swift/dbusdispatcher.h @@ -1,5 +1,5 @@ -// dbusdispatcher.h -// +// dbusdispatcher.h +// // Copyright (C) 2019 - swift Project Community / Contributors (http://swift-project.org/) // Adapted to Flightgear by Lars Toenning // @@ -22,93 +22,91 @@ #include "dbuscallbacks.h" -#include #include +#include +#include #include #include -#include -namespace FGSwiftBus +namespace FGSwiftBus { + +class WatchHandler; +class TimeoutHandler; +class CDBusConnection; +class CDBusDispatcher; + +//! Dispatchable Interface +class IDispatchable { +public: + //! Default constructor + IDispatchable() = default; - class WatchHandler; - class TimeoutHandler; - class CDBusConnection; - class CDBusDispatcher; + //! Default destructor + virtual ~IDispatchable() = default; - //! Dispatchable Interface - class IDispatchable - { - public: - //! Default constructor - IDispatchable() = default; + //! Dispatch execution method + virtual void dispatch() = 0; - //! Default destructor - virtual ~IDispatchable() = default; +private: + friend CDBusDispatcher; +}; - //! Dispatch execution method - virtual void dispatch() = 0; +//! DBus Dispatcher +class CDBusDispatcher +{ +public: + //! Constructor + CDBusDispatcher(); - private: - friend CDBusDispatcher; + //! Destructor + virtual ~CDBusDispatcher(); + + //! Add dispatchable object + void add(IDispatchable* dispatchable); + + //! Remove dispatchable object + void remove(IDispatchable* dispatchable); + + //! Waits for events to be dispatched and handles them + void waitAndRun(); + + //! Dispatches ready handlers and returns without waiting + void runOnce(); + +private: + friend class WatchHandler; + friend class TimeoutHandler; + friend class Timer; + friend class CDBusConnection; + friend class CDBusServer; + + struct EventBaseDeleter { + void operator()(event_base* obj) const { event_base_free(obj); } }; - //! DBus Dispatcher - class CDBusDispatcher - { - public: - //! Constructor - CDBusDispatcher(); + using WatchCallbacks = DBusAsyncCallbacks; + using TimeoutCallbacks = DBusAsyncCallbacks; - //! Destructor - virtual ~CDBusDispatcher(); + void dispatch(); - //! Add dispatchable object - void add(IDispatchable *dispatchable); + dbus_bool_t dbusAddWatch(DBusWatch* watch); + void dbusRemoveWatch(DBusWatch* watch); + void dbusWatchToggled(DBusWatch* watch); - //! Remove dispatchable object - void remove(IDispatchable *dispatchable); + dbus_bool_t dbusAddTimeout(DBusTimeout* timeout); + void dbusRemoveTimeout(DBusTimeout* timeout); + void dbusTimeoutToggled(DBusTimeout* timeout); - //! Waits for events to be dispatched and handles them - void waitAndRun(); + WatchCallbacks m_watchCallbacks; + TimeoutCallbacks m_timeoutCallbacks; + std::unordered_multimap> m_watchers; + std::vector> m_timeouts; + std::unique_ptr m_eventBase; - //! Dispatches ready handlers and returns without waiting - void runOnce(); - - private: - friend class WatchHandler; - friend class TimeoutHandler; - friend class Timer; - friend class CDBusConnection; - friend class CDBusServer; - - struct EventBaseDeleter - { - void operator()(event_base *obj) const { event_base_free(obj); } - }; - - using WatchCallbacks = DBusAsyncCallbacks; - using TimeoutCallbacks = DBusAsyncCallbacks; - - void dispatch(); - - dbus_bool_t dbusAddWatch(DBusWatch *watch); - void dbusRemoveWatch(DBusWatch *watch); - void dbusWatchToggled(DBusWatch *watch); - - dbus_bool_t dbusAddTimeout(DBusTimeout *timeout); - void dbusRemoveTimeout(DBusTimeout *timeout); - void dbusTimeoutToggled(DBusTimeout *timeout); - - WatchCallbacks m_watchCallbacks; - TimeoutCallbacks m_timeoutCallbacks; - std::unordered_multimap> m_watchers; - std::vector> m_timeouts; - std::unique_ptr m_eventBase; - - std::vector m_dispatchList; - }; -} + std::vector m_dispatchList; +}; +} // namespace FGSwiftBus #endif diff --git a/src/Network/Swift/dbuserror.cpp b/src/Network/Swift/dbuserror.cpp index 3a1aabd92..149a111f6 100644 --- a/src/Network/Swift/dbuserror.cpp +++ b/src/Network/Swift/dbuserror.cpp @@ -1,5 +1,5 @@ -// dbuserror.cpp -// +// dbuserror.cpp +// // Copyright (C) 2019 - swift Project Community / Contributors (http://swift-project.org/) // Adapted to Flightgear by Lars Toenning // @@ -19,11 +19,11 @@ #include "dbuserror.h" -namespace FGSwiftBus +namespace FGSwiftBus { + +CDBusError::CDBusError(const DBusError* error) + : m_name(error->name), m_message(error->message) { - - CDBusError::CDBusError(const DBusError *error) - : m_name(error->name), m_message(error->message) - { } - } + +} // namespace FGSwiftBus diff --git a/src/Network/Swift/dbuserror.h b/src/Network/Swift/dbuserror.h index 044bf703e..09bec4386 100644 --- a/src/Network/Swift/dbuserror.h +++ b/src/Network/Swift/dbuserror.h @@ -1,5 +1,5 @@ -// dbuserror.h -// +// dbuserror.h +// // Copyright (C) 2019 - swift Project Community / Contributors (http://swift-project.org/) // Adapted to Flightgear by Lars Toenning // @@ -23,35 +23,33 @@ #include #include -namespace FGSwiftBus +namespace FGSwiftBus { + +//! DBus error +class CDBusError { - - //! DBus error - class CDBusError - { - public: - //! Error type - enum ErrorType - { - NoError, - Other - }; - - //! Default constructur - CDBusError() = default; - - //! Constructor - explicit CDBusError(const DBusError *error); - - //! Get error type - ErrorType getType() const { return m_errorType; } - - private: - ErrorType m_errorType = NoError; - std::string m_name; - std::string m_message; +public: + //! Error type + enum ErrorType { + NoError, + Other }; -} + //! Default constructur + CDBusError() = default; + + //! Constructor + explicit CDBusError(const DBusError* error); + + //! Get error type + ErrorType getType() const { return m_errorType; } + +private: + ErrorType m_errorType = NoError; + std::string m_name; + std::string m_message; +}; + +} // namespace FGSwiftBus #endif // guard diff --git a/src/Network/Swift/dbusmessage.cpp b/src/Network/Swift/dbusmessage.cpp index 3a87c93c5..29d2bc669 100644 --- a/src/Network/Swift/dbusmessage.cpp +++ b/src/Network/Swift/dbusmessage.cpp @@ -1,5 +1,5 @@ -// dbusmessage.cpp -// +// dbusmessage.cpp +// // Copyright (C) 2019 - swift Project Community / Contributors (http://swift-project.org/) // Adapted to Flightgear by Lars Toenning // @@ -19,245 +19,241 @@ #include "dbusmessage.h" -namespace FGSwiftBus +namespace FGSwiftBus { + +CDBusMessage::CDBusMessage(DBusMessage* message) { - - CDBusMessage::CDBusMessage(DBusMessage *message) - { - m_message = dbus_message_ref(message); - } - - CDBusMessage::CDBusMessage(const CDBusMessage &other) - { - m_message = dbus_message_ref(other.m_message); - m_serial = other.m_serial; - } - - CDBusMessage::CDBusMessage(DBusMessage *message, dbus_uint32_t serial) - { - m_message = dbus_message_ref(message); - m_serial = serial; - } - - CDBusMessage::~CDBusMessage() - { - dbus_message_unref(m_message); - } - - CDBusMessage &CDBusMessage::operator =(CDBusMessage other) - { - std::swap(m_serial, other.m_serial); - m_message = dbus_message_ref(other.m_message); - return *this; - } - - bool CDBusMessage::isMethodCall() const - { - return dbus_message_get_type(m_message) == DBUS_MESSAGE_TYPE_METHOD_CALL; - } - - bool CDBusMessage::wantsReply() const - { - return !dbus_message_get_no_reply(m_message); - } - - std::string CDBusMessage::getSender() const - { - const char *sender = dbus_message_get_sender(m_message); - return sender ? std::string(sender) : std::string(); - } - - dbus_uint32_t CDBusMessage::getSerial() const - { - return dbus_message_get_serial(m_message); - } - - std::string CDBusMessage::getInterfaceName() const - { - return dbus_message_get_interface(m_message); - } - - std::string CDBusMessage::getObjectPath() const - { - return dbus_message_get_path(m_message); - } - - std::string CDBusMessage::getMethodName() const - { - return dbus_message_get_member(m_message); - } - - void CDBusMessage::beginArgumentWrite() - { - dbus_message_iter_init_append(m_message, &m_messageIterator); - } - - void CDBusMessage::appendArgument(bool value) - { - dbus_bool_t boolean = value ? 1 : 0; - dbus_message_iter_append_basic(&m_messageIterator, DBUS_TYPE_BOOLEAN, &boolean); - } - - void CDBusMessage::appendArgument(const char *value) - { - dbus_message_iter_append_basic(&m_messageIterator, DBUS_TYPE_STRING, &value); - } - - void CDBusMessage::appendArgument(const std::string &value) - { - const char *ptr = value.c_str(); - dbus_message_iter_append_basic(&m_messageIterator, DBUS_TYPE_STRING, &ptr); - } - - void CDBusMessage::appendArgument(int value) - { - dbus_int32_t i = value; - dbus_message_iter_append_basic(&m_messageIterator, DBUS_TYPE_INT32, &i); - } - - void CDBusMessage::appendArgument(double value) - { - dbus_message_iter_append_basic(&m_messageIterator, DBUS_TYPE_DOUBLE, &value); - } - - void CDBusMessage::appendArgument(const std::vector &array) - { - DBusMessageIter arrayIterator; - dbus_message_iter_open_container(&m_messageIterator, DBUS_TYPE_ARRAY, DBUS_TYPE_DOUBLE_AS_STRING, &arrayIterator); - const double *ptr = array.data(); - dbus_message_iter_append_fixed_array(&arrayIterator, DBUS_TYPE_DOUBLE, &ptr, static_cast(array.size())); - dbus_message_iter_close_container(&m_messageIterator, &arrayIterator); - } - - void CDBusMessage::appendArgument(const std::vector &array) - { - DBusMessageIter arrayIterator; - dbus_message_iter_open_container(&m_messageIterator, DBUS_TYPE_ARRAY, DBUS_TYPE_STRING_AS_STRING, &arrayIterator); - for (const auto &i : array) - { - const char *ptr = i.c_str(); - dbus_message_iter_append_basic(&arrayIterator, DBUS_TYPE_STRING, &ptr); - } - dbus_message_iter_close_container(&m_messageIterator, &arrayIterator); - } - - void CDBusMessage::beginArgumentRead() - { - dbus_message_iter_init(m_message, &m_messageIterator); - } - - void CDBusMessage::getArgument(int &value) - { - if (dbus_message_iter_get_arg_type(&m_messageIterator) != DBUS_TYPE_INT32) { return; } - dbus_int32_t i; - dbus_message_iter_get_basic(&m_messageIterator, &i); - value = i; - dbus_message_iter_next(&m_messageIterator); - } - - void CDBusMessage::getArgument(bool &value) - { - if (dbus_message_iter_get_arg_type(&m_messageIterator) != DBUS_TYPE_BOOLEAN) { return; } - dbus_bool_t v; - dbus_message_iter_get_basic(&m_messageIterator, &v); - if (v == TRUE) { value = true; } - else { value = false; } - dbus_message_iter_next(&m_messageIterator); - } - - void CDBusMessage::getArgument(double &value) - { - if (dbus_message_iter_get_arg_type(&m_messageIterator) != DBUS_TYPE_DOUBLE) { return; } - dbus_message_iter_get_basic(&m_messageIterator, &value); - dbus_message_iter_next(&m_messageIterator); - } - - void CDBusMessage::getArgument(std::string &value) - { - const char *str = nullptr; - if (dbus_message_iter_get_arg_type(&m_messageIterator) != DBUS_TYPE_STRING) { return; } - dbus_message_iter_get_basic(&m_messageIterator, &str); - dbus_message_iter_next(&m_messageIterator); - value = std::string(str); - } - - void CDBusMessage::getArgument(std::vector &value) - { - DBusMessageIter arrayIterator; - dbus_message_iter_recurse(&m_messageIterator, &arrayIterator); - do - { - if (dbus_message_iter_get_arg_type(&arrayIterator) != DBUS_TYPE_INT32) { return; } - dbus_int32_t i; - dbus_message_iter_get_basic(&arrayIterator, &i); - value.push_back(i); - } - while (dbus_message_iter_next(&arrayIterator)); - dbus_message_iter_next(&m_messageIterator); - } - - void CDBusMessage::getArgument(std::vector &value) - { - if (dbus_message_iter_get_arg_type(&m_messageIterator) != DBUS_TYPE_ARRAY) { return; } - DBusMessageIter arrayIterator; - dbus_message_iter_recurse(&m_messageIterator, &arrayIterator); - do - { - if (dbus_message_iter_get_arg_type(&arrayIterator) != DBUS_TYPE_BOOLEAN) { return; } - dbus_bool_t b; - dbus_message_iter_get_basic(&arrayIterator, &b); - if (b == TRUE) { value.push_back(true); } - else { value.push_back(false); } - } - while (dbus_message_iter_next(&arrayIterator)); - dbus_message_iter_next(&m_messageIterator); - } - - void CDBusMessage::getArgument(std::vector &value) - { - DBusMessageIter arrayIterator; - dbus_message_iter_recurse(&m_messageIterator, &arrayIterator); - do - { - if (dbus_message_iter_get_arg_type(&arrayIterator) != DBUS_TYPE_DOUBLE) { return; } - double d; - dbus_message_iter_get_basic(&arrayIterator, &d); - value.push_back(d); - } - while (dbus_message_iter_next(&arrayIterator)); - dbus_message_iter_next(&m_messageIterator); - } - - void CDBusMessage::getArgument(std::vector &value) - { - DBusMessageIter arrayIterator; - dbus_message_iter_recurse(&m_messageIterator, &arrayIterator); - do - { - if (dbus_message_iter_get_arg_type(&arrayIterator) != DBUS_TYPE_STRING) { return; } - const char *str = nullptr; - dbus_message_iter_get_basic(&arrayIterator, &str); - value.push_back(std::string(str)); - } - while (dbus_message_iter_next(&arrayIterator)); - dbus_message_iter_next(&m_messageIterator); - } - - CDBusMessage CDBusMessage::createSignal(const std::string &path, const std::string &interfaceName, const std::string &signalName) - { - DBusMessage *signal = dbus_message_new_signal(path.c_str(), interfaceName.c_str(), signalName.c_str()); - return CDBusMessage(signal); - } - - CDBusMessage CDBusMessage::createReply(const std::string &destination, dbus_uint32_t serial) - { - DBusMessage *reply = dbus_message_new(DBUS_MESSAGE_TYPE_METHOD_RETURN); - dbus_message_set_no_reply(reply, TRUE); - if (! destination.empty()) { dbus_message_set_destination(reply, destination.c_str()); } - dbus_message_set_reply_serial(reply, serial); - CDBusMessage msg(reply); - dbus_message_unref(reply); - return msg; - } - + m_message = dbus_message_ref(message); } + +CDBusMessage::CDBusMessage(const CDBusMessage& other) +{ + m_message = dbus_message_ref(other.m_message); + m_serial = other.m_serial; +} + +CDBusMessage::CDBusMessage(DBusMessage* message, dbus_uint32_t serial) +{ + m_message = dbus_message_ref(message); + m_serial = serial; +} + +CDBusMessage::~CDBusMessage() +{ + dbus_message_unref(m_message); +} + +CDBusMessage& CDBusMessage::operator=(CDBusMessage other) +{ + std::swap(m_serial, other.m_serial); + m_message = dbus_message_ref(other.m_message); + return *this; +} + +bool CDBusMessage::isMethodCall() const +{ + return dbus_message_get_type(m_message) == DBUS_MESSAGE_TYPE_METHOD_CALL; +} + +bool CDBusMessage::wantsReply() const +{ + return !dbus_message_get_no_reply(m_message); +} + +std::string CDBusMessage::getSender() const +{ + const char* sender = dbus_message_get_sender(m_message); + return sender ? std::string(sender) : std::string(); +} + +dbus_uint32_t CDBusMessage::getSerial() const +{ + return dbus_message_get_serial(m_message); +} + +std::string CDBusMessage::getInterfaceName() const +{ + return dbus_message_get_interface(m_message); +} + +std::string CDBusMessage::getObjectPath() const +{ + return dbus_message_get_path(m_message); +} + +std::string CDBusMessage::getMethodName() const +{ + return dbus_message_get_member(m_message); +} + +void CDBusMessage::beginArgumentWrite() +{ + dbus_message_iter_init_append(m_message, &m_messageIterator); +} + +void CDBusMessage::appendArgument(bool value) +{ + dbus_bool_t boolean = value ? 1 : 0; + dbus_message_iter_append_basic(&m_messageIterator, DBUS_TYPE_BOOLEAN, &boolean); +} + +void CDBusMessage::appendArgument(const char* value) +{ + dbus_message_iter_append_basic(&m_messageIterator, DBUS_TYPE_STRING, &value); +} + +void CDBusMessage::appendArgument(const std::string& value) +{ + const char* ptr = value.c_str(); + dbus_message_iter_append_basic(&m_messageIterator, DBUS_TYPE_STRING, &ptr); +} + +void CDBusMessage::appendArgument(int value) +{ + dbus_int32_t i = value; + dbus_message_iter_append_basic(&m_messageIterator, DBUS_TYPE_INT32, &i); +} + +void CDBusMessage::appendArgument(double value) +{ + dbus_message_iter_append_basic(&m_messageIterator, DBUS_TYPE_DOUBLE, &value); +} + +void CDBusMessage::appendArgument(const std::vector& array) +{ + DBusMessageIter arrayIterator; + dbus_message_iter_open_container(&m_messageIterator, DBUS_TYPE_ARRAY, DBUS_TYPE_DOUBLE_AS_STRING, &arrayIterator); + const double* ptr = array.data(); + dbus_message_iter_append_fixed_array(&arrayIterator, DBUS_TYPE_DOUBLE, &ptr, static_cast(array.size())); + dbus_message_iter_close_container(&m_messageIterator, &arrayIterator); +} + +void CDBusMessage::appendArgument(const std::vector& array) +{ + DBusMessageIter arrayIterator; + dbus_message_iter_open_container(&m_messageIterator, DBUS_TYPE_ARRAY, DBUS_TYPE_STRING_AS_STRING, &arrayIterator); + for (const auto& i : array) { + const char* ptr = i.c_str(); + dbus_message_iter_append_basic(&arrayIterator, DBUS_TYPE_STRING, &ptr); + } + dbus_message_iter_close_container(&m_messageIterator, &arrayIterator); +} + +void CDBusMessage::beginArgumentRead() +{ + dbus_message_iter_init(m_message, &m_messageIterator); +} + +void CDBusMessage::getArgument(int& value) +{ + if (dbus_message_iter_get_arg_type(&m_messageIterator) != DBUS_TYPE_INT32) { return; } + dbus_int32_t i; + dbus_message_iter_get_basic(&m_messageIterator, &i); + value = i; + dbus_message_iter_next(&m_messageIterator); +} + +void CDBusMessage::getArgument(bool& value) +{ + if (dbus_message_iter_get_arg_type(&m_messageIterator) != DBUS_TYPE_BOOLEAN) { return; } + dbus_bool_t v; + dbus_message_iter_get_basic(&m_messageIterator, &v); + if (v == TRUE) { + value = true; + } else { + value = false; + } + dbus_message_iter_next(&m_messageIterator); +} + +void CDBusMessage::getArgument(double& value) +{ + if (dbus_message_iter_get_arg_type(&m_messageIterator) != DBUS_TYPE_DOUBLE) { return; } + dbus_message_iter_get_basic(&m_messageIterator, &value); + dbus_message_iter_next(&m_messageIterator); +} + +void CDBusMessage::getArgument(std::string& value) +{ + const char* str = nullptr; + if (dbus_message_iter_get_arg_type(&m_messageIterator) != DBUS_TYPE_STRING) { return; } + dbus_message_iter_get_basic(&m_messageIterator, &str); + dbus_message_iter_next(&m_messageIterator); + value = std::string(str); +} + +void CDBusMessage::getArgument(std::vector& value) +{ + DBusMessageIter arrayIterator; + dbus_message_iter_recurse(&m_messageIterator, &arrayIterator); + do { + if (dbus_message_iter_get_arg_type(&arrayIterator) != DBUS_TYPE_INT32) { return; } + dbus_int32_t i; + dbus_message_iter_get_basic(&arrayIterator, &i); + value.push_back(i); + } while (dbus_message_iter_next(&arrayIterator)); + dbus_message_iter_next(&m_messageIterator); +} + +void CDBusMessage::getArgument(std::vector& value) +{ + if (dbus_message_iter_get_arg_type(&m_messageIterator) != DBUS_TYPE_ARRAY) { return; } + DBusMessageIter arrayIterator; + dbus_message_iter_recurse(&m_messageIterator, &arrayIterator); + do { + if (dbus_message_iter_get_arg_type(&arrayIterator) != DBUS_TYPE_BOOLEAN) { return; } + dbus_bool_t b; + dbus_message_iter_get_basic(&arrayIterator, &b); + if (b == TRUE) { + value.push_back(true); + } else { + value.push_back(false); + } + } while (dbus_message_iter_next(&arrayIterator)); + dbus_message_iter_next(&m_messageIterator); +} + +void CDBusMessage::getArgument(std::vector& value) +{ + DBusMessageIter arrayIterator; + dbus_message_iter_recurse(&m_messageIterator, &arrayIterator); + do { + if (dbus_message_iter_get_arg_type(&arrayIterator) != DBUS_TYPE_DOUBLE) { return; } + double d; + dbus_message_iter_get_basic(&arrayIterator, &d); + value.push_back(d); + } while (dbus_message_iter_next(&arrayIterator)); + dbus_message_iter_next(&m_messageIterator); +} + +void CDBusMessage::getArgument(std::vector& value) +{ + DBusMessageIter arrayIterator; + dbus_message_iter_recurse(&m_messageIterator, &arrayIterator); + do { + if (dbus_message_iter_get_arg_type(&arrayIterator) != DBUS_TYPE_STRING) { return; } + const char* str = nullptr; + dbus_message_iter_get_basic(&arrayIterator, &str); + value.push_back(std::string(str)); + } while (dbus_message_iter_next(&arrayIterator)); + dbus_message_iter_next(&m_messageIterator); +} + +CDBusMessage CDBusMessage::createSignal(const std::string& path, const std::string& interfaceName, const std::string& signalName) +{ + DBusMessage* signal = dbus_message_new_signal(path.c_str(), interfaceName.c_str(), signalName.c_str()); + return CDBusMessage(signal); +} + +CDBusMessage CDBusMessage::createReply(const std::string& destination, dbus_uint32_t serial) +{ + DBusMessage* reply = dbus_message_new(DBUS_MESSAGE_TYPE_METHOD_RETURN); + dbus_message_set_no_reply(reply, TRUE); + if (!destination.empty()) { dbus_message_set_destination(reply, destination.c_str()); } + dbus_message_set_reply_serial(reply, serial); + CDBusMessage msg(reply); + dbus_message_unref(reply); + return msg; +} + +} // namespace FGSwiftBus diff --git a/src/Network/Swift/dbusmessage.h b/src/Network/Swift/dbusmessage.h index 097aa07c4..a8780d3b4 100644 --- a/src/Network/Swift/dbusmessage.h +++ b/src/Network/Swift/dbusmessage.h @@ -1,5 +1,5 @@ -// dbusmessage.h -// +// dbusmessage.h +// // Copyright (C) 2019 - swift Project Community / Contributors (http://swift-project.org/) // Adapted to Flightgear by Lars Toenning // @@ -24,90 +24,89 @@ #include #include -namespace FGSwiftBus +namespace FGSwiftBus { + +//! DBus Message +class CDBusMessage { +public: + //! Constructor + //! @{ + CDBusMessage(DBusMessage* message); + CDBusMessage(const CDBusMessage& other); + //! @} - //! DBus Message - class CDBusMessage - { - public: - //! Constructor - //! @{ - CDBusMessage(DBusMessage *message); - CDBusMessage(const CDBusMessage &other); - //! @} + //! Destructor + ~CDBusMessage(); - //! Destructor - ~CDBusMessage(); + //! Assignment operator + CDBusMessage& operator=(CDBusMessage other); - //! Assignment operator - CDBusMessage &operator=(CDBusMessage other); + //! Is this message a method call? + bool isMethodCall() const; - //! Is this message a method call? - bool isMethodCall() const; + //! Does this message want a reply? + bool wantsReply() const; - //! Does this message want a reply? - bool wantsReply() const; + //! Get the message sender + std::string getSender() const; - //! Get the message sender - std::string getSender() const; + //! Get the message serial. This is usally required for reply message. + dbus_uint32_t getSerial() const; - //! Get the message serial. This is usally required for reply message. - dbus_uint32_t getSerial() const; + //! Get the called interface name + std::string getInterfaceName() const; - //! Get the called interface name - std::string getInterfaceName() const; + //! Get the called object path + std::string getObjectPath() const; - //! Get the called object path - std::string getObjectPath() const; + //! Get the called method name + std::string getMethodName() const; - //! Get the called method name - std::string getMethodName() const; + //! Begin writing argument + void beginArgumentWrite(); - //! Begin writing argument - void beginArgumentWrite(); + //! Append argument. Make sure to call \sa beginArgumentWrite() before. + //! @{ + void appendArgument(bool value); + void appendArgument(const char* value); + void appendArgument(const std::string& value); + void appendArgument(int value); + void appendArgument(double value); + void appendArgument(const std::vector& array); + void appendArgument(const std::vector& array); + //! @} - //! Append argument. Make sure to call \sa beginArgumentWrite() before. - //! @{ - void appendArgument(bool value); - void appendArgument(const char *value); - void appendArgument(const std::string &value); - void appendArgument(int value); - void appendArgument(double value); - void appendArgument(const std::vector &array); - void appendArgument(const std::vector &array); - //! @} + //! Begin reading arguments + void beginArgumentRead(); - //! Begin reading arguments - void beginArgumentRead(); + //! Read single argument. Make sure to call \sa beginArgumentRead() before. + //! @{ + void getArgument(int& value); + void getArgument(bool& value); + void getArgument(double& value); + void getArgument(std::string& value); + void getArgument(std::vector& value); + void getArgument(std::vector& value); + void getArgument(std::vector& value); + void getArgument(std::vector& value); + //! @} - //! Read single argument. Make sure to call \sa beginArgumentRead() before. - //! @{ - void getArgument(int &value); - void getArgument(bool &value); - void getArgument(double &value); - void getArgument(std::string &value); - void getArgument(std::vector &value); - void getArgument(std::vector &value); - void getArgument(std::vector &value); - void getArgument(std::vector &value); - //! @} + //! Creates a DBus message containing a DBus signal + static CDBusMessage createSignal(const std::string& path, const std::string& interfaceName, const std::string& signalName); - //! Creates a DBus message containing a DBus signal - static CDBusMessage createSignal(const std::string &path, const std::string &interfaceName, const std::string &signalName); + //! Creates a DBus message containing a DBus reply + static CDBusMessage createReply(const std::string& destination, dbus_uint32_t serial); - //! Creates a DBus message containing a DBus reply - static CDBusMessage createReply(const std::string &destination, dbus_uint32_t serial); +private: + friend class CDBusConnection; - private: - friend class CDBusConnection; + DBusMessage* m_message = nullptr; + DBusMessageIter m_messageIterator; + CDBusMessage(DBusMessage* message, dbus_uint32_t serial); + dbus_uint32_t m_serial = 0; +}; - DBusMessage *m_message = nullptr; - DBusMessageIter m_messageIterator; - CDBusMessage(DBusMessage *message, dbus_uint32_t serial); - dbus_uint32_t m_serial = 0; - }; - -} +} // namespace FGSwiftBus #endif // guard diff --git a/src/Network/Swift/dbusobject.cpp b/src/Network/Swift/dbusobject.cpp index 880ed2b17..d4de83ed2 100644 --- a/src/Network/Swift/dbusobject.cpp +++ b/src/Network/Swift/dbusobject.cpp @@ -1,5 +1,5 @@ -// dbusobject.cpp -// +// dbusobject.cpp +// // Copyright (C) 2019 - swift Project Community / Contributors (http://swift-project.org/) // Adapted to Flightgear by Lars Toenning // @@ -20,87 +20,85 @@ #include "dbusobject.h" #include -namespace FGSwiftBus +namespace FGSwiftBus { +CDBusObject::CDBusObject() { - CDBusObject::CDBusObject() - { } - - CDBusObject::~CDBusObject() - { - if (m_dbusConnection) { m_dbusConnection->unregisterDisconnectedCallback(this); } - }; - - void CDBusObject::setDBusConnection(const std::shared_ptr &dbusConnection) - { - m_dbusConnection = dbusConnection; - dbusConnectedHandler(); - CDBusConnection::DisconnectedCallback disconnectedHandler = std::bind(&CDBusObject::dbusDisconnectedHandler, this); - m_dbusConnection->registerDisconnectedCallback(this, disconnectedHandler); - } - - void CDBusObject::registerDBusObjectPath(const std::string &interfaceName, const std::string &objectPath) - { - assert(m_dbusConnection); - m_interfaceName = interfaceName; - m_objectPath = objectPath; - m_dbusConnection->registerObjectPath(this, interfaceName, objectPath, m_dbusObjectPathVTable); - } - - void CDBusObject::sendDBusSignal(const std::string &name) - { - if (! m_dbusConnection) { return; } - CDBusMessage signal = CDBusMessage::createSignal(m_objectPath, m_interfaceName, name); - m_dbusConnection->sendMessage(signal); - } - - void CDBusObject::sendDBusMessage(const CDBusMessage &message) - { - if (! m_dbusConnection) { return; } - m_dbusConnection->sendMessage(message); - } - - void CDBusObject::maybeSendEmptyDBusReply(bool wantsReply, const std::string &destination, dbus_uint32_t serial) - { - if (wantsReply) - { - CDBusMessage reply = CDBusMessage::createReply(destination, serial); - m_dbusConnection->sendMessage(reply); - } - } - - void CDBusObject::queueDBusCall(const std::function &func) - { - std::lock_guard lock(m_mutex); - m_qeuedDBusCalls.push_back(func); - } - - void CDBusObject::invokeQueuedDBusCalls() - { - std::lock_guard lock(m_mutex); - while (m_qeuedDBusCalls.size() > 0) - { - m_qeuedDBusCalls.front()(); - m_qeuedDBusCalls.pop_front(); - } - } - - void CDBusObject::dbusObjectPathUnregisterFunction(DBusConnection *connection, void *data) - { - (void)connection; // unused - (void)data; // unused - } - - DBusHandlerResult CDBusObject::dbusObjectPathMessageFunction(DBusConnection *connection, DBusMessage *message, void *data) - { - (void)connection; // unused - - auto *obj = static_cast(data); - - DBusError err; - dbus_error_init(&err); - - CDBusMessage dbusMessage(message); - return obj->dbusMessageHandler(dbusMessage); - } - } + +CDBusObject::~CDBusObject() +{ + if (m_dbusConnection) { m_dbusConnection->unregisterDisconnectedCallback(this); } +}; + +void CDBusObject::setDBusConnection(const std::shared_ptr& dbusConnection) +{ + m_dbusConnection = dbusConnection; + dbusConnectedHandler(); + CDBusConnection::DisconnectedCallback disconnectedHandler = std::bind(&CDBusObject::dbusDisconnectedHandler, this); + m_dbusConnection->registerDisconnectedCallback(this, disconnectedHandler); +} + +void CDBusObject::registerDBusObjectPath(const std::string& interfaceName, const std::string& objectPath) +{ + assert(m_dbusConnection); + m_interfaceName = interfaceName; + m_objectPath = objectPath; + m_dbusConnection->registerObjectPath(this, interfaceName, objectPath, m_dbusObjectPathVTable); +} + +void CDBusObject::sendDBusSignal(const std::string& name) +{ + if (!m_dbusConnection) { return; } + CDBusMessage signal = CDBusMessage::createSignal(m_objectPath, m_interfaceName, name); + m_dbusConnection->sendMessage(signal); +} + +void CDBusObject::sendDBusMessage(const CDBusMessage& message) +{ + if (!m_dbusConnection) { return; } + m_dbusConnection->sendMessage(message); +} + +void CDBusObject::maybeSendEmptyDBusReply(bool wantsReply, const std::string& destination, dbus_uint32_t serial) +{ + if (wantsReply) { + CDBusMessage reply = CDBusMessage::createReply(destination, serial); + m_dbusConnection->sendMessage(reply); + } +} + +void CDBusObject::queueDBusCall(const std::function& func) +{ + std::lock_guard lock(m_mutex); + m_qeuedDBusCalls.push_back(func); +} + +void CDBusObject::invokeQueuedDBusCalls() +{ + std::lock_guard lock(m_mutex); + while (m_qeuedDBusCalls.size() > 0) { + m_qeuedDBusCalls.front()(); + m_qeuedDBusCalls.pop_front(); + } +} + +void CDBusObject::dbusObjectPathUnregisterFunction(DBusConnection* connection, void* data) +{ + (void)connection; // unused + (void)data; // unused +} + +DBusHandlerResult CDBusObject::dbusObjectPathMessageFunction(DBusConnection* connection, DBusMessage* message, void* data) +{ + (void)connection; // unused + + auto* obj = static_cast(data); + + DBusError err; + dbus_error_init(&err); + + CDBusMessage dbusMessage(message); + return obj->dbusMessageHandler(dbusMessage); +} + +} // namespace FGSwiftBus diff --git a/src/Network/Swift/dbusobject.h b/src/Network/Swift/dbusobject.h index 4145533dd..0f09c56df 100644 --- a/src/Network/Swift/dbusobject.h +++ b/src/Network/Swift/dbusobject.h @@ -1,5 +1,5 @@ -// dbusobject.h -// +// dbusobject.h +// // Copyright (C) 2019 - swift Project Community / Contributors (http://swift-project.org/) // Adapted to Flightgear by Lars Toenning // @@ -21,88 +21,87 @@ #define BLACKSIM_FGSWIFTBUS_DBUSOBJECT_H #include "dbusconnection.h" -#include #include +#include -namespace FGSwiftBus +namespace FGSwiftBus { +//! DBus base object +class CDBusObject { - //! DBus base object - class CDBusObject +public: + //! Constructor + CDBusObject(); + + //! Destructor + virtual ~CDBusObject(); + + //! Set the assigned DBus connection. + //! \remark Currently one object can only manage one connection at a time + void setDBusConnection(const std::shared_ptr& dbusConnection); + + //! Register itself with interfaceName and objectPath + //! \warning Before calling this method, make sure that a valid DBus connection was set. + void registerDBusObjectPath(const std::string& interfaceName, const std::string& objectPath); + +protected: + //! Handler which is called when DBusCconnection is established + virtual void dbusConnectedHandler() {} + + //! DBus message handler + virtual DBusHandlerResult dbusMessageHandler(const CDBusMessage& message) = 0; + + //! Handler which is called when DBusConnection disconnected + virtual void dbusDisconnectedHandler() {} + + //! Send DBus signal + void sendDBusSignal(const std::string& name); + + //! Send DBus message + void sendDBusMessage(const CDBusMessage& message); + + //! Maybe sends an empty DBus reply (acknowledgement) + void maybeSendEmptyDBusReply(bool wantsReply, const std::string& destination, dbus_uint32_t serial); + + //! Send DBus reply + template + void sendDBusReply(const std::string& destination, dbus_uint32_t serial, const T& argument) { - public: - //! Constructor - CDBusObject(); + CDBusMessage reply = CDBusMessage::createReply(destination, serial); + reply.beginArgumentWrite(); + reply.appendArgument(argument); + m_dbusConnection->sendMessage(reply); + } - //! Destructor - virtual ~CDBusObject(); + //! Send DBus reply + template + void sendDBusReply(const std::string& destination, dbus_uint32_t serial, const std::vector& array) + { + CDBusMessage reply = CDBusMessage::createReply(destination, serial); + reply.beginArgumentWrite(); + reply.appendArgument(array); + m_dbusConnection->sendMessage(reply); + } - //! Set the assigned DBus connection. - //! \remark Currently one object can only manage one connection at a time - void setDBusConnection(const std::shared_ptr &dbusConnection); + //! Queue a DBus call to be executed in a different thread + void queueDBusCall(const std::function& func); - //! Register itself with interfaceName and objectPath - //! \warning Before calling this method, make sure that a valid DBus connection was set. - void registerDBusObjectPath(const std::string &interfaceName, const std::string &objectPath); + //! Invoke all pending DBus calls. They will be executed in the calling thread. + void invokeQueuedDBusCalls(); - protected: - //! Handler which is called when DBusCconnection is established - virtual void dbusConnectedHandler() {} +private: + static void dbusObjectPathUnregisterFunction(DBusConnection* connection, void* data); + static DBusHandlerResult dbusObjectPathMessageFunction(DBusConnection* connection, DBusMessage* message, void* data); - //! DBus message handler - virtual DBusHandlerResult dbusMessageHandler(const CDBusMessage &message) = 0; + std::shared_ptr m_dbusConnection; + std::string m_interfaceName; + std::string m_objectPath; - //! Handler which is called when DBusConnection disconnected - virtual void dbusDisconnectedHandler() {} + std::mutex m_mutex; + std::deque> m_qeuedDBusCalls; - //! Send DBus signal - void sendDBusSignal(const std::string &name); + const DBusObjectPathVTable m_dbusObjectPathVTable = {dbusObjectPathUnregisterFunction, dbusObjectPathMessageFunction, nullptr, nullptr, nullptr, nullptr}; +}; - //! Send DBus message - void sendDBusMessage(const CDBusMessage &message); - - //! Maybe sends an empty DBus reply (acknowledgement) - void maybeSendEmptyDBusReply(bool wantsReply, const std::string &destination, dbus_uint32_t serial); - - //! Send DBus reply - template - void sendDBusReply(const std::string &destination, dbus_uint32_t serial, const T &argument) - { - CDBusMessage reply = CDBusMessage::createReply(destination, serial); - reply.beginArgumentWrite(); - reply.appendArgument(argument); - m_dbusConnection->sendMessage(reply); - } - - //! Send DBus reply - template - void sendDBusReply(const std::string &destination, dbus_uint32_t serial, const std::vector &array) - { - CDBusMessage reply = CDBusMessage::createReply(destination, serial); - reply.beginArgumentWrite(); - reply.appendArgument(array); - m_dbusConnection->sendMessage(reply); - } - - //! Queue a DBus call to be executed in a different thread - void queueDBusCall(const std::function &func); - - //! Invoke all pending DBus calls. They will be executed in the calling thread. - void invokeQueuedDBusCalls(); - - private: - static void dbusObjectPathUnregisterFunction(DBusConnection *connection, void *data); - static DBusHandlerResult dbusObjectPathMessageFunction(DBusConnection *connection, DBusMessage *message, void *data); - - std::shared_ptr m_dbusConnection; - std::string m_interfaceName; - std::string m_objectPath; - - std::mutex m_mutex; - std::deque> m_qeuedDBusCalls; - - const DBusObjectPathVTable m_dbusObjectPathVTable = { dbusObjectPathUnregisterFunction, dbusObjectPathMessageFunction, nullptr, nullptr, nullptr, nullptr }; - }; - -} +} // namespace FGSwiftBus #endif // guard diff --git a/src/Network/Swift/dbusserver.cpp b/src/Network/Swift/dbusserver.cpp index 217a7ef4c..70834c836 100644 --- a/src/Network/Swift/dbusserver.cpp +++ b/src/Network/Swift/dbusserver.cpp @@ -1,7 +1,7 @@ #include -// dbusserver.cpp -// +// dbusserver.cpp +// // Copyright (C) 2019 - swift Project Community / Contributors (http://swift-project.org/) // Adapted to Flightgear by Lars Toenning // @@ -19,83 +19,81 @@ // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -#include "dbusserver.h" #include "dbusobject.h" +#include "dbusserver.h" #include #include #include -namespace FGSwiftBus +namespace FGSwiftBus { + +CDBusServer::CDBusServer() { - - CDBusServer::CDBusServer() - { - dbus_threads_init_default(); - } - - CDBusServer::~CDBusServer() - { - close(); - } - - bool CDBusServer::listen(const std::string &address) - { - DBusError error; - dbus_error_init(&error); - m_server.reset(dbus_server_listen(address.c_str(), &error)); - - if (! m_server) - { - return false; - } - - dbus_server_set_new_connection_function(m_server.get(), onNewConnection, this, nullptr); - return true; - } - - bool CDBusServer::isConnected() const - { - return m_server ? dbus_server_get_is_connected(m_server.get()) : false; - } - - void CDBusServer::close() - { - if (m_server) { dbus_server_disconnect(m_server.get()); } - } - - void CDBusServer::setDispatcher(CDBusDispatcher *dispatcher) - { - assert(dispatcher); - assert(m_server); - - m_dispatcher = dispatcher; - - dbus_server_set_watch_functions( - m_server.get(), - dispatcher->m_watchCallbacks.add, - dispatcher->m_watchCallbacks.remove, - dispatcher->m_watchCallbacks.toggled, - &dispatcher->m_watchCallbacks, nullptr); - - dbus_server_set_timeout_functions( - m_server.get(), - dispatcher->m_timeoutCallbacks.add, - dispatcher->m_timeoutCallbacks.remove, - dispatcher->m_timeoutCallbacks.toggled, - &dispatcher->m_timeoutCallbacks, nullptr); - } - - void CDBusServer::onNewConnection(DBusServer *, DBusConnection *conn) - { - auto dbusConnection = std::make_shared(conn); - m_newConnectionFunc(dbusConnection); - } - - void CDBusServer::onNewConnection(DBusServer *server, DBusConnection *conn, void *data) - { - auto *obj = static_cast(data); - obj->onNewConnection(server, conn); - } - + dbus_threads_init_default(); } + +CDBusServer::~CDBusServer() +{ + close(); +} + +bool CDBusServer::listen(const std::string& address) +{ + DBusError error; + dbus_error_init(&error); + m_server.reset(dbus_server_listen(address.c_str(), &error)); + + if (!m_server) { + return false; + } + + dbus_server_set_new_connection_function(m_server.get(), onNewConnection, this, nullptr); + return true; +} + +bool CDBusServer::isConnected() const +{ + return m_server ? dbus_server_get_is_connected(m_server.get()) : false; +} + +void CDBusServer::close() +{ + if (m_server) { dbus_server_disconnect(m_server.get()); } +} + +void CDBusServer::setDispatcher(CDBusDispatcher* dispatcher) +{ + assert(dispatcher); + assert(m_server); + + m_dispatcher = dispatcher; + + dbus_server_set_watch_functions( + m_server.get(), + dispatcher->m_watchCallbacks.add, + dispatcher->m_watchCallbacks.remove, + dispatcher->m_watchCallbacks.toggled, + &dispatcher->m_watchCallbacks, nullptr); + + dbus_server_set_timeout_functions( + m_server.get(), + dispatcher->m_timeoutCallbacks.add, + dispatcher->m_timeoutCallbacks.remove, + dispatcher->m_timeoutCallbacks.toggled, + &dispatcher->m_timeoutCallbacks, nullptr); +} + +void CDBusServer::onNewConnection(DBusServer*, DBusConnection* conn) +{ + auto dbusConnection = std::make_shared(conn); + m_newConnectionFunc(dbusConnection); +} + +void CDBusServer::onNewConnection(DBusServer* server, DBusConnection* conn, void* data) +{ + auto* obj = static_cast(data); + obj->onNewConnection(server, conn); +} + +} // namespace FGSwiftBus diff --git a/src/Network/Swift/dbusserver.h b/src/Network/Swift/dbusserver.h index cfe9d9d3f..6f0042cd4 100644 --- a/src/Network/Swift/dbusserver.h +++ b/src/Network/Swift/dbusserver.h @@ -1,5 +1,5 @@ // dbusserver.h -// +// // Copyright (C) 2019 - swift Project Community / Contributors (http://swift-project.org/) // Adapted to Flightgear by Lars Toenning // @@ -20,75 +20,73 @@ #ifndef BLACKSIM_FGSWIFTBUS_DBUSSERVER_H #define BLACKSIM_FGSWIFTBUS_DBUSSERVER_H -#include "dbusmessage.h" -#include "dbuserror.h" #include "dbuscallbacks.h" #include "dbusdispatcher.h" +#include "dbuserror.h" +#include "dbusmessage.h" -#include #include +#include +#include +#include #include #include #include -#include -#include -namespace FGSwiftBus +namespace FGSwiftBus { + +class CDBusObject; + +//! DBus connection +class CDBusServer : public IDispatchable { +public: + //! New connection handler function + using NewConnectionFunc = std::function)>; - class CDBusObject; + //! Constructor + CDBusServer(); - //! DBus connection - class CDBusServer : public IDispatchable + //! Destructor + ~CDBusServer(); + + //! Set the dispatcher + void setDispatcher(CDBusDispatcher* dispatcher); + + //! Connect to bus + bool listen(const std::string& address); + + //! Is connected? + bool isConnected() const; + + void dispatch() override {} + + //! Close connection + void close(); + + //! Get the last error + CDBusError lastError() const { return m_lastError; } + + //! Set the function to be used for handling new connections. + void setNewConnectionFunc(const NewConnectionFunc& func) { - public: - //! New connection handler function - using NewConnectionFunc = std::function)>; + m_newConnectionFunc = func; + } - //! Constructor - CDBusServer(); +private: + void onNewConnection(DBusServer* server, DBusConnection* conn); + static void onNewConnection(DBusServer* server, DBusConnection* conn, void* data); - //! Destructor - ~CDBusServer(); - - //! Set the dispatcher - void setDispatcher(CDBusDispatcher *dispatcher); - - //! Connect to bus - bool listen(const std::string &address); - - //! Is connected? - bool isConnected() const; - - void dispatch() override {} - - //! Close connection - void close(); - - //! Get the last error - CDBusError lastError() const { return m_lastError; } - - //! Set the function to be used for handling new connections. - void setNewConnectionFunc(const NewConnectionFunc &func) - { - m_newConnectionFunc = func; - } - - private: - void onNewConnection(DBusServer *server, DBusConnection *conn); - static void onNewConnection(DBusServer *server, DBusConnection *conn, void *data); - - struct DBusServerDeleter - { - void operator()(DBusServer *obj) const { dbus_server_unref(obj); } - }; - - CDBusDispatcher *m_dispatcher = nullptr; - std::unique_ptr m_server; - CDBusError m_lastError; - NewConnectionFunc m_newConnectionFunc; + struct DBusServerDeleter { + void operator()(DBusServer* obj) const { dbus_server_unref(obj); } }; -} + CDBusDispatcher* m_dispatcher = nullptr; + std::unique_ptr m_server; + CDBusError m_lastError; + NewConnectionFunc m_newConnectionFunc; +}; + +} // namespace FGSwiftBus #endif // guard diff --git a/src/Network/Swift/plugin.cpp b/src/Network/Swift/plugin.cpp index 9f452d8f4..69f6b080b 100644 --- a/src/Network/Swift/plugin.cpp +++ b/src/Network/Swift/plugin.cpp @@ -23,17 +23,15 @@ #include
#include
-#include #include #include #include -#include #include namespace { inline std::string fgswiftbusServiceName() { - return std::string("org.swift-project.fgswiftbus"); + return "org.swift-project.fgswiftbus"; } } // namespace @@ -79,17 +77,6 @@ void CPlugin::startServer() SG_LOG(SG_NETWORK, SG_INFO, "FGSwiftBus started"); } -float CPlugin::startServerDeferred(float, float, int, void* refcon) -{ - auto plugin = static_cast(refcon); - if (!plugin->m_isRunning) { - plugin->startServer(); - plugin->m_isRunning = true; - } - - return 0; -} - void CPlugin::fastLoop() { this->m_dbusDispatcher.runOnce(); diff --git a/src/Network/Swift/plugin.h b/src/Network/Swift/plugin.h index 5a8574c8a..243df61a6 100644 --- a/src/Network/Swift/plugin.h +++ b/src/Network/Swift/plugin.h @@ -1,5 +1,5 @@ // plugin.h -// +// // Copyright (C) 2019 - swift Project Community / Contributors (http://swift-project.org/) // Adapted to Flightgear by Lars Toenning // @@ -31,44 +31,41 @@ #define NOMINMAX #endif +#include "config.h" #include "dbusconnection.h" #include "dbusdispatcher.h" #include "dbusserver.h" -#include "config.h" #include #include -namespace FGSwiftBus -{ - class CService; - class CTraffic; - class CWeather; +namespace FGSwiftBus { +class CService; +class CTraffic; - /*! +/*! * Main plugin class */ - class CPlugin - { - public: - //! Constructor - CPlugin(); - void startServer(); - //! Destructor - ~CPlugin(); - static float startServerDeferred(float, float, int, void* refcon); - void fastLoop(); - - private: - CDBusDispatcher m_dbusDispatcher; - std::unique_ptr m_dbusP2PServer; - std::shared_ptr m_dbusConnection; - std::unique_ptr m_service; - std::unique_ptr m_traffic; +class CPlugin +{ +public: + //! Constructor + CPlugin(); + void startServer(); + //! Destructor + ~CPlugin(); + void fastLoop(); - std::thread m_dbusThread; - bool m_isRunning = false; - bool m_shouldStop = false; - }; -} +private: + CDBusDispatcher m_dbusDispatcher; + std::unique_ptr m_dbusP2PServer; + std::shared_ptr m_dbusConnection; + std::unique_ptr m_service; + std::unique_ptr m_traffic; -#endif // guard + std::thread m_dbusThread; + bool m_isRunning = false; + bool m_shouldStop = false; +}; +} // namespace FGSwiftBus + +#endif // BLACKSIM_FGSWIFTBUS_PLUGIN_H diff --git a/src/Network/Swift/service.cpp b/src/Network/Swift/service.cpp index ac636d32b..7fbfa9fd6 100644 --- a/src/Network/Swift/service.cpp +++ b/src/Network/Swift/service.cpp @@ -1,5 +1,5 @@ -// service.cpp - Service module for swift<->FG connection -// +// service.cpp - Service module for swift<->FG connection +// // Copyright (C) 2019 - swift Project Community / Contributors (http://swift-project.org/) // Adapted to Flightgear by Lars Toenning // @@ -20,9 +20,9 @@ #include "service.h" #include
#include +#include #include #include -#include #define FGSWIFTBUS_API_VERSION 3; @@ -31,51 +31,52 @@ namespace FGSwiftBus { CService::CService() { // Initialize node pointers - m_textMessageNode = fgGetNode("/sim/messages/copilot", true); - m_aircraftModelPathNode = fgGetNode("/sim/aircraft-dir", true); - m_aircraftDescriptionNode = fgGetNode("/sim/description", true); - m_isPausedNode = fgGetNode("/sim/freeze/master", true); - m_latitudeNode = fgGetNode("/position/latitude-deg", true); - m_longitudeNode = fgGetNode("/position/longitude-deg", true); - m_altitudeMSLNode = fgGetNode("/position/altitude-ft", true); - m_heightAGLNode = fgGetNode("/position/altitude-agl-ft", true); - m_groundSpeedNode = fgGetNode("/velocities/groundspeed-kt", true); - m_pitchNode = fgGetNode("/orientation/pitch-deg", true); - m_rollNode = fgGetNode("/orientation/roll-deg", true); - m_trueHeadingNode = fgGetNode("/orientation/heading-deg", true); - m_wheelsOnGroundNode = fgGetNode("/gear/gear/wow", true); - m_com1ActiveNode = fgGetNode("/instrumentation/comm/frequencies/selected-mhz", true); - m_com1StandbyNode = fgGetNode("/instrumentation/comm/frequencies/standby-mhz", true); - m_com2ActiveNode = fgGetNode("/instrumentation/comm[1]/frequencies/selected-mhz", true); - m_com2StandbyNode = fgGetNode("/instrumentation/comm[1]/frequencies/standby-mhz", true); - m_transponderCodeNode = fgGetNode("/instrumentation/transponder/id-code", true); - m_transponderModeNode = fgGetNode("/instrumentation/transponder/inputs/knob-mode", true); - m_transponderIdentNode = fgGetNode("/instrumentation/transponder/ident", true); - m_beaconLightsNode = fgGetNode("/controls/lighting/beacon", true); - m_landingLightsNode = fgGetNode("/controls/lighting/landing-lights", true); - m_navLightsNode = fgGetNode("/controls/lighting/nav-lights", true); - m_strobeLightsNode = fgGetNode("/controls/lighting/strobe", true); - m_taxiLightsNode = fgGetNode("/controls/lighting/taxi-light", true); - m_altimeterServiceableNode = fgGetNode("/instrumentation/altimeter/serviceable", true); - m_pressAltitudeFtNode = fgGetNode("/instrumentation/altimeter/pressure-alt-ft", true); - m_flapsDeployRatioNode = fgGetNode("/surface-positions/flap-pos-norm", true); - m_gearDeployRatioNode = fgGetNode("/gear/gear/position-norm", true); + m_textMessageNode = fgGetNode("/sim/messages/copilot", true); + m_aircraftModelPathNode = fgGetNode("/sim/aircraft-dir", true); + m_aircraftDescriptionNode = fgGetNode("/sim/description", true); + m_isPausedNode = fgGetNode("/sim/freeze/master", true); + m_latitudeNode = fgGetNode("/position/latitude-deg", true); + m_longitudeNode = fgGetNode("/position/longitude-deg", true); + m_altitudeMSLNode = fgGetNode("/position/altitude-ft", true); + m_heightAGLNode = fgGetNode("/position/altitude-agl-ft", true); + m_groundSpeedNode = fgGetNode("/velocities/groundspeed-kt", true); + m_pitchNode = fgGetNode("/orientation/pitch-deg", true); + m_rollNode = fgGetNode("/orientation/roll-deg", true); + m_trueHeadingNode = fgGetNode("/orientation/heading-deg", true); + m_wheelsOnGroundNode = fgGetNode("/gear/gear/wow", true); + m_com1ActiveNode = fgGetNode("/instrumentation/comm/frequencies/selected-mhz", true); + m_com1StandbyNode = fgGetNode("/instrumentation/comm/frequencies/standby-mhz", true); + m_com2ActiveNode = fgGetNode("/instrumentation/comm[1]/frequencies/selected-mhz", true); + m_com2StandbyNode = fgGetNode("/instrumentation/comm[1]/frequencies/standby-mhz", true); + m_transponderCodeNode = fgGetNode("/instrumentation/transponder/id-code", true); + m_transponderModeNode = fgGetNode("/instrumentation/transponder/inputs/knob-mode", true); + m_transponderIdentNode = fgGetNode("/instrumentation/transponder/ident", true); + m_beaconLightsNode = fgGetNode("/controls/lighting/beacon", true); + m_landingLightsNode = fgGetNode("/controls/lighting/landing-lights", true); + m_navLightsNode = fgGetNode("/controls/lighting/nav-lights", true); + m_strobeLightsNode = fgGetNode("/controls/lighting/strobe", true); + m_taxiLightsNode = fgGetNode("/controls/lighting/taxi-light", true); + m_altimeterServiceableNode = fgGetNode("/instrumentation/altimeter/serviceable", true); + m_pressAltitudeFtNode = fgGetNode("/instrumentation/altimeter/pressure-alt-ft", true); + m_flapsDeployRatioNode = fgGetNode("/surface-positions/flap-pos-norm", true); + m_gearDeployRatioNode = fgGetNode("/gear/gear/position-norm", true); m_speedBrakeDeployRatioNode = fgGetNode("/surface-positions/speedbrake-pos-norm", true); - m_aircraftNameNode = fgGetNode("/sim/aircraft", true); - m_groundElevationNode = fgGetNode("/position/ground-elev-m", true); - m_velocityXNode = fgGetNode("/velocities/speed-east-fps", true); - m_velocityYNode = fgGetNode("/velocities/speed-down-fps", true); - m_velocityZNode = fgGetNode("/velocities/speed-north-fps", true); - m_rollRateNode = fgGetNode("/orientation/roll-rate-degps", true); - m_pichRateNode = fgGetNode("/orientation/pitch-rate-degps", true); - m_yawRateNode = fgGetNode("/orientation/yaw-rate-degps", true); - m_com1VolumeNode = fgGetNode("/instrumentation/comm/volume", true); - m_com2VolumeNode = fgGetNode("/instrumentation/comm[1]/volume", true); + m_aircraftNameNode = fgGetNode("/sim/aircraft", true); + m_groundElevationNode = fgGetNode("/position/ground-elev-m", true); + m_velocityXNode = fgGetNode("/velocities/speed-east-fps", true); + m_velocityYNode = fgGetNode("/velocities/speed-down-fps", true); + m_velocityZNode = fgGetNode("/velocities/speed-north-fps", true); + m_rollRateNode = fgGetNode("/orientation/roll-rate-degps", true); + m_pichRateNode = fgGetNode("/orientation/pitch-rate-degps", true); + m_yawRateNode = fgGetNode("/orientation/yaw-rate-degps", true); + m_com1VolumeNode = fgGetNode("/instrumentation/comm/volume", true); + m_com2VolumeNode = fgGetNode("/instrumentation/comm[1]/volume", true); SG_LOG(SG_NETWORK, SG_INFO, "FGSwiftBus Service initialized"); } -const std::string& CService::InterfaceName() { +const std::string& CService::InterfaceName() +{ static const std::string s(FGSWIFTBUS_SERVICE_INTERFACENAME); return s; } @@ -98,164 +99,164 @@ void CService::addTextMessage(const std::string& text) m_textMessageNode->setStringValue(text); } -std::string CService::getAircraftModelPath() const -{ - return m_aircraftModelPathNode->getStringValue(); -} - -std::string CService::getAircraftLivery() const -{ - return ""; -} - -std::string CService::getAircraftIcaoCode() const -{ - return ""; -} - -std::string CService::getAircraftDescription() const -{ - return m_aircraftDescriptionNode->getStringValue(); -} - -bool CService::isPaused() const -{ - return m_isPausedNode->getBoolValue(); -} - -double CService::getLatitude() const -{ - return m_latitudeNode->getDoubleValue(); -} - -double CService::getLongitude() const -{ - return m_longitudeNode->getDoubleValue(); -} - -double CService::getAltitudeMSL() const -{ - return m_altitudeMSLNode->getDoubleValue(); -} - -double CService::getHeightAGL() const -{ - return m_heightAGLNode->getDoubleValue(); -} - -double CService::getGroundSpeed() const -{ - return m_groundSpeedNode->getDoubleValue(); -} - -double CService::getPitch() const -{ - return m_pitchNode->getDoubleValue(); -} - -double CService::getRoll() const -{ - return m_rollNode->getDoubleValue(); -} - -double CService::getTrueHeading() const -{ - return m_trueHeadingNode->getDoubleValue(); -} - -bool CService::getAllWheelsOnGround() const -{ - return m_wheelsOnGroundNode->getBoolValue(); -} - -int CService::getCom1Active() const +std::string CService::getAircraftModelPath() const { - return (int)(m_com1ActiveNode->getDoubleValue() * 1000); + return m_aircraftModelPathNode->getStringValue(); } -int CService::getCom1Standby() const -{ - return (int)(m_com1StandbyNode->getDoubleValue() * 1000); -} - -int CService::getCom2Active() const -{ - return (int)(m_com2ActiveNode->getDoubleValue() * 1000); -} - -int CService::getCom2Standby() const -{ - return (int)(m_com2StandbyNode->getDoubleValue() * 1000); -} - -int CService::getTransponderCode() const -{ - return m_transponderCodeNode->getIntValue(); -} - -int CService::getTransponderMode() const -{ - return m_transponderModeNode->getIntValue(); -} - -bool CService::getTransponderIdent() const -{ - return m_transponderIdentNode->getBoolValue(); -} - -bool CService::getBeaconLightsOn() const -{ - return m_beaconLightsNode->getBoolValue(); -} - -bool CService::getLandingLightsOn() const -{ - return m_landingLightsNode->getBoolValue(); -} - -bool CService::getNavLightsOn() const -{ - return m_navLightsNode->getBoolValue(); -} - - -bool CService::getStrobeLightsOn() const -{ - return m_strobeLightsNode->getBoolValue(); -} - -bool CService::getTaxiLightsOn() const -{ - return m_taxiLightsNode->getBoolValue(); -} - -double CService::getPressAlt() const -{ - if (m_altimeterServiceableNode->getBoolValue()){ - return m_pressAltitudeFtNode->getDoubleValue(); - } else { - return m_altitudeMSLNode->getDoubleValue(); - } -} - -void CService::setCom1Active(int freq) +std::string CService::getAircraftLivery() const { - m_com1ActiveNode->setDoubleValue(freq /(double)1000); + return ""; } -void CService::setCom1Standby(int freq) +std::string CService::getAircraftIcaoCode() const { - m_com1StandbyNode->setDoubleValue(freq /(double)1000); + return ""; } -void CService::setCom2Active(int freq) +std::string CService::getAircraftDescription() const { - m_com2ActiveNode->setDoubleValue(freq /(double)1000); + return m_aircraftDescriptionNode->getStringValue(); } -void CService::setCom2Standby(int freq) +bool CService::isPaused() const { - m_com2StandbyNode->setDoubleValue(freq /(double)1000); + return m_isPausedNode->getBoolValue(); +} + +double CService::getLatitude() const +{ + return m_latitudeNode->getDoubleValue(); +} + +double CService::getLongitude() const +{ + return m_longitudeNode->getDoubleValue(); +} + +double CService::getAltitudeMSL() const +{ + return m_altitudeMSLNode->getDoubleValue(); +} + +double CService::getHeightAGL() const +{ + return m_heightAGLNode->getDoubleValue(); +} + +double CService::getGroundSpeed() const +{ + return m_groundSpeedNode->getDoubleValue(); +} + +double CService::getPitch() const +{ + return m_pitchNode->getDoubleValue(); +} + +double CService::getRoll() const +{ + return m_rollNode->getDoubleValue(); +} + +double CService::getTrueHeading() const +{ + return m_trueHeadingNode->getDoubleValue(); +} + +bool CService::getAllWheelsOnGround() const +{ + return m_wheelsOnGroundNode->getBoolValue(); +} + +int CService::getCom1Active() const +{ + return (int)(m_com1ActiveNode->getDoubleValue() * 1000); +} + +int CService::getCom1Standby() const +{ + return (int)(m_com1StandbyNode->getDoubleValue() * 1000); +} + +int CService::getCom2Active() const +{ + return (int)(m_com2ActiveNode->getDoubleValue() * 1000); +} + +int CService::getCom2Standby() const +{ + return (int)(m_com2StandbyNode->getDoubleValue() * 1000); +} + +int CService::getTransponderCode() const +{ + return m_transponderCodeNode->getIntValue(); +} + +int CService::getTransponderMode() const +{ + return m_transponderModeNode->getIntValue(); +} + +bool CService::getTransponderIdent() const +{ + return m_transponderIdentNode->getBoolValue(); +} + +bool CService::getBeaconLightsOn() const +{ + return m_beaconLightsNode->getBoolValue(); +} + +bool CService::getLandingLightsOn() const +{ + return m_landingLightsNode->getBoolValue(); +} + +bool CService::getNavLightsOn() const +{ + return m_navLightsNode->getBoolValue(); +} + + +bool CService::getStrobeLightsOn() const +{ + return m_strobeLightsNode->getBoolValue(); +} + +bool CService::getTaxiLightsOn() const +{ + return m_taxiLightsNode->getBoolValue(); +} + +double CService::getPressAlt() const +{ + if (m_altimeterServiceableNode->getBoolValue()) { + return m_pressAltitudeFtNode->getDoubleValue(); + } else { + return m_altitudeMSLNode->getDoubleValue(); + } +} + +void CService::setCom1Active(int freq) +{ + m_com1ActiveNode->setDoubleValue(freq / (double)1000); +} + +void CService::setCom1Standby(int freq) +{ + m_com1StandbyNode->setDoubleValue(freq / (double)1000); +} + +void CService::setCom2Active(int freq) +{ + m_com2ActiveNode->setDoubleValue(freq / (double)1000); +} + +void CService::setCom2Standby(int freq) +{ + m_com2StandbyNode->setDoubleValue(freq / (double)1000); } void CService::setTransponderCode(int code) @@ -263,32 +264,32 @@ void CService::setTransponderCode(int code) m_transponderCodeNode->setIntValue(code); } -void CService::setTransponderMode(int mode) +void CService::setTransponderMode(int mode) { m_transponderModeNode->setIntValue(mode); } -double CService::getFlapsDeployRatio() const -{ - return m_flapsDeployRatioNode->getFloatValue(); +double CService::getFlapsDeployRatio() const +{ + return m_flapsDeployRatioNode->getFloatValue(); } -double CService::getGearDeployRatio() const -{ - return m_gearDeployRatioNode->getFloatValue(); +double CService::getGearDeployRatio() const +{ + return m_gearDeployRatioNode->getFloatValue(); } -int CService::getNumberOfEngines() const +int CService::getNumberOfEngines() const { // TODO Use correct property - return 2; + return 2; } std::vector CService::getEngineN1Percentage() const { // TODO use correct engine numbers std::vector list; - const auto number = static_cast(getNumberOfEngines()); + const auto number = static_cast(getNumberOfEngines()); list.reserve(number); for (unsigned int engineNumber = 0; engineNumber < number; ++engineNumber) { list.push_back(fgGetDouble("/engine/engine/n1")); @@ -296,9 +297,9 @@ std::vector CService::getEngineN1Percentage() const return list; } -double CService::getSpeedBrakeRatio() const -{ - return m_speedBrakeDeployRatioNode->getFloatValue(); +double CService::getSpeedBrakeRatio() const +{ + return m_speedBrakeDeployRatioNode->getFloatValue(); } double CService::getGroundElevation() const @@ -315,7 +316,7 @@ std::string CService::getAircraftModelFilename() const std::string CService::getAircraftModelString() const { - std::string modelName = getAircraftName(); + std::string modelName = getAircraftName(); std::string modelString = "FG " + modelName; return modelString; } @@ -369,10 +370,10 @@ static const char* introspection_service = DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_ DBusHandlerResult CService::dbusMessageHandler(const CDBusMessage& message_) { - CDBusMessage message(message_); - const std::string sender = message.getSender(); - const dbus_uint32_t serial = message.getSerial(); - const bool wantsReply = message.wantsReply(); + CDBusMessage message(message_); + const std::string sender = message.getSender(); + const dbus_uint32_t serial = message.getSerial(); + const bool wantsReply = message.wantsReply(); if (message.getInterfaceName() == DBUS_INTERFACE_INTROSPECTABLE) { if (message.getMethodName() == "Introspect") { @@ -390,15 +391,15 @@ DBusHandlerResult CService::dbusMessageHandler(const CDBusMessage& message_) }); } else if (message.getMethodName() == "getOwnAircraftSituationData") { queueDBusCall([=]() { - double lat = getLatitude(); - double lon = getLongitude(); - double alt = getAltitudeMSL(); - double gs = getGroundSpeed(); - double pitch = getPitch(); - double roll = getRoll(); - double trueHeading = getTrueHeading(); - double pressAlt = getPressAlt(); - CDBusMessage reply = CDBusMessage::createReply(sender, serial); + double lat = getLatitude(); + double lon = getLongitude(); + double alt = getAltitudeMSL(); + double gs = getGroundSpeed(); + double pitch = getPitch(); + double roll = getRoll(); + double trueHeading = getTrueHeading(); + double pressAlt = getPressAlt(); + CDBusMessage reply = CDBusMessage::createReply(sender, serial); reply.beginArgumentWrite(); reply.appendArgument(lat); reply.appendArgument(lon); @@ -412,13 +413,13 @@ DBusHandlerResult CService::dbusMessageHandler(const CDBusMessage& message_) }); } else if (message.getMethodName() == "getOwnAircraftVelocityData") { queueDBusCall([=]() { - double velocityX = getVelocityX(); - double velocityY = getVelocityY(); - double velocityZ = getVelocityZ(); - double pitchVelocity = getPitchRate(); - double rollVelocity = getRollRate(); - double yawVelocity = getYawRate(); - CDBusMessage reply = CDBusMessage::createReply(sender, serial); + double velocityX = getVelocityX(); + double velocityY = getVelocityY(); + double velocityZ = getVelocityZ(); + double pitchVelocity = getPitchRate(); + double rollVelocity = getRollRate(); + double yawVelocity = getYawRate(); + CDBusMessage reply = CDBusMessage::createReply(sender, serial); reply.beginArgumentWrite(); reply.appendArgument(velocityX); reply.appendArgument(velocityY); diff --git a/src/Network/Swift/service.h b/src/Network/Swift/service.h index b57160ee7..3c94d0abb 100644 --- a/src/Network/Swift/service.h +++ b/src/Network/Swift/service.h @@ -1,5 +1,5 @@ -// service.h - Service module for swift<->FG connection -// +// service.h - Service module for swift<->FG connection +// // Copyright (C) 2019 - swift Project Community / Contributors (http://swift-project.org/) // Adapted to Flightgear by Lars Toenning // @@ -28,9 +28,8 @@ #include "dbusobject.h" -#include -#include #include
+#include #include #include #include @@ -40,6 +39,7 @@ #include #include #include +#include //! \cond PRIVATE @@ -49,7 +49,7 @@ namespace FGSwiftBus { - /*! +/*! * FGSwiftBus service object which is accessible through DBus */ class CService : public CDBusObject @@ -268,8 +268,6 @@ private: SGPropertyNode_ptr m_yawRateNode; SGPropertyNode_ptr m_com1VolumeNode; SGPropertyNode_ptr m_com2VolumeNode; - - }; } // namespace FGSwiftBus diff --git a/src/Network/Swift/swift_connection.cxx b/src/Network/Swift/swift_connection.cxx index ffb8e0dde..99e3f6efc 100644 --- a/src/Network/Swift/swift_connection.cxx +++ b/src/Network/Swift/swift_connection.cxx @@ -24,15 +24,10 @@ #include "plugin.h" #include "swift_connection.hxx" #include
-#include -#include -#include -#include #include #include #include #include -#include namespace { inline std::string fgswiftbusServiceName() diff --git a/src/Network/Swift/traffic.cpp b/src/Network/Swift/traffic.cpp index ecfe4b749..2d1de5714 100644 --- a/src/Network/Swift/traffic.cpp +++ b/src/Network/Swift/traffic.cpp @@ -22,8 +22,10 @@ #ifndef NOMINMAX #define NOMINMAX #endif + #include "traffic.h" #include "SwiftAircraftManager.h" + #include #include @@ -82,7 +84,7 @@ void CTraffic::cleanup() void CTraffic::dbusDisconnectedHandler() { - if(acm) + if (acm) acm->removeAllPlanes(); } @@ -90,10 +92,10 @@ const char* introspection_traffic = DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE; DBusHandlerResult CTraffic::dbusMessageHandler(const CDBusMessage& message_) { - CDBusMessage message(message_); - const std::string sender = message.getSender(); - const dbus_uint32_t serial = message.getSerial(); - const bool wantsReply = message.wantsReply(); + CDBusMessage message(message_); + const std::string sender = message.getSender(); + const dbus_uint32_t serial = message.getSerial(); + const bool wantsReply = message.wantsReply(); if (message.getInterfaceName() == DBUS_INTERFACE_INTROSPECTABLE) { if (message.getMethodName() == "Introspect") { @@ -102,9 +104,9 @@ DBusHandlerResult CTraffic::dbusMessageHandler(const CDBusMessage& message_) } else if (message.getInterfaceName() == FGSWIFTBUS_TRAFFIC_INTERFACENAME) { if (message.getMethodName() == "acquireMultiplayerPlanes") { queueDBusCall([=]() { - std::string owner; - bool acquired = true; - CDBusMessage reply = CDBusMessage::createReply(sender, serial); + std::string owner; + bool acquired = true; + CDBusMessage reply = CDBusMessage::createReply(sender, serial); reply.beginArgumentWrite(); reply.appendArgument(acquired); reply.appendArgument(owner); @@ -152,14 +154,14 @@ DBusHandlerResult CTraffic::dbusMessageHandler(const CDBusMessage& message_) } else if (message.getMethodName() == "setPlanesPositions") { maybeSendEmptyDBusReply(wantsReply, sender, serial); std::vector callsigns; - std::vector latitudes; - std::vector longitudes; - std::vector altitudes; - std::vector pitches; - std::vector rolls; - std::vector headings; - std::vector groundspeeds; - std::vector onGrounds; + std::vector latitudes; + std::vector longitudes; + std::vector altitudes; + std::vector pitches; + std::vector rolls; + std::vector headings; + std::vector groundspeeds; + std::vector onGrounds; message.beginArgumentRead(); message.getArgument(callsigns); message.getArgument(latitudes); @@ -191,10 +193,10 @@ DBusHandlerResult CTraffic::dbusMessageHandler(const CDBusMessage& message_) message.getArgument(requestedcallsigns); queueDBusCall([=]() { std::vector callsigns = requestedcallsigns; - std::vector latitudesDeg; - std::vector longitudesDeg; - std::vector elevationsM; - std::vector verticalOffsets; + std::vector latitudesDeg; + std::vector longitudesDeg; + std::vector elevationsM; + std::vector verticalOffsets; acm->getRemoteAircraftData(callsigns, latitudesDeg, longitudesDeg, elevationsM, verticalOffsets); CDBusMessage reply = CDBusMessage::createReply(sender, serial); reply.beginArgumentWrite(); @@ -205,8 +207,7 @@ DBusHandlerResult CTraffic::dbusMessageHandler(const CDBusMessage& message_) reply.appendArgument(verticalOffsets); sendDBusMessage(reply); }); - } else if (message.getMethodName() == "getElevationAtPosition") - { + } else if (message.getMethodName() == "getElevationAtPosition") { std::string callsign; double latitudeDeg; double longitudeDeg; @@ -216,21 +217,19 @@ DBusHandlerResult CTraffic::dbusMessageHandler(const CDBusMessage& message_) message.getArgument(latitudeDeg); message.getArgument(longitudeDeg); message.getArgument(altitudeMeters); - queueDBusCall([ = ]() - { - SGGeod pos; - pos.setLatitudeDeg(latitudeDeg); - pos.setLongitudeDeg(longitudeDeg); - pos.setElevationM(altitudeMeters); - double elevation = acm->getElevationAtPosition(callsign, pos); - CDBusMessage reply = CDBusMessage::createReply(sender, serial); - reply.beginArgumentWrite(); - reply.appendArgument(callsign); - reply.appendArgument(elevation); - sendDBusMessage(reply); - }); - } else if (message.getMethodName() == "setPlanesTransponders") - { + queueDBusCall([=]() { + SGGeod pos; + pos.setLatitudeDeg(latitudeDeg); + pos.setLongitudeDeg(longitudeDeg); + pos.setElevationM(altitudeMeters); + double elevation = acm->getElevationAtPosition(callsign, pos); + CDBusMessage reply = CDBusMessage::createReply(sender, serial); + reply.beginArgumentWrite(); + reply.appendArgument(callsign); + reply.appendArgument(elevation); + sendDBusMessage(reply); + }); + } else if (message.getMethodName() == "setPlanesTransponders") { maybeSendEmptyDBusReply(wantsReply, sender, serial); std::vector callsigns; std::vector codes; @@ -243,16 +242,13 @@ DBusHandlerResult CTraffic::dbusMessageHandler(const CDBusMessage& message_) message.getArgument(idents); std::vector transponders; transponders.reserve(callsigns.size()); - for(long unsigned int i = 0; i < callsigns.size(); i++) - { + for (long unsigned int i = 0; i < callsigns.size(); i++) { transponders.emplace_back(callsigns.at(i), codes.at(i), modeCs.at(i), idents.at(i)); } - queueDBusCall([ = ]() - { - acm->setPlanesTransponders(transponders); - }); - } else if (message.getMethodName() == "setPlanesSurfaces") - { + queueDBusCall([=]() { + acm->setPlanesTransponders(transponders); + }); + } else if (message.getMethodName() == "setPlanesSurfaces") { maybeSendEmptyDBusReply(wantsReply, sender, serial); std::vector callsigns; std::vector gears; @@ -291,16 +287,14 @@ DBusHandlerResult CTraffic::dbusMessageHandler(const CDBusMessage& message_) message.getArgument(lightPatterns); std::vector surfaces; surfaces.reserve(callsigns.size()); - for(long unsigned int i = 0; i < callsigns.size(); i++) - { + for (long unsigned int i = 0; i < callsigns.size(); i++) { surfaces.emplace_back(callsigns.at(i), gears.at(i), flaps.at(i), spoilers.at(i), speedBrakes.at(i), slats.at(i), wingSweeps.at(i), thrusts.at(i), elevators.at(i), rudders.at(i), ailerons.at(i), landLights.at(i), taxiLights.at(i), beaconLights.at(i), strobeLights.at(i), navLights.at(i), lightPatterns.at(i)); } - queueDBusCall([ = ]() - { - acm->setPlanesSurfaces(surfaces); - }); + queueDBusCall([=]() { + acm->setPlanesSurfaces(surfaces); + }); } else { // Unknown message. Tell DBus that we cannot handle it return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; @@ -309,11 +303,11 @@ DBusHandlerResult CTraffic::dbusMessageHandler(const CDBusMessage& message_) return DBUS_HANDLER_RESULT_HANDLED; } - int CTraffic::process() - { - invokeQueuedDBusCalls(); - return 1; - } +int CTraffic::process() +{ + invokeQueuedDBusCalls(); + return 1; +} } // namespace FGSwiftBus diff --git a/src/Network/Swift/traffic.h b/src/Network/Swift/traffic.h index bce317127..30e4f6544 100644 --- a/src/Network/Swift/traffic.h +++ b/src/Network/Swift/traffic.h @@ -24,6 +24,7 @@ #include "SwiftAircraftManager.h" #include "dbusobject.h" + #include #include @@ -47,8 +48,8 @@ public: //! DBus interface name static const std::string& InterfaceName(); - - //! DBus object path + + //! DBus object path static const std::string& ObjectPath(); //! Initialize the multiplayer planes rendering and return true if successful @@ -69,11 +70,11 @@ private: void cleanup(); struct Plane { - void* id = nullptr; - std::string callsign; - char label[32]{}; + void* id = nullptr; + std::string callsign; + char label[32]{}; }; - + bool m_emitSimFrame = true; std::unique_ptr acm; };