1
0
Fork 0

swift cleanup

This commit is contained in:
Lars Toenning 2022-03-26 11:29:25 +01:00 committed by James Turner
parent 7a0be3f000
commit 9ec7d6b855
25 changed files with 1496 additions and 1558 deletions

View file

@ -25,8 +25,11 @@
#include <list> #include <list>
#include <map> #include <map>
#include <simgear/structure/subsystem_mgr.hxx> #include <simgear/math/SGVec3.hxx>
#include <simgear/misc/sg_path.hxx>
#include <simgear/props/props.hxx>
#include <simgear/structure/SGSharedPtr.hxx> #include <simgear/structure/SGSharedPtr.hxx>
#include <simgear/structure/subsystem_mgr.hxx>
class FGAIBase; class FGAIBase;
class FGAIThermal; class FGAIThermal;

View file

@ -33,7 +33,7 @@ FGAISwiftAircraft::FGAISwiftAircraft(const std::string& callsign, const std::str
_searchOrder = ModelSearchOrder::PREFER_AI; _searchOrder = ModelSearchOrder::PREFER_AI;
} }
void FGAISwiftAircraft::updatePosition(SGGeod& position, SGVec3<double>& orientation, double groundspeed, bool initPos) void FGAISwiftAircraft::updatePosition(const SGGeod &position, const SGVec3<double> &orientation, double groundspeed, bool initPos)
{ {
m_initPos = initPos; m_initPos = initPos;
_setLatitude(position.getLatitudeDeg()); _setLatitude(position.getLatitudeDeg());

View file

@ -25,8 +25,6 @@
#include "AIBaseAircraft.hxx" #include "AIBaseAircraft.hxx"
using charPtr = const char*;
struct AircraftTransponder struct AircraftTransponder
{ {
AircraftTransponder(std::string callsign, int code, bool modeC, bool ident) AircraftTransponder(std::string callsign, int code, bool modeC, bool ident)
@ -76,7 +74,7 @@ public:
string_view getTypeString() const override { return "swift"; } string_view getTypeString() const override { return "swift"; }
void update(double dt) override; void update(double dt) override;
void updatePosition(SGGeod& position, SGVec3<double>& orientation, double groundspeed, bool initPos); void updatePosition(const SGGeod &position, const SGVec3<double> &orientation, double groundspeed, bool initPos);
double getGroundElevation(const SGGeod& pos) const; double getGroundElevation(const SGGeod& pos) const;
void initProps(); void initProps();
void setPlaneSurface(const AircraftSurfaces& surfaces); void setPlaneSurface(const AircraftSurfaces& surfaces);

View file

@ -49,15 +49,12 @@ bool FGSwiftAircraftManager::addPlane(const std::string& callsign, const std::st
return true; return true;
} }
void FGSwiftAircraftManager::updatePlanes(std::vector<std::string> callsigns, std::vector<SGGeod> positions, std::vector<SGVec3d> orientations, std::vector<double> groundspeeds, std::vector<bool> onGrounds) void FGSwiftAircraftManager::updatePlanes(const std::vector<std::string>& callsigns, const std::vector<SGGeod>& positions, const std::vector<SGVec3d>& orientations, const std::vector<double>& groundspeeds, const std::vector<bool>& 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)); auto it = aircraftByCallsign.find(callsigns.at(i));
if(it != aircraftByCallsign.end()) if (it != aircraftByCallsign.end()) {
{ it->second->updatePosition(positions.at(i), orientations.at(i), groundspeeds.at(i), true);
it->second->updatePosition(positions.at(i), orientations.at(i), groundspeeds.at(i),true);
} }
} }
} }
@ -73,9 +70,9 @@ void FGSwiftAircraftManager::getRemoteAircraftData(std::vector<std::string>& cal
elevationsM.clear(); elevationsM.clear();
verticalOffsets.clear(); verticalOffsets.clear();
for (const auto & requestedCallsign : requestedCallsigns) { for (const auto& requestedCallsign : requestedCallsigns) {
const auto it = aircraftByCallsign.find(requestedCallsign); const auto it = aircraftByCallsign.find(requestedCallsign);
if(it == aircraftByCallsign.end()) { continue; } if (it == aircraftByCallsign.end()) { continue; }
const FGAISwiftAircraft* aircraft = it->second; const FGAISwiftAircraft* aircraft = it->second;
assert(aircraft); assert(aircraft);
@ -99,8 +96,7 @@ void FGSwiftAircraftManager::getRemoteAircraftData(std::vector<std::string>& cal
void FGSwiftAircraftManager::removePlane(const std::string& callsign) void FGSwiftAircraftManager::removePlane(const std::string& callsign)
{ {
auto it = aircraftByCallsign.find(callsign); auto it = aircraftByCallsign.find(callsign);
if(it != aircraftByCallsign.end()) if (it != aircraftByCallsign.end()) {
{
it->second->setDie(true); it->second->setDie(true);
aircraftByCallsign.erase(it); aircraftByCallsign.erase(it);
} }
@ -108,18 +104,16 @@ void FGSwiftAircraftManager::removePlane(const std::string& callsign)
void FGSwiftAircraftManager::removeAllPlanes() void FGSwiftAircraftManager::removeAllPlanes()
{ {
for(auto it = aircraftByCallsign.begin(); it!= aircraftByCallsign.end();) for (auto it = aircraftByCallsign.begin(); it != aircraftByCallsign.end();) {
{
it->second->setDie(true); it->second->setDie(true);
it = aircraftByCallsign.erase(it); 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); auto it = aircraftByCallsign.find(callsign);
if(it != aircraftByCallsign.end()) if (it != aircraftByCallsign.end()) {
{
return it->second->getGroundElevation(pos); return it->second->getGroundElevation(pos);
} }
// Aircraft not found in list // Aircraft not found in list
@ -128,11 +122,9 @@ double FGSwiftAircraftManager::getElevationAtPosition(const std::string &callsig
void FGSwiftAircraftManager::setPlanesTransponders(const std::vector<AircraftTransponder>& transponders) void FGSwiftAircraftManager::setPlanesTransponders(const std::vector<AircraftTransponder>& transponders)
{ {
for (const auto & transponder : transponders) for (const auto& transponder : transponders) {
{
auto it = aircraftByCallsign.find(transponder.callsign); auto it = aircraftByCallsign.find(transponder.callsign);
if(it != aircraftByCallsign.end()) if (it != aircraftByCallsign.end()) {
{
it->second->setPlaneTransponder(transponder); it->second->setPlaneTransponder(transponder);
} }
} }
@ -140,11 +132,9 @@ void FGSwiftAircraftManager::setPlanesTransponders(const std::vector<AircraftTra
void FGSwiftAircraftManager::setPlanesSurfaces(const std::vector<AircraftSurfaces>& surfaces) void FGSwiftAircraftManager::setPlanesSurfaces(const std::vector<AircraftSurfaces>& surfaces)
{ {
for (const auto & surface : surfaces) for (const auto& surface : surfaces) {
{
auto it = aircraftByCallsign.find(surface.callsign); auto it = aircraftByCallsign.find(surface.callsign);
if(it != aircraftByCallsign.end()) if (it != aircraftByCallsign.end()) {
{
it->second->setPlaneSurface(surface); it->second->setPlaneSurface(surface);
} }
} }

View file

@ -17,12 +17,12 @@
// along with this program; if not, write to the Free Software // along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#include <Scenery/scenery.hxx>
#include <AIModel/AISwiftAircraft.h>
#include <AIModel/AIManager.hxx> #include <AIModel/AIManager.hxx>
#include <AIModel/AISwiftAircraft.h>
#include <Scenery/scenery.hxx>
#include <vector>
#include <unordered_map> #include <unordered_map>
#include <vector>
#ifndef FGSWIFTAIRCRAFTMANAGER_H #ifndef FGSWIFTAIRCRAFTMANAGER_H
#define FGSWIFTAIRCRAFTMANAGER_H #define FGSWIFTAIRCRAFTMANAGER_H
@ -35,19 +35,18 @@ public:
FGSwiftAircraftManager(); FGSwiftAircraftManager();
~FGSwiftAircraftManager(); ~FGSwiftAircraftManager();
bool addPlane(const std::string& callsign, const std::string& modelString); bool addPlane(const std::string& callsign, const std::string& modelString);
void updatePlanes(std::vector<std::string> callsigns, std::vector<SGGeod> positions, std::vector<SGVec3d> orientations, std::vector<double> groundspeeds, std::vector<bool> onGrounds); void updatePlanes(const std::vector<std::string>& callsigns, const std::vector<SGGeod>& positions, const std::vector<SGVec3d>& orientations, const std::vector<double>& groundspeeds, const std::vector<bool>& onGrounds);
void getRemoteAircraftData(std::vector<std::string>& callsigns, std::vector<double>& latitudesDeg, std::vector<double>& longitudesDeg, void getRemoteAircraftData(std::vector<std::string>& callsigns, std::vector<double>& latitudesDeg, std::vector<double>& longitudesDeg,
std::vector<double>& elevationsM, std::vector<double>& verticalOffsets) const; std::vector<double>& elevationsM, std::vector<double>& verticalOffsets) const;
void removePlane(const std::string& callsign); void removePlane(const std::string& callsign);
void removeAllPlanes(); void removeAllPlanes();
void setPlanesTransponders(const std::vector<AircraftTransponder>& transponders); void setPlanesTransponders(const std::vector<AircraftTransponder>& transponders);
double getElevationAtPosition(const std::string &callsign, const SGGeod& pos) const; double getElevationAtPosition(const std::string& callsign, const SGGeod& pos) const;
bool isInitialized() const; bool isInitialized() const;
void setPlanesSurfaces(const std::vector<AircraftSurfaces>& surfaces); void setPlanesSurfaces(const std::vector<AircraftSurfaces>& surfaces);
private: private:
std::unordered_map<std::string, FGAISwiftAircraftPtr> aircraftByCallsign; std::unordered_map<std::string, FGAISwiftAircraftPtr> aircraftByCallsign;
bool m_initialized = false; bool m_initialized = false;
}; };
#endif #endif

View file

@ -23,42 +23,42 @@
#include <dbus/dbus.h> #include <dbus/dbus.h>
#include <functional> #include <functional>
namespace FGSwiftBus namespace FGSwiftBus {
//! \cond PRIVATE
template <typename T>
class DBusAsyncCallbacks
{ {
//! \cond PRIVATE public:
template <typename T>
class DBusAsyncCallbacks
{
public:
DBusAsyncCallbacks() = default; DBusAsyncCallbacks() = default;
DBusAsyncCallbacks(const std::function<dbus_bool_t(T *)> &add, DBusAsyncCallbacks(const std::function<dbus_bool_t(T*)>& add,
const std::function<void(T *)> &remove, const std::function<void(T*)>& remove,
const std::function<void(T *)> &toggled) const std::function<void(T*)>& toggled)
: m_addHandler(add), m_removeHandler(remove), m_toggledHandler(toggled) : m_addHandler(add), m_removeHandler(remove), m_toggledHandler(toggled)
{ }
static dbus_bool_t add(T *watch, void *refcon)
{ {
return static_cast<DBusAsyncCallbacks *>(refcon)->m_addHandler(watch);
} }
static void remove(T *watch, void *refcon) static dbus_bool_t add(T* watch, void* refcon)
{ {
return static_cast<DBusAsyncCallbacks *>(refcon)->m_removeHandler(watch); return static_cast<DBusAsyncCallbacks*>(refcon)->m_addHandler(watch);
} }
static void toggled(T *watch, void *refcon) static void remove(T* watch, void* refcon)
{ {
return static_cast<DBusAsyncCallbacks *>(refcon)->m_toggledHandler(watch); return static_cast<DBusAsyncCallbacks*>(refcon)->m_removeHandler(watch);
} }
private: static void toggled(T* watch, void* refcon)
std::function<dbus_bool_t(T *)> m_addHandler; {
std::function<void(T *)> m_removeHandler; return static_cast<DBusAsyncCallbacks*>(refcon)->m_toggledHandler(watch);
std::function<void(T *)> m_toggledHandler; }
};
//! \endcond
} private:
std::function<dbus_bool_t(T*)> m_addHandler;
std::function<void(T*)> m_removeHandler;
std::function<void(T*)> m_toggledHandler;
};
//! \endcond
} // namespace FGSwiftBus
#endif // guard #endif // guard

View file

@ -1,5 +1,3 @@
#include <utility>
// dbusconnection.cpp // dbusconnection.cpp
// //
// Copyright (C) 2019 - swift Project Community / Contributors (http://swift-project.org/) // Copyright (C) 2019 - swift Project Community / Contributors (http://swift-project.org/)
@ -26,45 +24,42 @@
#include <cassert> #include <cassert>
#include <memory> #include <memory>
namespace FGSwiftBus namespace FGSwiftBus {
CDBusConnection::CDBusConnection()
{ {
CDBusConnection::CDBusConnection()
{
dbus_threads_init_default(); dbus_threads_init_default();
} }
CDBusConnection::CDBusConnection(DBusConnection *connection) CDBusConnection::CDBusConnection(DBusConnection* connection)
{ {
m_connection.reset(connection); m_connection.reset(connection);
dbus_connection_ref(connection); dbus_connection_ref(connection);
// Don't exit application, if the connection is disconnected // Don't exit application, if the connection is disconnected
dbus_connection_set_exit_on_disconnect(connection, false); dbus_connection_set_exit_on_disconnect(connection, false);
dbus_connection_add_filter(connection, filterDisconnectedFunction, this, nullptr); dbus_connection_add_filter(connection, filterDisconnectedFunction, this, nullptr);
} }
CDBusConnection::~CDBusConnection() CDBusConnection::~CDBusConnection()
{ {
close(); close();
if (m_connection) { dispatch(); } // dispatch is virtual, but safe to call in dtor, as it's declared final 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); } if (m_dispatcher) { m_dispatcher->remove(this); }
} }
bool CDBusConnection::connect(BusType type) bool CDBusConnection::connect(BusType type)
{ {
assert(type == SessionBus); assert(type == SessionBus);
DBusError error; DBusError error;
dbus_error_init(&error); dbus_error_init(&error);
DBusBusType dbusBusType; DBusBusType dbusBusType;
switch (type) switch (type) {
{
case SessionBus: dbusBusType = DBUS_BUS_SESSION; break; case SessionBus: dbusBusType = DBUS_BUS_SESSION; break;
} }
m_connection.reset(dbus_bus_get_private(dbusBusType, &error)); m_connection.reset(dbus_bus_get_private(dbusBusType, &error));
if (dbus_error_is_set(&error)) if (dbus_error_is_set(&error)) {
{
m_lastError = CDBusError(&error); m_lastError = CDBusError(&error);
return false; return false;
} }
@ -72,10 +67,10 @@ namespace FGSwiftBus
// Don't exit application, if the connection is disconnected // Don't exit application, if the connection is disconnected
dbus_connection_set_exit_on_disconnect(m_connection.get(), false); dbus_connection_set_exit_on_disconnect(m_connection.get(), false);
return true; return true;
} }
void CDBusConnection::setDispatcher(CDBusDispatcher *dispatcher) void CDBusConnection::setDispatcher(CDBusDispatcher* dispatcher)
{ {
assert(dispatcher); assert(dispatcher);
m_dispatcher = dispatcher; m_dispatcher = dispatcher;
@ -95,68 +90,67 @@ namespace FGSwiftBus
dispatcher->m_timeoutCallbacks.remove, dispatcher->m_timeoutCallbacks.remove,
dispatcher->m_timeoutCallbacks.toggled, dispatcher->m_timeoutCallbacks.toggled,
&dispatcher->m_timeoutCallbacks, nullptr); &dispatcher->m_timeoutCallbacks, nullptr);
} }
void CDBusConnection::requestName(const std::string &name) void CDBusConnection::requestName(const std::string& name)
{ {
DBusError error; DBusError error;
dbus_error_init(&error); dbus_error_init(&error);
dbus_bus_request_name(m_connection.get(), name.c_str(), 0, &error); dbus_bus_request_name(m_connection.get(), name.c_str(), 0, &error);
} }
bool CDBusConnection::isConnected() const bool CDBusConnection::isConnected() const
{ {
return m_connection && dbus_connection_get_is_connected(m_connection.get()); return m_connection && dbus_connection_get_is_connected(m_connection.get());
} }
void CDBusConnection::registerDisconnectedCallback(CDBusObject *obj, DisconnectedCallback func) void CDBusConnection::registerDisconnectedCallback(CDBusObject* obj, DisconnectedCallback func)
{ {
m_disconnectedCallbacks[obj] = func; m_disconnectedCallbacks[obj] = func;
} }
void CDBusConnection::unregisterDisconnectedCallback(CDBusObject *obj) void CDBusConnection::unregisterDisconnectedCallback(CDBusObject* obj)
{ {
auto it = m_disconnectedCallbacks.find(obj); auto it = m_disconnectedCallbacks.find(obj);
if (it == m_disconnectedCallbacks.end()) { return; } if (it == m_disconnectedCallbacks.end()) { return; }
m_disconnectedCallbacks.erase(it); m_disconnectedCallbacks.erase(it);
} }
void CDBusConnection::registerObjectPath(CDBusObject *object, const std::string &interfaceName, const std::string &objectPath, const DBusObjectPathVTable &dbusObjectPathVTable) void CDBusConnection::registerObjectPath(CDBusObject* object, const std::string& interfaceName, const std::string& objectPath, const DBusObjectPathVTable& dbusObjectPathVTable)
{ {
(void) interfaceName; (void)interfaceName;
if (!m_connection) { return; } if (!m_connection) { return; }
dbus_connection_try_register_object_path(m_connection.get(), objectPath.c_str(), &dbusObjectPathVTable, object, nullptr); dbus_connection_try_register_object_path(m_connection.get(), objectPath.c_str(), &dbusObjectPathVTable, object, nullptr);
} }
void CDBusConnection::sendMessage(const CDBusMessage &message) void CDBusConnection::sendMessage(const CDBusMessage& message)
{ {
if (!isConnected()) { return; } if (!isConnected()) { return; }
dbus_uint32_t serial = message.getSerial(); dbus_uint32_t serial = message.getSerial();
dbus_connection_send(m_connection.get(), message.m_message, &serial); dbus_connection_send(m_connection.get(), message.m_message, &serial);
} }
void CDBusConnection::close() void CDBusConnection::close()
{ {
if (m_connection) { dbus_connection_close(m_connection.get()); } if (m_connection) { dbus_connection_close(m_connection.get()); }
} }
void CDBusConnection::dispatch() void CDBusConnection::dispatch()
{ {
dbus_connection_ref(m_connection.get()); dbus_connection_ref(m_connection.get());
if (dbus_connection_get_dispatch_status(m_connection.get()) == DBUS_DISPATCH_DATA_REMAINS) if (dbus_connection_get_dispatch_status(m_connection.get()) == DBUS_DISPATCH_DATA_REMAINS) {
{ while (dbus_connection_dispatch(m_connection.get()) == DBUS_DISPATCH_DATA_REMAINS)
while (dbus_connection_dispatch(m_connection.get()) == DBUS_DISPATCH_DATA_REMAINS); ;
} }
dbus_connection_unref(m_connection.get()); dbus_connection_unref(m_connection.get());
} }
void CDBusConnection::setDispatchStatus(DBusConnection *connection, DBusDispatchStatus status) void CDBusConnection::setDispatchStatus(DBusConnection* connection, DBusDispatchStatus status)
{ {
if (dbus_connection_get_is_connected(connection) == FALSE) { return; } if (dbus_connection_get_is_connected(connection) == FALSE) { return; }
switch (status) switch (status) {
{
case DBUS_DISPATCH_DATA_REMAINS: case DBUS_DISPATCH_DATA_REMAINS:
//m_dispatcher->add(this); //m_dispatcher->add(this);
break; break;
@ -164,32 +158,30 @@ namespace FGSwiftBus
case DBUS_DISPATCH_NEED_MEMORY: case DBUS_DISPATCH_NEED_MEMORY:
break; break;
} }
} }
void CDBusConnection::setDispatchStatus(DBusConnection *connection, DBusDispatchStatus status, void *data) void CDBusConnection::setDispatchStatus(DBusConnection* connection, DBusDispatchStatus status, void* data)
{ {
auto *obj = static_cast<CDBusConnection *>(data); auto* obj = static_cast<CDBusConnection*>(data);
obj->setDispatchStatus(connection, status); obj->setDispatchStatus(connection, status);
} }
DBusHandlerResult CDBusConnection::filterDisconnectedFunction(DBusConnection *connection, DBusMessage *message, void *data) DBusHandlerResult CDBusConnection::filterDisconnectedFunction(DBusConnection* connection, DBusMessage* message, void* data)
{ {
(void)connection; // unused (void)connection; // unused
auto *obj = static_cast<CDBusConnection *>(data); auto* obj = static_cast<CDBusConnection*>(data);
DBusError err; DBusError err;
dbus_error_init(&err); dbus_error_init(&err);
if (dbus_message_is_signal (message, DBUS_INTERFACE_LOCAL, "Disconnected")) if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
{ for (auto it = obj->m_disconnectedCallbacks.begin(); it != obj->m_disconnectedCallbacks.end(); ++it) {
for (auto it = obj->m_disconnectedCallbacks.begin(); it != obj->m_disconnectedCallbacks.end(); ++it)
{
it->second(); it->second();
} }
return DBUS_HANDLER_RESULT_HANDLED; return DBUS_HANDLER_RESULT_HANDLED;
} }
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
} }
} // namespace FGSwiftBus

View file

@ -20,26 +20,25 @@
#ifndef BLACKSIM_FGSWIFTBUS_DBUSCONNECTION_H #ifndef BLACKSIM_FGSWIFTBUS_DBUSCONNECTION_H
#define BLACKSIM_FGSWIFTBUS_DBUSCONNECTION_H #define BLACKSIM_FGSWIFTBUS_DBUSCONNECTION_H
#include "dbusmessage.h"
#include "dbuserror.h"
#include "dbuscallbacks.h" #include "dbuscallbacks.h"
#include "dbusdispatcher.h" #include "dbusdispatcher.h"
#include "dbuserror.h"
#include "dbusmessage.h"
#include <event2/event.h>
#include <dbus/dbus.h> #include <dbus/dbus.h>
#include <event2/event.h>
#include <memory>
#include <string> #include <string>
#include <unordered_map> #include <unordered_map>
#include <memory>
namespace FGSwiftBus namespace FGSwiftBus {
class CDBusObject;
//! DBus connection
class CDBusConnection : public IDispatchable
{ {
public:
class CDBusObject;
//! DBus connection
class CDBusConnection : public IDispatchable
{
public:
//! Bus type //! Bus type
enum BusType { SessionBus }; enum BusType { SessionBus };
@ -50,43 +49,43 @@ namespace FGSwiftBus
CDBusConnection(); CDBusConnection();
//! Constructor //! Constructor
CDBusConnection(DBusConnection *connection); CDBusConnection(DBusConnection* connection);
//! Destructor //! Destructor
~CDBusConnection() override; ~CDBusConnection() override;
// The ones below are not implemented yet. // The ones below are not implemented yet.
// If you need them, make sure that connection reference count is correct // If you need them, make sure that connection reference count is correct
CDBusConnection(const CDBusConnection &) = delete; CDBusConnection(const CDBusConnection&) = delete;
CDBusConnection &operator=(const CDBusConnection &) = delete; CDBusConnection& operator=(const CDBusConnection&) = delete;
//! Connect to bus //! Connect to bus
bool connect(BusType type); bool connect(BusType type);
//! Set dispatcher //! Set dispatcher
void setDispatcher(CDBusDispatcher *dispatcher); void setDispatcher(CDBusDispatcher* dispatcher);
//! Request name to the bus //! Request name to the bus
void requestName(const std::string &name); void requestName(const std::string& name);
//! Is connected? //! Is connected?
bool isConnected() const; bool isConnected() const;
//! Register a disconnected callback //! Register a disconnected callback
void registerDisconnectedCallback(CDBusObject *obj, DisconnectedCallback func); void registerDisconnectedCallback(CDBusObject* obj, DisconnectedCallback func);
//! Register a disconnected callback //! Register a disconnected callback
void unregisterDisconnectedCallback(CDBusObject *obj); void unregisterDisconnectedCallback(CDBusObject* obj);
//! Register DBus object with interfaceName and objectPath. //! Register DBus object with interfaceName and objectPath.
//! \param object //! \param object
//! \param interfaceName //! \param interfaceName
//! \param objectPath //! \param objectPath
//! \param dbusObjectPathVTable Virtual table handling DBus messages //! \param dbusObjectPathVTable Virtual table handling DBus messages
void registerObjectPath(CDBusObject *object, const std::string &interfaceName, const std::string &objectPath, const DBusObjectPathVTable &dbusObjectPathVTable); void registerObjectPath(CDBusObject* object, const std::string& interfaceName, const std::string& objectPath, const DBusObjectPathVTable& dbusObjectPathVTable);
//! Send message to bus //! Send message to bus
void sendMessage(const CDBusMessage &message); void sendMessage(const CDBusMessage& message);
//! Close connection //! Close connection
void close(); void close();
@ -94,26 +93,25 @@ namespace FGSwiftBus
//! Get the last error //! Get the last error
CDBusError lastError() const { return m_lastError; } CDBusError lastError() const { return m_lastError; }
protected: protected:
// cppcheck-suppress virtualCallInConstructor // cppcheck-suppress virtualCallInConstructor
virtual void dispatch() override final; virtual void dispatch() override final;
private: private:
void setDispatchStatus(DBusConnection *connection, DBusDispatchStatus status); void setDispatchStatus(DBusConnection* connection, DBusDispatchStatus status);
static void setDispatchStatus(DBusConnection *connection, DBusDispatchStatus status, void *data); static void setDispatchStatus(DBusConnection* connection, DBusDispatchStatus status, void* data);
static DBusHandlerResult filterDisconnectedFunction(DBusConnection *connection, DBusMessage *message, void *data); static DBusHandlerResult filterDisconnectedFunction(DBusConnection* connection, DBusMessage* message, void* data);
struct DBusConnectionDeleter struct DBusConnectionDeleter {
{ void operator()(DBusConnection* obj) const { dbus_connection_unref(obj); }
void operator()(DBusConnection *obj) const { dbus_connection_unref(obj); }
}; };
CDBusDispatcher *m_dispatcher = nullptr; CDBusDispatcher* m_dispatcher = nullptr;
std::unique_ptr<DBusConnection, DBusConnectionDeleter> m_connection; std::unique_ptr<DBusConnection, DBusConnectionDeleter> m_connection;
CDBusError m_lastError; CDBusError m_lastError;
std::unordered_map<CDBusObject *, DisconnectedCallback> m_disconnectedCallbacks; std::unordered_map<CDBusObject*, DisconnectedCallback> m_disconnectedCallbacks;
}; };
} } // namespace FGSwiftBus
#endif // guard #endif // guard

View file

@ -24,32 +24,31 @@
namespace { // anonymosu namespace namespace { // anonymosu namespace
template <typename T, typename... Args> template <typename T, typename... Args>
std::unique_ptr<T> our_make_unique(Args&&... args) { std::unique_ptr<T> our_make_unique(Args&&... args)
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
} }
} // end of anonymous namespace } // end of anonymous namespace
namespace FGSwiftBus namespace FGSwiftBus {
{
//! Functor struct deleteing an event //! Functor struct deleteing an event
struct EventDeleter struct EventDeleter {
{
//! Delete functor //! Delete functor
void operator()(event *obj) const void operator()(event* obj) const
{ {
event_del(obj); event_del(obj);
event_free(obj); event_free(obj);
} }
}; };
//! DBus watch handler //! DBus watch handler
class WatchHandler class WatchHandler
{ {
public: public:
//! Constructor //! Constructor
WatchHandler(event_base *base, DBusWatch *watch) WatchHandler(event_base* base, DBusWatch* watch)
: m_base(base), m_watch(watch) : m_base(base), m_watch(watch)
{ {
const unsigned int flags = dbus_watch_get_flags(watch); const unsigned int flags = dbus_watch_get_flags(watch);
@ -64,17 +63,17 @@ namespace FGSwiftBus
} }
//! Get DBus watch //! Get DBus watch
DBusWatch *getWatch() { return m_watch; } DBusWatch* getWatch() { return m_watch; }
//! Get DBus watch //! Get DBus watch
const DBusWatch *getWatch() const { return m_watch; } const DBusWatch* getWatch() const { return m_watch; }
private: private:
//! Event callback //! Event callback
static void callback(evutil_socket_t fd, short event, void *data) static void callback(evutil_socket_t fd, short event, void* data)
{ {
(void) fd; // Not really unused, but GCC/Clang still complain about it. (void)fd; // Not really unused, but GCC/Clang still complain about it.
auto *watchHandler = static_cast<WatchHandler *>(data); auto* watchHandler = static_cast<WatchHandler*>(data);
unsigned int flags = 0; unsigned int flags = 0;
if (event & EV_READ) { flags |= DBUS_WATCH_READABLE; } if (event & EV_READ) { flags |= DBUS_WATCH_READABLE; }
@ -82,17 +81,17 @@ namespace FGSwiftBus
dbus_watch_handle(watchHandler->m_watch, flags); dbus_watch_handle(watchHandler->m_watch, flags);
} }
event_base *m_base = nullptr; event_base* m_base = nullptr;
std::unique_ptr<event, EventDeleter> m_event; std::unique_ptr<event, EventDeleter> m_event;
DBusWatch *m_watch = nullptr; DBusWatch* m_watch = nullptr;
}; };
//! DBus timeout handler //! DBus timeout handler
class TimeoutHandler class TimeoutHandler
{ {
public: public:
//! Constructor //! Constructor
TimeoutHandler(event_base *base, DBusTimeout *timeout) TimeoutHandler(event_base* base, DBusTimeout* timeout)
: m_base(base), m_timeout(timeout) : m_base(base), m_timeout(timeout)
{ {
timeval timer; timeval timer;
@ -105,55 +104,54 @@ namespace FGSwiftBus
} }
//! Get DBus timeout //! Get DBus timeout
const DBusTimeout *getTimeout() const { return m_timeout; } const DBusTimeout* getTimeout() const { return m_timeout; }
private: private:
//! Event callback //! Event callback
static void callback(evutil_socket_t fd, short event, void *data) static void callback(evutil_socket_t fd, short event, void* data)
{ {
(void) fd; // unused (void)fd; // unused
(void) event; // unused (void)event; // unused
auto *timeoutHandler = static_cast<TimeoutHandler *>(data); auto* timeoutHandler = static_cast<TimeoutHandler*>(data);
dbus_timeout_handle(timeoutHandler->m_timeout); dbus_timeout_handle(timeoutHandler->m_timeout);
} }
event_base *m_base = nullptr; event_base* m_base = nullptr;
std::unique_ptr<event, EventDeleter> m_event; std::unique_ptr<event, EventDeleter> m_event;
DBusTimeout *m_timeout = nullptr; DBusTimeout* m_timeout = nullptr;
}; };
//! Generic Timer //! Generic Timer
class Timer class Timer
{ {
public: public:
Timer() = default; Timer() = default;
//! Constructor //! Constructor
Timer(event_base *base, const timeval &timeout, const std::function<void()> &func) Timer(event_base* base, const timeval& timeout, const std::function<void()>& func)
: m_base(base), m_func(func) : m_base(base), m_func(func)
{ {
m_event.reset(evtimer_new(m_base, callback, this)); m_event.reset(evtimer_new(m_base, callback, this));
evtimer_add(m_event.get(), &timeout); evtimer_add(m_event.get(), &timeout);
} }
private: private:
//! Event callback //! Event callback
static void callback(evutil_socket_t fd, short event, void *data) static void callback(evutil_socket_t fd, short event, void* data)
{ {
(void) fd; // unused (void)fd; // unused
(void) event; // unused (void)event; // unused
auto *timer = static_cast<Timer *>(data); auto* timer = static_cast<Timer*>(data);
timer->m_func(); timer->m_func();
delete timer; delete timer;
} }
event_base *m_base = nullptr; event_base* m_base = nullptr;
std::unique_ptr<event, EventDeleter> m_event; std::unique_ptr<event, EventDeleter> m_event;
std::function<void()> m_func; std::function<void()> m_func;
}; };
CDBusDispatcher::CDBusDispatcher() : CDBusDispatcher::CDBusDispatcher() : m_eventBase(event_base_new())
m_eventBase(event_base_new()) {
{
using namespace std::placeholders; using namespace std::placeholders;
m_watchCallbacks = WatchCallbacks(std::bind(&CDBusDispatcher::dbusAddWatch, this, _1), m_watchCallbacks = WatchCallbacks(std::bind(&CDBusDispatcher::dbusAddWatch, this, _1),
std::bind(&CDBusDispatcher::dbusRemoveWatch, this, _1), std::bind(&CDBusDispatcher::dbusRemoveWatch, this, _1),
@ -162,93 +160,96 @@ namespace FGSwiftBus
m_timeoutCallbacks = TimeoutCallbacks(std::bind(&CDBusDispatcher::dbusAddTimeout, this, _1), m_timeoutCallbacks = TimeoutCallbacks(std::bind(&CDBusDispatcher::dbusAddTimeout, this, _1),
std::bind(&CDBusDispatcher::dbusRemoveTimeout, this, _1), std::bind(&CDBusDispatcher::dbusRemoveTimeout, this, _1),
std::bind(&CDBusDispatcher::dbusTimeoutToggled, this, _1)); std::bind(&CDBusDispatcher::dbusTimeoutToggled, this, _1));
} }
CDBusDispatcher::~CDBusDispatcher() CDBusDispatcher::~CDBusDispatcher()
{ {
} }
void CDBusDispatcher::add(IDispatchable *dispatchable) void CDBusDispatcher::add(IDispatchable* dispatchable)
{ {
m_dispatchList.push_back(dispatchable); m_dispatchList.push_back(dispatchable);
} }
void CDBusDispatcher::remove(IDispatchable *dispatchable) void CDBusDispatcher::remove(IDispatchable* dispatchable)
{ {
auto it = std::find(m_dispatchList.begin(), m_dispatchList.end(), dispatchable); auto it = std::find(m_dispatchList.begin(), m_dispatchList.end(), dispatchable);
if (it != m_dispatchList.end()) { m_dispatchList.erase(it); } if (it != m_dispatchList.end()) { m_dispatchList.erase(it); }
} }
void CDBusDispatcher::waitAndRun() void CDBusDispatcher::waitAndRun()
{ {
if (!m_eventBase) { return; } if (!m_eventBase) { return; }
event_base_dispatch(m_eventBase.get()); event_base_dispatch(m_eventBase.get());
} }
void CDBusDispatcher::runOnce() void CDBusDispatcher::runOnce()
{ {
if (!m_eventBase) { return; } if (!m_eventBase) { return; }
event_base_loop(m_eventBase.get(), EVLOOP_NONBLOCK); event_base_loop(m_eventBase.get(), EVLOOP_NONBLOCK);
dispatch(); dispatch();
} }
void CDBusDispatcher::dispatch() void CDBusDispatcher::dispatch()
{ {
if (m_dispatchList.empty()) { return; } if (m_dispatchList.empty()) { return; }
for (IDispatchable *dispatchable : m_dispatchList) for (IDispatchable* dispatchable : m_dispatchList) {
{
dispatchable->dispatch(); dispatchable->dispatch();
} }
} }
dbus_bool_t CDBusDispatcher::dbusAddWatch(DBusWatch *watch) dbus_bool_t CDBusDispatcher::dbusAddWatch(DBusWatch* watch)
{ {
if (dbus_watch_get_enabled(watch) == FALSE) { return true; } if (dbus_watch_get_enabled(watch) == FALSE) { return true; }
int fd = dbus_watch_get_unix_fd(watch); int fd = dbus_watch_get_unix_fd(watch);
m_watchers.emplace(fd, our_make_unique<WatchHandler>(m_eventBase.get(), watch)); m_watchers.emplace(fd, our_make_unique<WatchHandler>(m_eventBase.get(), watch));
return true; return true;
} }
void CDBusDispatcher::dbusRemoveWatch(DBusWatch *watch) void CDBusDispatcher::dbusRemoveWatch(DBusWatch* watch)
{ {
for (auto it = m_watchers.begin(); it != m_watchers.end();) for (auto it = m_watchers.begin(); it != m_watchers.end();) {
{ if (it->second->getWatch() == watch) {
if (it->second->getWatch() == watch) { it = m_watchers.erase(it); } it = m_watchers.erase(it);
else { ++it; } } else {
++it;
} }
} }
}
void CDBusDispatcher::dbusWatchToggled(DBusWatch *watch) void CDBusDispatcher::dbusWatchToggled(DBusWatch* watch)
{ {
if (dbus_watch_get_enabled(watch) == TRUE) { dbusAddWatch(watch); } if (dbus_watch_get_enabled(watch) == TRUE) {
else { dbusRemoveWatch(watch); } dbusAddWatch(watch);
} else {
dbusRemoveWatch(watch);
} }
}
dbus_bool_t CDBusDispatcher::dbusAddTimeout(DBusTimeout *timeout) dbus_bool_t CDBusDispatcher::dbusAddTimeout(DBusTimeout* timeout)
{ {
if (dbus_timeout_get_enabled(timeout) == FALSE) { return TRUE; } if (dbus_timeout_get_enabled(timeout) == FALSE) { return TRUE; }
m_timeouts.emplace_back(new TimeoutHandler(m_eventBase.get(), timeout)); m_timeouts.emplace_back(new TimeoutHandler(m_eventBase.get(), timeout));
return true; return true;
} }
void CDBusDispatcher::dbusRemoveTimeout(DBusTimeout *timeout) void CDBusDispatcher::dbusRemoveTimeout(DBusTimeout* timeout)
{ {
auto predicate = [timeout](const std::unique_ptr<TimeoutHandler> &ptr) auto predicate = [timeout](const std::unique_ptr<TimeoutHandler>& ptr) {
{
return ptr->getTimeout() == timeout; return ptr->getTimeout() == timeout;
}; };
m_timeouts.erase(std::remove_if(m_timeouts.begin(), m_timeouts.end(), predicate), m_timeouts.end()); m_timeouts.erase(std::remove_if(m_timeouts.begin(), m_timeouts.end(), predicate), m_timeouts.end());
} }
void CDBusDispatcher::dbusTimeoutToggled(DBusTimeout *timeout) void CDBusDispatcher::dbusTimeoutToggled(DBusTimeout* timeout)
{ {
if (dbus_timeout_get_enabled(timeout) == TRUE) if (dbus_timeout_get_enabled(timeout) == TRUE)
dbusAddTimeout(timeout); dbusAddTimeout(timeout);
else else
dbusRemoveTimeout(timeout); dbusRemoveTimeout(timeout);
}
} }
} // namespace FGSwiftBus

View file

@ -22,25 +22,24 @@
#include "dbuscallbacks.h" #include "dbuscallbacks.h"
#include <event2/event.h>
#include <dbus/dbus.h> #include <dbus/dbus.h>
#include <event2/event.h>
#include <memory>
#include <unordered_map> #include <unordered_map>
#include <vector> #include <vector>
#include <memory>
namespace FGSwiftBus namespace FGSwiftBus {
class WatchHandler;
class TimeoutHandler;
class CDBusConnection;
class CDBusDispatcher;
//! Dispatchable Interface
class IDispatchable
{ {
public:
class WatchHandler;
class TimeoutHandler;
class CDBusConnection;
class CDBusDispatcher;
//! Dispatchable Interface
class IDispatchable
{
public:
//! Default constructor //! Default constructor
IDispatchable() = default; IDispatchable() = default;
@ -50,14 +49,14 @@ namespace FGSwiftBus
//! Dispatch execution method //! Dispatch execution method
virtual void dispatch() = 0; virtual void dispatch() = 0;
private: private:
friend CDBusDispatcher; friend CDBusDispatcher;
}; };
//! DBus Dispatcher //! DBus Dispatcher
class CDBusDispatcher class CDBusDispatcher
{ {
public: public:
//! Constructor //! Constructor
CDBusDispatcher(); CDBusDispatcher();
@ -65,10 +64,10 @@ namespace FGSwiftBus
virtual ~CDBusDispatcher(); virtual ~CDBusDispatcher();
//! Add dispatchable object //! Add dispatchable object
void add(IDispatchable *dispatchable); void add(IDispatchable* dispatchable);
//! Remove dispatchable object //! Remove dispatchable object
void remove(IDispatchable *dispatchable); void remove(IDispatchable* dispatchable);
//! Waits for events to be dispatched and handles them //! Waits for events to be dispatched and handles them
void waitAndRun(); void waitAndRun();
@ -76,16 +75,15 @@ namespace FGSwiftBus
//! Dispatches ready handlers and returns without waiting //! Dispatches ready handlers and returns without waiting
void runOnce(); void runOnce();
private: private:
friend class WatchHandler; friend class WatchHandler;
friend class TimeoutHandler; friend class TimeoutHandler;
friend class Timer; friend class Timer;
friend class CDBusConnection; friend class CDBusConnection;
friend class CDBusServer; friend class CDBusServer;
struct EventBaseDeleter struct EventBaseDeleter {
{ void operator()(event_base* obj) const { event_base_free(obj); }
void operator()(event_base *obj) const { event_base_free(obj); }
}; };
using WatchCallbacks = DBusAsyncCallbacks<DBusWatch>; using WatchCallbacks = DBusAsyncCallbacks<DBusWatch>;
@ -93,13 +91,13 @@ namespace FGSwiftBus
void dispatch(); void dispatch();
dbus_bool_t dbusAddWatch(DBusWatch *watch); dbus_bool_t dbusAddWatch(DBusWatch* watch);
void dbusRemoveWatch(DBusWatch *watch); void dbusRemoveWatch(DBusWatch* watch);
void dbusWatchToggled(DBusWatch *watch); void dbusWatchToggled(DBusWatch* watch);
dbus_bool_t dbusAddTimeout(DBusTimeout *timeout); dbus_bool_t dbusAddTimeout(DBusTimeout* timeout);
void dbusRemoveTimeout(DBusTimeout *timeout); void dbusRemoveTimeout(DBusTimeout* timeout);
void dbusTimeoutToggled(DBusTimeout *timeout); void dbusTimeoutToggled(DBusTimeout* timeout);
WatchCallbacks m_watchCallbacks; WatchCallbacks m_watchCallbacks;
TimeoutCallbacks m_timeoutCallbacks; TimeoutCallbacks m_timeoutCallbacks;
@ -108,7 +106,7 @@ namespace FGSwiftBus
std::unique_ptr<event_base, EventBaseDeleter> m_eventBase; std::unique_ptr<event_base, EventBaseDeleter> m_eventBase;
std::vector<IDispatchable*> m_dispatchList; std::vector<IDispatchable*> m_dispatchList;
}; };
} } // namespace FGSwiftBus
#endif #endif

View file

@ -19,11 +19,11 @@
#include "dbuserror.h" #include "dbuserror.h"
namespace FGSwiftBus namespace FGSwiftBus {
{
CDBusError::CDBusError(const DBusError *error) CDBusError::CDBusError(const DBusError* error)
: m_name(error->name), m_message(error->message) : m_name(error->name), m_message(error->message)
{ } {
} }
} // namespace FGSwiftBus

View file

@ -23,16 +23,14 @@
#include <dbus/dbus.h> #include <dbus/dbus.h>
#include <string> #include <string>
namespace FGSwiftBus namespace FGSwiftBus {
{
//! DBus error //! DBus error
class CDBusError class CDBusError
{ {
public: public:
//! Error type //! Error type
enum ErrorType enum ErrorType {
{
NoError, NoError,
Other Other
}; };
@ -41,17 +39,17 @@ namespace FGSwiftBus
CDBusError() = default; CDBusError() = default;
//! Constructor //! Constructor
explicit CDBusError(const DBusError *error); explicit CDBusError(const DBusError* error);
//! Get error type //! Get error type
ErrorType getType() const { return m_errorType; } ErrorType getType() const { return m_errorType; }
private: private:
ErrorType m_errorType = NoError; ErrorType m_errorType = NoError;
std::string m_name; std::string m_name;
std::string m_message; std::string m_message;
}; };
} } // namespace FGSwiftBus
#endif // guard #endif // guard

View file

@ -19,245 +19,241 @@
#include "dbusmessage.h" #include "dbusmessage.h"
namespace FGSwiftBus namespace FGSwiftBus {
CDBusMessage::CDBusMessage(DBusMessage* message)
{ {
CDBusMessage::CDBusMessage(DBusMessage *message)
{
m_message = dbus_message_ref(message); m_message = dbus_message_ref(message);
} }
CDBusMessage::CDBusMessage(const CDBusMessage &other) CDBusMessage::CDBusMessage(const CDBusMessage& other)
{ {
m_message = dbus_message_ref(other.m_message); m_message = dbus_message_ref(other.m_message);
m_serial = other.m_serial; m_serial = other.m_serial;
} }
CDBusMessage::CDBusMessage(DBusMessage *message, dbus_uint32_t serial) CDBusMessage::CDBusMessage(DBusMessage* message, dbus_uint32_t serial)
{ {
m_message = dbus_message_ref(message); m_message = dbus_message_ref(message);
m_serial = serial; m_serial = serial;
} }
CDBusMessage::~CDBusMessage() CDBusMessage::~CDBusMessage()
{ {
dbus_message_unref(m_message); dbus_message_unref(m_message);
} }
CDBusMessage &CDBusMessage::operator =(CDBusMessage other) CDBusMessage& CDBusMessage::operator=(CDBusMessage other)
{ {
std::swap(m_serial, other.m_serial); std::swap(m_serial, other.m_serial);
m_message = dbus_message_ref(other.m_message); m_message = dbus_message_ref(other.m_message);
return *this; return *this;
} }
bool CDBusMessage::isMethodCall() const bool CDBusMessage::isMethodCall() const
{ {
return dbus_message_get_type(m_message) == DBUS_MESSAGE_TYPE_METHOD_CALL; return dbus_message_get_type(m_message) == DBUS_MESSAGE_TYPE_METHOD_CALL;
} }
bool CDBusMessage::wantsReply() const bool CDBusMessage::wantsReply() const
{ {
return !dbus_message_get_no_reply(m_message); return !dbus_message_get_no_reply(m_message);
} }
std::string CDBusMessage::getSender() const std::string CDBusMessage::getSender() const
{ {
const char *sender = dbus_message_get_sender(m_message); const char* sender = dbus_message_get_sender(m_message);
return sender ? std::string(sender) : std::string(); return sender ? std::string(sender) : std::string();
} }
dbus_uint32_t CDBusMessage::getSerial() const dbus_uint32_t CDBusMessage::getSerial() const
{ {
return dbus_message_get_serial(m_message); return dbus_message_get_serial(m_message);
} }
std::string CDBusMessage::getInterfaceName() const std::string CDBusMessage::getInterfaceName() const
{ {
return dbus_message_get_interface(m_message); return dbus_message_get_interface(m_message);
} }
std::string CDBusMessage::getObjectPath() const std::string CDBusMessage::getObjectPath() const
{ {
return dbus_message_get_path(m_message); return dbus_message_get_path(m_message);
} }
std::string CDBusMessage::getMethodName() const std::string CDBusMessage::getMethodName() const
{ {
return dbus_message_get_member(m_message); return dbus_message_get_member(m_message);
} }
void CDBusMessage::beginArgumentWrite() void CDBusMessage::beginArgumentWrite()
{ {
dbus_message_iter_init_append(m_message, &m_messageIterator); dbus_message_iter_init_append(m_message, &m_messageIterator);
} }
void CDBusMessage::appendArgument(bool value) void CDBusMessage::appendArgument(bool value)
{ {
dbus_bool_t boolean = value ? 1 : 0; dbus_bool_t boolean = value ? 1 : 0;
dbus_message_iter_append_basic(&m_messageIterator, DBUS_TYPE_BOOLEAN, &boolean); dbus_message_iter_append_basic(&m_messageIterator, DBUS_TYPE_BOOLEAN, &boolean);
} }
void CDBusMessage::appendArgument(const char *value) void CDBusMessage::appendArgument(const char* value)
{ {
dbus_message_iter_append_basic(&m_messageIterator, DBUS_TYPE_STRING, &value); dbus_message_iter_append_basic(&m_messageIterator, DBUS_TYPE_STRING, &value);
} }
void CDBusMessage::appendArgument(const std::string &value) void CDBusMessage::appendArgument(const std::string& value)
{ {
const char *ptr = value.c_str(); const char* ptr = value.c_str();
dbus_message_iter_append_basic(&m_messageIterator, DBUS_TYPE_STRING, &ptr); dbus_message_iter_append_basic(&m_messageIterator, DBUS_TYPE_STRING, &ptr);
} }
void CDBusMessage::appendArgument(int value) void CDBusMessage::appendArgument(int value)
{ {
dbus_int32_t i = value; dbus_int32_t i = value;
dbus_message_iter_append_basic(&m_messageIterator, DBUS_TYPE_INT32, &i); dbus_message_iter_append_basic(&m_messageIterator, DBUS_TYPE_INT32, &i);
} }
void CDBusMessage::appendArgument(double value) void CDBusMessage::appendArgument(double value)
{ {
dbus_message_iter_append_basic(&m_messageIterator, DBUS_TYPE_DOUBLE, &value); dbus_message_iter_append_basic(&m_messageIterator, DBUS_TYPE_DOUBLE, &value);
} }
void CDBusMessage::appendArgument(const std::vector<double> &array) void CDBusMessage::appendArgument(const std::vector<double>& array)
{ {
DBusMessageIter arrayIterator; DBusMessageIter arrayIterator;
dbus_message_iter_open_container(&m_messageIterator, DBUS_TYPE_ARRAY, DBUS_TYPE_DOUBLE_AS_STRING, &arrayIterator); dbus_message_iter_open_container(&m_messageIterator, DBUS_TYPE_ARRAY, DBUS_TYPE_DOUBLE_AS_STRING, &arrayIterator);
const double *ptr = array.data(); const double* ptr = array.data();
dbus_message_iter_append_fixed_array(&arrayIterator, DBUS_TYPE_DOUBLE, &ptr, static_cast<int>(array.size())); dbus_message_iter_append_fixed_array(&arrayIterator, DBUS_TYPE_DOUBLE, &ptr, static_cast<int>(array.size()));
dbus_message_iter_close_container(&m_messageIterator, &arrayIterator); dbus_message_iter_close_container(&m_messageIterator, &arrayIterator);
} }
void CDBusMessage::appendArgument(const std::vector<std::string> &array) void CDBusMessage::appendArgument(const std::vector<std::string>& array)
{ {
DBusMessageIter arrayIterator; DBusMessageIter arrayIterator;
dbus_message_iter_open_container(&m_messageIterator, DBUS_TYPE_ARRAY, DBUS_TYPE_STRING_AS_STRING, &arrayIterator); dbus_message_iter_open_container(&m_messageIterator, DBUS_TYPE_ARRAY, DBUS_TYPE_STRING_AS_STRING, &arrayIterator);
for (const auto &i : array) for (const auto& i : array) {
{ const char* ptr = i.c_str();
const char *ptr = i.c_str();
dbus_message_iter_append_basic(&arrayIterator, DBUS_TYPE_STRING, &ptr); dbus_message_iter_append_basic(&arrayIterator, DBUS_TYPE_STRING, &ptr);
} }
dbus_message_iter_close_container(&m_messageIterator, &arrayIterator); dbus_message_iter_close_container(&m_messageIterator, &arrayIterator);
} }
void CDBusMessage::beginArgumentRead() void CDBusMessage::beginArgumentRead()
{ {
dbus_message_iter_init(m_message, &m_messageIterator); dbus_message_iter_init(m_message, &m_messageIterator);
} }
void CDBusMessage::getArgument(int &value) void CDBusMessage::getArgument(int& value)
{ {
if (dbus_message_iter_get_arg_type(&m_messageIterator) != DBUS_TYPE_INT32) { return; } if (dbus_message_iter_get_arg_type(&m_messageIterator) != DBUS_TYPE_INT32) { return; }
dbus_int32_t i; dbus_int32_t i;
dbus_message_iter_get_basic(&m_messageIterator, &i); dbus_message_iter_get_basic(&m_messageIterator, &i);
value = i; value = i;
dbus_message_iter_next(&m_messageIterator); dbus_message_iter_next(&m_messageIterator);
} }
void CDBusMessage::getArgument(bool &value) void CDBusMessage::getArgument(bool& value)
{ {
if (dbus_message_iter_get_arg_type(&m_messageIterator) != DBUS_TYPE_BOOLEAN) { return; } if (dbus_message_iter_get_arg_type(&m_messageIterator) != DBUS_TYPE_BOOLEAN) { return; }
dbus_bool_t v; dbus_bool_t v;
dbus_message_iter_get_basic(&m_messageIterator, &v); dbus_message_iter_get_basic(&m_messageIterator, &v);
if (v == TRUE) { value = true; } if (v == TRUE) {
else { value = false; } value = true;
dbus_message_iter_next(&m_messageIterator); } else {
value = false;
} }
dbus_message_iter_next(&m_messageIterator);
}
void CDBusMessage::getArgument(double &value) void CDBusMessage::getArgument(double& value)
{ {
if (dbus_message_iter_get_arg_type(&m_messageIterator) != DBUS_TYPE_DOUBLE) { return; } if (dbus_message_iter_get_arg_type(&m_messageIterator) != DBUS_TYPE_DOUBLE) { return; }
dbus_message_iter_get_basic(&m_messageIterator, &value); dbus_message_iter_get_basic(&m_messageIterator, &value);
dbus_message_iter_next(&m_messageIterator); dbus_message_iter_next(&m_messageIterator);
} }
void CDBusMessage::getArgument(std::string &value) void CDBusMessage::getArgument(std::string& value)
{ {
const char *str = nullptr; const char* str = nullptr;
if (dbus_message_iter_get_arg_type(&m_messageIterator) != DBUS_TYPE_STRING) { return; } if (dbus_message_iter_get_arg_type(&m_messageIterator) != DBUS_TYPE_STRING) { return; }
dbus_message_iter_get_basic(&m_messageIterator, &str); dbus_message_iter_get_basic(&m_messageIterator, &str);
dbus_message_iter_next(&m_messageIterator); dbus_message_iter_next(&m_messageIterator);
value = std::string(str); value = std::string(str);
} }
void CDBusMessage::getArgument(std::vector<int> &value) void CDBusMessage::getArgument(std::vector<int>& value)
{ {
DBusMessageIter arrayIterator; DBusMessageIter arrayIterator;
dbus_message_iter_recurse(&m_messageIterator, &arrayIterator); dbus_message_iter_recurse(&m_messageIterator, &arrayIterator);
do do {
{
if (dbus_message_iter_get_arg_type(&arrayIterator) != DBUS_TYPE_INT32) { return; } if (dbus_message_iter_get_arg_type(&arrayIterator) != DBUS_TYPE_INT32) { return; }
dbus_int32_t i; dbus_int32_t i;
dbus_message_iter_get_basic(&arrayIterator, &i); dbus_message_iter_get_basic(&arrayIterator, &i);
value.push_back(i); value.push_back(i);
} } while (dbus_message_iter_next(&arrayIterator));
while (dbus_message_iter_next(&arrayIterator));
dbus_message_iter_next(&m_messageIterator); dbus_message_iter_next(&m_messageIterator);
} }
void CDBusMessage::getArgument(std::vector<bool> &value) void CDBusMessage::getArgument(std::vector<bool>& value)
{ {
if (dbus_message_iter_get_arg_type(&m_messageIterator) != DBUS_TYPE_ARRAY) { return; } if (dbus_message_iter_get_arg_type(&m_messageIterator) != DBUS_TYPE_ARRAY) { return; }
DBusMessageIter arrayIterator; DBusMessageIter arrayIterator;
dbus_message_iter_recurse(&m_messageIterator, &arrayIterator); dbus_message_iter_recurse(&m_messageIterator, &arrayIterator);
do do {
{
if (dbus_message_iter_get_arg_type(&arrayIterator) != DBUS_TYPE_BOOLEAN) { return; } if (dbus_message_iter_get_arg_type(&arrayIterator) != DBUS_TYPE_BOOLEAN) { return; }
dbus_bool_t b; dbus_bool_t b;
dbus_message_iter_get_basic(&arrayIterator, &b); dbus_message_iter_get_basic(&arrayIterator, &b);
if (b == TRUE) { value.push_back(true); } if (b == TRUE) {
else { value.push_back(false); } value.push_back(true);
} else {
value.push_back(false);
} }
while (dbus_message_iter_next(&arrayIterator)); } while (dbus_message_iter_next(&arrayIterator));
dbus_message_iter_next(&m_messageIterator); dbus_message_iter_next(&m_messageIterator);
} }
void CDBusMessage::getArgument(std::vector<double> &value) void CDBusMessage::getArgument(std::vector<double>& value)
{ {
DBusMessageIter arrayIterator; DBusMessageIter arrayIterator;
dbus_message_iter_recurse(&m_messageIterator, &arrayIterator); dbus_message_iter_recurse(&m_messageIterator, &arrayIterator);
do do {
{
if (dbus_message_iter_get_arg_type(&arrayIterator) != DBUS_TYPE_DOUBLE) { return; } if (dbus_message_iter_get_arg_type(&arrayIterator) != DBUS_TYPE_DOUBLE) { return; }
double d; double d;
dbus_message_iter_get_basic(&arrayIterator, &d); dbus_message_iter_get_basic(&arrayIterator, &d);
value.push_back(d); value.push_back(d);
} } while (dbus_message_iter_next(&arrayIterator));
while (dbus_message_iter_next(&arrayIterator));
dbus_message_iter_next(&m_messageIterator); dbus_message_iter_next(&m_messageIterator);
} }
void CDBusMessage::getArgument(std::vector<std::string> &value) void CDBusMessage::getArgument(std::vector<std::string>& value)
{ {
DBusMessageIter arrayIterator; DBusMessageIter arrayIterator;
dbus_message_iter_recurse(&m_messageIterator, &arrayIterator); dbus_message_iter_recurse(&m_messageIterator, &arrayIterator);
do do {
{
if (dbus_message_iter_get_arg_type(&arrayIterator) != DBUS_TYPE_STRING) { return; } if (dbus_message_iter_get_arg_type(&arrayIterator) != DBUS_TYPE_STRING) { return; }
const char *str = nullptr; const char* str = nullptr;
dbus_message_iter_get_basic(&arrayIterator, &str); dbus_message_iter_get_basic(&arrayIterator, &str);
value.push_back(std::string(str)); value.push_back(std::string(str));
} } while (dbus_message_iter_next(&arrayIterator));
while (dbus_message_iter_next(&arrayIterator));
dbus_message_iter_next(&m_messageIterator); dbus_message_iter_next(&m_messageIterator);
} }
CDBusMessage CDBusMessage::createSignal(const std::string &path, const std::string &interfaceName, const std::string &signalName) 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()); DBusMessage* signal = dbus_message_new_signal(path.c_str(), interfaceName.c_str(), signalName.c_str());
return CDBusMessage(signal); return CDBusMessage(signal);
} }
CDBusMessage CDBusMessage::createReply(const std::string &destination, dbus_uint32_t serial) CDBusMessage CDBusMessage::createReply(const std::string& destination, dbus_uint32_t serial)
{ {
DBusMessage *reply = dbus_message_new(DBUS_MESSAGE_TYPE_METHOD_RETURN); DBusMessage* reply = dbus_message_new(DBUS_MESSAGE_TYPE_METHOD_RETURN);
dbus_message_set_no_reply(reply, TRUE); dbus_message_set_no_reply(reply, TRUE);
if (! destination.empty()) { dbus_message_set_destination(reply, destination.c_str()); } if (!destination.empty()) { dbus_message_set_destination(reply, destination.c_str()); }
dbus_message_set_reply_serial(reply, serial); dbus_message_set_reply_serial(reply, serial);
CDBusMessage msg(reply); CDBusMessage msg(reply);
dbus_message_unref(reply); dbus_message_unref(reply);
return msg; return msg;
}
} }
} // namespace FGSwiftBus

View file

@ -24,24 +24,23 @@
#include <string> #include <string>
#include <vector> #include <vector>
namespace FGSwiftBus namespace FGSwiftBus {
{
//! DBus Message //! DBus Message
class CDBusMessage class CDBusMessage
{ {
public: public:
//! Constructor //! Constructor
//! @{ //! @{
CDBusMessage(DBusMessage *message); CDBusMessage(DBusMessage* message);
CDBusMessage(const CDBusMessage &other); CDBusMessage(const CDBusMessage& other);
//! @} //! @}
//! Destructor //! Destructor
~CDBusMessage(); ~CDBusMessage();
//! Assignment operator //! Assignment operator
CDBusMessage &operator=(CDBusMessage other); CDBusMessage& operator=(CDBusMessage other);
//! Is this message a method call? //! Is this message a method call?
bool isMethodCall() const; bool isMethodCall() const;
@ -70,12 +69,12 @@ namespace FGSwiftBus
//! Append argument. Make sure to call \sa beginArgumentWrite() before. //! Append argument. Make sure to call \sa beginArgumentWrite() before.
//! @{ //! @{
void appendArgument(bool value); void appendArgument(bool value);
void appendArgument(const char *value); void appendArgument(const char* value);
void appendArgument(const std::string &value); void appendArgument(const std::string& value);
void appendArgument(int value); void appendArgument(int value);
void appendArgument(double value); void appendArgument(double value);
void appendArgument(const std::vector<double> &array); void appendArgument(const std::vector<double>& array);
void appendArgument(const std::vector<std::string> &array); void appendArgument(const std::vector<std::string>& array);
//! @} //! @}
//! Begin reading arguments //! Begin reading arguments
@ -83,31 +82,31 @@ namespace FGSwiftBus
//! Read single argument. Make sure to call \sa beginArgumentRead() before. //! Read single argument. Make sure to call \sa beginArgumentRead() before.
//! @{ //! @{
void getArgument(int &value); void getArgument(int& value);
void getArgument(bool &value); void getArgument(bool& value);
void getArgument(double &value); void getArgument(double& value);
void getArgument(std::string &value); void getArgument(std::string& value);
void getArgument(std::vector<int> &value); void getArgument(std::vector<int>& value);
void getArgument(std::vector<bool> &value); void getArgument(std::vector<bool>& value);
void getArgument(std::vector<double> &value); void getArgument(std::vector<double>& value);
void getArgument(std::vector<std::string> &value); void getArgument(std::vector<std::string>& value);
//! @} //! @}
//! Creates a DBus message containing a DBus signal //! Creates a DBus message containing a DBus signal
static CDBusMessage createSignal(const std::string &path, const std::string &interfaceName, const std::string &signalName); static CDBusMessage createSignal(const std::string& path, const std::string& interfaceName, const std::string& signalName);
//! Creates a DBus message containing a DBus reply //! Creates a DBus message containing a DBus reply
static CDBusMessage createReply(const std::string &destination, dbus_uint32_t serial); static CDBusMessage createReply(const std::string& destination, dbus_uint32_t serial);
private: private:
friend class CDBusConnection; friend class CDBusConnection;
DBusMessage *m_message = nullptr; DBusMessage* m_message = nullptr;
DBusMessageIter m_messageIterator; DBusMessageIter m_messageIterator;
CDBusMessage(DBusMessage *message, dbus_uint32_t serial); CDBusMessage(DBusMessage* message, dbus_uint32_t serial);
dbus_uint32_t m_serial = 0; dbus_uint32_t m_serial = 0;
}; };
} } // namespace FGSwiftBus
#endif // guard #endif // guard

View file

@ -20,87 +20,85 @@
#include "dbusobject.h" #include "dbusobject.h"
#include <cassert> #include <cassert>
namespace FGSwiftBus namespace FGSwiftBus {
CDBusObject::CDBusObject()
{ {
CDBusObject::CDBusObject() }
{ }
CDBusObject::~CDBusObject() CDBusObject::~CDBusObject()
{ {
if (m_dbusConnection) { m_dbusConnection->unregisterDisconnectedCallback(this); } if (m_dbusConnection) { m_dbusConnection->unregisterDisconnectedCallback(this); }
}; };
void CDBusObject::setDBusConnection(const std::shared_ptr<CDBusConnection> &dbusConnection) void CDBusObject::setDBusConnection(const std::shared_ptr<CDBusConnection>& dbusConnection)
{ {
m_dbusConnection = dbusConnection; m_dbusConnection = dbusConnection;
dbusConnectedHandler(); dbusConnectedHandler();
CDBusConnection::DisconnectedCallback disconnectedHandler = std::bind(&CDBusObject::dbusDisconnectedHandler, this); CDBusConnection::DisconnectedCallback disconnectedHandler = std::bind(&CDBusObject::dbusDisconnectedHandler, this);
m_dbusConnection->registerDisconnectedCallback(this, disconnectedHandler); m_dbusConnection->registerDisconnectedCallback(this, disconnectedHandler);
} }
void CDBusObject::registerDBusObjectPath(const std::string &interfaceName, const std::string &objectPath) void CDBusObject::registerDBusObjectPath(const std::string& interfaceName, const std::string& objectPath)
{ {
assert(m_dbusConnection); assert(m_dbusConnection);
m_interfaceName = interfaceName; m_interfaceName = interfaceName;
m_objectPath = objectPath; m_objectPath = objectPath;
m_dbusConnection->registerObjectPath(this, interfaceName, objectPath, m_dbusObjectPathVTable); m_dbusConnection->registerObjectPath(this, interfaceName, objectPath, m_dbusObjectPathVTable);
} }
void CDBusObject::sendDBusSignal(const std::string &name) void CDBusObject::sendDBusSignal(const std::string& name)
{ {
if (! m_dbusConnection) { return; } if (!m_dbusConnection) { return; }
CDBusMessage signal = CDBusMessage::createSignal(m_objectPath, m_interfaceName, name); CDBusMessage signal = CDBusMessage::createSignal(m_objectPath, m_interfaceName, name);
m_dbusConnection->sendMessage(signal); m_dbusConnection->sendMessage(signal);
} }
void CDBusObject::sendDBusMessage(const CDBusMessage &message) void CDBusObject::sendDBusMessage(const CDBusMessage& message)
{ {
if (! m_dbusConnection) { return; } if (!m_dbusConnection) { return; }
m_dbusConnection->sendMessage(message); m_dbusConnection->sendMessage(message);
} }
void CDBusObject::maybeSendEmptyDBusReply(bool wantsReply, const std::string &destination, dbus_uint32_t serial) void CDBusObject::maybeSendEmptyDBusReply(bool wantsReply, const std::string& destination, dbus_uint32_t serial)
{ {
if (wantsReply) if (wantsReply) {
{
CDBusMessage reply = CDBusMessage::createReply(destination, serial); CDBusMessage reply = CDBusMessage::createReply(destination, serial);
m_dbusConnection->sendMessage(reply); m_dbusConnection->sendMessage(reply);
} }
} }
void CDBusObject::queueDBusCall(const std::function<void ()> &func) void CDBusObject::queueDBusCall(const std::function<void()>& func)
{ {
std::lock_guard<std::mutex> lock(m_mutex); std::lock_guard<std::mutex> lock(m_mutex);
m_qeuedDBusCalls.push_back(func); m_qeuedDBusCalls.push_back(func);
} }
void CDBusObject::invokeQueuedDBusCalls() void CDBusObject::invokeQueuedDBusCalls()
{ {
std::lock_guard<std::mutex> lock(m_mutex); std::lock_guard<std::mutex> lock(m_mutex);
while (m_qeuedDBusCalls.size() > 0) while (m_qeuedDBusCalls.size() > 0) {
{
m_qeuedDBusCalls.front()(); m_qeuedDBusCalls.front()();
m_qeuedDBusCalls.pop_front(); m_qeuedDBusCalls.pop_front();
} }
} }
void CDBusObject::dbusObjectPathUnregisterFunction(DBusConnection *connection, void *data) void CDBusObject::dbusObjectPathUnregisterFunction(DBusConnection* connection, void* data)
{ {
(void)connection; // unused (void)connection; // unused
(void)data; // unused (void)data; // unused
} }
DBusHandlerResult CDBusObject::dbusObjectPathMessageFunction(DBusConnection *connection, DBusMessage *message, void *data) DBusHandlerResult CDBusObject::dbusObjectPathMessageFunction(DBusConnection* connection, DBusMessage* message, void* data)
{ {
(void)connection; // unused (void)connection; // unused
auto *obj = static_cast<CDBusObject *>(data); auto* obj = static_cast<CDBusObject*>(data);
DBusError err; DBusError err;
dbus_error_init(&err); dbus_error_init(&err);
CDBusMessage dbusMessage(message); CDBusMessage dbusMessage(message);
return obj->dbusMessageHandler(dbusMessage); return obj->dbusMessageHandler(dbusMessage);
}
} }
} // namespace FGSwiftBus

View file

@ -21,15 +21,14 @@
#define BLACKSIM_FGSWIFTBUS_DBUSOBJECT_H #define BLACKSIM_FGSWIFTBUS_DBUSOBJECT_H
#include "dbusconnection.h" #include "dbusconnection.h"
#include <mutex>
#include <deque> #include <deque>
#include <mutex>
namespace FGSwiftBus namespace FGSwiftBus {
//! DBus base object
class CDBusObject
{ {
//! DBus base object public:
class CDBusObject
{
public:
//! Constructor //! Constructor
CDBusObject(); CDBusObject();
@ -38,34 +37,34 @@ namespace FGSwiftBus
//! Set the assigned DBus connection. //! Set the assigned DBus connection.
//! \remark Currently one object can only manage one connection at a time //! \remark Currently one object can only manage one connection at a time
void setDBusConnection(const std::shared_ptr<CDBusConnection> &dbusConnection); void setDBusConnection(const std::shared_ptr<CDBusConnection>& dbusConnection);
//! Register itself with interfaceName and objectPath //! Register itself with interfaceName and objectPath
//! \warning Before calling this method, make sure that a valid DBus connection was set. //! \warning Before calling this method, make sure that a valid DBus connection was set.
void registerDBusObjectPath(const std::string &interfaceName, const std::string &objectPath); void registerDBusObjectPath(const std::string& interfaceName, const std::string& objectPath);
protected: protected:
//! Handler which is called when DBusCconnection is established //! Handler which is called when DBusCconnection is established
virtual void dbusConnectedHandler() {} virtual void dbusConnectedHandler() {}
//! DBus message handler //! DBus message handler
virtual DBusHandlerResult dbusMessageHandler(const CDBusMessage &message) = 0; virtual DBusHandlerResult dbusMessageHandler(const CDBusMessage& message) = 0;
//! Handler which is called when DBusConnection disconnected //! Handler which is called when DBusConnection disconnected
virtual void dbusDisconnectedHandler() {} virtual void dbusDisconnectedHandler() {}
//! Send DBus signal //! Send DBus signal
void sendDBusSignal(const std::string &name); void sendDBusSignal(const std::string& name);
//! Send DBus message //! Send DBus message
void sendDBusMessage(const CDBusMessage &message); void sendDBusMessage(const CDBusMessage& message);
//! Maybe sends an empty DBus reply (acknowledgement) //! Maybe sends an empty DBus reply (acknowledgement)
void maybeSendEmptyDBusReply(bool wantsReply, const std::string &destination, dbus_uint32_t serial); void maybeSendEmptyDBusReply(bool wantsReply, const std::string& destination, dbus_uint32_t serial);
//! Send DBus reply //! Send DBus reply
template <typename T> template <typename T>
void sendDBusReply(const std::string &destination, dbus_uint32_t serial, const T &argument) void sendDBusReply(const std::string& destination, dbus_uint32_t serial, const T& argument)
{ {
CDBusMessage reply = CDBusMessage::createReply(destination, serial); CDBusMessage reply = CDBusMessage::createReply(destination, serial);
reply.beginArgumentWrite(); reply.beginArgumentWrite();
@ -75,7 +74,7 @@ namespace FGSwiftBus
//! Send DBus reply //! Send DBus reply
template <typename T> template <typename T>
void sendDBusReply(const std::string &destination, dbus_uint32_t serial, const std::vector<T> &array) void sendDBusReply(const std::string& destination, dbus_uint32_t serial, const std::vector<T>& array)
{ {
CDBusMessage reply = CDBusMessage::createReply(destination, serial); CDBusMessage reply = CDBusMessage::createReply(destination, serial);
reply.beginArgumentWrite(); reply.beginArgumentWrite();
@ -84,14 +83,14 @@ namespace FGSwiftBus
} }
//! Queue a DBus call to be executed in a different thread //! Queue a DBus call to be executed in a different thread
void queueDBusCall(const std::function<void()> &func); void queueDBusCall(const std::function<void()>& func);
//! Invoke all pending DBus calls. They will be executed in the calling thread. //! Invoke all pending DBus calls. They will be executed in the calling thread.
void invokeQueuedDBusCalls(); void invokeQueuedDBusCalls();
private: private:
static void dbusObjectPathUnregisterFunction(DBusConnection *connection, void *data); static void dbusObjectPathUnregisterFunction(DBusConnection* connection, void* data);
static DBusHandlerResult dbusObjectPathMessageFunction(DBusConnection *connection, DBusMessage *message, void *data); static DBusHandlerResult dbusObjectPathMessageFunction(DBusConnection* connection, DBusMessage* message, void* data);
std::shared_ptr<CDBusConnection> m_dbusConnection; std::shared_ptr<CDBusConnection> m_dbusConnection;
std::string m_interfaceName; std::string m_interfaceName;
@ -100,9 +99,9 @@ namespace FGSwiftBus
std::mutex m_mutex; std::mutex m_mutex;
std::deque<std::function<void()>> m_qeuedDBusCalls; std::deque<std::function<void()>> m_qeuedDBusCalls;
const DBusObjectPathVTable m_dbusObjectPathVTable = { dbusObjectPathUnregisterFunction, dbusObjectPathMessageFunction, nullptr, nullptr, nullptr, nullptr }; const DBusObjectPathVTable m_dbusObjectPathVTable = {dbusObjectPathUnregisterFunction, dbusObjectPathMessageFunction, nullptr, nullptr, nullptr, nullptr};
}; };
} } // namespace FGSwiftBus
#endif // guard #endif // guard

View file

@ -19,53 +19,51 @@
// along with this program; if not, write to the Free Software // along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#include "dbusserver.h"
#include "dbusobject.h" #include "dbusobject.h"
#include "dbusserver.h"
#include <algorithm> #include <algorithm>
#include <cassert> #include <cassert>
#include <memory> #include <memory>
namespace FGSwiftBus namespace FGSwiftBus {
CDBusServer::CDBusServer()
{ {
CDBusServer::CDBusServer()
{
dbus_threads_init_default(); dbus_threads_init_default();
} }
CDBusServer::~CDBusServer() CDBusServer::~CDBusServer()
{ {
close(); close();
} }
bool CDBusServer::listen(const std::string &address) bool CDBusServer::listen(const std::string& address)
{ {
DBusError error; DBusError error;
dbus_error_init(&error); dbus_error_init(&error);
m_server.reset(dbus_server_listen(address.c_str(), &error)); m_server.reset(dbus_server_listen(address.c_str(), &error));
if (! m_server) if (!m_server) {
{
return false; return false;
} }
dbus_server_set_new_connection_function(m_server.get(), onNewConnection, this, nullptr); dbus_server_set_new_connection_function(m_server.get(), onNewConnection, this, nullptr);
return true; return true;
} }
bool CDBusServer::isConnected() const bool CDBusServer::isConnected() const
{ {
return m_server ? dbus_server_get_is_connected(m_server.get()) : false; return m_server ? dbus_server_get_is_connected(m_server.get()) : false;
} }
void CDBusServer::close() void CDBusServer::close()
{ {
if (m_server) { dbus_server_disconnect(m_server.get()); } if (m_server) { dbus_server_disconnect(m_server.get()); }
} }
void CDBusServer::setDispatcher(CDBusDispatcher *dispatcher) void CDBusServer::setDispatcher(CDBusDispatcher* dispatcher)
{ {
assert(dispatcher); assert(dispatcher);
assert(m_server); assert(m_server);
@ -84,18 +82,18 @@ namespace FGSwiftBus
dispatcher->m_timeoutCallbacks.remove, dispatcher->m_timeoutCallbacks.remove,
dispatcher->m_timeoutCallbacks.toggled, dispatcher->m_timeoutCallbacks.toggled,
&dispatcher->m_timeoutCallbacks, nullptr); &dispatcher->m_timeoutCallbacks, nullptr);
} }
void CDBusServer::onNewConnection(DBusServer *, DBusConnection *conn) void CDBusServer::onNewConnection(DBusServer*, DBusConnection* conn)
{ {
auto dbusConnection = std::make_shared<CDBusConnection>(conn); auto dbusConnection = std::make_shared<CDBusConnection>(conn);
m_newConnectionFunc(dbusConnection); m_newConnectionFunc(dbusConnection);
}
void CDBusServer::onNewConnection(DBusServer *server, DBusConnection *conn, void *data)
{
auto *obj = static_cast<CDBusServer *>(data);
obj->onNewConnection(server, conn);
}
} }
void CDBusServer::onNewConnection(DBusServer* server, DBusConnection* conn, void* data)
{
auto* obj = static_cast<CDBusServer*>(data);
obj->onNewConnection(server, conn);
}
} // namespace FGSwiftBus

View file

@ -20,28 +20,27 @@
#ifndef BLACKSIM_FGSWIFTBUS_DBUSSERVER_H #ifndef BLACKSIM_FGSWIFTBUS_DBUSSERVER_H
#define BLACKSIM_FGSWIFTBUS_DBUSSERVER_H #define BLACKSIM_FGSWIFTBUS_DBUSSERVER_H
#include "dbusmessage.h"
#include "dbuserror.h"
#include "dbuscallbacks.h" #include "dbuscallbacks.h"
#include "dbusdispatcher.h" #include "dbusdispatcher.h"
#include "dbuserror.h"
#include "dbusmessage.h"
#include <event2/event.h>
#include <dbus/dbus.h> #include <dbus/dbus.h>
#include <event2/event.h>
#include <functional>
#include <memory>
#include <string> #include <string>
#include <unordered_map> #include <unordered_map>
#include <vector> #include <vector>
#include <memory>
#include <functional>
namespace FGSwiftBus namespace FGSwiftBus {
class CDBusObject;
//! DBus connection
class CDBusServer : public IDispatchable
{ {
public:
class CDBusObject;
//! DBus connection
class CDBusServer : public IDispatchable
{
public:
//! New connection handler function //! New connection handler function
using NewConnectionFunc = std::function<void(std::shared_ptr<CDBusConnection>)>; using NewConnectionFunc = std::function<void(std::shared_ptr<CDBusConnection>)>;
@ -52,10 +51,10 @@ namespace FGSwiftBus
~CDBusServer(); ~CDBusServer();
//! Set the dispatcher //! Set the dispatcher
void setDispatcher(CDBusDispatcher *dispatcher); void setDispatcher(CDBusDispatcher* dispatcher);
//! Connect to bus //! Connect to bus
bool listen(const std::string &address); bool listen(const std::string& address);
//! Is connected? //! Is connected?
bool isConnected() const; bool isConnected() const;
@ -69,26 +68,25 @@ namespace FGSwiftBus
CDBusError lastError() const { return m_lastError; } CDBusError lastError() const { return m_lastError; }
//! Set the function to be used for handling new connections. //! Set the function to be used for handling new connections.
void setNewConnectionFunc(const NewConnectionFunc &func) void setNewConnectionFunc(const NewConnectionFunc& func)
{ {
m_newConnectionFunc = func; m_newConnectionFunc = func;
} }
private: private:
void onNewConnection(DBusServer *server, DBusConnection *conn); void onNewConnection(DBusServer* server, DBusConnection* conn);
static void onNewConnection(DBusServer *server, DBusConnection *conn, void *data); static void onNewConnection(DBusServer* server, DBusConnection* conn, void* data);
struct DBusServerDeleter struct DBusServerDeleter {
{ void operator()(DBusServer* obj) const { dbus_server_unref(obj); }
void operator()(DBusServer *obj) const { dbus_server_unref(obj); }
}; };
CDBusDispatcher *m_dispatcher = nullptr; CDBusDispatcher* m_dispatcher = nullptr;
std::unique_ptr<DBusServer, DBusServerDeleter> m_server; std::unique_ptr<DBusServer, DBusServerDeleter> m_server;
CDBusError m_lastError; CDBusError m_lastError;
NewConnectionFunc m_newConnectionFunc; NewConnectionFunc m_newConnectionFunc;
}; };
} } // namespace FGSwiftBus
#endif // guard #endif // guard

View file

@ -23,17 +23,15 @@
#include <Main/fg_props.hxx> #include <Main/fg_props.hxx>
#include <Main/globals.hxx> #include <Main/globals.hxx>
#include <cmath>
#include <functional> #include <functional>
#include <iostream> #include <iostream>
#include <simgear/structure/commands.hxx> #include <simgear/structure/commands.hxx>
#include <simgear/structure/event_mgr.hxx>
#include <thread> #include <thread>
namespace { namespace {
inline std::string fgswiftbusServiceName() inline std::string fgswiftbusServiceName()
{ {
return std::string("org.swift-project.fgswiftbus"); return "org.swift-project.fgswiftbus";
} }
} // namespace } // namespace
@ -79,17 +77,6 @@ void CPlugin::startServer()
SG_LOG(SG_NETWORK, SG_INFO, "FGSwiftBus started"); SG_LOG(SG_NETWORK, SG_INFO, "FGSwiftBus started");
} }
float CPlugin::startServerDeferred(float, float, int, void* refcon)
{
auto plugin = static_cast<CPlugin*>(refcon);
if (!plugin->m_isRunning) {
plugin->startServer();
plugin->m_isRunning = true;
}
return 0;
}
void CPlugin::fastLoop() void CPlugin::fastLoop()
{ {
this->m_dbusDispatcher.runOnce(); this->m_dbusDispatcher.runOnce();

View file

@ -31,34 +31,31 @@
#define NOMINMAX #define NOMINMAX
#endif #endif
#include "config.h"
#include "dbusconnection.h" #include "dbusconnection.h"
#include "dbusdispatcher.h" #include "dbusdispatcher.h"
#include "dbusserver.h" #include "dbusserver.h"
#include "config.h"
#include <memory> #include <memory>
#include <thread> #include <thread>
namespace FGSwiftBus namespace FGSwiftBus {
{ class CService;
class CService; class CTraffic;
class CTraffic;
class CWeather;
/*! /*!
* Main plugin class * Main plugin class
*/ */
class CPlugin class CPlugin
{ {
public: public:
//! Constructor //! Constructor
CPlugin(); CPlugin();
void startServer(); void startServer();
//! Destructor //! Destructor
~CPlugin(); ~CPlugin();
static float startServerDeferred(float, float, int, void* refcon);
void fastLoop(); void fastLoop();
private: private:
CDBusDispatcher m_dbusDispatcher; CDBusDispatcher m_dbusDispatcher;
std::unique_ptr<CDBusServer> m_dbusP2PServer; std::unique_ptr<CDBusServer> m_dbusP2PServer;
std::shared_ptr<CDBusConnection> m_dbusConnection; std::shared_ptr<CDBusConnection> m_dbusConnection;
@ -68,7 +65,7 @@ namespace FGSwiftBus
std::thread m_dbusThread; std::thread m_dbusThread;
bool m_isRunning = false; bool m_isRunning = false;
bool m_shouldStop = false; bool m_shouldStop = false;
}; };
} } // namespace FGSwiftBus
#endif // guard #endif // BLACKSIM_FGSWIFTBUS_PLUGIN_H

View file

@ -20,9 +20,9 @@
#include "service.h" #include "service.h"
#include <Main/fg_props.hxx> #include <Main/fg_props.hxx>
#include <iostream> #include <iostream>
#include <simgear/constants.h>
#include <simgear/debug/logstream.hxx> #include <simgear/debug/logstream.hxx>
#include <simgear/structure/commands.hxx> #include <simgear/structure/commands.hxx>
#include <simgear/constants.h>
#define FGSWIFTBUS_API_VERSION 3; #define FGSWIFTBUS_API_VERSION 3;
@ -75,7 +75,8 @@ CService::CService()
SG_LOG(SG_NETWORK, SG_INFO, "FGSwiftBus Service initialized"); 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); static const std::string s(FGSWIFTBUS_SERVICE_INTERFACENAME);
return s; return s;
} }
@ -231,7 +232,7 @@ bool CService::getTaxiLightsOn() const
double CService::getPressAlt() const double CService::getPressAlt() const
{ {
if (m_altimeterServiceableNode->getBoolValue()){ if (m_altimeterServiceableNode->getBoolValue()) {
return m_pressAltitudeFtNode->getDoubleValue(); return m_pressAltitudeFtNode->getDoubleValue();
} else { } else {
return m_altitudeMSLNode->getDoubleValue(); return m_altitudeMSLNode->getDoubleValue();
@ -240,22 +241,22 @@ double CService::getPressAlt() const
void CService::setCom1Active(int freq) void CService::setCom1Active(int freq)
{ {
m_com1ActiveNode->setDoubleValue(freq /(double)1000); m_com1ActiveNode->setDoubleValue(freq / (double)1000);
} }
void CService::setCom1Standby(int freq) void CService::setCom1Standby(int freq)
{ {
m_com1StandbyNode->setDoubleValue(freq /(double)1000); m_com1StandbyNode->setDoubleValue(freq / (double)1000);
} }
void CService::setCom2Active(int freq) void CService::setCom2Active(int freq)
{ {
m_com2ActiveNode->setDoubleValue(freq /(double)1000); m_com2ActiveNode->setDoubleValue(freq / (double)1000);
} }
void CService::setCom2Standby(int freq) void CService::setCom2Standby(int freq)
{ {
m_com2StandbyNode->setDoubleValue(freq /(double)1000); m_com2StandbyNode->setDoubleValue(freq / (double)1000);
} }
void CService::setTransponderCode(int code) void CService::setTransponderCode(int code)

View file

@ -28,9 +28,8 @@
#include "dbusobject.h" #include "dbusobject.h"
#include <chrono>
#include <string>
#include <Main/fg_props.hxx> #include <Main/fg_props.hxx>
#include <chrono>
#include <simgear/compiler.h> #include <simgear/compiler.h>
#include <simgear/debug/logstream.hxx> #include <simgear/debug/logstream.hxx>
#include <simgear/io/raw_socket.hxx> #include <simgear/io/raw_socket.hxx>
@ -40,6 +39,7 @@
#include <simgear/structure/event_mgr.hxx> #include <simgear/structure/event_mgr.hxx>
#include <simgear/structure/subsystem_mgr.hxx> #include <simgear/structure/subsystem_mgr.hxx>
#include <simgear/timing/timestamp.hxx> #include <simgear/timing/timestamp.hxx>
#include <string>
//! \cond PRIVATE //! \cond PRIVATE
@ -49,7 +49,7 @@
namespace FGSwiftBus { namespace FGSwiftBus {
/*! /*!
* FGSwiftBus service object which is accessible through DBus * FGSwiftBus service object which is accessible through DBus
*/ */
class CService : public CDBusObject class CService : public CDBusObject
@ -268,8 +268,6 @@ private:
SGPropertyNode_ptr m_yawRateNode; SGPropertyNode_ptr m_yawRateNode;
SGPropertyNode_ptr m_com1VolumeNode; SGPropertyNode_ptr m_com1VolumeNode;
SGPropertyNode_ptr m_com2VolumeNode; SGPropertyNode_ptr m_com2VolumeNode;
}; };
} // namespace FGSwiftBus } // namespace FGSwiftBus

View file

@ -24,15 +24,10 @@
#include "plugin.h" #include "plugin.h"
#include "swift_connection.hxx" #include "swift_connection.hxx"
#include <Main/fg_props.hxx> #include <Main/fg_props.hxx>
#include <simgear/compiler.h>
#include <simgear/debug/logstream.hxx>
#include <simgear/io/raw_socket.hxx>
#include <simgear/misc/stdint.hxx>
#include <simgear/props/props.hxx> #include <simgear/props/props.hxx>
#include <simgear/structure/commands.hxx> #include <simgear/structure/commands.hxx>
#include <simgear/structure/event_mgr.hxx> #include <simgear/structure/event_mgr.hxx>
#include <simgear/structure/subsystem_mgr.hxx> #include <simgear/structure/subsystem_mgr.hxx>
#include <simgear/timing/timestamp.hxx>
namespace { namespace {
inline std::string fgswiftbusServiceName() inline std::string fgswiftbusServiceName()

View file

@ -22,8 +22,10 @@
#ifndef NOMINMAX #ifndef NOMINMAX
#define NOMINMAX #define NOMINMAX
#endif #endif
#include "traffic.h" #include "traffic.h"
#include "SwiftAircraftManager.h" #include "SwiftAircraftManager.h"
#include <algorithm> #include <algorithm>
#include <iostream> #include <iostream>
@ -82,7 +84,7 @@ void CTraffic::cleanup()
void CTraffic::dbusDisconnectedHandler() void CTraffic::dbusDisconnectedHandler()
{ {
if(acm) if (acm)
acm->removeAllPlanes(); acm->removeAllPlanes();
} }
@ -205,8 +207,7 @@ DBusHandlerResult CTraffic::dbusMessageHandler(const CDBusMessage& message_)
reply.appendArgument(verticalOffsets); reply.appendArgument(verticalOffsets);
sendDBusMessage(reply); sendDBusMessage(reply);
}); });
} else if (message.getMethodName() == "getElevationAtPosition") } else if (message.getMethodName() == "getElevationAtPosition") {
{
std::string callsign; std::string callsign;
double latitudeDeg; double latitudeDeg;
double longitudeDeg; double longitudeDeg;
@ -216,8 +217,7 @@ DBusHandlerResult CTraffic::dbusMessageHandler(const CDBusMessage& message_)
message.getArgument(latitudeDeg); message.getArgument(latitudeDeg);
message.getArgument(longitudeDeg); message.getArgument(longitudeDeg);
message.getArgument(altitudeMeters); message.getArgument(altitudeMeters);
queueDBusCall([ = ]() queueDBusCall([=]() {
{
SGGeod pos; SGGeod pos;
pos.setLatitudeDeg(latitudeDeg); pos.setLatitudeDeg(latitudeDeg);
pos.setLongitudeDeg(longitudeDeg); pos.setLongitudeDeg(longitudeDeg);
@ -229,8 +229,7 @@ DBusHandlerResult CTraffic::dbusMessageHandler(const CDBusMessage& message_)
reply.appendArgument(elevation); reply.appendArgument(elevation);
sendDBusMessage(reply); sendDBusMessage(reply);
}); });
} else if (message.getMethodName() == "setPlanesTransponders") } else if (message.getMethodName() == "setPlanesTransponders") {
{
maybeSendEmptyDBusReply(wantsReply, sender, serial); maybeSendEmptyDBusReply(wantsReply, sender, serial);
std::vector<std::string> callsigns; std::vector<std::string> callsigns;
std::vector<int> codes; std::vector<int> codes;
@ -243,16 +242,13 @@ DBusHandlerResult CTraffic::dbusMessageHandler(const CDBusMessage& message_)
message.getArgument(idents); message.getArgument(idents);
std::vector<AircraftTransponder> transponders; std::vector<AircraftTransponder> transponders;
transponders.reserve(callsigns.size()); 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)); transponders.emplace_back(callsigns.at(i), codes.at(i), modeCs.at(i), idents.at(i));
} }
queueDBusCall([ = ]() queueDBusCall([=]() {
{
acm->setPlanesTransponders(transponders); acm->setPlanesTransponders(transponders);
}); });
} else if (message.getMethodName() == "setPlanesSurfaces") } else if (message.getMethodName() == "setPlanesSurfaces") {
{
maybeSendEmptyDBusReply(wantsReply, sender, serial); maybeSendEmptyDBusReply(wantsReply, sender, serial);
std::vector<std::string> callsigns; std::vector<std::string> callsigns;
std::vector<double> gears; std::vector<double> gears;
@ -291,14 +287,12 @@ DBusHandlerResult CTraffic::dbusMessageHandler(const CDBusMessage& message_)
message.getArgument(lightPatterns); message.getArgument(lightPatterns);
std::vector<AircraftSurfaces> surfaces; std::vector<AircraftSurfaces> surfaces;
surfaces.reserve(callsigns.size()); 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), 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), 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)); landLights.at(i), taxiLights.at(i), beaconLights.at(i), strobeLights.at(i), navLights.at(i), lightPatterns.at(i));
} }
queueDBusCall([ = ]() queueDBusCall([=]() {
{
acm->setPlanesSurfaces(surfaces); acm->setPlanesSurfaces(surfaces);
}); });
} else { } else {
@ -309,11 +303,11 @@ DBusHandlerResult CTraffic::dbusMessageHandler(const CDBusMessage& message_)
return DBUS_HANDLER_RESULT_HANDLED; return DBUS_HANDLER_RESULT_HANDLED;
} }
int CTraffic::process() int CTraffic::process()
{ {
invokeQueuedDBusCalls(); invokeQueuedDBusCalls();
return 1; return 1;
} }
} // namespace FGSwiftBus } // namespace FGSwiftBus

View file

@ -24,6 +24,7 @@
#include "SwiftAircraftManager.h" #include "SwiftAircraftManager.h"
#include "dbusobject.h" #include "dbusobject.h"
#include <functional> #include <functional>
#include <utility> #include <utility>