Move MQTT module from plugin to manager 74/242574/8
authorYu <jiung.yu@samsung.com>
Sun, 30 Aug 2020 23:09:46 +0000 (08:09 +0900)
committerYu <jiung.yu@samsung.com>
Tue, 1 Sep 2020 03:29:20 +0000 (12:29 +0900)
Change-Id: Id19d65656dd781061c24dbd972fa54a40364e384
Signed-off-by: Yu jiung <jiung.yu@samsung.com>
43 files changed:
CMakeLists.txt
hpi/uwb-hpi.c
hpi/uwb-hpi.h
include/LocationManager.h [new file with mode: 0644]
include/MqttContext.h [new file with mode: 0644]
include/Node.h [new file with mode: 0644]
include/UwbConfig.h
include/UwbDbusIfaceAdapter.h [new file with mode: 0644]
include/UwbDbusManager.h
include/UwbManager.h [deleted file]
include/UwbMqttMessage.h [new file with mode: 0644]
include/UwbMqttRequest.h [new file with mode: 0644]
include/UwbNetwork.h
include/UwbNode.h [deleted file]
include/UwbPlugin.h [moved from include/UwbIfaceHandler.h with 55% similarity]
include/UwbPluginManager.h
include/UwbPosition.h [new file with mode: 0644]
include/UwbRangePlugin.h
include/uwb-log-def.h
interface/uwb-manager-iface.xml
packaging/dwm1001.conf [new file with mode: 0644]
packaging/uwb-manager.spec
plugin/dwm1001/CMakeLists.txt [new file with mode: 0755]
plugin/dwm1001/include/uwb-plugin-dwm1001-private.h [new file with mode: 0755]
plugin/dwm1001/include/uwb-plugin-dwm1001.h [new file with mode: 0755]
plugin/dwm1001/include/uwb-plugin-log.h [new file with mode: 0755]
plugin/dwm1001/uwb-plugin-dwm1001.c [new file with mode: 0755]
src/CMakeLists.txt
src/LocationManager.cpp [new file with mode: 0644]
src/MqttContext.cpp [new file with mode: 0644]
src/UwbConfig.cpp
src/UwbDbusIfaceAdapter.cpp [new file with mode: 0644]
src/UwbDbusManager.cpp
src/UwbIfaceHandler.cpp [deleted file]
src/UwbManager.cpp [deleted file]
src/UwbMqttMessage.cpp [new file with mode: 0644]
src/UwbMqttRequest.cpp [new file with mode: 0644]
src/UwbNetwork.cpp [changed mode: 0755->0644]
src/UwbNode.cpp [deleted file]
src/UwbPluginManager.cpp
src/UwbPosition.cpp [new file with mode: 0644]
src/UwbRangePlugin.cpp [changed mode: 0755->0644]
src/main.cpp

index 277031e..4026830 100644 (file)
 # @file        CMakeLists.txt
 #
 
-CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
-PROJECT(uwb-manager C CXX)
+############################# Check minimum CMake version #####################
 
-SET(DAEMON "uwb-manager")
+CMAKE_MINIMUM_REQUIRED(VERSION 2.8.3)
+PROJECT(uwb-manager)
+
+############################# cmake packages ##################################
 
 INCLUDE(FindPkgConfig)
 
+SET(COMMON_DEPS "glib-2.0 gio-2.0 gio-unix-2.0 dlog libtzplatform-config json-glib-1.0")
+
+SET(TARGET_UWB_MANAGER "uwb-manager")
+
+ADD_DEFINITIONS("-DUSE_DLOG")
+
 ADD_SUBDIRECTORY(interface)
 ADD_SUBDIRECTORY(src)
-
-IF(BUILD_GTESTS)
-       ADD_SUBDIRECTORY(unittest)
-ENDIF(BUILD_GTESTS)
-IF(BUILD_TEST_APP)
-       ADD_SUBDIRECTORY(test)
-ENDIF(BUILD_TEST_APP)
index 8e2ef72..69183bf 100755 (executable)
@@ -18,7 +18,7 @@
  */
 
 /**
- * This file implements UWB Hardware Plug-in Interface(HPI) functions.
+ * This file implements UWB Hardware Plug-in Interface(HPI) dwm1001 functions.
  *
  * @file       uwb-hpi.c
  * @author     Jiung Yu (jiung.yu@samsung.com)
@@ -68,6 +68,22 @@ int uwb_hpi_factory_reset(uwb_hpi_ops_s *ops)
        return ops->factory_reset();
 }
 
+int uwb_hpi_enable_network(uwb_hpi_ops_s *ops)
+{
+       if (!ops->enable_network)
+               return -1;
+
+       return ops->enable_network();
+}
+
+int uwb_hpi_disable_network(uwb_hpi_ops_s *ops)
+{
+       if (!ops->disable_network)
+               return -1;
+
+       return ops->disable_network();
+}
+
 int uwb_hpi_get_own_node(uwb_hpi_ops_s *ops, uwb_hpi_node_s **own_node)
 {
        if (!ops->get_own_node)
@@ -102,7 +118,7 @@ int uwb_hpi_get_configurations(uwb_hpi_ops_s *ops, uint16_t node_id, GVariant **
 
 }
 
-int uwb_hpi_set_position(uwb_hpi_ops_s *ops, uint16_t node_id, int x, int y, int z)
+int uwb_hpi_set_position(uwb_hpi_ops_s *ops, uint64_t node_id, int x, int y, int z)
 {
        if (!ops->set_position)
                return -1;
index 6164e79..f5e571a 100755 (executable)
@@ -18,9 +18,9 @@
  */
 
 /**
- * This file declares UWB Hardware Plug-in Interface(HPI) functions and structures.
+ * This file declares UWB Hardware Plug-in Interface(HPI) dwm1001 functions and structures.
  *
- * @file       uwb-hpi.h
+ * @file       uwb-hpi-dwm1001.h
  * @author     Jiung Yu (jiung.yu@samsung.com)
  */
 
@@ -66,10 +66,12 @@ typedef struct {
        int (*test) (void);
        int (*reset) (void);
        int (*factory_reset) (void);
+       int (*enable_network) (void);
+       int (*disable_network) (void);
        int (*get_network_info) (uwb_hpi_network_s **network_info);
        int (*set_configurations) (uint16_t node_id, const GVariant *configurations);
        int (*get_configurations) (uint16_t node_id, GVariant **configurations);
-       int (*set_position) (uint16_t node_id, int x, int y, int z);
+       int (*set_position) (uint64_t node_id, int x, int y, int z);
        int (*get_own_node) (uwb_hpi_node_s **own_node);
        int (*send_message) (const unsigned char *message, int message_length);
        int (*send_message_to) (uint16_t node_id, const unsigned char *message, int message_length);
@@ -80,10 +82,12 @@ int uwb_hpi_deinit(uwb_hpi_ops_s *ops);
 int uwb_hpi_test(uwb_hpi_ops_s *ops);
 int uwb_hpi_reset(uwb_hpi_ops_s *ops);
 int uwb_hpi_factory_reset(uwb_hpi_ops_s *ops);
+int uwb_hpi_enable_network(uwb_hpi_ops_s *ops);
+int uwb_hpi_disable_network(uwb_hpi_ops_s *ops);
 int uwb_hpi_get_network_info(uwb_hpi_ops_s *ops, uwb_hpi_network_s **network_info);
 int uwb_hpi_set_configurations(uwb_hpi_ops_s *ops, uint16_t node_id, const GVariant *configurations);
 int uwb_hpi_get_configurations(uwb_hpi_ops_s *ops, uint16_t node_id, GVariant **configurations);
-int uwb_hpi_set_position(uwb_hpi_ops_s *ops, uint16_t node_id, int x, int y, int z);
+int uwb_hpi_set_position(uwb_hpi_ops_s *ops, uint64_t node_id, int x, int y, int z);
 int uwb_hpi_get_own_node(uwb_hpi_ops_s *ops, uwb_hpi_node_s **own_node);
 int uwb_hpi_send_message(uwb_hpi_ops_s *ops, const unsigned char *message, int message_length);
 int uwb_hpi_send_message_to(uwb_hpi_ops_s *ops, uint16_t node_id, const unsigned char *message, int message_length);
diff --git a/include/LocationManager.h b/include/LocationManager.h
new file mode 100644 (file)
index 0000000..425a7ea
--- /dev/null
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __LOCATION_MANAGER_H__
+#define __LOCATION_MANAGER_H__
+
+#include <list>
+#include <map>
+#include <memory>
+
+#include <UwbMqttRequest.h>
+
+#include <UwbPosition.h>
+#include "MqttContext.h"
+
+namespace UwbManagerNamespace {
+
+class LocationManager {
+
+public:
+       LocationManager(std::shared_ptr<UwbPosition> uwb_position);
+       ~LocationManager();
+
+       void setPositionUpdatedCallback(std::function<void(Node *node)> updated_cb);
+       void unsetPositionUpdatedCallback();
+
+       void setNodeAddedCallback(std::function<void(Node *node)> added_cb);
+       void unsetNodeAddedCallback();
+       void setNodeUpdatedCallback(std::function<void(Node *node)> updated_cb);
+       void unsetNodeUpdatedCallback();
+       void setNodeRemovedCallback(std::function<void(Node *node)> removed_cb);
+       void unsetNodeRemovedCallback();
+
+       int start(const char *server, int port);
+       int stop(void);
+
+       int updateUwbPosition(void);
+       Node &getCurrentPosition(void) {return _current;};
+       std::map<int, std::unique_ptr<Node>> &getNodeMap(void) {return _node_map;};
+       int requestBroadcast(std::unique_ptr<UwbMqttMessage> mqtt_msg);
+
+       bool isPositionBroadcastSourceAvailable(void) {return _position_broadcast_source != 0;}
+
+       /* Warning: getMqttContext should be used only for test purpose */
+       MqttContext *getMqttContextPtr() {return _mqtt_context.get();};
+       static constexpr int _position_broadcast_interval = 1;
+       static constexpr int _default_mqtt_qos = 1;
+       static constexpr int _default_remove_duration = 10;
+       static constexpr int _default_tizen_uwb_broadcast_topic_len = 21;
+       static constexpr int _default_tizen_uwb_broadcast_payload_len = 16;
+private:
+
+       int tryConnect(void);
+       void connectionState(bool connected);
+       void messageArrived(char *topic, int topic_len,
+                       unsigned char *payload, int payload_len);
+
+       int connectMqttBroker(const char *server, int port);
+
+       void updateOwnUwbPosition(void);
+       void updateUwbNodes(void);
+       void removeOutdatedUwbNodes(void);
+
+       int subscribePositionBroadcast(void);
+       int unsubscribePositionBroadcast(void);
+
+       int startPublishPosition(void);
+       void stopPublishPosition(void);
+
+       void extractNodeInfo(char *topic, unsigned char *payload, Node *node);
+
+       guint _position_broadcast_source;
+
+       std::shared_ptr<UwbPosition> _uwb_position;
+       std::unique_ptr<MqttContext> _mqtt_context;
+
+       Node _current;
+       std::map<int, std::unique_ptr<Node>> _node_map;
+       std::function<void(Node *node)> _position_updated_cb;
+       std::function<void(Node *node)> _node_added_cb;
+       std::function<void(Node *node)> _node_updated_cb;
+       std::function<void(Node *node)> _node_removed_cb;
+};
+
+}
+
+#endif /* __LOCATION_MANAGER_H__ */
diff --git a/include/MqttContext.h b/include/MqttContext.h
new file mode 100644 (file)
index 0000000..2c3bc3e
--- /dev/null
@@ -0,0 +1,84 @@
+/*
+ * UWB MQTT Context
+ *
+ * Copyright (c) 2020 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+/**
+ * This file declares MQTT plugin context class.
+ *
+ * @file               MqttContext.h
+ * @author     Jiung Yu (jiung.yu@samsung.com)
+ */
+
+#ifndef __MQTT_CONTEXT_H__
+#define __MQTT_CONTEXT_H__
+
+#include <stdbool.h>
+#include <list>
+
+#include "MQTTAsync.h"
+#include "UwbMqttRequest.h"
+
+namespace UwbManagerNamespace {
+
+class MqttContext {
+public:
+       MqttContext(void) : _retry_connect_source(0), _mqtt_client(nullptr),
+       _connection_state_cb(nullptr), _message_arrived_cb(nullptr) {};
+       ~MqttContext();
+
+       void setConnectionStateCallback(std::function<void(bool)> connection_state_cb)
+       {_connection_state_cb = connection_state_cb;};
+       void unsetConnectionStateCallback()
+       {_connection_state_cb = nullptr;};
+       void setMessageArrivedCallback(
+                       std::function<void(char *topic, int topic_len,
+                                       unsigned char *payload, int payload_len)> message_arrived_cb)
+       {_message_arrived_cb = message_arrived_cb;};
+       void unsetMessageArrivedCallback()
+       {_message_arrived_cb = nullptr;};
+       std::function<void(bool)>getConnectionStateCb() {return _connection_state_cb;};
+       std::function<void(char *topic, int topic_len,
+                               unsigned char *payload, int payload_len)> getMessageArrivedCb() {return _message_arrived_cb;};
+
+       int createMqttClient(const char *server, int port);
+       int destroyMqttClient(void);
+       MQTTAsync getMqttClient(void);
+
+       bool isConnected(void);
+       void disableRetryingConnect(void);
+       void clearRetyringConnectSource(void) {_retry_connect_source = 0;};
+       void enableRetryingConnect(void);
+
+       int connectBroker(void);
+       int disconnectBroker(void);
+       int subscribe(std::unique_ptr<UwbMqttRequest> request);
+       int unsubscribe(std::unique_ptr<UwbMqttRequest> request);
+       int publish(std::unique_ptr<UwbMqttRequest> request);
+private:
+       static constexpr int _mqtt_connect_timeout = 2;
+       static constexpr int _connection_retry_timeout = 5;
+       guint _retry_connect_source;
+       MQTTAsync _mqtt_client;
+       std::function<void(bool)> _connection_state_cb;
+       std::function<void(char *topic, int topic_len,
+                       unsigned char *payload, int payload_len)> _message_arrived_cb;
+};
+
+}
+
+#endif /* __MQTT_CONTEXT_H__ */
diff --git a/include/Node.h b/include/Node.h
new file mode 100644 (file)
index 0000000..beb0b83
--- /dev/null
@@ -0,0 +1,110 @@
+/*
+ * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __NODE_H__
+#define __NODE_H__
+
+//#include <uwb-log-def.h>
+#include <uwb-hpi.h>
+
+#define TECH_UNKNOWN 0x00
+#define TECH_UWB 0x01
+#define TECH_MQTT 0x02
+
+namespace UwbManagerNamespace {
+
+class Node {
+public:
+       Node(): _distance(0), _pan_id(0), _node_id(0), _x(0), _y(0), _z(0),
+       _is_remote(false), _is_calculated(false), _tech(TECH_UNKNOWN), _last_update(0) {};
+
+       Node(int pan_id, unsigned long long node_id, int x, int y, int z) :
+               _distance(0), _pan_id(pan_id), _node_id(node_id), _x(x), _y(y), _z(z),
+               _is_remote(false), _is_calculated(false), _tech(TECH_UNKNOWN), _last_update(0) {};
+
+       Node(unsigned long long distance, int pan_id, unsigned long long node_id,
+                       int x, int y, int z, bool is_remote, bool is_calculated, int tech) :
+               _distance(distance), _pan_id(pan_id), _node_id(node_id),
+               _x(x), _y(y), _z(z), _is_remote(is_remote), _is_calculated(is_calculated),
+               _tech(tech), _last_update(0) {};
+
+       Node(uwb_hpi_node_s *node) :
+               _distance(node->distance), _pan_id(node->pan_id), _node_id(node->node_id),
+               _x(node->x), _y(node->y), _z(node->z), _is_remote(node->is_remote),
+               _is_calculated(false), _tech(TECH_UWB), _last_update(0){};
+       Node(const Node &node) {
+               _distance = node._distance;
+               _pan_id = node._pan_id;
+               _node_id = node._node_id;
+               _x = node._x;
+               _y = node._y;
+               _z = node._z;
+               _is_remote = node._is_remote;
+               _is_calculated = node._is_calculated;
+               _tech = node._tech;
+               _last_update = node._last_update;
+       }
+       Node(const Node *node) {
+               _distance = node->_distance;
+               _pan_id = node->_pan_id;
+               _node_id = node->_node_id;
+               _x = node->_x;
+               _y = node->_y;
+               _z = node->_z;
+               _is_remote = node->_is_remote;
+               _is_calculated = node->_is_calculated;
+               _tech = node->_tech;
+               _last_update = node->_last_update;
+       }
+
+       //~Node(){UWB_LOGI("%lld removed", _last_update);}
+       void setDistance(unsigned long long distance) {_distance = distance;};
+       unsigned long long getDistance() {return _distance;};
+       void setPanId(int id) {_pan_id = id;};
+       int getPanId(void) {return _pan_id;};
+       void setNodeId(unsigned long long id) {_node_id = id;};
+       unsigned long long getNodeId() {return _node_id;};
+       int getX(void) {return _x;};
+       void setX(int x) {_x = x;};
+       int getY(void) {return _y;};
+       void setY(int y) {_y = y;};
+       int getZ(void) {return _z;};
+       void setZ(int z) {_z = z;};
+       bool getIsRemote(void) {return _is_remote;};
+       void setIsRemote(bool is_remote) {_is_remote = is_remote;};
+       bool getIsCalculated(void) {return _is_calculated;};
+       void setIsCalculated(bool is_calculated) {_is_calculated = is_calculated;};
+       bool getTech(void) {return _tech;};
+       void setTech(int tech) {_tech = tech;};
+       uint64_t getLastUpdate(void) {return _last_update;};
+       void setLastUpdate(uint64_t update_time) {_last_update = update_time;};
+       bool hasSamePosition(Node *node) {return (_x == node->_x && _y == node->_y && _z == node->_z);};
+private:
+       unsigned long long _distance;
+       int _pan_id;
+       unsigned long long _node_id;
+       int _x;
+       int _y;
+       int _z;
+       bool _is_remote;
+       bool _is_calculated;
+       int _tech;
+       uint64_t _last_update;
+};
+
+}
+
+#endif /* __NODE_H__ */
index f065111..c7f1ed6 100644 (file)
 #ifndef __UWB_CONFIG_H__
 #define __UWB_CONFIG_H__
 
+#include <memory>
 #include <glib.h>
+#include <UwbRangePlugin.h>
 
 namespace UwbManagerNamespace {
 
 class UwbConfig {
 public:
        UwbConfig() :
-               _node_id(0), _configurations(nullptr) {};
+               _configurations(nullptr), _range_plugin(nullptr) {};
+       UwbConfig(std::shared_ptr<UwbRangePlugin> range_plugin) :
+               _configurations(nullptr), _range_plugin(range_plugin) {};
 
-       UwbConfig(int node_id, int pan_id, GVariant *configurations);
-       UwbConfig(const UwbConfig* config);
+       UwbConfig(const UwbConfig& config);
        ~UwbConfig();
 
-       int setNodeId(int node_id);
-       int getNodeId();
-       int setPanId(int pan_id);
-       int getPanId();
-       int setConfigurations(const GVariant *configurations);
-       GVariant *getConfigurations();
+       int loadConfiguration(void);
+       int setConfigurations(GVariant *configurations);
+       GVariant *getConfigurations(void);
 private:
-       int _node_id;
-       int _pan_id;
        GVariant *_configurations;
+       std::shared_ptr<UwbRangePlugin> _range_plugin;
+       void getConfigurationFromPlugin(void);
 };
 
 }
diff --git a/include/UwbDbusIfaceAdapter.h b/include/UwbDbusIfaceAdapter.h
new file mode 100644 (file)
index 0000000..d62ae9a
--- /dev/null
@@ -0,0 +1,142 @@
+/*
+ * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __UWB_DBUS_IFACE_ADAPTER_H__
+#define __UWB_DBUS_IFACE_ADAPTER_H__
+
+
+#include <functional>
+#include <map>
+#include <memory>
+
+#include <gio/gio.h>
+
+#include "generated-code.h"
+
+#include <Node.h>
+
+namespace UwbManagerNamespace {
+
+class UwbDbusIfaceAdapter {
+public:
+       UwbDbusIfaceAdapter() :
+               _test(nullptr),
+               _reset(nullptr),
+               _factory_reset(nullptr),
+               _enable_network(nullptr),
+               _disable_network(nullptr),
+               _start_location_engine(nullptr),
+               _stop_location_engine(nullptr),
+               _get_own_node(nullptr),
+               _get_network_info(nullptr),
+               _set_configurations(nullptr),
+               _get_configurations(nullptr),
+               _set_position(nullptr),
+               _send_message(nullptr),
+               _send_message_to(nullptr) {};
+       ~UwbDbusIfaceAdapter();
+
+       void setTest(std::function<int (void)> test)
+       {_test = test;};
+       void unsetTest(void) {_test = nullptr;};
+       std::function<int (void)> getTest(void) {return _test;};
+
+       void setReset(std::function<int (void)> reset)
+       {_reset = reset;};
+       void unsetReset(void) {_reset = nullptr;};
+       std::function<int (void)> getReset(void) {return _reset;};
+
+       void setFactoryReset(std::function<int (void)> factory_reset)
+       {_factory_reset = factory_reset;};
+       void unsetFactoryReset(void) {_factory_reset = nullptr;};
+       std::function<int (void)> getFactoryReset(void) {return _factory_reset;};
+
+       void setEnableNetwork(std::function<int (void)> enable_network)
+       {_enable_network = enable_network;};
+       void unsetEnableNetwork(void) {_enable_network = nullptr;};
+       std::function<int (void)> getEnableNetwork(void) {return _enable_network;};
+
+       void setDisableNetwork(std::function<int (void)> disable_network)
+       {_disable_network = disable_network;};
+       void unsetDisableNetwork(void) {_disable_network = nullptr;};
+       std::function<int (void)> getDisableNetwork(void) {return _disable_network;};
+
+       void setStartLocationEngine(std::function<int (const char *, int)> start_location_engine)
+       {_start_location_engine = start_location_engine;};
+       void setStartLocationEngine(void) {_start_location_engine= nullptr;};
+       std::function<int (const char *, int)> getStartLocationEngine(void) {return _start_location_engine;};
+
+       void setStopLocationEngine(std::function<int (void)> stop_location_engine)
+       {_stop_location_engine = stop_location_engine;};
+       void unsetStopLocationEngine(void) {_stop_location_engine = nullptr;};
+       std::function<int (void)> getStopLocationEngine(void) {return _stop_location_engine;};
+
+       void setGetOwnNode(std::function<Node &(void)> get_own_node)
+       {_get_own_node = get_own_node;};
+       void unsetGetOwnNode(void) {_get_own_node = nullptr;};
+       std::function<Node &(void)> getGetOwnNode(void) {return _get_own_node;};
+
+       void setGetNetworkInfo(std::function<std::map<int, std::unique_ptr<Node>> &(void)> get_network_info)
+       {_get_network_info = get_network_info;};
+       void unsetGetNetworkInfo(void) {_get_network_info = nullptr;};
+       std::function<std::map<int, std::unique_ptr<Node>> &(void)> getGetNetworkInfo(void) {return _get_network_info;};
+
+       void setSetConfigurations(std::function<int (GVariant *)> set_configurations)
+       {_set_configurations = set_configurations;};
+       void unsetSetConfigurations(void) {_set_configurations = nullptr;};
+       std::function<int (GVariant *)> getSetConfigurations(void) {return _set_configurations;};
+
+       void setGetConfigurations(std::function<GVariant *(void)> get_configurations)
+       {_get_configurations = get_configurations;};
+       void unsetGetConfigurations(void) {_get_configurations = nullptr;};
+       std::function<GVariant *(void)> getGetConfigurations(void) {return _get_configurations;};
+
+       void setSetPosition(std::function<void (int, int, int)> set_position) {_set_position = set_position;};
+       void unsetSetPosition(void) {_set_position = nullptr;};
+       std::function<void (int, int, int)> getSetPosition(void) {return _set_position;};
+
+       void setSendMessage(std::function<int (unsigned char *, int)> send_message) {_send_message = send_message;};
+       void unsetSendMessage(void) {_send_message = nullptr;};
+       std::function<int (unsigned char *, int)> getSendMessage(void) {return _send_message;};
+
+       void setSendMessageTo(std::function<int (int, unsigned char *, int)> send_message_to)
+       {_send_message_to = send_message_to;};
+       void unsetSendMessageTo(void) {_send_message_to = nullptr;};
+       std::function<int (int, unsigned char *, int)> getSendMessageTo(void) {return _send_message_to;};
+
+       void init(GDBusConnection *connection, UwbGdbuslibManager *manager_skeleton);
+       void deinit(void);
+private:
+       const std::string _uwb_dbus_path_str =
+                       std::string("/org/tizen/uwb/manager");
+       std::function<int (void)> _test;
+       std::function<int (void)> _reset;
+       std::function<int (void)> _factory_reset;
+       std::function<int (void)> _enable_network;
+       std::function<int (void)> _disable_network;
+       std::function<int (const char *, int)> _start_location_engine;
+       std::function<int (void)> _stop_location_engine;
+       std::function<Node &(void)> _get_own_node;
+       std::function<std::map<int, std::unique_ptr<Node>> &(void)> _get_network_info;
+       std::function<int (GVariant *)> _set_configurations;
+       std::function<GVariant *(void)> _get_configurations;
+       std::function<void (int, int, int)> _set_position;
+       std::function<int (unsigned char *, int)> _send_message;
+       std::function<int (int, unsigned char *, int)> _send_message_to;
+};
+
+}
+#endif /* __UWB_DBUS_IFACE_ADAPTER_H__ */
index 62626e2..7dbdae6 100644 (file)
 #ifndef __UWB_DBUS_MANAGER_H__
 #define __UWB_DBUS_MANAGER_H__
 
+#include <functional>
+
 #include <gio/gio.h>
 
-#include <UwbIfaceHandler.h>
+#include "generated-code.h"
+
+#include <Node.h>
 
 namespace UwbManagerNamespace {
 
 class UwbDbusManager {
 public:
-       UwbDbusManager() : _owner_id(0) {};
+       UwbDbusManager() : _owner_id(0), _manager_skeleton(nullptr), _bus_acquired_cb(nullptr) {};
        ~UwbDbusManager();
 
-       /* TODO: Make this pointer to vector if there's multiple handlers */
-       void init(UwbIfaceHandler *iface_handler);
+       void setBusAcquiredCallback(std::function<void(GDBusConnection *, UwbGdbuslibManager *)> bus_acquired_cb)
+       {_bus_acquired_cb = bus_acquired_cb;};
+       void unsetBusAcquiredCallback(void) {_bus_acquired_cb = nullptr;};
+       std::function<void(GDBusConnection *, UwbGdbuslibManager *)> getBusAcquiredCallback(void) {return _bus_acquired_cb;};
+       void init(void);
        void deinit(void);
-       static void emitMessageReceivedSignal(uint16_t node_id,
-               const unsigned char *message, int message_length);
-       static void emitPositionChangedSignal(uint16_t node_id, int x, int y, int z);
-
+       void emitPositionUpdatedSignal(Node *p_node);
+       void emitNodeAddedSignal(Node *p_node);
+       void emitNodeUpdatedSignal(Node *p_node);
+       void emitNodeRemovedSignal(Node *p_node);
+       UwbGdbuslibManager *getManagerSkeleton(void) {return _manager_skeleton;};
 private:
        const std::string uwb_dbus_service_str =
                        std::string("org.tizen.uwb");
        guint _owner_id;
-       static void onBusAcquired(GDBusConnection *connection, const gchar *name, gpointer user_data);
+
+       /* Add interface to default object path */
+       UwbGdbuslibManager *_manager_skeleton;
+       std::function<void(GDBusConnection *, UwbGdbuslibManager *)> _bus_acquired_cb;
 };
 
 }
-
 #endif /* __UWB_DBUS_MANAGER_H__ */
diff --git a/include/UwbManager.h b/include/UwbManager.h
deleted file mode 100644 (file)
index d3c8504..0000000
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __UWB_MANAGER_H__
-#define __UWB_MANAGER_H__
-
-#include <UwbConfig.h>
-#include <UwbNetwork.h>
-#include <UwbRangePlugin.h>
-
-namespace UwbManagerNamespace {
-
-class UwbManager {
-public:
-       UwbManager() :
-               _uwb_config(nullptr), _range_plugin(nullptr) {};
-       UwbManager(UwbConfig *uwb_config, UwbRangePlugin *range_plugin) :
-               _uwb_config(uwb_config), _range_plugin(range_plugin) {};
-       int test(void);
-       int reset(void);
-       int factoryReset(void);
-       int setPosition(int node_id, int x, int y, int z);
-       int setDefaultConfigurations(void);
-       int setConfigurations(int node_id, GVariant *configurations);
-       int getConfigurations(int node_id, GVariant **configurations);
-       UwbNetwork *getNetwork();
-       UwbNode *getOwnNode();
-       int sendMessage(const unsigned char *message, int message_length);
-       int sendMessageTo(uint16_t node_id, const unsigned char *message, int message_length);
-private:
-       UwbConfig *_uwb_config;
-       UwbRangePlugin *_range_plugin;
-};
-
-}
-
-#endif /* __UWB_MANAGER_H__ */
diff --git a/include/UwbMqttMessage.h b/include/UwbMqttMessage.h
new file mode 100644 (file)
index 0000000..01e5eac
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __UWB_MQTT_MESSAGE_H__
+#define __UWB_MQTT_MESSAGE_H__
+
+#include <string>
+
+#include <Node.h>
+
+namespace UwbManagerNamespace {
+
+enum class UwbMqttMessageType {
+       BroadcastPosition
+};
+
+class UwbMqttMessage {
+public:
+       UwbMqttMessage();
+       ~UwbMqttMessage();
+       UwbMqttMessage(Node &node_info);
+       std::string &getTopic(void);
+       std::string &getPayload(void);
+private:
+       static constexpr int _location_payload_length = 12;
+       static constexpr int _node_payload_length = 16;
+       const std::string _broadcast_position_topic_prefix =
+                       std::string("/TIZEN/UWB/BROADCAST/");
+       std::string _topic;
+       std::string _payload;
+};
+
+}
+
+#endif /* __UWB_MQTT_MESSAGE_H__ */
diff --git a/include/UwbMqttRequest.h b/include/UwbMqttRequest.h
new file mode 100644 (file)
index 0000000..80d5ddc
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __UWB_MQTT_REQUEST_H__
+#define __UWB_MQTT_REQUEST_H__
+
+#include <string>
+#include <functional>
+#include <memory>
+
+#include <UwbMqttMessage.h>
+
+namespace UwbManagerNamespace {
+
+class UwbMqttRequest {
+public:
+       UwbMqttRequest(void);
+       UwbMqttRequest(int qos, std::unique_ptr<UwbMqttMessage> mqtt_msg);
+       UwbMqttRequest(int qos, int retained, std::unique_ptr<UwbMqttMessage> mqtt_msg);
+       int getQos(void) {return _qos;};
+       int getRetained(void) {return _retained;};
+       std::string &getTopic(void) {return _mqtt_msg->getTopic();};
+       std::string &getPayload(void) {return _mqtt_msg->getPayload();};
+
+       ~UwbMqttRequest(void);
+private:
+       int _qos;
+       int _retained;
+       std::unique_ptr<UwbMqttMessage> _mqtt_msg;
+};
+
+}
+
+#endif /* __UWB_MQTT_REQUEST_H__ */
index dedb5be..aa8ec8b 100644 (file)
 #ifndef __UWB_NETWORK_H__
 #define __UWB_NETWORK_H__
 
-#include <list>
+#include <memory>
 
-#include <UwbNode.h>
+#include <UwbRangePlugin.h>
 
 namespace UwbManagerNamespace {
 
 class UwbNetwork {
 public:
-       UwbNetwork(int pan_id) :
-               _pan_id(pan_id) {};
+       UwbNetwork() :
+               _is_enable(false), _pan_id(0), _range_plugin(nullptr){};
+       UwbNetwork(std::shared_ptr<UwbRangePlugin> range_plugin) :
+               _is_enable(false), _pan_id(0), _range_plugin(range_plugin){};
        ~UwbNetwork();
-       void setPanId(int pan_id);
-       int getPanId();
-       int addNode(UwbNode *node);
-       int removeNode(UwbNode *node);
-       std::list<UwbNode *> *getNodeList();
+       void setPanId(int pan_id) {_pan_id = pan_id;};
+       int getPanId(void) {return _pan_id;};
+       bool is_enable(void) {return _is_enable;};
+
+       int enable(void);
+       int disable(void);
 
 private:
+       bool _is_enable;
        int _pan_id;
-       std::list<UwbNode *> _node_list;
+
+       std::shared_ptr<UwbRangePlugin> _range_plugin;
 };
 
 }
diff --git a/include/UwbNode.h b/include/UwbNode.h
deleted file mode 100644 (file)
index bc781bc..0000000
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __UWB_NODE_H__
-#define __UWB_NODE_H__
-
-namespace UwbManagerNamespace {
-
-class UwbNode {
-public:
-       UwbNode(): _distance(0), _pan_id(0), _node_id(0), _x(0), _y(0), _z(0), _is_remote(false) {};
-       UwbNode(unsigned long long distance, int pan_id, unsigned long long node_id, int x, int y, int z, bool is_remote):
-               _distance(distance), _pan_id(pan_id), _node_id(node_id), _x(x), _y(y), _z(z), _is_remote(is_remote) {};
-       UwbNode(UwbNode *node);
-       void setDistance(unsigned long long distance);
-       unsigned long long getDistance();
-       void setPanId(int id);
-       int getPanId();
-       void setNodeId(unsigned long long id);
-       unsigned long long getNodeId();
-       int getX();
-       void setX(int x);
-       int getY();
-       void setY(int y);
-       int getZ();
-       void setZ(int z);
-       bool getIsRemote();
-       void setIsRemote(bool is_remote);
-private:
-       unsigned long long _distance;
-       int _pan_id;
-       unsigned long long _node_id;
-       int _x;
-       int _y;
-       int _z;
-       bool _is_remote;
-};
-
-}
-
-#endif /* __UWB_NETWORK_H__ */
similarity index 55%
rename from include/UwbIfaceHandler.h
rename to include/UwbPlugin.h
index 35b2b8a..74a9c21 100644 (file)
  * limitations under the License.
  */
 
-#ifndef __UWB_IFACE_HANDLER_H__
-#define __UWB_IFACE_HANDLER_H__
+#ifndef __UWB_PLUGIN_H__
+#define __UWB_PLUGIN_H__
 
 #include <string>
-#include <vector>
-
-#include <gio/gio.h>
-
-#include "generated-code.h"
-
-#include <UwbManager.h>
-#include <MethodHandler.h>
 
 namespace UwbManagerNamespace {
 
-class UwbIfaceHandler {
-public:
-       UwbIfaceHandler(UwbManager* uwb_manager);
-       ~UwbIfaceHandler();
+class UwbPlugin {
 
-       std::string get_dbus_path_str(void);
-       void registerHandler(UwbGdbuslibManager *manager_skeleton);
-private:
-       const std::string _uwb_dbus_path_str =
-                       std::string("/org/tizen/uwb/manager");
-       std::vector<MethodHandler *> _handler_vec;
+public:
+       virtual ~UwbPlugin() {};
+       virtual int init(void *uwb_plugin_load) = 0;
+       virtual int deinit(void) = 0;
+       virtual std::string getPluginPath(void) = 0;
 };
 
 }
 
-#endif /* __UWB_IFACE_HANDLER_H__ */
+#endif /* __UWB_PLUGIN_H__ */
index c6683eb..e6a878f 100644 (file)
 #define __UWB_PLUGIN_MANAGER_H__
 
 #include <string>
+#include <map>
+#include <memory>
+
+#include <dlfcn.h>
+
+#include <UwbPlugin.h>
 
 namespace UwbManagerNamespace {
 
 class UwbPluginManager {
 public:
-       UwbPluginManager(): _dl_handle(nullptr) {};
        ~UwbPluginManager();
-       int load(const std::string lib_path_str);
-       void unload(void);
-       void *get_symbol(const std::string symbol_str);
+       int load(std::shared_ptr<UwbPlugin> plugin);
+       int unload(std::shared_ptr<UwbPlugin> plugin);
 private:
-       void *_dl_handle;
+       std::map <std::shared_ptr<UwbPlugin>, void *>_plugins;
+       const std::string _func_tbl_symbol = std::string("uwb_plugin_load");
 };
 
 }
diff --git a/include/UwbPosition.h b/include/UwbPosition.h
new file mode 100644 (file)
index 0000000..cdd205b
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __UWB_POSITION_H__
+#define __UWB_POSITION_H__
+
+#include <list>
+#include <memory>
+
+#include <Node.h>
+#include <UwbRangePlugin.h>
+
+namespace UwbManagerNamespace {
+
+class UwbPosition {
+public:
+       UwbPosition(std::shared_ptr<UwbRangePlugin> range_plugin) :
+               _range_plugin(range_plugin){};
+       ~UwbPosition();
+
+       int update(void);
+
+       Node getOwnNode(void);
+       void setOwnNode(const Node &node);
+       void setPosition(int x, int y, int z);
+
+       int addNode(const Node &node);
+       Node *getNode(unsigned long long node_id);
+       int removeNode(unsigned long long node_id);
+       void clearNodes(void);
+
+       std::list<std::unique_ptr<Node>> *getNodes() {return &_node_list;};
+
+private:
+       int updateUwbOwnNode(void);
+       int updateUwbNodes(void);
+       int trilaterate(void);
+       int calculatePosition(void);
+       bool hasOwnPosition(void);
+       int calculateOwnPosition(void);
+       bool isPositionComputable(void);
+
+       static constexpr double EPS = 1e-10;
+       Node _own_node;
+       std::list<std::unique_ptr<Node>> _node_list;
+       std::shared_ptr<UwbRangePlugin> _range_plugin;
+};
+
+}
+
+#endif /* __UWB_POSITION_H__ */
index a1acae5..e1eef3e 100644 (file)
 #include <glib.h>
 
 #include <uwb-hpi.h>
-#include <UwbConfig.h>
-#include <UwbPluginManager.h>
+#include <UwbPlugin.h>
 
 namespace UwbManagerNamespace {
 
-class UwbRangePlugin {
+class UwbRangePlugin : public UwbPlugin {
 public:
-       int init(UwbPluginManager *plugin_manager);
-       int deinit(void);
+       int init(void *uwb_plugin_load) override;
+       int deinit() override;
+       std::string getPluginPath(void) override;
+
        int test(void);
        int reset(void);
        int factoryReset(void);
-       int getOwnNode(uwb_hpi_node_s **own_node);
-       int getNetworkInfo(uwb_hpi_network_s **network_info);
+
        int setConfigurations(uint16_t node_id, const GVariant *configurations);
        int getConfigurations(uint16_t node_id, GVariant **configurations);
-       int setPosition(uint16_t node_id, int x, int y, int z);
+
+       int enableNetwork(void);
+       int disableNetwork(void);
+       int getOwnNode(uwb_hpi_node_s **own_node);
+       int getNetworkInfo(uwb_hpi_network_s **network_info);
+       int setPosition(uint64_t node_id, int x, int y, int z);
+
        int sendMessage(const unsigned char *message, int message_length);
        int sendMessageTo(uint16_t node_id, const unsigned char *message, int message_length);
+
        static void messageReceivedCb(uint16_t node_id, unsigned char *message, int message_length);
        static void positionChangedCb(uint16_t node_id, int x, int y, int z);
 private:
        uwb_hpi_event_cbs_s event_cbs;
        uwb_hpi_ops_s ops;
+       const std::string _plugin_path =
+                       std::string("uwb-plugin-dwm1001.so");
 };
 
 }
index 4d2010f..c2dacb0 100644 (file)
 #define __UWB_LOG_FUNC_ENTER__ UWB_LOGI("Enter")
 #define __UWB_LOG_FUNC_EXIT__ UWB_LOGI("Quit")
 
+#define ret_if(expr) do { \
+               if (expr) { \
+                       UWB_LOGE("(%s)", #expr); \
+                       __UWB_LOG_FUNC_EXIT__; \
+                       return; \
+               } \
+       } while (0)
+
+#define retv_if(expr, val) do { \
+               if (expr) { \
+                       UWB_LOGE("(%s)", #expr); \
+                       __UWB_LOG_FUNC_EXIT__; \
+                       return (val); \
+               } \
+       } while (0)
+
 #endif /* __UWB_LOG_DEF_H__ */
index 4cba98f..9e43337 100755 (executable)
                </method>
                <method name="FactoryReset">
                </method>
+               <method name="EnableNetwork">
+               </method>
+               <method name="DisableNetwork">
+               </method>
+               <method name="StartLocationEngine">
+                       <arg type="s" name="server" direction="in" />
+                       <arg type="i" name="port" direction="in" />
+               </method>
+               <method name="StopLocationEngine">
+               </method>
                <method name="GetOwnNode">
                        <arg type="a{sv}" name="own_node" direction="out" />
                </method>
                        <arg type="i" name="y" />
                        <arg type="i" name="z" />
                </signal>
+               <signal name="PositionUpdated">
+                       <arg type="q" name="node_id" />
+                       <arg type="i" name="x" />
+                       <arg type="i" name="y" />
+                       <arg type="i" name="z" />
+               </signal>
+               <signal name="NodeAdded">
+                       <arg type="i" name="pan_id" />
+                       <arg type="q" name="node_id" />
+                       <arg type="i" name="x" />
+                       <arg type="i" name="y" />
+                       <arg type="i" name="z" />
+               </signal>
+               <signal name="NodeUpdated">
+                       <arg type="i" name="pan_id" />
+                       <arg type="q" name="node_id" />
+                       <arg type="i" name="x" />
+                       <arg type="i" name="y" />
+                       <arg type="i" name="z" />
+               </signal>
+               <signal name="NodeRemoved">
+                       <arg type="i" name="pan_id" />
+                       <arg type="q" name="node_id" />
+                       <arg type="i" name="x" />
+                       <arg type="i" name="y" />
+                       <arg type="i" name="z" />
+               </signal>
        </interface>
 </node>
diff --git a/packaging/dwm1001.conf b/packaging/dwm1001.conf
new file mode 100644 (file)
index 0000000..f6f7491
--- /dev/null
@@ -0,0 +1,25 @@
+{
+    "PANID": 17570,
+    "MODE": "ANCHOR",
+    "ANCHOR_BRIDGE": false,
+    "ANCHOR_INITIATOR": true,
+    "ANCHOR_UWB_BH_ROUTING": 1,
+    "ANCHOR_ENC_EN": false,
+    "ANCHOR_LED_EN": true,
+    "ANCHOR_BLE_EN": true,
+    "ANCHOR_UWB_MODE": 2,
+    "ANCHOR_FW_UPDATE_EN": false,
+    "TAG_STNRY_EN": true,
+    "TAG_LOW_POWER_EN": false,
+    "TAG_MEAS_MODE": 0,
+    "TAG_LOC_ENGINE_EN": true,
+    "TAG_ENC_EN": false,
+    "TAG_LED_EN": true,
+    "TAG_BLE_EN": true,
+    "TAG_UWB_MODE": 2,
+    "TAG_FW_UPDATE_EN": false,
+    "UPDATE_RATE": 1,
+    "STATIONARY_UPDATE_RATE": 1,
+    "NETWORK_TIMEOUT": 1500,
+    "HARDWARE_WAIT_TIME": 2000
+}
index a1f4fea..e1b8056 100644 (file)
@@ -1,6 +1,6 @@
 Name:       uwb-manager
 Summary:    This is the daemon managing UWB related functionalities
-Version:    0.0.1
+Version:    0.0.2
 Release:    1
 Group:      Network & Connectivity/Wireless
 License:    Apache-2.0
@@ -12,17 +12,15 @@ BuildRequires:  pkgconfig(gio-2.0)
 BuildRequires:  pkgconfig(dlog)
 BuildRequires:  pkgconfig(libtzplatform-config)
 BuildRequires:  pkgconfig(json-glib-1.0)
+BuildRequires:  pkgconfig(paho-mqtt-c)
 Source1:       dbus-uwb-manager.conf
 Source2:       org.tizen.uwb.service
 Source3:       uwb-manager.service
+Source4:       dwm1001.conf
 
 Requires(post): /sbin/ldconfig
 Requires(postun): /sbin/ldconfig
 
-%if 0%{?gtests:1}
-BuildRequires: pkgconfig(gmock)
-%endif
-
 %description
 Manager for handling UWB functionalities
 
@@ -33,16 +31,14 @@ chmod 644 %{SOURCE0}
 chmod 644 %{SOURCE1}
 chmod 644 %{SOURCE2}
 chmod 644 %{SOURCE3}
+chmod 644 %{SOURCE4}
 cp -a %{SOURCE1} ./uwb-manager.conf
 cp -a %{SOURCE2} .
 cp -a %{SOURCE3} .
+cp -a %{SOURCE4} ./uwb-plugin.conf
 
 %build
 
-export CFLAGS="$CFLAGS -DTIZEN_DEBUG_ENABLE"
-export CXXFLAGS="$CXXFLAGS -DTIZEN_DEBUG_ENABLE"
-export FFLAGS="$FFLAGS -DTIZEN_DEBUG_ENABLE"
-
 %if 0%{?gcov:1}
 export CFLAGS+=" -fprofile-arcs -ftest-coverage"
 export CXXFLAGS+=" -fprofile-arcs -ftest-coverage"
@@ -57,26 +53,20 @@ export LDFLAGS+=" -lgcov"
        -DLIB_DIR=%{_libdir} \
        -DBIN_DIR=%{_bindir} \
        -DTZ_SYS_RO_ETC=%{TZ_SYS_RO_ETC} \
-       -DBUILD_GTESTS=%{?gtests:1}%{!?gtests:0} \
        -DBUILD_GCOV=%{?gcov:1}%{!?gcov:0} \
-       -DBUILD_TEST_APP=%{?test_app:1}%{!?test_app:0}
 
 make %{?_smp_mflags}
 
 %install
-rm -rf %{buildroot}
 
 %make_install
 
 mkdir -p %{buildroot}%{_datadir}/dbus-1/system-services/
 cp org.tizen.uwb.service %{buildroot}%{_datadir}/dbus-1/system-services/
-mkdir -p %{buildroot}%{_libdir}/systemd/system/
-cp uwb-manager.service %{buildroot}%{_libdir}/systemd/system/uwb-manager.service
-%if "%{?_lib}" == "lib64"
 mkdir -p %{buildroot}%{_unitdir}
 cp uwb-manager.service %{buildroot}%{_unitdir}/uwb-manager.service
-%endif
 mkdir -p %{buildroot}%{_sysconfdir}/uwb/
+cp uwb-plugin.conf %{buildroot}%{_sysconfdir}/uwb/
 
 #DBus DAC
 mkdir -p %{buildroot}%{_sysconfdir}/dbus-1/system.d
@@ -91,10 +81,8 @@ cp uwb-manager.conf %{buildroot}%{_sysconfdir}/dbus-1/system.d/uwb-manager.conf
 %attr(500,root,root) %{_bindir}/*
 
 %attr(644,root,root) %{_datadir}/dbus-1/system-services/org.tizen.uwb.service
-%attr(644,root,root) %{_libdir}/systemd/system/*
-%if "%{?_lib}" == "lib64"
 %attr(644,root,root) %{_unitdir}/uwb-manager.service
-%endif
+%attr(644,root,root) %{_sysconfdir}/uwb/uwb-plugin.conf
 
 #DBus DAC
 %attr(644,root,root) %{_sysconfdir}/dbus-1/system.d/uwb-manager.conf
diff --git a/plugin/dwm1001/CMakeLists.txt b/plugin/dwm1001/CMakeLists.txt
new file mode 100755 (executable)
index 0000000..3eac0b2
--- /dev/null
@@ -0,0 +1,44 @@
+# Copyright (c) 2020 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+# @file        CMakeLists.txt
+#
+########################## search for packages ################################
+
+PKG_CHECK_MODULES(TARGET_DWM1001_PLUGIN_REQ_PKGS REQUIRED glib-2.0 dlog dwm1001-host-api json-glib-1.0)
+
+############################# compiler flags ##################################
+
+SET(EXTRA_FLAGS "-Wall -Werror")
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_FLAGS} ${CFLAGS}")
+SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed -pie")
+
+########################  directory configuration  ############################
+
+INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/hpi)
+INCLUDE_DIRECTORIES(include)
+INCLUDE_DIRECTORIES(${TARGET_DWM1001_PLUGIN_REQ_PKGS_INCLUDE_DIRS})
+LINK_DIRECTORIES(${TARGET_DWM1001_PLUGIN_REQ_PKGS_LIBRARY_DIRS})
+
+SET(DWM1001_PLUGIN_SRCS
+       uwb-plugin-dwm1001.c
+       )
+
+# library build
+ADD_LIBRARY(${TARGET_DWM1001_PLUGIN} SHARED ${DWM1001_PLUGIN_SRCS})
+TARGET_LINK_LIBRARIES(${TARGET_DWM1001_PLUGIN} ${TARGET_DWM1001_PLUGIN_REQ_PKGS_LIBRARIES})
+SET_TARGET_PROPERTIES(${TARGET_DWM1001_PLUGIN} PROPERTIES PREFIX "" OUTPUT_NAME ${TARGET_DWM1001_PLUGIN})
+
+# install
+INSTALL(TARGETS ${TARGET_DWM1001_PLUGIN} LIBRARY DESTINATION ${LIB_DIR})
diff --git a/plugin/dwm1001/include/uwb-plugin-dwm1001-private.h b/plugin/dwm1001/include/uwb-plugin-dwm1001-private.h
new file mode 100755 (executable)
index 0000000..1174a48
--- /dev/null
@@ -0,0 +1,87 @@
+/*
+ * UWB Plug-in Logger
+ *
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+/**
+ * This file declares UWB dwm1001 plugin logger functions and structures.
+ *
+ * @file       uwb-plugin-dwm1001-private.h
+ * @author     Jiung Yu (jiung.yu@samsung.com)
+ */
+
+#ifndef __UWB_PLUGIN_DWM1001_PRIVATE_H_
+#define __UWB_PLUGIN_DWM1001_PRIVATE_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <dlog.h>
+#include <glib.h>
+#include <unistd.h>
+
+#undef LOG_TAG
+#define LOG_TAG "UWB_PLUGIN_DWM1001"
+
+#define UWB_PLUGIN_LOGV(format, args...) LOGV(format, ##args)
+#define UWB_PLUGIN_LOGD(format, args...) LOGD(format, ##args)
+#define UWB_PLUGIN_LOGI(format, args...) LOGI(format, ##args)
+#define UWB_PLUGIN_LOGW(format, args...) LOGW(format, ##args)
+#define UWB_PLUGIN_LOGE(format, args...) LOGE(format, ##args)
+#define UWB_PLUGIN_LOGF(format, args...) LOGF(format, ##args)
+
+#define __UWB_PLUGIN_LOG_FUNC_ENTER__ LOGD("Enter")
+#define __UWB_PLUGIN_LOG_FUNC_EXIT__ LOGD("Quit")
+
+#define UWB_PLUGIN_SECLOGI(format, args...) SECURE_LOG(LOG_INFO, LOG_TAG, format, ##args)
+#define UWB_PLUGIN_SECLOGD(format, args...) SECURE_LOG(LOG_DEBUG, LOG_TAG, format, ##args)
+
+#define ret_if(expr) do { \
+               if (expr) { \
+                       UWB_PLUGIN_LOGE("(%s)", #expr); \
+                       return; \
+               } \
+       } while (0)
+
+#define retv_if(expr, val) do { \
+               if (expr) { \
+                       UWB_PLUGIN_LOGE("(%s)", #expr); \
+                       return (val); \
+               } \
+       } while (0)
+
+typedef enum {
+       UWB_DWM1001_DATA_TYPE_INVALID = 0,
+       UWB_DWM1001_DATA_TYPE_SEND_MESSAGE,
+       UWB_DWM1001_DATA_TYPE_SET_POSITION,
+       UWB_DWM1001_DATA_TYPE_GET_NODE,
+       UWB_DWM1001_DATA_TYPE_MAX,
+} uwb_dwm1001_data_type_e;
+
+typedef enum {
+       UWB_DWM1001_DIRECTION_TYPE_INVALID = 0,
+       UWB_DWM1001_DIRECTION_TYPE_REQUEST,
+       UWB_DWM1001_DIRECTION_TYPE_RESPONSE,
+       UWB_DWM1001_DIRECTION_TYPE_MAX,
+} uwb_dwm1001_direction_type_e;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __UWB_PLUGIN_DWM1001_PRIVATE_H_ */
diff --git a/plugin/dwm1001/include/uwb-plugin-dwm1001.h b/plugin/dwm1001/include/uwb-plugin-dwm1001.h
new file mode 100755 (executable)
index 0000000..95226b6
--- /dev/null
@@ -0,0 +1,82 @@
+/*
+ * UWB Range Plug-in
+ *
+ * Copyright (c) 2020 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+/**
+ * This file declares UWB DWM1001 board plugin functions and structures.
+ *
+ * @file               uwb-plugin-dwm1001.h
+ * @author     Jiung Yu (jiung.yu@samsung.com)
+ */
+
+#ifndef __UWB_PLUGIN_DWM1001_H__
+#define __UWB_PLUGIN_DWM1001_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <dwm_api.h>
+#include <glib.h>
+#include <stdlib.h>
+
+typedef struct {
+       uint64_t node_id;
+       uint16_t pan_id;
+       bool is_remote;
+       uint64_t distance;
+       int x;
+       int y;
+       int z;
+} uwb_node_s;
+
+typedef struct {
+       uint16_t pan_id;
+       GSList *remote_node_list;
+       int remote_node_count;
+} uwb_network_s;
+
+typedef struct {
+       void (*message_received_cb) (uint16_t node_id, unsigned char *message, int message_length);
+       void (*position_changed_cb) (uint16_t node_id, int x, int y, int z);
+} uwb_hpi_event_cbs_s;
+
+typedef struct {
+       int (*init) (uwb_hpi_event_cbs_s *event_cbs);
+       int (*deinit) (void);
+       int (*test) (void);
+       int (*reset) (void);
+       int (*factory_reset) (void);
+       int (*enable_network) (void);
+       int (*disable_network) (void);
+       int (*get_network_info) (uwb_network_s **network_info);
+       int (*set_configurations) (uint16_t node_id, const GVariant *configurations);
+       int (*get_configurations) (uint16_t node_id, GVariant **configurations);
+       int (*set_position) (uint64_t node_id, int x, int y, int z);
+       int (*get_own_node) (uwb_node_s **own_node);
+       int (*send_message) (unsigned char *message, int message_length);
+       int (*send_message_to) (uint16_t node_id, unsigned char *message, int message_length);
+} uwb_hpi_ops_s;
+
+int uwb_plugin_load(uwb_hpi_ops_s *ops);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __UWB_PLUGIN_DWM1001_H__ */
diff --git a/plugin/dwm1001/include/uwb-plugin-log.h b/plugin/dwm1001/include/uwb-plugin-log.h
new file mode 100755 (executable)
index 0000000..9cb0c70
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * UWB Plug-in Logger
+ *
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+/**
+ * This file declares UWB dwm1001 plugin logger functions and structures.
+ *
+ * @file       uwb-plugin-log.h
+ * @author     Jiung Yu (jiung.yu@samsung.com)
+ */
+
+#ifndef __UWB_PLUGIN_LOG_H_
+#define __UWB_PLUGIN_LOG_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+#include <dlog.h>
+
+#undef LOG_TAG
+#define LOG_TAG "UWB_PLUGIN"
+
+#define UWB_PLUGIN_LOGV(format, args...) LOGV(format, ##args)
+#define UWB_PLUGIN_LOGD(format, args...) LOGD(format, ##args)
+#define UWB_PLUGIN_LOGI(format, args...) LOGI(format, ##args)
+#define UWB_PLUGIN_LOGW(format, args...) LOGW(format, ##args)
+#define UWB_PLUGIN_LOGE(format, args...) LOGE(format, ##args)
+#define UWB_PLUGIN_LOGF(format, args...) LOGF(format, ##args)
+
+#define __UWB_PLUGIN_LOG_FUNC_ENTER__ UWB_PLUGIN_LOGI("Enter")
+#define __UWB_PLUGIN_LOG_FUNC_EXIT__ UWB_PLUGIN_LOGI("Quit")
+
+#define UWB_PLUGIN_SECLOGI(format, args...) SECURE_LOG(LOG_INFO, LOG_TAG, format, ##args)
+#define UWB_PLUGIN_SECLOGD(format, args...) SECURE_LOG(LOG_DEBUG, LOG_TAG, format, ##args)
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __UWB_PLUGIN_LOG_H_ */
diff --git a/plugin/dwm1001/uwb-plugin-dwm1001.c b/plugin/dwm1001/uwb-plugin-dwm1001.c
new file mode 100755 (executable)
index 0000000..93c5bbd
--- /dev/null
@@ -0,0 +1,603 @@
+/*
+ * UWB Plug-in for ranging
+ *
+ * Copyright (c) 2020 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+/**
+ * This file implements UWB ranging plugin functions.
+ *
+ * @file       uwb-plugin-dwm1001.c
+ * @author     Jiung Yu (jiung.yu@samsung.com)
+ */
+#include <inttypes.h>
+
+#include "uwb-plugin-dwm1001.h"
+#include "uwb-plugin-dwm1001-private.h"
+
+#define DBUS_DEBUG_VARIANT(var) \
+       do {\
+               gchar *var_debug_str = NULL;\
+               if (var)\
+                       var_debug_str = g_variant_print((var), TRUE);\
+               UWB_PLUGIN_LOGI("value [%s]", var_debug_str ? var_debug_str : "NULL");\
+               g_free(var_debug_str);\
+       } while (0)
+
+#define DEFAULT_PANID 0x44a2
+#define DEFAULT_MODE DWM_MODE_ANCHOR
+#define DEFAULT_NETWORK_TIMEOUT 1500
+#define DEFAULT_HARDWARE_WAIT_TIME 2000
+
+static struct _dwm1001_ctx {
+       bool is_enable;
+       uint16_t pan_id;
+       uint64_t node_id;
+       dwm_cfg_anchor_t cfg_anchor;
+       dwm_cfg_tag_t cfg_tag;
+       uint16_t update_rate;
+       uint16_t stationary_update_rate;
+       int network_timeout;
+       int hardware_wait_time;
+       dwm_mode_t mode;
+       uwb_hpi_event_cbs_s *event_cbs;
+} dwm1001_ctx;
+
+static void __destroy_node(gpointer data)
+{
+       if (data != NULL) {
+               uwb_node_s *node = (uwb_node_s *)data;
+               free(node);
+       }
+}
+
+static void __clean_dwm1001_ctx()
+{
+       __UWB_PLUGIN_LOG_FUNC_ENTER__;
+
+       dwm1001_ctx.event_cbs = NULL;
+       dwm1001_ctx.is_enable = false;
+
+       __UWB_PLUGIN_LOG_FUNC_EXIT__;
+}
+
+static void __set_config_anchor()
+{
+       __UWB_PLUGIN_LOG_FUNC_ENTER__;
+
+       dwm_cfg_anchor_set(&(dwm1001_ctx.cfg_anchor));
+       dwm1001_ctx.mode = DWM_MODE_ANCHOR;
+
+       __UWB_PLUGIN_LOG_FUNC_EXIT__;
+}
+
+static void __set_config_tag()
+{
+       __UWB_PLUGIN_LOG_FUNC_ENTER__;
+
+       dwm_cfg_tag_set(&(dwm1001_ctx.cfg_tag));
+       dwm1001_ctx.mode = DWM_MODE_TAG;
+
+       __UWB_PLUGIN_LOG_FUNC_EXIT__;
+}
+
+static void __set_default_dwm1001_ctx()
+{
+       dwm1001_ctx.pan_id = DEFAULT_PANID;
+       dwm1001_ctx.cfg_anchor.bridge = false;
+       dwm1001_ctx.cfg_anchor.initiator = true;
+       dwm1001_ctx.cfg_anchor.uwb_bh_routing = true;
+       dwm1001_ctx.cfg_anchor.common.enc_en = false;
+       dwm1001_ctx.cfg_anchor.common.led_en = true;
+       dwm1001_ctx.cfg_anchor.common.ble_en = true;
+       dwm1001_ctx.cfg_anchor.common.uwb_mode = DWM_UWB_MODE_ACTIVE;
+       dwm1001_ctx.cfg_anchor.common.fw_update_en = false;
+
+       dwm1001_ctx.cfg_tag.stnry_en = true;
+       dwm1001_ctx.cfg_tag.low_power_en = false;
+       dwm1001_ctx.cfg_tag.meas_mode = DWM_MEAS_MODE_TWR;
+       dwm1001_ctx.cfg_tag.loc_engine_en = true;
+       dwm1001_ctx.cfg_tag.common.enc_en = false;
+       dwm1001_ctx.cfg_tag.common.led_en = true;
+       dwm1001_ctx.cfg_tag.common.ble_en = true;
+       dwm1001_ctx.cfg_tag.common.uwb_mode = DWM_UWB_MODE_ACTIVE;
+       dwm1001_ctx.cfg_tag.common.fw_update_en = false;
+       dwm1001_ctx.mode = DWM_MODE_ANCHOR;
+       dwm1001_ctx.update_rate = 1;
+       dwm1001_ctx.stationary_update_rate = 1;
+       dwm1001_ctx.network_timeout = DEFAULT_NETWORK_TIMEOUT;
+       dwm1001_ctx.hardware_wait_time = DEFAULT_HARDWARE_WAIT_TIME;
+
+}
+
+static int uwb_dwm1001_init(uwb_hpi_event_cbs_s *event_cbs)
+{
+       int ret = 0;
+
+       __UWB_PLUGIN_LOG_FUNC_ENTER__;
+
+       dwm1001_ctx.is_enable = false;
+       __set_default_dwm1001_ctx();
+       dwm1001_ctx.event_cbs = event_cbs;
+
+       __UWB_PLUGIN_LOG_FUNC_EXIT__;
+       return ret;
+}
+
+static int uwb_dwm1001_deinit(void)
+{
+       __UWB_PLUGIN_LOG_FUNC_ENTER__;
+
+       dwm_deinit();
+       __clean_dwm1001_ctx();
+       dwm1001_ctx.is_enable = false;
+
+       __UWB_PLUGIN_LOG_FUNC_EXIT__;
+       return 0;
+}
+
+static int uwb_dwm1001_test(void)
+{
+       __UWB_PLUGIN_LOG_FUNC_ENTER__;
+
+       __UWB_PLUGIN_LOG_FUNC_EXIT__;
+       return 0;
+}
+
+static int uwb_dwm1001_reset(void)
+{
+       int ret = 0;
+       __UWB_PLUGIN_LOG_FUNC_ENTER__;
+
+       retv_if(!dwm1001_ctx.is_enable, -1);
+
+       dwm_reset();
+
+       usleep(dwm1001_ctx.hardware_wait_time * 1000);
+
+       __UWB_PLUGIN_LOG_FUNC_EXIT__;
+       return ret;
+}
+
+
+int uwb_dwm1001_factory_reset(void)
+{
+       int ret = 0;
+       __UWB_PLUGIN_LOG_FUNC_ENTER__;
+
+       retv_if(!dwm1001_ctx.is_enable, -1);
+
+       ret = dwm_factory_reset();
+       if (ret != RV_OK) {
+               UWB_PLUGIN_LOGE("dwm factory reset FAIL : %d", ret);
+               ret = -1;
+       }
+
+       usleep(dwm1001_ctx.hardware_wait_time * 1000);
+
+       (DEFAULT_MODE == DWM_MODE_ANCHOR) ?
+                       __set_config_anchor() : __set_config_tag();
+
+       dwm_upd_rate_set(dwm1001_ctx.update_rate, dwm1001_ctx.stationary_update_rate);
+       dwm_panid_set(dwm1001_ctx.pan_id);
+
+       __UWB_PLUGIN_LOG_FUNC_EXIT__;
+       return ret;
+}
+
+int uwb_dwm1001_enable_network(void)
+{
+       int ret = 0;
+       __UWB_PLUGIN_LOG_FUNC_ENTER__;
+
+       retv_if(dwm1001_ctx.is_enable, -1);
+
+       dwm_init();
+
+       (dwm1001_ctx.mode == DWM_MODE_ANCHOR) ?
+                       __set_config_anchor() : __set_config_tag();
+       dwm_upd_rate_set(dwm1001_ctx.update_rate, dwm1001_ctx.stationary_update_rate);
+       dwm_panid_set((uint16_t)dwm1001_ctx.pan_id);
+
+       ret = dwm_node_id_get(&dwm1001_ctx.node_id);
+       if (ret != RV_OK) {
+               UWB_PLUGIN_LOGE("dwm_node_id_get FAIL : %d", ret);
+               dwm_reset();
+               __UWB_PLUGIN_LOG_FUNC_EXIT__;
+               return -1;
+       }
+
+       ret = dwm_panid_get(&dwm1001_ctx.pan_id);
+       if (ret != RV_OK) {
+               UWB_PLUGIN_LOGE("dwm_panid_get FAIL : %d", ret);
+               dwm_reset();
+               __UWB_PLUGIN_LOG_FUNC_EXIT__;
+               return -1;
+       }
+
+       UWB_PLUGIN_LOGI("MODE : %d, pan_id : %" PRIu16 " node_id : %" PRIu64,
+               dwm1001_ctx.mode, dwm1001_ctx.pan_id, dwm1001_ctx.node_id);
+       __UWB_PLUGIN_LOG_FUNC_EXIT__;
+       dwm1001_ctx.is_enable = true;
+
+       return 0;
+}
+
+int uwb_dwm1001_disable_network(void)
+{
+       __UWB_PLUGIN_LOG_FUNC_ENTER__;
+
+       retv_if(!dwm1001_ctx.is_enable, -1);
+
+       dwm_deinit();
+       __clean_dwm1001_ctx();
+       dwm1001_ctx.is_enable = false;
+
+       __UWB_PLUGIN_LOG_FUNC_EXIT__;
+       return 0;
+}
+
+int uwb_dwm1001_get_own_node(uwb_node_s **own_node)
+{
+       int ret = 0;
+       dwm_pos_t pos;
+
+       __UWB_PLUGIN_LOG_FUNC_ENTER__;
+
+       retv_if(own_node == NULL, -1);
+       retv_if(!dwm1001_ctx.is_enable, -1);
+
+       ret = dwm_pos_get(&pos);
+       if (ret != RV_OK) {
+               UWB_PLUGIN_LOGE("dwm_pos_get FAIL : %d", ret);
+               dwm_reset();
+               __UWB_PLUGIN_LOG_FUNC_EXIT__;
+               return -1;
+       }
+
+       *own_node = (uwb_node_s *)malloc(sizeof(uwb_node_s));
+       if (*own_node == NULL) {
+               UWB_PLUGIN_LOGE("own_node is NULL");
+               __UWB_PLUGIN_LOG_FUNC_EXIT__;
+               return -1;
+       }
+
+       (*own_node)->distance = 0;
+       (*own_node)->is_remote = false;
+       (*own_node)->node_id = dwm1001_ctx.node_id;
+       (*own_node)->pan_id = dwm1001_ctx.pan_id;
+       (*own_node)->x = pos.x;
+       (*own_node)->y = pos.y;
+       (*own_node)->z = pos.z;
+
+       UWB_PLUGIN_LOGI("obtained node_id : %" PRIu64, dwm1001_ctx.node_id);
+       UWB_PLUGIN_LOGI("X: %d Y: %d Z: %d", pos.x, pos.y, pos.z);
+       __UWB_PLUGIN_LOG_FUNC_EXIT__;
+
+       return ret;
+}
+
+static GSList *__get_anchor_list_anchor()
+{
+       dwm_anchor_list_t list;
+       GSList *node_list = NULL;
+       int ret;
+
+       /* Get anchor nodes */
+       ret = dwm_anchor_list_get(&list);
+       if (ret != RV_OK) {
+               UWB_PLUGIN_LOGE("dwm_anchor_list_get FAIL : %d", ret);
+               dwm_reset();
+               return NULL;
+       }
+
+       /* Insert Nodes to node list */
+       for (int i = 0; i < list.cnt; ++i) {
+               uwb_node_s *node;
+
+               /* Calculator distance between anchor node */
+               node = (uwb_node_s *)malloc(sizeof(uwb_node_s));
+               if (node == NULL) {
+                       UWB_PLUGIN_LOGE("Alloc failed");
+                       continue;
+               }
+               node->is_remote = true;
+               node->node_id = list.v[i].node_id;
+               node->pan_id = dwm1001_ctx.pan_id;
+               node->x = list.v[i].x;
+               node->y = list.v[i].y;
+               node->z = list.v[i].z;
+               node_list = g_slist_append(node_list, node);
+       }
+
+       return node_list;
+}
+
+static GSList *__get_anchor_list_tag()
+{
+       dwm_loc_data_t loc;
+       dwm_pos_t pos;
+       GSList *node_list = NULL;
+       int ret;
+
+       loc.p_pos = &pos;
+       ret = dwm_loc_get(&loc);
+       if (ret != RV_OK) {
+               UWB_PLUGIN_LOGE("dwm_loc_get FAIL : %d", ret);
+               dwm_reset();
+               return NULL;
+       }
+
+       for (int i = 0; i < loc.anchors.dist.cnt; ++i) {
+               uwb_node_s *node;
+               node = (uwb_node_s *)malloc(sizeof(uwb_node_s));
+               if (node == NULL) {
+                       UWB_PLUGIN_LOGE("Alloc failed");
+                       continue;
+               }
+
+               node->distance = loc.anchors.dist.dist[i];
+               node->is_remote = true;
+               node->node_id = loc.anchors.dist.addr[i];
+               node->pan_id = dwm1001_ctx.pan_id;
+               node->x = loc.anchors.an_pos.pos[i].x;
+               node->y = loc.anchors.an_pos.pos[i].y;
+               node->z = loc.anchors.an_pos.pos[i].z;
+               node_list = g_slist_append(node_list, node);
+       }
+
+       return node_list;
+}
+
+int uwb_dwm1001_get_network_info(uwb_network_s **network_info)
+{
+       GSList *node_list = NULL;
+
+       __UWB_PLUGIN_LOG_FUNC_ENTER__;
+
+       retv_if(network_info == NULL, -1);
+       retv_if(!dwm1001_ctx.is_enable, -1);
+
+       /* Get Anchor list */
+       (dwm1001_ctx.mode == DWM_MODE_ANCHOR) ?
+                       (node_list = __get_anchor_list_anchor()) :
+                       (node_list = __get_anchor_list_tag());
+
+       *network_info = (uwb_network_s *)malloc(sizeof(uwb_network_s));
+       if (*network_info == NULL) {
+               UWB_PLUGIN_LOGE("network info is NULL");
+               g_slist_free_full(node_list, __destroy_node);
+               return -1;
+       }
+
+       (*network_info)->pan_id = dwm1001_ctx.pan_id;
+       (*network_info)->remote_node_list = node_list;
+       (*network_info)->remote_node_count  = g_slist_length(node_list);
+
+       if ((*network_info)->remote_node_count == 0) {
+               UWB_PLUGIN_LOGE("No anchor in network");
+       }
+
+       __UWB_PLUGIN_LOG_FUNC_EXIT__;
+       return 0;
+}
+
+static void __set_dwm1001_ctx(GVariantIter *iter)
+{
+       const gchar *key = NULL;
+       GVariant *value = NULL;
+
+       if (!iter)
+               return;
+
+       while (g_variant_iter_loop(iter, "{sv}", &key, &value)) {
+               UWB_PLUGIN_LOGI("key : %s", key);
+               DBUS_DEBUG_VARIANT(value);
+               if (g_strcmp0(key, "MODE") == 0) {
+                       const char *mode = NULL;
+                       mode = g_variant_get_string(value, NULL);
+                       if (strncmp(mode, "ANCHOR", strlen(mode)) == 0)
+                               dwm1001_ctx.mode = DWM_MODE_ANCHOR;
+                       else if (strncmp(mode, "TAG", strlen(mode)) == 0)
+                               dwm1001_ctx.mode = DWM_MODE_TAG;
+
+               } else if (g_strcmp0(key, "ANCHOR_BRIDGE") == 0)
+                       dwm1001_ctx.cfg_anchor.bridge = (bool)g_variant_get_boolean(value);
+               else if (g_strcmp0(key, "ANCHOR_INITIATOR") == 0)
+                       dwm1001_ctx.cfg_anchor.initiator = (bool)g_variant_get_boolean(value);
+               else if (g_strcmp0(key, "ANCHOR_UWB_BH_ROUTING") == 0)
+                       dwm1001_ctx.cfg_anchor.uwb_bh_routing = (int)g_variant_get_int64(value);
+               else if (g_strcmp0(key, "ANCHOR_ENC_EN") == 0)
+                       dwm1001_ctx.cfg_anchor.common.enc_en = (bool)g_variant_get_boolean(value);
+               else if (g_strcmp0(key, "ANCHOR_LED_EN") == 0)
+                       dwm1001_ctx.cfg_anchor.common.led_en = (bool)g_variant_get_boolean(value);
+               else if (g_strcmp0(key, "ANCHOR_BLE_EN") == 0)
+                       dwm1001_ctx.cfg_anchor.common.ble_en = (bool)g_variant_get_boolean(value);
+               else if (g_strcmp0(key, "ANCHOR_UWB_MODE") == 0)
+                       dwm1001_ctx.cfg_anchor.common.uwb_mode = (int)g_variant_get_int64(value);
+               else if (g_strcmp0(key, "ANCHOR_FW_UPDATE_EN") == 0)
+                       dwm1001_ctx.cfg_anchor.common.fw_update_en = (bool)g_variant_get_boolean(value);
+
+               else if (g_strcmp0(key, "TAG_STNRY_EN") == 0)
+                       dwm1001_ctx.cfg_tag.stnry_en = (bool)g_variant_get_boolean(value);
+               else if (g_strcmp0(key, "TAG_LOW_POWER_EN") == 0)
+                       dwm1001_ctx.cfg_tag.low_power_en = (bool)g_variant_get_boolean(value);
+               else if (g_strcmp0(key, "TAG_MEAS_MODE") == 0)
+                       dwm1001_ctx.cfg_tag.meas_mode = (int)g_variant_get_int64(value);
+               else if (g_strcmp0(key, "TAG_LOC_ENGINE_EN") == 0)
+                       dwm1001_ctx.cfg_tag.loc_engine_en = (bool)g_variant_get_boolean(value);
+               else if (g_strcmp0(key, "TAG_ENC_EN") == 0)
+                       dwm1001_ctx.cfg_tag.common.enc_en = (bool)g_variant_get_boolean(value);
+               else if (g_strcmp0(key, "TAG_LED_EN") == 0)
+                       dwm1001_ctx.cfg_tag.common.led_en = (bool)g_variant_get_boolean(value);
+               else if (g_strcmp0(key, "TAG_BLE_EN") == 0)
+                       dwm1001_ctx.cfg_tag.common.ble_en = (bool)g_variant_get_boolean(value);
+               else if (g_strcmp0(key, "TAG_UWB_MODE") == 0)
+                       dwm1001_ctx.cfg_tag.common.uwb_mode = (int)g_variant_get_int64(value);
+               else if (g_strcmp0(key, "TAG_FW_UPDATE_EN") == 0)
+                       dwm1001_ctx.cfg_tag.common.fw_update_en = (bool)g_variant_get_boolean(value);
+
+               else if (g_strcmp0(key, "UPDATE_RATE") == 0)
+                       dwm1001_ctx.update_rate = (int)g_variant_get_int64(value);
+               else if (g_strcmp0(key, "NETWORK_TIMEOUT") == 0)
+                       dwm1001_ctx.network_timeout = (int)g_variant_get_int64(value);
+               else if (g_strcmp0(key, "HARDWARE_WAIT_TIME") == 0)
+                       dwm1001_ctx.hardware_wait_time = (int)g_variant_get_int64(value);
+               else if (g_strcmp0(key, "PANID") == 0)
+                       dwm1001_ctx.pan_id = (uint16_t)g_variant_get_int64(value);
+       }
+       UWB_PLUGIN_LOGE("pan_id : %d", (int)dwm1001_ctx.pan_id);
+       UWB_PLUGIN_LOGE("hardware_wait_time : %d", dwm1001_ctx.hardware_wait_time);
+       UWB_PLUGIN_LOGE("network_timeout : %d", dwm1001_ctx.network_timeout);
+}
+
+int uwb_dwm1001_set_configurations(uint16_t node_id, const GVariant *configurations)
+{
+       GVariantIter *iter = NULL;
+       __UWB_PLUGIN_LOG_FUNC_ENTER__;
+
+       retv_if(dwm1001_ctx.is_enable, -1);
+
+       g_variant_get((GVariant *)configurations, "a{sv}", &iter);
+
+       __set_dwm1001_ctx(iter);
+
+       g_variant_iter_free(iter);
+
+       __UWB_PLUGIN_LOG_FUNC_EXIT__;
+       return 0;
+}
+
+static void __build_configuration(GVariantBuilder *builder)
+{
+       if (!builder)
+               return;
+
+       if (dwm1001_ctx.mode == DWM_MODE_ANCHOR)
+               g_variant_builder_add(builder, "{sv}", "MODE", g_variant_new("s", "ANCHOR"));
+       else
+               g_variant_builder_add(builder, "{sv}", "MODE", g_variant_new("s", "TAG"));
+       UWB_PLUGIN_LOGE("network_timeout : %d", dwm1001_ctx.network_timeout);
+       g_variant_builder_add(builder, "{sv}", "NETWORK_TIMEOUT", g_variant_new("x", (int64_t)dwm1001_ctx.network_timeout));
+       g_variant_builder_add(builder, "{sv}", "HARDWARE_WAIT_TIME", g_variant_new("x", (int64_t)dwm1001_ctx.hardware_wait_time));
+       g_variant_builder_add(builder, "{sv}", "PANID", g_variant_new("x", (int64_t)dwm1001_ctx.pan_id));
+
+       g_variant_builder_add(builder, "{sv}", "ANCHOR_BRIDGE", g_variant_new("b", dwm1001_ctx.cfg_anchor.bridge));
+       g_variant_builder_add(builder, "{sv}", "ANCHOR_INITIATOR", g_variant_new("b", dwm1001_ctx.cfg_anchor.initiator));
+       g_variant_builder_add(builder, "{sv}", "ANCHOR_UWB_BH_ROUTING", g_variant_new("x", (int64_t)dwm1001_ctx.cfg_anchor.uwb_bh_routing));
+       g_variant_builder_add(builder, "{sv}", "ANCHOR_ENC_EN", g_variant_new("b", dwm1001_ctx.cfg_anchor.common.enc_en));
+       g_variant_builder_add(builder, "{sv}", "ANCHOR_LED_EN", g_variant_new("b", dwm1001_ctx.cfg_anchor.common.led_en));
+       g_variant_builder_add(builder, "{sv}", "ANCHOR_BLE_EN", g_variant_new("b", dwm1001_ctx.cfg_anchor.common.ble_en));
+       g_variant_builder_add(builder, "{sv}", "ANCHOR_UWB_MODE", g_variant_new("x", (int64_t)dwm1001_ctx.cfg_anchor.common.uwb_mode));
+       g_variant_builder_add(builder, "{sv}", "ANCHOR_FW_UPDATE_EN", g_variant_new("b", dwm1001_ctx.cfg_anchor.common.fw_update_en));
+
+       g_variant_builder_add(builder, "{sv}", "TAG_STNRY_EN", g_variant_new("b", dwm1001_ctx.cfg_tag.stnry_en));
+       g_variant_builder_add(builder, "{sv}", "TAG_LOW_POWER_EN", g_variant_new("b", dwm1001_ctx.cfg_tag.low_power_en));
+       g_variant_builder_add(builder, "{sv}", "TAG_MEAS_MODE", g_variant_new("x", (int64_t)dwm1001_ctx.cfg_tag.meas_mode));
+       g_variant_builder_add(builder, "{sv}", "TAG_LOC_ENGINE_EN", g_variant_new("b", dwm1001_ctx.cfg_tag.loc_engine_en));
+       g_variant_builder_add(builder, "{sv}", "TAG_ENC_EN", g_variant_new("b", dwm1001_ctx.cfg_tag.common.enc_en));
+       g_variant_builder_add(builder, "{sv}", "TAG_LED_EN", g_variant_new("b", dwm1001_ctx.cfg_tag.common.led_en));
+       g_variant_builder_add(builder, "{sv}", "TAG_BLE_EN", g_variant_new("b", dwm1001_ctx.cfg_tag.common.ble_en));
+       g_variant_builder_add(builder, "{sv}", "TAG_UWB_MODE", g_variant_new("x", (int64_t)dwm1001_ctx.cfg_tag.common.uwb_mode));
+       g_variant_builder_add(builder, "{sv}", "TAG_FW_UPDATE_EN", g_variant_new("b", dwm1001_ctx.cfg_tag.common.fw_update_en));
+
+}
+
+int uwb_dwm1001_get_configurations(uint16_t node_id, GVariant **configurations)
+{
+       GVariantBuilder *builder;
+       int ret = 0;
+
+       __UWB_PLUGIN_LOG_FUNC_ENTER__;
+
+       builder = g_variant_builder_new(G_VARIANT_TYPE("a{sv}"));
+       __build_configuration(builder);
+       *configurations = g_variant_new("a{sv}", builder);
+
+       g_variant_builder_unref(builder);
+
+       __UWB_PLUGIN_LOG_FUNC_EXIT__;
+       return ret;
+}
+
+int uwb_dwm1001_set_position(uint64_t node_id, int x, int y, int z)
+{
+       int ret = 0;
+       dwm_pos_t position;
+
+       __UWB_PLUGIN_LOG_FUNC_ENTER__;
+
+       retv_if(node_id == 0, -1);
+       retv_if(!dwm1001_ctx.is_enable, -1);
+
+       if (node_id != dwm1001_ctx.node_id) {
+               UWB_PLUGIN_LOGE("Invalid node ID");
+               return -1;
+
+       }
+
+       if (dwm1001_ctx.mode == DWM_MODE_TAG) {
+               UWB_PLUGIN_LOGE("Tag mode is not support set position");
+               return -1;
+       }
+
+       position.qf = 100;
+       position.x = x;
+       position.y = y;
+       position.z = z;
+
+       UWB_PLUGIN_LOGI("Position set to (%d, %d, %d)",
+                       position.x, position.y, position.z);
+       ret = dwm_pos_set(&position);
+       if (ret != RV_OK) {
+               UWB_PLUGIN_LOGE("dwm_pos_set FAIL : %d", ret);
+               dwm_reset();
+               return -1;
+       }
+
+       __UWB_PLUGIN_LOG_FUNC_EXIT__;
+       return ret;
+}
+
+int uwb_plugin_load(uwb_hpi_ops_s *ops)
+{
+       __UWB_PLUGIN_LOG_FUNC_ENTER__;
+
+       if (!ops) {
+               UWB_PLUGIN_LOGE("Invalid parameter");
+               __UWB_PLUGIN_LOG_FUNC_EXIT__;
+               return -1;
+       }
+
+       ops->init = uwb_dwm1001_init;
+       ops->deinit = uwb_dwm1001_deinit;
+       ops->test = uwb_dwm1001_test;
+       ops->reset = uwb_dwm1001_reset;
+       ops->factory_reset = uwb_dwm1001_factory_reset;
+       ops->enable_network = uwb_dwm1001_enable_network;
+       ops->disable_network = uwb_dwm1001_disable_network;
+       ops->get_own_node = uwb_dwm1001_get_own_node;
+       ops->get_network_info = uwb_dwm1001_get_network_info;
+       ops->set_configurations = uwb_dwm1001_set_configurations;
+       ops->get_configurations = uwb_dwm1001_get_configurations;
+       ops->set_position = uwb_dwm1001_set_position;
+       ops->send_message = NULL;
+       ops->send_message_to = NULL;
+       dwm1001_ctx.is_enable = false;
+
+       __UWB_PLUGIN_LOG_FUNC_EXIT__;
+       return 0;
+}
index b3931db..a3010a6 100755 (executable)
 #
 # @file        CMakeLists.txt
 #
+########################## search for packages ################################
+
+PKG_CHECK_MODULES(TARGET_UWB_MANAGER_REQ_PKGS REQUIRED ${COMMON_DEPS})
+
+############################# compiler flags ##################################
+
+SET(EXTRA_FLAGS "-Wall -Werror")
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_FLAGS} ${CFLAGS} -fPIE")
+SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${EXTRA_FLAGS} -std=c++11 -fPIE")
+SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed -pie")
+
+########################  directory configuration  ############################
+
+INCLUDE_DIRECTORIES(${TARGET_UWB_MANAGER_REQ_PKGS_INCLUDE_DIRS})
+LINK_DIRECTORIES(${TARGET_UWB_MANAGER_REQ_PKGS_LIBRARY_DIRS})
 
 INCLUDE_DIRECTORIES(
        ${CMAKE_SOURCE_DIR}/include
        ${CMAKE_SOURCE_DIR}/hpi
-       ${CMAKE_SOURCE_DIR}/src
+       ${CMAKE_SOURCE_DIR}/interface
        )
 
-INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/interface)
-
-
-AUX_SOURCE_DIRECTORY(./ SRCS)
+FILE(GLOB SRCS *.cpp)
 SET(SRCS ${SRCS} ${CMAKE_SOURCE_DIR}/hpi/uwb-hpi.c)
 SET(SRCS ${SRCS} ${CMAKE_SOURCE_DIR}/interface/generated-code.c)
 
 SET_SOURCE_FILES_PROPERTIES(${CMAKE_SOURCE_DIR}/interface/generated-code.c PROPERTIES GENERATED TRUE)
 
-PKG_CHECK_MODULES(daemon_pkgs REQUIRED glib-2.0 gio-2.0 gio-unix-2.0 dlog libtzplatform-config json-glib-1.0)
-
-IF(TIZEN_ARCH_64)
-       ADD_DEFINITIONS(-DTIZEN_ARCH_64)
-ENDIF(TIZEN_ARCH_64)
-
-FOREACH(flag ${daemon_pkgs_CFLAGS})
-       SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
-ENDFOREACH(flag)
-
-FOREACH(flag ${daemon_pkgs_CXXFLAGS})
-       SET(EXTRA_CXXFLAGS "${EXTRA_CXXFLAGS} ${flag}")
-ENDFOREACH(flag)
-
-INCLUDE_DIRECTORIES(${daemon_pkgs_INCLUDE_DIRS})
-
-SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS} -g -Werror -fPIE")
-SET(CMAKE_C_FLAGS_DEBUG "O0 -g -fPIE")
-SET(CMAKE_C_FLAGS_RELEASE "O2 -fPIE")
-SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${EXTRA_CXXFLAGS} -g -Werror -fPIE")
-SET(CMAKE_CXX_FLAGS_DEBUG "O0 -g -fPIE")
-SET(CMAKE_CXX_FLAGS_RELEASE "O2 -fPIE")
-
-SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed -pie")
-
-ADD_EXECUTABLE(${DAEMON} ${SRCS})
-ADD_DEPENDENCIES(${DAEMON} GENERATED_DBUS_CODE)
-
-TARGET_LINK_LIBRARIES(${DAEMON} ${daemon_pkgs_LDFLAGS} -ldl)
-INSTALL(TARGETS ${DAEMON} DESTINATION bin)
-
-IF (BUILD_GTESTS)
-SET(DAEMON_LIB "uwb-mgr")
-
-ADD_LIBRARY(${DAEMON_LIB} SHARED ${SRCS})
-
-SET_TARGET_PROPERTIES(${DAEMON_LIB}
-       PROPERTIES
-       SOVERSION 0.1.0
-       CLEAN_DIRECT_OUTPUT 1)
-
-TARGET_LINK_LIBRARIES(${DAEMON_LIB} ${daemon_pkgs_LDFLAGS} -ldl)
-ADD_DEPENDENCIES(${DAEMON_LIB} GENERATED_DBUS_CODE)
+ADD_EXECUTABLE(${TARGET_UWB_MANAGER} ${SRCS})
+ADD_DEPENDENCIES(${TARGET_UWB_MANAGER} GENERATED_DBUS_CODE)
 
-INSTALL(TARGETS ${DAEMON_LIB} DESTINATION ${LIB_INSTALL_DIR} COMPONENT RuntimeLibraries)
-ENDIF (BUILD_GTESTS)
+TARGET_LINK_LIBRARIES(${TARGET_UWB_MANAGER} ${TARGET_UWB_MANAGER_REQ_PKGS_LIBRARIES} -ldl -lpaho-mqtt3a -lpthread)
+INSTALL(TARGETS ${TARGET_UWB_MANAGER} DESTINATION ${BIN_DIR})
diff --git a/src/LocationManager.cpp b/src/LocationManager.cpp
new file mode 100644 (file)
index 0000000..583f27a
--- /dev/null
@@ -0,0 +1,453 @@
+/*
+ * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include <unistd.h>
+#include <sys/types.h>
+#include <algorithm>
+#include <chrono>
+
+#include <uwb-log-def.h>
+
+#include <LocationManager.h>
+
+using namespace UwbManagerNamespace;
+
+LocationManager::~LocationManager()
+{
+       __UWB_LOG_FUNC_ENTER__;
+       this->stopPublishPosition();
+       this->unsubscribePositionBroadcast();
+
+       this->_mqtt_context->destroyMqttClient();
+       this->_node_map.clear();
+       __UWB_LOG_FUNC_EXIT__;
+}
+
+void LocationManager::setPositionUpdatedCallback(std::function<void(Node *node)> updated_cb)
+{
+       this->_position_updated_cb = updated_cb;
+}
+
+void LocationManager::unsetPositionUpdatedCallback()
+{
+       this->_position_updated_cb = nullptr;
+}
+
+void LocationManager::setNodeAddedCallback(std::function<void(Node *node)> added_cb)
+{
+       this->_node_added_cb = added_cb;
+}
+
+void LocationManager::unsetNodeAddedCallback()
+{
+       this->_node_added_cb = nullptr;
+}
+
+void LocationManager::setNodeUpdatedCallback(std::function<void(Node *node)> updated_cb)
+{
+       this->_node_updated_cb = updated_cb;
+}
+
+void LocationManager::unsetNodeUpdatedCallback()
+{
+       this->_node_updated_cb = nullptr;
+}
+
+void LocationManager::setNodeRemovedCallback(std::function<void(Node *node)> removed_cb)
+{
+       this->_node_removed_cb = removed_cb;
+}
+
+void LocationManager::unsetNodeRemovedCallback()
+{
+       this->_node_removed_cb = nullptr;
+}
+
+static uint64_t __get_current_miliseconds()
+{
+       return std::chrono::duration_cast<std::chrono::milliseconds>\
+                       (std::chrono::high_resolution_clock::now().time_since_epoch()).count();
+}
+
+void LocationManager::extractNodeInfo(char *topic, unsigned char *payload, Node *node)
+{
+       std::string node_id_str = std::string(topic).substr(
+                       LocationManager::_default_tizen_uwb_broadcast_topic_len);
+       unsigned long long node_id = std::stoull(node_id_str, nullptr, 0);
+
+       int location_idx = 0;
+       int pan_id = payload[location_idx]
+               + (payload[location_idx + 1] << 8)
+               + (payload[location_idx + 2] << 16)
+               + (payload[location_idx + 3] << 24);
+       location_idx += sizeof(int32_t);
+       int x = payload[location_idx]
+               + (payload[location_idx + 1] << 8)
+               + (payload[location_idx + 2] << 16)
+               + (payload[location_idx + 3] << 24);
+       location_idx += sizeof(int32_t);
+       int y = payload[location_idx]
+               + (payload[location_idx + 1] << 8)
+               + (payload[location_idx + 2] << 16)
+               + (payload[location_idx + 3] << 24);
+       location_idx += sizeof(int32_t);
+       int z = payload[location_idx]
+               + (payload[location_idx + 1] << 8)
+               + (payload[location_idx + 2] << 16)
+               + (payload[location_idx + 3] << 24);
+
+       node->setNodeId(node_id);
+       node->setPanId(pan_id);
+       node->setX(x);
+       node->setY(y);
+       node->setZ(z);
+       node->setLastUpdate(__get_current_miliseconds());
+}
+
+static bool __is_mqtt_message_vaild(char *topic, int topic_len,
+               unsigned char *payload, int payload_len)
+{
+       __UWB_LOG_FUNC_ENTER__;
+       if (!topic || !payload) {
+               UWB_LOGI("Invalid Topic or payload pointer");
+               __UWB_LOG_FUNC_EXIT__;
+               return false;
+       }
+
+       if (topic_len < LocationManager::_default_tizen_uwb_broadcast_topic_len) {
+               UWB_LOGI("Invalid Topic Length");
+               __UWB_LOG_FUNC_EXIT__;
+               return false;
+       }
+
+       if (payload_len != LocationManager::_default_tizen_uwb_broadcast_payload_len) {
+               UWB_LOGI("Invalid Payload Length");
+               __UWB_LOG_FUNC_EXIT__;
+               return false;
+       }
+
+       __UWB_LOG_FUNC_EXIT__;
+       return true;
+}
+
+void LocationManager::messageArrived(char *topic, int topic_len,
+               unsigned char *payload, int payload_len)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+       if (!__is_mqtt_message_vaild(topic, topic_len, payload, payload_len)) {
+               __UWB_LOG_FUNC_EXIT__;
+               return;
+       }
+
+       std::unique_ptr<Node> node_info(new Node());
+       this->extractNodeInfo(topic, payload, node_info.get());
+       if (node_info->getNodeId() == this->_current.getNodeId()) {
+               UWB_LOGI("Ignore node which has same node ID");
+               /* TODO: check Pan ID if needed */
+               __UWB_LOG_FUNC_EXIT__;
+               return;
+       }
+
+       auto itr = this->_node_map.find(node_info->getNodeId());
+       bool added = itr == this->_node_map.end();
+
+       if (added) {
+               if (this->_node_added_cb != nullptr)
+                       this->_node_added_cb(node_info.get());
+       } else {
+               if (this->_node_updated_cb != nullptr)
+                       this->_node_updated_cb(node_info.get());
+       }
+
+       this->_node_map[node_info->getNodeId()] =
+                       std::move(node_info);
+
+       __UWB_LOG_FUNC_EXIT__;
+}
+
+void LocationManager::connectionState(bool connected)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+       if (connected) {
+               this->subscribePositionBroadcast();
+               this->startPublishPosition();
+       } else {
+               this->stopPublishPosition();
+               this->unsubscribePositionBroadcast();
+       }
+
+       __UWB_LOG_FUNC_EXIT__;
+}
+
+int LocationManager::subscribePositionBroadcast(void)
+{
+       std::unique_ptr<UwbMqttMessage> mqtt_msg(new UwbMqttMessage());
+       std::unique_ptr<UwbMqttRequest> \
+       mqtt_request(new UwbMqttRequest(this->_default_mqtt_qos,
+                       std::move(mqtt_msg)));
+
+       int ret = this->_mqtt_context->subscribe(std::move(mqtt_request));
+       if (ret != 0)
+               return -1;
+
+       return 0;
+}
+
+int LocationManager::unsubscribePositionBroadcast(void)
+{
+       std::unique_ptr<UwbMqttMessage> mqtt_msg(new UwbMqttMessage());
+       std::unique_ptr<UwbMqttRequest> \
+       mqtt_request(new UwbMqttRequest(this->_default_mqtt_qos,
+                       std::move(mqtt_msg)));
+
+       int ret = this->_mqtt_context->unsubscribe(std::move(mqtt_request));
+       if (ret != 0)
+               return -1;
+
+       return 0;
+}
+
+int LocationManager::requestBroadcast(std::unique_ptr<UwbMqttMessage> mqtt_msg)
+{
+       std::unique_ptr<UwbMqttRequest> \
+       mqtt_request(new UwbMqttRequest(LocationManager::_default_mqtt_qos,
+                       1, std::move(mqtt_msg)));
+
+       int ret = this->_mqtt_context->publish(std::move(mqtt_request));
+       if (ret != 0)
+               return -1;
+
+       return ret;
+}
+
+static gboolean __broadcast_position(gpointer user_data)
+{
+       LocationManager *loc_mgr = (LocationManager *)user_data;
+       if (!loc_mgr || !loc_mgr->isPositionBroadcastSourceAvailable())
+               return false;
+
+       if (loc_mgr->updateUwbPosition() != 0)
+               return true;
+
+       auto current_position = loc_mgr->getCurrentPosition();
+       if (!current_position.getIsCalculated()) {
+               UWB_LOGI("Don't broadcast static position informaiton");
+               return true;
+       }
+
+       std::unique_ptr<UwbMqttMessage> \
+       broadcast_msg(new UwbMqttMessage(current_position));
+
+       int ret = loc_mgr->requestBroadcast(std::move(broadcast_msg));
+       if (ret != 0)
+               UWB_LOGI("Broadcast Position failed");
+
+       return true;
+}
+
+int LocationManager::startPublishPosition(void)
+{
+       this->_position_broadcast_source =
+                       g_timeout_add(LocationManager::_position_broadcast_interval * 1000,
+                                       __broadcast_position,
+                                       (gpointer)this);
+       return 0;
+}
+
+void LocationManager::stopPublishPosition(void)
+{
+       if (this->_position_broadcast_source) {
+               g_source_remove(this->_position_broadcast_source);
+               this->_position_broadcast_source = 0;
+       }
+
+       return;
+}
+
+LocationManager::LocationManager(std::shared_ptr<UwbPosition> uwb_position)
+{
+       __UWB_LOG_FUNC_ENTER__;
+       this->_position_broadcast_source = 0;
+       this->_position_updated_cb = nullptr;
+       this->_node_added_cb = nullptr;
+       this->_node_updated_cb = nullptr;
+       this->_node_removed_cb = nullptr;
+
+       this->_uwb_position = uwb_position;
+
+       std::unique_ptr<MqttContext> \
+       mqtt_context(new MqttContext());
+
+       this->_mqtt_context = std::move(mqtt_context);
+
+       __UWB_LOG_FUNC_EXIT__;
+}
+
+int LocationManager::tryConnect(void)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+       int ret = this->_mqtt_context->connectBroker();
+       if (ret != 0) {
+               __UWB_LOG_FUNC_EXIT__;
+               return -1;
+       }
+
+       __UWB_LOG_FUNC_EXIT__;
+       return 0;
+}
+
+int LocationManager::connectMqttBroker(const char *server, int port)
+{
+       __UWB_LOG_FUNC_ENTER__;
+       /* TODO: Clear up MQTT messaging sequence */
+       int ret = this->_mqtt_context->createMqttClient(server, port);
+       if (ret != 0) {
+               __UWB_LOG_FUNC_EXIT__;
+               return -1;
+       }
+
+       ret = this->tryConnect();
+       if (ret != 0) {
+               this->_mqtt_context->destroyMqttClient();
+               __UWB_LOG_FUNC_EXIT__;
+               return -1;
+       }
+
+       __UWB_LOG_FUNC_EXIT__;
+       return 0;
+}
+
+void LocationManager::updateOwnUwbPosition(void)
+{
+       this->_current = this->_uwb_position->getOwnNode();
+       if (this->_position_updated_cb != nullptr)
+               this->_position_updated_cb(&(this->_current));
+}
+
+void LocationManager::updateUwbNodes(void)
+{
+       auto uwb_node_list = this->_uwb_position->getNodes();
+       auto it = uwb_node_list->begin();
+       for (; it != uwb_node_list->end(); ++it) {
+               Node *p_node = (*it).get();
+
+       auto itr = this->_node_map.find(p_node->getNodeId());
+       bool added = itr == this->_node_map.end();
+
+       p_node->setLastUpdate(__get_current_miliseconds());
+       this->_node_map[p_node->getNodeId()] =
+                       std::unique_ptr<Node>((Node *)new Node(p_node));
+
+       if (added) {
+               if (this->_node_added_cb != nullptr)
+                       this->_node_added_cb(p_node);
+       } else {
+               if (this->_node_updated_cb != nullptr)
+                       this->_node_updated_cb(p_node);
+       }
+    }
+}
+
+void LocationManager::removeOutdatedUwbNodes(void)
+{
+       uint64_t current_mil = __get_current_miliseconds();
+
+       /* remove node which is not found during
+       *LocationManager::_default_remove_duration * 1000 miliseconds
+       */
+
+       for (auto itr = this->_node_map.begin(); itr != this->_node_map.end();) {
+       Node *node_ptr = itr->second.get();
+       if (current_mil - node_ptr->getLastUpdate()
+                        > LocationManager::_default_remove_duration * 1000) {
+               if (this->_node_removed_cb != nullptr)
+                       this->_node_removed_cb(node_ptr);
+               itr = this->_node_map.erase(itr);
+       } else
+               ++itr;
+       }
+}
+
+int LocationManager::updateUwbPosition(void)
+{
+       __UWB_LOG_FUNC_ENTER__;
+       int ret = this->_uwb_position->update();
+       if (ret != 0) {
+               UWB_LOGI("UWB position update failed");
+           __UWB_LOG_FUNC_EXIT__;
+           return -1;
+       }
+
+       this->updateOwnUwbPosition();
+       this->updateUwbNodes();
+       this->removeOutdatedUwbNodes();
+
+    __UWB_LOG_FUNC_EXIT__;
+       return 0;
+}
+
+int LocationManager::start(const char *server, int port)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+       if (server == nullptr ||
+                       port <= 0 || port >65535) {
+               __UWB_LOG_FUNC_EXIT__;
+               return -1;
+       }
+
+       using namespace std::placeholders;
+
+       auto message_arrived_cb = std::bind(&LocationManager::messageArrived,
+                       this, _1, _2, _3, _4);
+       this->_mqtt_context->setMessageArrivedCallback(message_arrived_cb);
+       auto connection_state_cb = std::bind(&LocationManager::connectionState,
+                       this, _1);
+       this->_mqtt_context->setConnectionStateCallback(connection_state_cb);
+
+       this->updateUwbPosition();
+
+       int ret = this->connectMqttBroker(server, port);
+       if (ret != 0) {
+               __UWB_LOG_FUNC_EXIT__;
+               return -1;
+       }
+
+       __UWB_LOG_FUNC_EXIT__;
+       return 0;
+}
+
+int LocationManager::stop(void)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+       this->_mqtt_context->unsetConnectionStateCallback();
+       this->_mqtt_context->unsetMessageArrivedCallback();
+       this->stopPublishPosition();
+       this->unsubscribePositionBroadcast();
+       int ret = this->_mqtt_context->destroyMqttClient();
+       if (ret != 0) {
+               __UWB_LOG_FUNC_EXIT__;
+               return -1;
+       }
+
+       this->_node_map.clear();
+
+       __UWB_LOG_FUNC_EXIT__;
+       return 0;
+}
diff --git a/src/MqttContext.cpp b/src/MqttContext.cpp
new file mode 100644 (file)
index 0000000..3522374
--- /dev/null
@@ -0,0 +1,423 @@
+/*
+ * UWB Plug-in context for MQTT
+ *
+ * Copyright (c) 2020 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+/**
+ * This file declares UWB MQTT plugin context class.
+ *
+ * @file               MqttContext.cpp
+ * @author     Jiung Yu (jiung.yu@samsung.com)
+ */
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <glib.h>
+
+#include <MqttContext.h>
+#include "uwb-log-def.h"
+
+using namespace UwbManagerNamespace;
+
+#define MQTT_BROKER_URI "tcp://%s:%d"
+#define MQTT_CLIENT_ID_PREFIX "TIZEN-%04hX"
+
+MqttContext::~MqttContext()
+{
+       __UWB_LOG_FUNC_ENTER__;
+       ret_if(this->_mqtt_client == nullptr);
+
+       this->disableRetryingConnect();
+
+       MQTTAsync_setCallbacks(this->_mqtt_client, nullptr, nullptr,
+                       nullptr, nullptr);
+       MQTTAsync_setConnected(this->_mqtt_client, nullptr, nullptr);
+       MQTTAsync_setDisconnected(this->_mqtt_client, nullptr, nullptr);
+
+       MQTTAsync_destroy(&this->_mqtt_client);
+       __UWB_LOG_FUNC_EXIT__;
+}
+
+// Message Arrived callback should return true if message
+//Handling is successful
+int __message_arrived(void *context, char *topic_name,
+               int topic_len, MQTTAsync_message *message)
+{
+       __UWB_LOG_FUNC_ENTER__;
+       retv_if(context == nullptr, 1);
+
+       MqttContext *mqtt_ctx = (MqttContext *)context;
+       if (mqtt_ctx->getMessageArrivedCb() == nullptr) {
+               __UWB_LOG_FUNC_EXIT__;
+               return 1;
+       }
+
+       mqtt_ctx->getMessageArrivedCb()(topic_name, topic_len,
+                       (unsigned char *)message->payload, message->payloadlen);
+
+       __UWB_LOG_FUNC_EXIT__;
+       return 1;
+}
+
+void __connected(void *context, char *cause)
+{
+       __UWB_LOG_FUNC_ENTER__;
+       ret_if(context == nullptr);
+
+       MqttContext *mqtt_ctx = (MqttContext *)context;
+       if (mqtt_ctx->getConnectionStateCb() == nullptr) {
+               __UWB_LOG_FUNC_EXIT__;
+               return;
+       }
+
+       mqtt_ctx->getConnectionStateCb()(true);
+       __UWB_LOG_FUNC_EXIT__;
+       return;
+}
+
+void __disconnected(void *context, MQTTProperties *properties,
+               enum MQTTReasonCodes reasonCode)
+{
+       __UWB_LOG_FUNC_ENTER__;
+       ret_if(context == nullptr);
+
+       MqttContext *mqtt_ctx = (MqttContext *)context;
+       if (mqtt_ctx->getConnectionStateCb() == nullptr) {
+               __UWB_LOG_FUNC_EXIT__;
+               return;
+       }
+
+       mqtt_ctx->getConnectionStateCb()(false);
+       __UWB_LOG_FUNC_EXIT__;
+       return;
+}
+
+void __connection_lost(void *context, char *cause)
+{
+       __UWB_LOG_FUNC_ENTER__;
+       ret_if(context == nullptr);
+
+       MqttContext *mqtt_ctx = (MqttContext *)context;
+       if (mqtt_ctx->getConnectionStateCb() == nullptr) {
+               __UWB_LOG_FUNC_EXIT__;
+               return;
+       }
+
+       mqtt_ctx->getConnectionStateCb()(false);
+       /* depends on Mqtt connection retry logic in Mqtt paho */
+       MQTTAsync_setConnected(mqtt_ctx->getMqttClient(), mqtt_ctx, __connected);
+
+       __UWB_LOG_FUNC_EXIT__;
+       return;
+}
+
+int MqttContext::createMqttClient(const char *server, int port)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+       retv_if(this->_mqtt_client != nullptr, -1);
+
+       UWB_LOGI("Connect to %s:tcp %d", server, port);
+
+       gchar *mqtt_client_id = g_strdup_printf(MQTT_CLIENT_ID_PREFIX, getpid());
+       gchar *broker_uri = g_strdup_printf(MQTT_BROKER_URI, server, port);
+
+       if (!mqtt_client_id  || ! broker_uri) {
+               g_free(mqtt_client_id);
+               g_free(broker_uri);
+
+               UWB_LOGE("failed to generate client ID or broker URI");
+               __UWB_LOG_FUNC_EXIT__;
+               return -1;
+       }
+
+       int ret = MQTTAsync_create(&this->_mqtt_client, broker_uri,
+                       mqtt_client_id, MQTTCLIENT_PERSISTENCE_NONE, NULL);
+       if (ret !=  MQTTASYNC_SUCCESS)
+               UWB_LOGE("MQTTAsync_create failed");
+
+       g_free(mqtt_client_id);
+       g_free(broker_uri);
+
+       MQTTAsync_setCallbacks(this->_mqtt_client, this, __connection_lost,
+                       __message_arrived, nullptr);
+
+       __UWB_LOG_FUNC_EXIT__;
+       return this->_mqtt_client != nullptr ? 0 : -1;
+}
+
+int MqttContext::destroyMqttClient(void)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+       retv_if(this->_mqtt_client == nullptr, -1);
+
+       this->disableRetryingConnect();
+
+       MQTTAsync_setCallbacks(this->_mqtt_client, nullptr, nullptr,
+                       nullptr, nullptr);
+       MQTTAsync_setConnected(this->_mqtt_client, nullptr, nullptr);
+       MQTTAsync_setDisconnected(this->_mqtt_client, nullptr, nullptr);
+       MQTTAsync_destroy(&this->_mqtt_client);
+       this->_mqtt_client = nullptr;
+
+       __UWB_LOG_FUNC_EXIT__;
+       return 0;
+}
+
+MQTTAsync MqttContext::getMqttClient(void)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+       retv_if(this->_mqtt_client == nullptr, nullptr);
+
+       __UWB_LOG_FUNC_EXIT__;
+       return this->_mqtt_client;
+}
+
+bool MqttContext::isConnected(void)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+       retv_if(this->_mqtt_client == nullptr, false);
+
+       __UWB_LOG_FUNC_EXIT__;
+       return MQTTAsync_isConnected(this->_mqtt_client) != 0;
+}
+
+static void __connect_on_success_cb(void *context, MQTTAsync_successData *response)
+{
+       __UWB_LOG_FUNC_ENTER__;
+       ret_if(context == nullptr);
+
+       MqttContext *mqtt_ctx = (MqttContext *)context;
+
+       if (mqtt_ctx->getConnectionStateCb() == nullptr)
+               return;
+
+       mqtt_ctx->getConnectionStateCb()(true);
+       MQTTAsync_setDisconnected(mqtt_ctx->getMqttClient(), mqtt_ctx, __disconnected);
+
+       __UWB_LOG_FUNC_EXIT__;
+}
+
+
+void MqttContext::disableRetryingConnect(void)
+{
+       if (this->_retry_connect_source) {
+               g_source_remove(this->_retry_connect_source);
+               this->_retry_connect_source = 0;
+       }
+       return;
+}
+
+static gboolean __retry_connect(gpointer user_data)
+{
+       MqttContext *mqtt_context = (MqttContext *)user_data;
+       if (mqtt_context == nullptr)
+               return false;
+
+       mqtt_context->connectBroker();
+       mqtt_context->clearRetyringConnectSource();
+       return false;
+}
+
+void MqttContext::enableRetryingConnect(void)
+{
+       if (this->_retry_connect_source) {
+               UWB_LOGI("Already retry to connect...");
+               return;
+       }
+
+       this->_retry_connect_source =
+                       g_timeout_add(MqttContext::_connection_retry_timeout * 1000,
+                                       __retry_connect,
+                                       (gpointer)this);
+}
+
+static void __connect_on_failure_cb(void *context, MQTTAsync_failureData *response)
+{
+       __UWB_LOG_FUNC_ENTER__;
+       ret_if(context == nullptr);
+       ret_if(response == nullptr);
+       if (response->code == MQTTASYNC_OPERATION_INCOMPLETE) {
+               UWB_LOGI("Mqtt client destroyed");
+               __UWB_LOG_FUNC_EXIT__;
+               return;
+       }
+
+       MqttContext *mqtt_ctx = (MqttContext *)context;
+       mqtt_ctx->enableRetryingConnect();
+
+       __UWB_LOG_FUNC_EXIT__;
+}
+
+/* default keepAliveInterval 60
+ * default minRetryInterval 1
+ * default maxRetryInterval 60
+ */
+int MqttContext::connectBroker(void)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+       retv_if(this->_mqtt_client == nullptr, -1);
+
+       MQTTAsync_connectOptions opts = MQTTAsync_connectOptions_initializer;
+
+       opts.keepAliveInterval = 20;
+
+       opts.connectTimeout = this->_mqtt_connect_timeout;
+       opts.cleansession = 1;
+       opts.onSuccess = __connect_on_success_cb;
+       opts.onFailure = __connect_on_failure_cb;
+
+       opts.context = (void *)this;
+
+       opts.automaticReconnect = 1;
+
+       int ret = MQTTAsync_connect(this->_mqtt_client, &opts);
+       if (ret !=  MQTTASYNC_SUCCESS) {
+               UWB_LOGE("MQTTClient_connect failed\n");
+               __UWB_LOG_FUNC_EXIT__;
+               return -1;
+       }
+
+       __UWB_LOG_FUNC_EXIT__;
+       return 0;
+}
+
+static void __disconnect_on_success_cb(void *context, MQTTAsync_successData *response)
+{
+       __UWB_LOG_FUNC_ENTER__;
+       ret_if(context == nullptr);
+       MqttContext *mqtt_ctx = (MqttContext *)context;
+
+       if (mqtt_ctx->getConnectionStateCb() == nullptr)
+               return;
+
+       mqtt_ctx->getConnectionStateCb()(false);
+
+       __UWB_LOG_FUNC_EXIT__;
+}
+
+static void __disconnect_on_failure_cb(void *context, MQTTAsync_failureData *response)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+       __UWB_LOG_FUNC_EXIT__;
+}
+
+int MqttContext::disconnectBroker(void)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+       retv_if(this->_mqtt_client == nullptr, -1);
+       retv_if(!this->isConnected(), -1);
+
+       MQTTAsync_disconnectOptions opts = MQTTAsync_disconnectOptions_initializer;
+
+       opts.onSuccess = __disconnect_on_success_cb;
+       opts.onFailure = __disconnect_on_failure_cb;
+
+       opts.context = (void *)this;
+
+       int ret = MQTTAsync_disconnect(this->_mqtt_client, &opts);
+       if (ret != MQTTASYNC_SUCCESS) {
+               UWB_LOGE("Failed to disconnect, return code %d\n", ret);
+               __UWB_LOG_FUNC_EXIT__;
+               ret = -1;
+       }
+
+       MQTTAsync_setConnected(this->_mqtt_client, nullptr, nullptr);
+       MQTTAsync_setDisconnected(this->_mqtt_client, nullptr, nullptr);
+       __UWB_LOG_FUNC_EXIT__;
+       return ret;
+}
+
+int MqttContext::subscribe(std::unique_ptr<UwbMqttRequest> request)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+       retv_if(this->_mqtt_client == nullptr, -1);
+       retv_if(request == nullptr, -1);
+       retv_if(!this->isConnected(), -1);
+
+       MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
+
+       int ret = MQTTAsync_subscribe(this->_mqtt_client,
+                       request->getTopic().c_str(),
+                       request->getQos(),
+                       &opts);
+       if (ret != MQTTASYNC_SUCCESS) {
+               printf("Failed to subscribe, return code %d\n", ret);
+               __UWB_LOG_FUNC_EXIT__;
+               return -1;
+       }
+
+       __UWB_LOG_FUNC_EXIT__;
+       return 0;
+}
+
+int MqttContext::unsubscribe(std::unique_ptr<UwbMqttRequest> request)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+       retv_if(this->_mqtt_client == nullptr, -1);
+       retv_if(request == nullptr, -1);
+       retv_if(!this->isConnected(), -1);
+
+       MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
+
+       int ret = MQTTAsync_unsubscribe(this->_mqtt_client,
+                       request->getTopic().c_str(),
+                       &opts);
+       if (ret != MQTTASYNC_SUCCESS) {
+               printf("Failed to unsubscribe, return code %d\n", ret);
+               __UWB_LOG_FUNC_EXIT__;
+               return -1;
+       }
+
+       __UWB_LOG_FUNC_EXIT__;
+       return 0;
+}
+
+int MqttContext::publish(std::unique_ptr<UwbMqttRequest> request)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+       retv_if(this->_mqtt_client == nullptr, -1);
+       retv_if(request == nullptr, -1);
+       retv_if(!this->isConnected(), -1);
+
+       MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
+       MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
+
+       pubmsg.payload = (void *)request->getPayload().c_str();
+       pubmsg.payloadlen = request->getPayload().size();
+       pubmsg.qos = request->getQos();
+       pubmsg.retained = request->getRetained();
+
+       int ret = MQTTAsync_sendMessage(this->_mqtt_client, request->getTopic().c_str(), &pubmsg, &opts);
+       if (ret != MQTTASYNC_SUCCESS) {
+                       printf("Failed to publish, return code %d\n", ret);
+                       __UWB_LOG_FUNC_EXIT__;
+                       return -1;
+       }
+
+       __UWB_LOG_FUNC_EXIT__;
+       return 0;
+}
index dedd183..7319821 100755 (executable)
  * limitations under the License.
  */
 
+#include <json-glib/json-glib.h>
+
+#include <tzplatform_config.h>
+
 #include <uwb-log-def.h>
 
 #include <UwbConfig.h>
 
 using namespace UwbManagerNamespace;
 
-UwbConfig::UwbConfig(int node_id, int pan_id, GVariant *configurations)
-{
-       __UWB_LOG_FUNC_ENTER__;
-
-       _node_id = node_id;
-       _pan_id = pan_id;
-       _configurations = configurations;
-
-       __UWB_LOG_FUNC_EXIT__;
-}
+#define CONFIGFILE     tzplatform_mkpath(TZ_SYS_RO_ETC, "/uwb/uwb-plugin.conf")
 
 
-UwbConfig::UwbConfig(const UwbConfig* config)
+UwbConfig::UwbConfig(const UwbConfig& config)
 {
-       _node_id = config->_node_id;
-       _pan_id = config->_pan_id;
-       _configurations = config->_configurations;
+       this->_configurations = g_variant_ref(config._configurations);
 }
 
 UwbConfig::~UwbConfig()
 {
        __UWB_LOG_FUNC_ENTER__;
 
+       if(this->_configurations)
+               g_variant_unref(this->_configurations);
+
        __UWB_LOG_FUNC_EXIT__;
 }
 
-int UwbConfig::setNodeId(int node_id)
+int UwbConfig::loadConfiguration(void)
 {
+       JsonParser *parser = NULL;
+       GVariant *configuration = NULL;
+       GError *error = NULL;
+
        __UWB_LOG_FUNC_ENTER__;
 
-       _node_id = node_id;
+       parser = json_parser_new();
+
+       json_parser_load_from_file(parser, CONFIGFILE, &error);
+       if (error != NULL) {
+               UWB_LOGD("json_parser_load_from_file failed : %s", error->message);
+               return -1;
+       }
+
+       if (!parser) {
+               UWB_LOGD("json_parser_load_from_file failed");
+               return -1;
+       }
+
+       configuration = json_gvariant_deserialize(json_parser_get_root(parser), "a{sv}", &error);
+       if (error != NULL) {
+               UWB_LOGD("json_gvariant_deserialize failed : %s", error->message);
+               g_object_unref(parser);
+               return -1;
+       }
+
+       if (!configuration) {
+               UWB_LOGD("json_parser_load_from_file failed");
+               g_object_unref(parser);
+               return -1;
+       }
+
+       if(this->_configurations)
+               g_variant_unref(this->_configurations);
+       this->_configurations = configuration;
 
+       if (this->_range_plugin != nullptr)
+               this->_range_plugin->setConfigurations(0, configuration);
+
+       g_object_unref(parser);
        __UWB_LOG_FUNC_EXIT__;
        return 0;
+
 }
 
-int UwbConfig::getNodeId()
+int UwbConfig::setConfigurations(GVariant *configurations)
 {
        __UWB_LOG_FUNC_ENTER__;
 
-       __UWB_LOG_FUNC_EXIT__;
-       return _node_id;
-}
+       if (!configurations) {
+               __UWB_LOG_FUNC_EXIT__;
+               return -1;
+       }
 
-int UwbConfig::setPanId(int pan_id)
-{
-       __UWB_LOG_FUNC_ENTER__;
+       if (this->_range_plugin == nullptr) {
+               UWB_LOGI("Range plugin is not loaded");
+               UWB_LOGI("Configuration is not set");
+               __UWB_LOG_FUNC_EXIT__;
+               return 0;
+       }
 
-       _pan_id = pan_id;
+       this->_range_plugin->setConfigurations(0, configurations);
+       this->getConfigurationFromPlugin();
 
        __UWB_LOG_FUNC_EXIT__;
        return 0;
+
 }
 
-int UwbConfig::getPanId()
+GVariant *UwbConfig::getConfigurations(void)
 {
        __UWB_LOG_FUNC_ENTER__;
 
+       this->getConfigurationFromPlugin();
+
        __UWB_LOG_FUNC_EXIT__;
-       return _pan_id;
+       return this->_configurations;
 }
 
-int UwbConfig::setConfigurations(const GVariant *configurations)
+void UwbConfig::getConfigurationFromPlugin(void)
 {
        __UWB_LOG_FUNC_ENTER__;
 
-       //_configurations = configurations;
+       if (this->_range_plugin == nullptr) {
+               __UWB_LOG_FUNC_EXIT__;
+               return;
+       }
 
-       __UWB_LOG_FUNC_EXIT__;
-       return 0;
+       GVariant *configuration = NULL;
+       if (this->_range_plugin->getConfigurations(0, &configuration) != 0) {
+               __UWB_LOG_FUNC_EXIT__;
+               return;
+       }
 
-}
+       if(this->_configurations)
+               g_variant_unref(this->_configurations);
+
+       this->_configurations = configuration;
 
-GVariant *UwbConfig::getConfigurations()
-{
-       __UWB_LOG_FUNC_ENTER__;
        __UWB_LOG_FUNC_EXIT__;
-       return _configurations;
 }
diff --git a/src/UwbDbusIfaceAdapter.cpp b/src/UwbDbusIfaceAdapter.cpp
new file mode 100644 (file)
index 0000000..f5a6fa5
--- /dev/null
@@ -0,0 +1,574 @@
+/*
+ * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <uwb-log-def.h>
+#include <uwb-error-def.h>
+
+#include <GdbusError.h>
+#include <UwbDbusIfaceAdapter.h>
+
+using namespace UwbManagerNamespace;
+
+#define ret_err_if_nullptr(value) do { \
+               if ((value) == nullptr) { \
+                       __dbus_return_err(UWB_ERROR_OPERATION_FAILED, invocation); \
+                       __UWB_LOG_FUNC_EXIT__; \
+                       return TRUE; \
+               } \
+       } while (0)
+
+#define ret_err_if_non_zero(value) do { \
+               if ((value) != 0) { \
+                       __dbus_return_err(UWB_ERROR_OPERATION_FAILED, invocation); \
+                       __UWB_LOG_FUNC_EXIT__; \
+                       return TRUE; \
+               } \
+       } while (0)
+
+#define DBUS_DEBUG_VARIANT(parameters) \
+       do {\
+               gchar *parameters_debug_str = NULL;\
+               if (parameters)\
+                       parameters_debug_str = g_variant_print(parameters, TRUE);\
+               UWB_LOGI("signal params [%s]", parameters_debug_str ? parameters_debug_str : "NULL");\
+               g_free(parameters_debug_str);\
+       } while (0)
+
+UwbDbusIfaceAdapter::~UwbDbusIfaceAdapter()
+{
+}
+
+static void __dbus_return_err(uwb_error_e ret, GDBusMethodInvocation *invocation)
+{
+       GdbusError gdbus_error;
+       GError *err = NULL;
+       gchar* dbus_error_name = NULL;
+
+       if (!invocation)
+               return;
+
+       gdbus_error.setGerror(ret, &err);
+       dbus_error_name = g_dbus_error_encode_gerror(err);
+       UWB_LOGI("g_dbus_method_invocation_return_gerror with [%s]", dbus_error_name);
+       g_free(dbus_error_name);
+       g_dbus_method_invocation_return_gerror(invocation, err);
+       g_clear_error(&err);
+       return;
+}
+
+static gboolean __handle_test(
+                      UwbGdbuslibManager *gdbus_manager,
+                      GDBusMethodInvocation *invocation,
+                      gpointer user_data)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+       UwbDbusIfaceAdapter *iface_adapter = (UwbDbusIfaceAdapter *)user_data;
+       ret_err_if_nullptr(iface_adapter);
+
+       auto handler = iface_adapter->getTest();
+       ret_err_if_nullptr(handler);
+
+       int ret = handler();
+       ret_err_if_non_zero(ret);
+
+       uwb_gdbuslib_manager_complete_test(gdbus_manager, invocation);
+
+       __UWB_LOG_FUNC_EXIT__;
+       return TRUE;
+}
+
+static gboolean __handle_reset(
+                      UwbGdbuslibManager *gdbus_manager,
+                      GDBusMethodInvocation *invocation,
+                      gpointer user_data)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+
+       UwbDbusIfaceAdapter *iface_adapter = (UwbDbusIfaceAdapter *)user_data;
+       ret_err_if_nullptr(iface_adapter);
+
+       auto handler = iface_adapter->getReset();
+       ret_err_if_nullptr(handler);
+
+       int ret = handler();
+       ret_err_if_non_zero(ret);
+
+       uwb_gdbuslib_manager_complete_reset(gdbus_manager, invocation);
+
+       __UWB_LOG_FUNC_EXIT__;
+       return TRUE;
+}
+
+static gboolean __handle_factory_reset(
+                      UwbGdbuslibManager *gdbus_manager,
+                      GDBusMethodInvocation *invocation,
+                      gpointer user_data)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+
+       UwbDbusIfaceAdapter *iface_adapter = (UwbDbusIfaceAdapter *)user_data;
+       ret_err_if_nullptr(iface_adapter);
+
+       auto handler = iface_adapter->getFactoryReset();
+       ret_err_if_nullptr(handler);
+
+       int ret = handler();
+       ret_err_if_non_zero(ret);
+
+       uwb_gdbuslib_manager_complete_factory_reset(gdbus_manager, invocation);
+
+       __UWB_LOG_FUNC_EXIT__;
+       return TRUE;
+}
+
+static gboolean __handle_enable_network(
+                      UwbGdbuslibManager *gdbus_manager,
+                      GDBusMethodInvocation *invocation,
+                      gpointer user_data)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+
+       UwbDbusIfaceAdapter *iface_adapter = (UwbDbusIfaceAdapter *)user_data;
+       ret_err_if_nullptr(iface_adapter);
+
+       auto handler = iface_adapter->getEnableNetwork();
+       ret_err_if_nullptr(handler);
+
+       int ret = handler();
+       ret_err_if_non_zero(ret);
+
+       uwb_gdbuslib_manager_complete_enable_network(gdbus_manager, invocation);
+
+       __UWB_LOG_FUNC_EXIT__;
+       return TRUE;
+}
+
+static gboolean __handle_disable_network(
+                      UwbGdbuslibManager *gdbus_manager,
+                      GDBusMethodInvocation *invocation,
+                      gpointer user_data)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+
+       UwbDbusIfaceAdapter *iface_adapter = (UwbDbusIfaceAdapter *)user_data;
+       ret_err_if_nullptr(iface_adapter);
+
+       auto handler = iface_adapter->getDisableNetwork();
+       ret_err_if_nullptr(handler);
+
+       int ret = handler();
+       ret_err_if_non_zero(ret);
+
+       uwb_gdbuslib_manager_complete_disable_network(gdbus_manager, invocation);
+
+       __UWB_LOG_FUNC_EXIT__;
+       return TRUE;
+}
+
+static gboolean __handle_start_location_engine(
+                      UwbGdbuslibManager *gdbus_manager,
+                      GDBusMethodInvocation *invocation,
+                                  const gchar *server,
+                                  gint32 port,
+                      gpointer user_data)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+
+       UwbDbusIfaceAdapter *iface_adapter = (UwbDbusIfaceAdapter *)user_data;
+       ret_err_if_nullptr(iface_adapter);
+
+       auto handler = iface_adapter->getStartLocationEngine();
+       ret_err_if_nullptr(handler);
+
+       int ret = handler(server, port);
+       ret_err_if_non_zero(ret);
+
+       uwb_gdbuslib_manager_complete_start_location_engine(gdbus_manager, invocation);
+
+       __UWB_LOG_FUNC_EXIT__;
+       return TRUE;
+}
+
+static gboolean __handle_stop_location_engine(
+                      UwbGdbuslibManager *gdbus_manager,
+                      GDBusMethodInvocation *invocation,
+                      gpointer user_data)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+
+       UwbDbusIfaceAdapter *iface_adapter = (UwbDbusIfaceAdapter *)user_data;
+       ret_err_if_nullptr(iface_adapter);
+
+       auto handler = iface_adapter->getStopLocationEngine();
+       ret_err_if_nullptr(handler);
+
+       int ret = handler();
+       ret_err_if_non_zero(ret);
+
+       uwb_gdbuslib_manager_complete_stop_location_engine(gdbus_manager, invocation);
+
+       __UWB_LOG_FUNC_EXIT__;
+       return TRUE;
+}
+
+static void __build_node_variant(Node &node, GVariant **node_gvar)
+{
+       GVariantBuilder *builder = g_variant_builder_new(G_VARIANT_TYPE("a{sv}"));
+
+       g_variant_builder_open(builder, G_VARIANT_TYPE_VARDICT);
+       g_variant_builder_add(builder, "{sv}", "Distance",
+                                                       g_variant_new_uint64(node.getDistance()));
+       g_variant_builder_add(builder, "{sv}", "PanID",
+                                                       g_variant_new_uint16(node.getPanId()));
+       g_variant_builder_add(builder, "{sv}", "NodeID",
+                                                       g_variant_new_uint64(node.getNodeId()));
+       g_variant_builder_add(builder, "{sv}", "X",
+                                                       g_variant_new_int32(node.getX()));
+       g_variant_builder_add(builder, "{sv}", "Y",
+                                                       g_variant_new_int32(node.getY()));
+       g_variant_builder_add(builder, "{sv}", "Z",
+                                                       g_variant_new_int32(node.getZ()));
+       g_variant_builder_close(builder);
+
+       *node_gvar = g_variant_builder_end(builder);
+       g_variant_builder_unref(builder);
+}
+
+static gboolean __handle_get_own_node(
+                      UwbGdbuslibManager *gdbus_manager,
+                      GDBusMethodInvocation *invocation,
+                      gpointer user_data)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+
+       UwbDbusIfaceAdapter *iface_adapter = (UwbDbusIfaceAdapter *)user_data;
+       ret_err_if_nullptr(iface_adapter);
+
+       auto handler = iface_adapter->getGetOwnNode();
+       ret_err_if_nullptr(handler);
+
+       Node &node_ref = handler();
+       GVariant *node_gvar = nullptr;
+       __build_node_variant(node_ref, &node_gvar);
+
+       uwb_gdbuslib_manager_complete_get_own_node(gdbus_manager, invocation, node_gvar);
+
+       __UWB_LOG_FUNC_EXIT__;
+       return TRUE;
+}
+
+static void __build_network_variant(std::map<int, std::unique_ptr<Node>> &node_map, GVariant **networks_gvar)
+{
+       GVariantBuilder *builder = g_variant_builder_new(G_VARIANT_TYPE("aa{sv}"));
+
+       for (const auto &elem : node_map) {
+               Node *node_ptr = elem.second.get();
+               g_variant_builder_open(builder, G_VARIANT_TYPE_VARDICT);
+               g_variant_builder_add(builder, "{sv}", "Distance",
+                                               g_variant_new_uint64(node_ptr->getDistance()));
+               g_variant_builder_add(builder, "{sv}", "PanID",
+                                               g_variant_new_uint16(node_ptr->getPanId()));
+               g_variant_builder_add(builder, "{sv}", "NodeID",
+                                               g_variant_new_uint64(node_ptr->getNodeId()));
+               g_variant_builder_add(builder, "{sv}", "X",
+                                               g_variant_new_int32(node_ptr->getX()));
+               g_variant_builder_add(builder, "{sv}", "Y",
+                                               g_variant_new_int32(node_ptr->getY()));
+               g_variant_builder_add(builder, "{sv}", "Z",
+                                               g_variant_new_int32(node_ptr->getZ()));
+               g_variant_builder_close(builder);
+       }
+
+       *networks_gvar = g_variant_builder_end(builder);
+       g_variant_builder_unref(builder);
+}
+
+static gboolean __handle_get_network_info(
+                      UwbGdbuslibManager *gdbus_manager,
+                      GDBusMethodInvocation *invocation,
+                      gpointer user_data)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+
+       UwbDbusIfaceAdapter *iface_adapter = (UwbDbusIfaceAdapter *)user_data;
+       ret_err_if_nullptr(iface_adapter);
+
+       auto handler = iface_adapter->getGetNetworkInfo();
+       ret_err_if_nullptr(handler);
+
+       GVariant *networks_gvar = nullptr;
+       auto &network_map = handler();
+       __build_network_variant(network_map, &networks_gvar);
+
+       uwb_gdbuslib_manager_complete_get_network_info(gdbus_manager, invocation,
+                       (uint16_t)0, networks_gvar);
+
+       __UWB_LOG_FUNC_EXIT__;
+       return TRUE;
+}
+
+static gboolean __handle_set_configurations(
+                      UwbGdbuslibManager *gdbus_manager,
+                      GDBusMethodInvocation *invocation,
+                                  guint16 node_id,
+                                  GVariant *configurations,
+                      gpointer user_data)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+
+       UwbDbusIfaceAdapter *iface_adapter = (UwbDbusIfaceAdapter *)user_data;
+       ret_err_if_nullptr(iface_adapter);
+
+       auto handler = iface_adapter->getSetConfigurations();
+       ret_err_if_nullptr(handler);
+
+       DBUS_DEBUG_VARIANT(configurations);
+       int ret = handler(configurations);
+       ret_err_if_non_zero(ret);
+
+       uwb_gdbuslib_manager_complete_set_configurations(gdbus_manager, invocation);
+
+       __UWB_LOG_FUNC_EXIT__;
+       return TRUE;
+}
+
+static gboolean __handle_get_configurations(
+                      UwbGdbuslibManager *gdbus_manager,
+                      GDBusMethodInvocation *invocation,
+                                  guint16 node_id,
+                      gpointer user_data)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+
+       UwbDbusIfaceAdapter *iface_adapter = (UwbDbusIfaceAdapter *)user_data;
+       ret_err_if_nullptr(iface_adapter);
+
+       auto handler = iface_adapter->getGetConfigurations();
+       ret_err_if_nullptr(handler);
+
+       GVariant *config_gvar = handler();
+       ret_err_if_nullptr(config_gvar);
+
+       g_variant_ref(config_gvar);
+       DBUS_DEBUG_VARIANT(config_gvar);
+       uwb_gdbuslib_manager_complete_get_configurations(gdbus_manager, invocation, config_gvar);
+
+       __UWB_LOG_FUNC_EXIT__;
+       return TRUE;
+}
+
+static gboolean __handle_set_position(
+                      UwbGdbuslibManager *gdbus_manager,
+                      GDBusMethodInvocation *invocation,
+                                  guint16 node_id,
+                                  gint x,
+                                  gint y,
+                                  gint z,
+                      gpointer user_data)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+
+       UwbDbusIfaceAdapter *iface_adapter = (UwbDbusIfaceAdapter *)user_data;
+       ret_err_if_nullptr(iface_adapter);
+
+       auto handler = iface_adapter->getSetPosition();
+       ret_err_if_nullptr(handler);
+
+       handler(x, y, z);
+
+       uwb_gdbuslib_manager_complete_set_position(gdbus_manager, invocation);
+
+       __UWB_LOG_FUNC_EXIT__;
+       return TRUE;
+}
+
+static gint __ay_to_guchar(GVariant *src, int size, guchar **dst)
+{
+       if (src == nullptr || dst == nullptr || size == 0)
+               return 0;
+
+       GVariantIter *iter;
+       g_variant_get(src, "a(y)", &iter);
+
+       int result_size = g_variant_iter_n_children(iter);
+       if (result_size == 0 || result_size != size)
+               return 0;
+
+       guchar *buffer = (guchar *)g_try_malloc0(result_size);
+       if (!buffer)
+               return 0;
+
+       guint8 element;
+       guint pos = 0;
+
+       while (g_variant_iter_loop(iter, "(y)", &element)) {
+               *(buffer + pos) = element;
+               ++pos;
+       }
+
+       g_variant_iter_free(iter);
+
+       *dst = buffer;
+       return result_size;
+}
+
+static gboolean __handle_send_message(
+                      UwbGdbuslibManager *gdbus_manager,
+                      GDBusMethodInvocation *invocation,
+                                  GVariant * message,
+                                  gint message_length,
+                      gpointer user_data)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+
+       UwbDbusIfaceAdapter *iface_adapter = (UwbDbusIfaceAdapter *)user_data;
+       ret_err_if_nullptr(iface_adapter);
+
+       auto handler = iface_adapter->getSendMessage();
+       ret_err_if_nullptr(handler);
+
+       guchar *buffer = nullptr;
+       if (__ay_to_guchar(message, message_length, &buffer) == 0) {
+               __dbus_return_err(UWB_ERROR_INVALID_PARAMETER, invocation);
+               __UWB_LOG_FUNC_EXIT__;
+               return TRUE;
+       }
+
+       int ret = handler(buffer, message_length);
+       g_free(buffer);
+       ret_err_if_non_zero(ret);
+
+       uwb_gdbuslib_manager_complete_send_message(gdbus_manager, invocation);
+
+       __UWB_LOG_FUNC_EXIT__;
+       return TRUE;
+}
+
+static gboolean __handle_send_message_to(
+                      UwbGdbuslibManager *gdbus_manager,
+                      GDBusMethodInvocation *invocation,
+                                  guint16 node_id,
+                                  GVariant * message,
+                                  gint message_length,
+                      gpointer user_data)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+       UwbDbusIfaceAdapter *iface_adapter = (UwbDbusIfaceAdapter *)user_data;
+       ret_err_if_nullptr(iface_adapter);
+
+       auto handler = iface_adapter->getSendMessageTo();
+       ret_err_if_nullptr(handler);
+
+       guchar *buffer = nullptr;
+       if (__ay_to_guchar(message, message_length, &buffer) == 0) {
+               __dbus_return_err(UWB_ERROR_INVALID_PARAMETER, invocation);
+               __UWB_LOG_FUNC_EXIT__;
+               return TRUE;
+       }
+
+       int ret = handler(node_id, buffer, message_length);
+       g_free(buffer);
+       ret_err_if_non_zero(ret);
+
+       uwb_gdbuslib_manager_complete_send_message_to(gdbus_manager, invocation);
+
+       __UWB_LOG_FUNC_EXIT__;
+       return TRUE;
+}
+
+typedef gboolean (*method_handler)(
+               UwbGdbuslibManager *gdbus_manager,
+               GDBusMethodInvocation *invocation,
+               gpointer user_data);
+
+static struct {
+       const char *method_name;
+       //trick
+       void * handler;
+} handlers[] = {
+               {"handle-test", (void *)__handle_test},
+               {"handle-reset", (void *)__handle_reset},
+               {"handle-factory-reset", (void *)__handle_factory_reset},
+
+               {"handle-enable-network", (void *)__handle_enable_network},
+               {"handle-disable-network", (void *)__handle_disable_network},
+
+               {"handle-start-location-engine", (void *)__handle_start_location_engine},
+               {"handle-stop-location-engine", (void *)__handle_stop_location_engine},
+
+               {"handle-get-own-node", (void *)__handle_get_own_node},
+               {"handle-get-network-info", (void *)__handle_get_network_info},
+
+               {"handle-set-configurations", (void *)__handle_set_configurations},
+               {"handle-get-configurations", (void *)__handle_get_configurations},
+
+               {"handle-set-position", (void *)__handle_set_position},
+
+               {"handle-send-message", (void *)__handle_send_message},
+               {"handle-send-message-to", (void *)__handle_send_message_to},
+               {NULL, NULL}
+};
+
+void UwbDbusIfaceAdapter::init(GDBusConnection *connection,
+               UwbGdbuslibManager *manager_skeleton)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+       /* Register method callbacks as signal callback */
+       for (int i = 0; handlers[i].method_name != NULL; ++i)
+               g_signal_connect(
+                               manager_skeleton,
+                               handlers[i].method_name,
+                               G_CALLBACK(handlers[i].handler),
+                               gpointer(this));
+
+       /* Set connection to 'manager' */
+       GDBusObjectManagerServer *manager =
+                       g_dbus_object_manager_server_new(this->_uwb_dbus_path_str.c_str());
+       g_dbus_object_manager_server_set_connection(manager, connection);
+
+       /* Export 'manager' interface on UWB DBUS */
+       GError *error = NULL;
+       gboolean ret = g_dbus_interface_skeleton_export(
+               G_DBUS_INTERFACE_SKELETON(manager_skeleton),
+               connection, this->_uwb_dbus_path_str.c_str(), &error);
+
+       if (ret == FALSE) {
+               UWB_LOGE("Can not skeleton_export %s", error->message);
+               g_error_free(error);
+       }
+
+       __UWB_LOG_FUNC_EXIT__;
+}
+
+void deinit(void)
+{
+
+}
index 4f58e51..a4867bc 100644 (file)
@@ -16,6 +16,7 @@
 #include <uwb-log-def.h>
 
 #include <GdbusError.h>
+
 #include <UwbDbusManager.h>
 
 using namespace UwbManagerNamespace;
@@ -24,14 +25,30 @@ UwbDbusManager::~UwbDbusManager()
 {
        if (_owner_id) {
                g_bus_unown_name(_owner_id);
+               UWB_LOGI("Unown [%u]", _owner_id);
                _owner_id = 0;
        }
 }
 
-void UwbDbusManager::init(UwbIfaceHandler *iface_handler)
+static void __gdbus_acquired_callback(GDBusConnection *connection,
+               const gchar *name,
+        gpointer user_data)
 {
-       GdbusError gdbus_error = GdbusError();
-       if (_owner_id) {
+       UwbDbusManager *uwb_dbus_mgr = (UwbDbusManager *)user_data;
+       if (uwb_dbus_mgr == nullptr)
+               return;
+
+       auto bus_acquired_cb = uwb_dbus_mgr->getBusAcquiredCallback();
+       if (bus_acquired_cb == nullptr)
+               return;
+
+       bus_acquired_cb(connection, uwb_dbus_mgr->getManagerSkeleton());
+}
+
+void UwbDbusManager::init(void)
+{
+       GdbusError gdbus_error;
+       if (this->_owner_id != 0) {
                UWB_LOGI("Already initialized");
                return;
        }
@@ -40,12 +57,13 @@ void UwbDbusManager::init(UwbIfaceHandler *iface_handler)
        _owner_id = g_bus_own_name(G_BUS_TYPE_SYSTEM,
                        uwb_dbus_service_str.c_str(),
                        G_BUS_NAME_OWNER_FLAGS_NONE,
-                       onBusAcquired,
+                       __gdbus_acquired_callback,
                        NULL,
                        NULL,
-                       (gpointer)iface_handler,
+                       (gpointer)this,
                        NULL);
        UWB_LOGI("Request to Own [%u]", _owner_id);
+       this->_manager_skeleton = uwb_gdbuslib_manager_skeleton_new();
 }
 
 void UwbDbusManager::deinit(void)
@@ -55,70 +73,44 @@ void UwbDbusManager::deinit(void)
        gdbus_error.deregisterGdbusError();
        if (_owner_id) {
                g_bus_unown_name(_owner_id);
+               UWB_LOGI("Unown [%u]", _owner_id);
                _owner_id = 0;
        }
 }
 
-UwbGdbuslibManager *manager_skeleton;
-
-void UwbDbusManager::onBusAcquired(GDBusConnection *connection, const gchar *name, gpointer user_data)
+void UwbDbusManager::emitPositionUpdatedSignal(Node *p_node)
 {
-       gboolean ret = FALSE;
-       GError *error = NULL;
-
-       GDBusObjectManagerServer *manager;
-       UwbIfaceHandler *iface_handler = (UwbIfaceHandler *)user_data;
-
-       __UWB_LOG_FUNC_ENTER__;
-       /* Add interface to default object path */
-       manager_skeleton = uwb_gdbuslib_manager_skeleton_new();
-
-       /* Register method callbacks as signal callback */
-       iface_handler->registerHandler(manager_skeleton);
-
-       /* Set connection to 'manager' */
-       manager = g_dbus_object_manager_server_new(iface_handler->get_dbus_path_str().c_str());
-       g_dbus_object_manager_server_set_connection(manager, connection);
-
-       /* Export 'manager' interface on UWB DBUS */
-       ret = g_dbus_interface_skeleton_export(
-               G_DBUS_INTERFACE_SKELETON(manager_skeleton),
-               connection, iface_handler->get_dbus_path_str().c_str(), &error);
+       if (p_node == nullptr || _manager_skeleton == nullptr)
+               return;
 
-       if (ret == FALSE) {
-               UWB_LOGE("Can not skeleton_export %s", error->message);
-               g_error_free(error);
-       }
-       __UWB_LOG_FUNC_EXIT__;
+       uwb_gdbuslib_manager_emit_position_updated(_manager_skeleton,
+                       p_node->getNodeId(), p_node->getX(), p_node->getY(), p_node->getZ());
 }
 
-static GVariant *__data_to_variant(const unsigned char *data, int length)
+void UwbDbusManager::emitNodeAddedSignal(Node *p_node)
 {
-       GVariantBuilder builder;
+       if (p_node == nullptr || _manager_skeleton == nullptr)
+               return;
 
-       g_variant_builder_init(&builder, G_VARIANT_TYPE("a(y)"));
+       uwb_gdbuslib_manager_emit_node_added(_manager_skeleton, p_node->getPanId(),
+                       p_node->getNodeId(), p_node->getX(), p_node->getY(), p_node->getZ());
 
-       if (data && length > 0)
-       {
-               for(int i = 0; i < length; i++)
-                       g_variant_builder_add(&builder, "(y)", *(data + i));
-       }
-
-       return g_variant_builder_end(&builder);
 }
 
-void UwbDbusManager::emitMessageReceivedSignal(uint16_t node_id,
-       const unsigned char *message, int message_length)
+void UwbDbusManager::emitNodeUpdatedSignal(Node *p_node)
 {
-       GVariant *data = __data_to_variant(message, message_length);
-
-       uwb_gdbuslib_manager_emit_message_received(manager_skeleton, node_id, data, message_length);
+       if (p_node == nullptr || _manager_skeleton == nullptr)
+               return;
 
-       g_variant_unref(data);
+       uwb_gdbuslib_manager_emit_node_updated(_manager_skeleton, p_node->getPanId(),
+                       p_node->getNodeId(), p_node->getX(), p_node->getY(), p_node->getZ());
 }
 
-void UwbDbusManager::emitPositionChangedSignal(uint16_t node_id, int x, int y, int z)
+void UwbDbusManager::emitNodeRemovedSignal(Node *p_node)
 {
-       uwb_gdbuslib_manager_emit_position_changed(manager_skeleton, node_id, x, y, z);
-}
+       if (p_node == nullptr || _manager_skeleton == nullptr)
+               return;
 
+       uwb_gdbuslib_manager_emit_node_removed(_manager_skeleton, p_node->getPanId(),
+                       p_node->getNodeId(), p_node->getX(), p_node->getY(), p_node->getZ());
+}
diff --git a/src/UwbIfaceHandler.cpp b/src/UwbIfaceHandler.cpp
deleted file mode 100644 (file)
index abb8f7b..0000000
+++ /dev/null
@@ -1,762 +0,0 @@
-/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <algorithm>
-
-#include <uwb-log-def.h>
-#include <uwb-error-def.h>
-
-#include <GdbusError.h>
-#include <UwbIfaceHandler.h>
-
-using namespace UwbManagerNamespace;
-
-static void __dbus_return_err(uwb_error_e ret, GDBusMethodInvocation *invocation)
-{
-       GdbusError gdbus_error;
-       GError *err = NULL;
-       gchar* dbus_error_name = NULL;
-
-       if (!invocation)
-               return;
-
-       gdbus_error.setGerror(ret, &err);
-       dbus_error_name = g_dbus_error_encode_gerror(err);
-       UWB_LOGI("g_dbus_method_invocation_return_gerror with [%s]", dbus_error_name);
-       g_free(dbus_error_name);
-       g_dbus_method_invocation_return_gerror(invocation, err);
-       g_clear_error(&err);
-       return;
-}
-
-static  UwbManager *__get_uwb_manager(MethodHandler *handler)
-{
-       if (!handler)
-               return NULL;
-
-       return handler->getManager();
-}
-
-class testMethodHandler : MethodHandler
-{
-public:
-       testMethodHandler(UwbManager* manager): _manager(manager) {};
-       ~testMethodHandler()
-       {
-
-       }
-
-       void registerHandler(UwbGdbuslibManager *manager_skeleton) override
-       {
-               g_signal_connect(
-                               manager_skeleton,
-                               this->_method_name.c_str(),
-                               G_CALLBACK(__uwb_iface_handler_callback),
-                               gpointer(this));
-       }
-
-       UwbManager *getManager()
-       {
-               return this->_manager;
-       }
-
-private:
-       UwbManager *_manager;
-       const std::string _method_name =
-                       std::string("handle-test");
-
-       static gboolean __uwb_iface_handler_callback(
-                      UwbGdbuslibManager *gdbus_manager,
-                      GDBusMethodInvocation *invocation,
-                      gpointer user_data)
-       {
-               __UWB_LOG_FUNC_ENTER__;
-
-               UwbManager *uwb_manager = __get_uwb_manager((MethodHandler *)user_data);
-               if (!uwb_manager) {
-                       __dbus_return_err(UWB_ERROR_OPERATION_FAILED, invocation);
-                       __UWB_LOG_FUNC_EXIT__;
-                       return TRUE;
-               }
-
-               int result = uwb_manager->test();
-               if (result !=  0) {
-                       __dbus_return_err(UWB_ERROR_OPERATION_FAILED, invocation);
-                       __UWB_LOG_FUNC_EXIT__;
-                       return TRUE;
-               }
-
-               uwb_gdbuslib_manager_complete_test(gdbus_manager, invocation);
-               __UWB_LOG_FUNC_EXIT__;
-               return TRUE;
-       }
-};
-
-
-class resetMethodHandler : MethodHandler
-{
-public:
-       resetMethodHandler(UwbManager* manager): _manager(manager) {};
-       ~resetMethodHandler()
-       {
-
-       }
-
-       void registerHandler(UwbGdbuslibManager *manager_skeleton) override
-       {
-               g_signal_connect(
-                               manager_skeleton,
-                               this->_method_name.c_str(),
-                               G_CALLBACK(__uwb_iface_handler_callback),
-                               gpointer(this));
-       }
-
-       UwbManager *getManager()
-       {
-               return this->_manager;
-       }
-
-private:
-       UwbManager *_manager;
-       const std::string _method_name =
-                       std::string("handle-reset");
-
-       static gboolean __uwb_iface_handler_callback(
-                      UwbGdbuslibManager *gdbus_manager,
-                      GDBusMethodInvocation *invocation,
-                      gpointer user_data)
-       {
-               __UWB_LOG_FUNC_ENTER__;
-
-               UwbManager *uwb_manager = __get_uwb_manager((MethodHandler *)user_data);
-               if (!uwb_manager) {
-                       __dbus_return_err(UWB_ERROR_OPERATION_FAILED, invocation);
-                       __UWB_LOG_FUNC_EXIT__;
-                       return TRUE;
-               }
-
-               int result = uwb_manager->reset();
-               if (result !=  0) {
-                       __dbus_return_err(UWB_ERROR_OPERATION_FAILED, invocation);
-                       __UWB_LOG_FUNC_EXIT__;
-                       return TRUE;
-               }
-
-               uwb_gdbuslib_manager_complete_reset(gdbus_manager, invocation);
-               __UWB_LOG_FUNC_EXIT__;
-               return TRUE;
-       }
-};
-
-class factoryResetMethodHandler : MethodHandler
-{
-public:
-       factoryResetMethodHandler(UwbManager* manager): _manager(manager) {};
-       ~factoryResetMethodHandler()
-       {
-
-       }
-
-       void registerHandler(UwbGdbuslibManager *manager_skeleton) override
-       {
-               g_signal_connect(
-                               manager_skeleton,
-                               this->_method_name.c_str(),
-                               G_CALLBACK(__uwb_iface_handler_callback),
-                               gpointer(this));
-       }
-
-       UwbManager *getManager()
-       {
-               return this->_manager;
-       }
-private:
-       UwbManager *_manager;
-       const std::string _method_name =
-                       std::string("handle-factory-reset");
-       static gboolean __uwb_iface_handler_callback(
-                      UwbGdbuslibManager *gdbus_manager,
-                      GDBusMethodInvocation *invocation,
-                      gpointer user_data)
-       {
-               __UWB_LOG_FUNC_ENTER__;
-
-               UwbManager *uwb_manager = __get_uwb_manager((MethodHandler *)user_data);
-               if (!uwb_manager) {
-                       __dbus_return_err(UWB_ERROR_OPERATION_FAILED, invocation);
-                       __UWB_LOG_FUNC_EXIT__;
-                       return TRUE;
-               }
-
-               int result = uwb_manager->factoryReset();
-               if (result !=  0) {
-                       __dbus_return_err(UWB_ERROR_OPERATION_FAILED, invocation);
-                       __UWB_LOG_FUNC_EXIT__;
-                       return TRUE;
-               }
-
-               uwb_gdbuslib_manager_complete_factory_reset(gdbus_manager, invocation);
-               __UWB_LOG_FUNC_EXIT__;
-               return TRUE;
-       }
-};
-
-class getOwnNodeMethodHandler : MethodHandler
-{
-public:
-       getOwnNodeMethodHandler(UwbManager* manager): _manager(manager) {};
-       ~getOwnNodeMethodHandler()
-       {
-
-       }
-
-       void registerHandler(UwbGdbuslibManager *manager_skeleton) override
-       {
-               g_signal_connect(
-                               manager_skeleton,
-                               this->_method_name.c_str(),
-                               G_CALLBACK(__uwb_iface_handler_callback),
-                               gpointer(this));
-       }
-
-       UwbManager *getManager()
-       {
-               return this->_manager;
-       }
-private:
-       UwbManager *_manager;
-       const std::string _method_name =
-                       std::string("handle-get-own-node");
-       static void buildNodeGvar(UwbNode *node, GVariant **node_gvar)
-       {
-               GVariantBuilder *builder;
-
-               builder = g_variant_builder_new(G_VARIANT_TYPE("a{sv}"));
-
-               g_variant_builder_open(builder, G_VARIANT_TYPE_VARDICT);
-               g_variant_builder_add(builder, "{sv}", "Distance",
-                                                               g_variant_new_uint64(node->getDistance()));
-               g_variant_builder_add(builder, "{sv}", "PanID",
-                                                               g_variant_new_uint16(node->getPanId()));
-               g_variant_builder_add(builder, "{sv}", "NodeID",
-                                                               g_variant_new_uint64(node->getNodeId()));
-               g_variant_builder_add(builder, "{sv}", "X",
-                                                               g_variant_new_int32(node->getX()));
-               g_variant_builder_add(builder, "{sv}", "Y",
-                                                               g_variant_new_int32(node->getY()));
-               g_variant_builder_add(builder, "{sv}", "Z",
-                                                               g_variant_new_int32(node->getZ()));
-               g_variant_builder_close(builder);
-
-               *node_gvar = g_variant_builder_end(builder);
-               g_variant_builder_unref(builder);
-       }
-
-       static gboolean __uwb_iface_handler_callback(
-                      UwbGdbuslibManager *gdbus_manager,
-                      GDBusMethodInvocation *invocation,
-                      gpointer user_data)
-       {
-               __UWB_LOG_FUNC_ENTER__;
-
-               UwbManager *uwb_manager = __get_uwb_manager((MethodHandler *)user_data);
-               if (!uwb_manager) {
-                       __dbus_return_err(UWB_ERROR_OPERATION_FAILED, invocation);
-                       __UWB_LOG_FUNC_EXIT__;
-                       return TRUE;
-               }
-
-               UwbNode *uwb_node = uwb_manager->getOwnNode();
-               if (!uwb_node) {
-                       __dbus_return_err(UWB_ERROR_OPERATION_FAILED, invocation);
-                       __UWB_LOG_FUNC_EXIT__;
-                       return TRUE;
-               }
-
-               GVariant *node_gvar = nullptr;
-               buildNodeGvar(uwb_node, &node_gvar);
-               delete uwb_node;
-
-               uwb_gdbuslib_manager_complete_get_own_node(gdbus_manager, invocation, node_gvar);
-               __UWB_LOG_FUNC_EXIT__;
-               return TRUE;
-       }
-};
-
-class getNetworkMethodHandler : MethodHandler
-{
-public:
-       getNetworkMethodHandler(UwbManager* manager): _manager(manager) {};
-       ~getNetworkMethodHandler()
-       {
-
-       }
-
-       void registerHandler(UwbGdbuslibManager *manager_skeleton) override
-       {
-               g_signal_connect(
-                               manager_skeleton,
-                               this->_method_name.c_str(),
-                               G_CALLBACK(__uwb_iface_handler_callback),
-                               gpointer(this));
-       }
-
-       UwbManager *getManager()
-       {
-               return this->_manager;
-       }
-private:
-       UwbManager *_manager;
-       const std::string _method_name =
-                       std::string("handle-get-network-info");
-       static void buildNetworkGvar(std::list<UwbNode *> *node_list, GVariant **networks_gvar)
-       {
-               GVariantBuilder *builder;
-               std::list<UwbNode *>::iterator it;
-
-               builder = g_variant_builder_new(G_VARIANT_TYPE("aa{sv}"));
-               it = node_list->begin();
-               for (; it != node_list->end(); ++it) {
-                       UwbNode *node = *it;
-                       g_variant_builder_open(builder, G_VARIANT_TYPE_VARDICT);
-                       g_variant_builder_add(builder, "{sv}", "Distance",
-                                                       g_variant_new_uint64(node->getDistance()));
-                       g_variant_builder_add(builder, "{sv}", "PanID",
-                                                       g_variant_new_uint16(node->getPanId()));
-                       g_variant_builder_add(builder, "{sv}", "NodeID",
-                                                       g_variant_new_uint64(node->getNodeId()));
-                       g_variant_builder_add(builder, "{sv}", "X",
-                                                       g_variant_new_int32(node->getX()));
-                       g_variant_builder_add(builder, "{sv}", "Y",
-                                                       g_variant_new_int32(node->getY()));
-                       g_variant_builder_add(builder, "{sv}", "Z",
-                                                       g_variant_new_int32(node->getZ()));
-                       g_variant_builder_close(builder);
-               }
-
-               *networks_gvar = g_variant_builder_end(builder);
-               g_variant_builder_unref(builder);
-       }
-
-       static gboolean __uwb_iface_handler_callback(
-                      UwbGdbuslibManager *gdbus_manager,
-                      GDBusMethodInvocation *invocation,
-                      gpointer user_data)
-       {
-               __UWB_LOG_FUNC_ENTER__;
-
-               UwbManager *uwb_manager = __get_uwb_manager((MethodHandler *)user_data);
-               if (!uwb_manager) {
-                       __dbus_return_err(UWB_ERROR_OPERATION_FAILED, invocation);
-                       __UWB_LOG_FUNC_EXIT__;
-                       return TRUE;
-               }
-
-               UwbNetwork *uwb_network = uwb_manager->getNetwork();
-               if (!uwb_network) {
-                       __dbus_return_err(UWB_ERROR_OPERATION_FAILED, invocation);
-                       __UWB_LOG_FUNC_EXIT__;
-                       return TRUE;
-               }
-
-               std::list<UwbNode *> *node_list = uwb_network->getNodeList();
-               if (!node_list) {
-                       __dbus_return_err(UWB_ERROR_OPERATION_FAILED, invocation);
-                       __UWB_LOG_FUNC_EXIT__;
-                       return TRUE;
-               }
-
-               GVariant *networks_gvar = nullptr;
-               buildNetworkGvar(node_list, &networks_gvar);
-
-               uwb_gdbuslib_manager_complete_get_network_info(gdbus_manager, invocation,
-                               (uint16_t)uwb_network->getPanId(), networks_gvar);
-
-               delete node_list;
-               delete uwb_network;
-
-               __UWB_LOG_FUNC_EXIT__;
-               return TRUE;
-       }
-};
-
-class setConfigurationsMethodHandler : MethodHandler
-{
-public:
-       setConfigurationsMethodHandler(UwbManager* manager): _manager(manager) {};
-       ~setConfigurationsMethodHandler()
-       {
-
-       }
-
-       void registerHandler(UwbGdbuslibManager *manager_skeleton) override
-       {
-               g_signal_connect(
-                               manager_skeleton,
-                               this->_method_name.c_str(),
-                               G_CALLBACK(__uwb_iface_handler_callback),
-                               gpointer(this));
-       }
-
-       UwbManager *getManager()
-       {
-               return this->_manager;
-       }
-private:
-       UwbManager *_manager;
-       const std::string _method_name =
-                       std::string("handle-set-configurations");
-       static gboolean __uwb_iface_handler_callback(
-                      UwbGdbuslibManager *gdbus_manager,
-                      GDBusMethodInvocation *invocation,
-                                  guint16 node_id,
-                                  GVariant *configurations,
-                      gpointer user_data)
-       {
-               __UWB_LOG_FUNC_ENTER__;
-
-               UwbManager *uwb_manager = __get_uwb_manager((MethodHandler *)user_data);
-               if (!uwb_manager) {
-                       __dbus_return_err(UWB_ERROR_OPERATION_FAILED, invocation);
-                       __UWB_LOG_FUNC_EXIT__;
-                       return TRUE;
-               }
-
-               int result = uwb_manager->setConfigurations(node_id, configurations);
-               if (result !=  0) {
-                       __dbus_return_err(UWB_ERROR_OPERATION_FAILED, invocation);
-                       __UWB_LOG_FUNC_EXIT__;
-                       return TRUE;
-               }
-
-               uwb_gdbuslib_manager_complete_set_configurations(gdbus_manager, invocation);
-               __UWB_LOG_FUNC_EXIT__;
-               return TRUE;
-       }
-};
-
-class getConfigurationsMethodHandler : MethodHandler
-{
-public:
-       getConfigurationsMethodHandler(UwbManager* manager): _manager(manager) {};
-       ~getConfigurationsMethodHandler()
-       {
-
-       }
-
-       void registerHandler(UwbGdbuslibManager *manager_skeleton) override
-       {
-               g_signal_connect(
-                               manager_skeleton,
-                               this->_method_name.c_str(),
-                               G_CALLBACK(__uwb_iface_handler_callback),
-                               gpointer(this));
-       }
-
-       UwbManager *getManager()
-       {
-               return this->_manager;
-       }
-private:
-       UwbManager *_manager;
-       const std::string _method_name =
-                       std::string("handle-get-configurations");
-       static gboolean __uwb_iface_handler_callback(
-                      UwbGdbuslibManager *gdbus_manager,
-                      GDBusMethodInvocation *invocation,
-                                  guint16 node_id,
-                      gpointer user_data)
-       {
-               __UWB_LOG_FUNC_ENTER__;
-
-               UwbManager *uwb_manager = __get_uwb_manager((MethodHandler *)user_data);
-               if (!uwb_manager) {
-                       __dbus_return_err(UWB_ERROR_OPERATION_FAILED, invocation);
-                       __UWB_LOG_FUNC_EXIT__;
-                       return TRUE;
-               }
-
-               GVariant *config_gvar = nullptr;
-               int result = uwb_manager->getConfigurations(node_id, &config_gvar);
-               if (result != 0) {
-                       __dbus_return_err(UWB_ERROR_OPERATION_FAILED, invocation);
-                       __UWB_LOG_FUNC_EXIT__;
-                       return TRUE;
-               }
-
-               uwb_gdbuslib_manager_complete_get_configurations(gdbus_manager, invocation, config_gvar);
-               __UWB_LOG_FUNC_EXIT__;
-               return TRUE;
-       }
-};
-
-class setPositionMethodHandler : MethodHandler
-{
-public:
-       setPositionMethodHandler(UwbManager* manager): _manager(manager) {};
-       ~setPositionMethodHandler()
-       {
-
-       }
-
-       void registerHandler(UwbGdbuslibManager *manager_skeleton) override
-       {
-               g_signal_connect(
-                               manager_skeleton,
-                               this->_method_name.c_str(),
-                               G_CALLBACK(__uwb_iface_handler_callback),
-                               gpointer(this));
-       }
-
-       UwbManager *getManager()
-       {
-               return this->_manager;
-       }
-private:
-       UwbManager *_manager;
-       const std::string _method_name =
-                       std::string("handle-set-position");
-       static gboolean __uwb_iface_handler_callback(
-                      UwbGdbuslibManager *gdbus_manager,
-                      GDBusMethodInvocation *invocation,
-                                  guint16 node_id,
-                                  gint x,
-                                  gint y,
-                                  gint z,
-                      gpointer user_data)
-       {
-               __UWB_LOG_FUNC_ENTER__;
-
-               UwbManager *uwb_manager = __get_uwb_manager((MethodHandler *)user_data);
-               if (!uwb_manager) {
-                       __dbus_return_err(UWB_ERROR_OPERATION_FAILED, invocation);
-                       __UWB_LOG_FUNC_EXIT__;
-                       return TRUE;
-               }
-
-               int result = uwb_manager->setPosition(node_id, x, y, z);
-               if (result !=  0) {
-                       __dbus_return_err(UWB_ERROR_OPERATION_FAILED, invocation);
-                       __UWB_LOG_FUNC_EXIT__;
-                       return TRUE;
-               }
-
-               uwb_gdbuslib_manager_complete_set_position(gdbus_manager, invocation);
-               __UWB_LOG_FUNC_EXIT__;
-               return TRUE;
-       }
-};
-
-static gint __ay_to_guchar(GVariant *src, int size, guchar **dst)
-{
-       if (src == nullptr || dst == nullptr || size == 0)
-               return 0;
-
-       GVariantIter *iter;
-       g_variant_get(src, "a(y)", &iter);
-
-       int result_size = g_variant_iter_n_children(iter);
-       if (result_size == 0 || result_size != size)
-               return 0;
-
-       guchar *buffer = (guchar *)g_try_malloc0(result_size);
-       if (!buffer)
-               return 0;
-
-       guint8 element;
-       guint pos = 0;
-
-       while (g_variant_iter_loop(iter, "(y)", &element)) {
-               *(buffer + pos) = element;
-               ++pos;
-       }
-
-       g_variant_iter_free(iter);
-
-       *dst = buffer;
-       return result_size;
-}
-
-class sendMessageMethodHandler : MethodHandler
-{
-public:
-       sendMessageMethodHandler(UwbManager* manager): _manager(manager) {};
-       ~sendMessageMethodHandler()
-       {
-
-       }
-
-       void registerHandler(UwbGdbuslibManager *manager_skeleton) override
-       {
-               g_signal_connect(
-                               manager_skeleton,
-                               this->_method_name.c_str(),
-                               G_CALLBACK(__uwb_iface_handler_callback),
-                               gpointer(this));
-       }
-
-       UwbManager *getManager()
-       {
-               return this->_manager;
-       }
-private:
-       UwbManager *_manager;
-       const std::string _method_name =
-                       std::string("handle-send-message");
-       static gboolean __uwb_iface_handler_callback(
-                      UwbGdbuslibManager *gdbus_manager,
-                      GDBusMethodInvocation *invocation,
-                                  GVariant * message,
-                                  gint message_length,
-                      gpointer user_data)
-       {
-               __UWB_LOG_FUNC_ENTER__;
-
-               UwbManager *uwb_manager = __get_uwb_manager((MethodHandler *)user_data);
-               if (!uwb_manager) {
-                       __dbus_return_err(UWB_ERROR_OPERATION_FAILED, invocation);
-                       __UWB_LOG_FUNC_EXIT__;
-                       return TRUE;
-               }
-
-               guchar *buffer = nullptr;
-               if (__ay_to_guchar(message, message_length, &buffer) == 0) {
-                       __dbus_return_err(UWB_ERROR_INVALID_PARAMETER, invocation);
-                       __UWB_LOG_FUNC_EXIT__;
-                       return TRUE;
-               }
-
-               int result = uwb_manager->sendMessage(buffer, message_length);
-               if (result !=  0) {
-                       __dbus_return_err(UWB_ERROR_OPERATION_FAILED, invocation);
-                       g_free(buffer);
-                       __UWB_LOG_FUNC_EXIT__;
-                       return TRUE;
-               }
-
-               uwb_gdbuslib_manager_complete_send_message(gdbus_manager, invocation);
-               g_free(buffer);
-               __UWB_LOG_FUNC_EXIT__;
-               return TRUE;
-       }
-};
-
-class sendMessageToMethodHandler : MethodHandler
-{
-public:
-       sendMessageToMethodHandler(UwbManager* manager): _manager(manager) {};
-       ~sendMessageToMethodHandler()
-       {
-
-       }
-
-       void registerHandler(UwbGdbuslibManager *manager_skeleton) override
-       {
-               g_signal_connect(
-                               manager_skeleton,
-                               this->_method_name.c_str(),
-                               G_CALLBACK(__uwb_iface_handler_callback),
-                               gpointer(this));
-       }
-
-       UwbManager *getManager()
-       {
-               return this->_manager;
-       }
-private:
-       UwbManager *_manager;
-       const std::string _method_name =
-                       std::string("handle-send-message-to");
-       static gboolean __uwb_iface_handler_callback(
-                      UwbGdbuslibManager *gdbus_manager,
-                      GDBusMethodInvocation *invocation,
-                                  guint16 node_id,
-                                  GVariant * message,
-                                  gint message_length,
-                      gpointer user_data)
-       {
-               __UWB_LOG_FUNC_ENTER__;
-
-               UwbManager *uwb_manager = __get_uwb_manager((MethodHandler *)user_data);
-               if (!uwb_manager) {
-                       __dbus_return_err(UWB_ERROR_OPERATION_FAILED, invocation);
-                       __UWB_LOG_FUNC_EXIT__;
-                       return TRUE;
-               }
-
-               guchar *buffer = nullptr;
-               if (__ay_to_guchar(message, message_length, &buffer) == 0) {
-                       __dbus_return_err(UWB_ERROR_INVALID_PARAMETER, invocation);
-                       __UWB_LOG_FUNC_EXIT__;
-                       return TRUE;
-               }
-
-               int result = uwb_manager->sendMessageTo(node_id, buffer, message_length);
-               if (result !=  0) {
-                       __dbus_return_err(UWB_ERROR_OPERATION_FAILED, invocation);
-                       g_free(buffer);
-                       __UWB_LOG_FUNC_EXIT__;
-                       return TRUE;
-               }
-
-               uwb_gdbuslib_manager_complete_send_message_to(gdbus_manager, invocation);
-               g_free(buffer);
-               __UWB_LOG_FUNC_EXIT__;
-               return TRUE;
-       }
-};
-
-UwbIfaceHandler::UwbIfaceHandler(UwbManager* uwb_manager)
-{
-       /* create handler objects */
-
-       _handler_vec.push_back((MethodHandler *)new testMethodHandler(uwb_manager));
-       _handler_vec.push_back((MethodHandler *)new resetMethodHandler(uwb_manager));
-       _handler_vec.push_back((MethodHandler *)new factoryResetMethodHandler(uwb_manager));
-       _handler_vec.push_back((MethodHandler *)new getOwnNodeMethodHandler(uwb_manager));
-       _handler_vec.push_back((MethodHandler *)new getNetworkMethodHandler(uwb_manager));
-       _handler_vec.push_back((MethodHandler *)new setConfigurationsMethodHandler(uwb_manager));
-       _handler_vec.push_back((MethodHandler *)new getConfigurationsMethodHandler(uwb_manager));
-       _handler_vec.push_back((MethodHandler *)new setPositionMethodHandler(uwb_manager));
-       _handler_vec.push_back((MethodHandler *)new sendMessageMethodHandler(uwb_manager));
-       _handler_vec.push_back((MethodHandler *)new sendMessageToMethodHandler(uwb_manager));
-}
-
-UwbIfaceHandler::~UwbIfaceHandler()
-{
-       /* destroy handler objects */
-
-       std::vector<MethodHandler *>::iterator itr = _handler_vec.begin();
-       for (; itr != _handler_vec.end(); ++itr) {
-               MethodHandler *handler = *itr;
-               delete handler;
-       }
-}
-
-std::string UwbIfaceHandler::get_dbus_path_str(void)
-{
-       return _uwb_dbus_path_str;
-}
-
-void UwbIfaceHandler::registerHandler(UwbGdbuslibManager *manager_skeleton)
-{
-       /* Register for method callbacks as signal callbacks */
-       std::vector<MethodHandler *>::iterator itr = _handler_vec.begin();
-       for (; itr != _handler_vec.end(); ++itr) {
-               MethodHandler * handler = *itr;
-               handler->registerHandler(manager_skeleton);
-       }
-}
diff --git a/src/UwbManager.cpp b/src/UwbManager.cpp
deleted file mode 100755 (executable)
index aacdab3..0000000
+++ /dev/null
@@ -1,285 +0,0 @@
-/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <uwb-log-def.h>
-
-#include <UwbManager.h>
-#include <json-glib/json-glib.h>
-#include <tzplatform_config.h>
-
-#define CONFIGFILE     tzplatform_mkpath(TZ_SYS_RO_ETC, "/uwb/uwb-plugin.conf")
-
-using namespace UwbManagerNamespace;
-
-int UwbManager::test(void)
-{
-       int res;
-       __UWB_LOG_FUNC_ENTER__;
-
-       if (!_range_plugin) {
-               __UWB_LOG_FUNC_EXIT__;
-               return -1;
-       }
-       res = _range_plugin->test();
-
-       __UWB_LOG_FUNC_EXIT__;
-       return res;
-}
-
-int UwbManager::reset(void)
-{
-       int res;
-       __UWB_LOG_FUNC_ENTER__;
-
-       if (!_range_plugin) {
-               __UWB_LOG_FUNC_EXIT__;
-               return -1;
-       }
-       res = _range_plugin->reset();
-
-       __UWB_LOG_FUNC_EXIT__;
-       return res;
-}
-
-int UwbManager::factoryReset(void)
-{
-       int res;
-       __UWB_LOG_FUNC_ENTER__;
-
-       if (!_range_plugin) {
-               __UWB_LOG_FUNC_EXIT__;
-               return -1;
-       }
-       res = _range_plugin->factoryReset();
-
-       __UWB_LOG_FUNC_EXIT__;
-       return res;
-}
-
-int UwbManager::setPosition(int node_id, int x, int y, int z)
-{
-       int res;
-       __UWB_LOG_FUNC_ENTER__;
-
-       if (!_range_plugin) {
-               __UWB_LOG_FUNC_EXIT__;
-               return -1;
-       }
-       res = _range_plugin->setPosition(node_id, x, y, z);
-
-       __UWB_LOG_FUNC_EXIT__;
-       return res;
-}
-
-int UwbManager::setDefaultConfigurations()
-{
-       int res;
-       int node_id = 0;
-       GVariant *configurations = NULL;
-       JsonParser *parser = NULL;
-       GError *error = NULL;
-
-       __UWB_LOG_FUNC_ENTER__;
-
-       if (!_range_plugin) {
-               __UWB_LOG_FUNC_EXIT__;
-               return -1;
-       }
-
-       parser = json_parser_new();
-
-       json_parser_load_from_file(parser, CONFIGFILE, &error);
-       if (error != NULL) {
-               UWB_LOGD("json_parser_load_from_file failed : %s", error->message);
-               return -1;
-       }
-
-       configurations = json_gvariant_deserialize(json_parser_get_root(parser), "a{sv}", &error);
-       if (error != NULL) {
-               UWB_LOGD("json_gvariant_deserialize failed : %s", error->message);
-               return -1;
-       }
-
-       res = _range_plugin->setConfigurations(node_id, configurations);
-       if (res != 0)  {
-               __UWB_LOG_FUNC_EXIT__;
-               return -1;
-       }
-
-       __UWB_LOG_FUNC_EXIT__;
-       return res;
-}
-
-int UwbManager::setConfigurations(int node_id, GVariant *configurations)
-{
-       int res;
-       __UWB_LOG_FUNC_ENTER__;
-
-       if (!_range_plugin) {
-               __UWB_LOG_FUNC_EXIT__;
-               return -1;
-       }
-
-       res = _range_plugin->setConfigurations(node_id, configurations);
-       if (res != 0)  {
-               __UWB_LOG_FUNC_EXIT__;
-               return -1;
-       }
-
-       __UWB_LOG_FUNC_EXIT__;
-       return res;
-}
-
-int UwbManager::getConfigurations(int node_id, GVariant **configurations)
-{
-       int res;
-       __UWB_LOG_FUNC_ENTER__;
-
-       if (!_range_plugin) {
-               __UWB_LOG_FUNC_EXIT__;
-               return -1;
-       }
-
-       res = _range_plugin->getConfigurations(node_id, configurations);
-       if (res != 0)  {
-               __UWB_LOG_FUNC_EXIT__;
-               return -1;
-       }
-
-       __UWB_LOG_FUNC_EXIT__;
-       return res;
-}
-
-static void __foreach_node(gpointer data, gpointer user_data)
-{
-       uwb_hpi_node_s *node = (uwb_hpi_node_s *)data;
-       UwbNetwork *uwb_network = (UwbNetwork *)user_data;
-       UwbNode uwb_node = new UwbNode();
-
-       uwb_node.setDistance(node->distance);
-       uwb_node.setPanId(node->pan_id);
-       uwb_node.setNodeId(node->node_id);
-       uwb_node.setX(node->x);
-       uwb_node.setY(node->y);
-       uwb_node.setZ(node->z);
-       uwb_node.setIsRemote(node->is_remote);
-
-       uwb_network->addNode(&uwb_node);
-}
-
-UwbNetwork *UwbManager::getNetwork(void)
-{
-       uwb_hpi_network_s *network_info = nullptr;
-       UwbNetwork *uwb_network_ret;
-       int res;
-       __UWB_LOG_FUNC_ENTER__;
-
-       if (!_range_plugin) {
-               __UWB_LOG_FUNC_EXIT__;
-               return nullptr;
-       }
-
-       res = _range_plugin->getNetworkInfo(&network_info);
-       if (res != 0 || !network_info) {
-               __UWB_LOG_FUNC_EXIT__;
-               return nullptr;
-       }
-       UWB_LOGD("panid : 0x%x, count : %d", network_info->pan_id, network_info->remote_node_count);
-       uwb_network_ret = new UwbNetwork(network_info->pan_id);
-       if (!uwb_network_ret) {
-               __UWB_LOG_FUNC_EXIT__;
-               return nullptr;
-       }
-
-       g_slist_foreach(network_info->remote_node_list, __foreach_node, uwb_network_ret);
-
-       __UWB_LOG_FUNC_EXIT__;
-       return uwb_network_ret;
-
-}
-
-
-UwbNode *UwbManager::getOwnNode(void)
-{
-       uwb_hpi_node_s *own_node = nullptr;
-       UwbNode *uwb_node_ret;
-       int res;
-       __UWB_LOG_FUNC_ENTER__;
-
-       if (!_range_plugin) {
-               __UWB_LOG_FUNC_EXIT__;
-               return nullptr;
-       }
-
-       res = _range_plugin->getOwnNode(&own_node);
-       if (res != 0 || !own_node) {
-               __UWB_LOG_FUNC_EXIT__;
-               return nullptr;
-       }
-
-       uwb_node_ret = new UwbNode(own_node->distance, own_node->pan_id, own_node->node_id,
-                                                                       own_node->x, own_node->y, own_node->z, own_node->is_remote);
-       if (!uwb_node_ret) {
-               __UWB_LOG_FUNC_EXIT__;
-               return nullptr;
-       }
-
-       __UWB_LOG_FUNC_EXIT__;
-       return uwb_node_ret;
-}
-
-int UwbManager::sendMessage(const unsigned char *message, int message_length)
-{
-       int res = 0;
-
-       __UWB_LOG_FUNC_ENTER__;
-
-       if (!_range_plugin) {
-               __UWB_LOG_FUNC_EXIT__;
-               return res;
-       }
-
-       res = _range_plugin->sendMessage(message, message_length);
-       if (res != 0) {
-               __UWB_LOG_FUNC_EXIT__;
-               return res;
-       }
-
-       __UWB_LOG_FUNC_EXIT__;
-       return res;
-}
-
-int UwbManager::sendMessageTo(uint16_t node_id, const unsigned char *message, int message_length)
-{
-       int res = 0;
-
-       __UWB_LOG_FUNC_ENTER__;
-
-       if (!_range_plugin) {
-               __UWB_LOG_FUNC_EXIT__;
-               return res;
-       }
-
-       res = _range_plugin->sendMessageTo(node_id, message, message_length);
-       if (res != 0) {
-               __UWB_LOG_FUNC_EXIT__;
-               return res;
-       }
-
-       __UWB_LOG_FUNC_EXIT__;
-       return res;
-}
-
diff --git a/src/UwbMqttMessage.cpp b/src/UwbMqttMessage.cpp
new file mode 100644 (file)
index 0000000..e9a0a66
--- /dev/null
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include <cstdint>
+#include <memory>
+#include <algorithm>
+
+#include "uwb-log-def.h"
+#include "UwbMqttMessage.h"
+
+using namespace UwbManagerNamespace;
+
+UwbMqttMessage::~UwbMqttMessage()
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+       __UWB_LOG_FUNC_EXIT__;
+}
+
+UwbMqttMessage::UwbMqttMessage()
+{
+       this->_topic = this->_broadcast_position_topic_prefix + std::string("+");
+}
+
+UwbMqttMessage::UwbMqttMessage(Node &node_info)
+{
+       this->_topic = this->_broadcast_position_topic_prefix +
+                       std::to_string(node_info.getNodeId());
+
+       std::unique_ptr<unsigned char[]>\
+       payload(new unsigned char[this->_node_payload_length]);
+       int location_idx = 0;
+       *(int32_t *)((payload.get()) + location_idx) = node_info.getPanId();
+       location_idx += sizeof(int32_t);
+       *(int32_t *)((payload.get()) + location_idx) = node_info.getX();
+       location_idx += sizeof(int32_t);
+       *(int32_t *)((payload.get()) + location_idx) = node_info.getY();
+       location_idx += sizeof(int32_t);
+       *(int32_t *)((payload.get()) + location_idx) = node_info.getZ();
+       location_idx += sizeof(int32_t);
+
+       this->_payload = std::string(reinterpret_cast<char const *>(payload.get()),
+                       this->_node_payload_length);
+
+}
+
+std::string &UwbMqttMessage::getTopic(void)
+{
+       return this->_topic;
+}
+
+std::string &UwbMqttMessage::getPayload(void)
+{
+       return this->_payload;
+}
+
diff --git a/src/UwbMqttRequest.cpp b/src/UwbMqttRequest.cpp
new file mode 100644 (file)
index 0000000..a65fddd
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <uwb-log-def.h>
+
+#include "UwbMqttRequest.h"
+
+using namespace UwbManagerNamespace;
+
+UwbMqttRequest::UwbMqttRequest(void)
+{
+       this->_qos = 0;
+       this->_retained = 0;
+       std::unique_ptr<UwbMqttMessage> mqtt_msg(new UwbMqttMessage());
+       this->_mqtt_msg = std::move(mqtt_msg);
+}
+
+UwbMqttRequest::UwbMqttRequest(int qos, std::unique_ptr<UwbMqttMessage> mqtt_msg)
+{
+       this->_qos = qos;
+       this->_retained = 0;
+       this->_mqtt_msg = std::move(mqtt_msg);
+}
+
+UwbMqttRequest::UwbMqttRequest(int qos, int retained,
+               std::unique_ptr<UwbMqttMessage> mqtt_msg)
+{
+       this->_qos = 0;
+       this->_retained = retained;
+       this->_mqtt_msg = std::move(mqtt_msg);
+}
+
+UwbMqttRequest::~UwbMqttRequest(void)
+{
+       __UWB_LOG_FUNC_ENTER__;
+       __UWB_LOG_FUNC_EXIT__;
+}
+
old mode 100755 (executable)
new mode 100644 (file)
index 9df0a07..1f9d645
@@ -14,8 +14,6 @@
  * limitations under the License.
  */
 
-#include <algorithm>
-
 #include <uwb-log-def.h>
 
 #include <UwbNetwork.h>
@@ -24,66 +22,69 @@ using namespace UwbManagerNamespace;
 
 UwbNetwork::~UwbNetwork()
 {
-       std::list<UwbNode *>::iterator it;
-
-    it = _node_list.begin();
-    for (; it != _node_list.end(); ++it) {
-       UwbNode *node = *it;
-       delete node;
-    }
-
-       _node_list.clear();
+       __UWB_LOG_FUNC_ENTER__;
 
+       __UWB_LOG_FUNC_EXIT__;
        return;
 }
 
-void UwbNetwork::setPanId(int pan_id)
+static void __destroy_node(gpointer data)
 {
-       _pan_id = pan_id;
-
-       return;
+       if (data != NULL) {
+               uwb_hpi_node_s *node = (uwb_hpi_node_s *)data;
+               free(node);
+       }
 }
 
-int UwbNetwork::getPanId()
+int UwbNetwork::enable(void)
 {
-       return _pan_id;
-}
+       __UWB_LOG_FUNC_ENTER__;
 
-int UwbNetwork::addNode(UwbNode *node)
-{
-       UwbNode *dst;
+       this->_is_enable = true;
+
+       if (this->_range_plugin == nullptr) {
+               __UWB_LOG_FUNC_EXIT__;
+               return 0;
+       }
+
+       int ret = this->_range_plugin->enableNetwork();
+       if (ret != 0) {
+               __UWB_LOG_FUNC_EXIT__;
 
-       if (!node)
+               this->_is_enable = false;
                return -1;
+       }
 
-       dst = new UwbNode(node);
-       _node_list.push_front(dst);
+       uwb_hpi_network_s *network_info = nullptr;
+       int res = this->_range_plugin->getNetworkInfo(&network_info);
+       if (res != 0 || !network_info) {
+               __UWB_LOG_FUNC_EXIT__;
+               return -1;
+       }
+
+       UWB_LOGD("panid : 0x%x, count : %d", network_info->pan_id, network_info->remote_node_count);
+       this->setPanId(network_info->pan_id);
 
+       g_slist_free_full(network_info->remote_node_list, __destroy_node);
+       free(network_info);
+
+       __UWB_LOG_FUNC_EXIT__;
        return 0;
 }
 
-int UwbNetwork::removeNode(UwbNode *node)
+int UwbNetwork::disable(void)
 {
-       std::list<UwbNode *>::iterator it;
+       __UWB_LOG_FUNC_ENTER__;
+
+       this->_is_enable = false;
 
-       if (!node)
+       if (this->_range_plugin == nullptr) {
+               __UWB_LOG_FUNC_EXIT__;
                return -1;
+       }
 
-    it = _node_list.begin();
-    for (; it != _node_list.end(); ++it) {
-       UwbNode *it_node = *it;
-       if (it_node->getNodeId() == node->getNodeId()) {
-               _node_list.erase(it);
-               break;
-       }
-    }
+       this->_range_plugin->disableNetwork();
 
+       __UWB_LOG_FUNC_EXIT__;
        return 0;
 }
-
-std::list<UwbNode *> *UwbNetwork::getNodeList()
-{
-       std::list<UwbNode *> *node_list = new std::list<UwbNode *>(_node_list);
-
-       return node_list;
-}
diff --git a/src/UwbNode.cpp b/src/UwbNode.cpp
deleted file mode 100755 (executable)
index 59bccc6..0000000
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <uwb-log-def.h>
-
-#include <UwbNode.h>
-
-using namespace UwbManagerNamespace;
-
-UwbNode::UwbNode(UwbNode *node)
-{
-       _distance = node->_distance;
-       _pan_id = node->_pan_id;
-       _node_id = node->_node_id;
-       _x = node->_x;
-       _y = node->_y;
-       _z = node->_z;
-       _is_remote = node->_is_remote;
-}
-
-void UwbNode::setDistance(unsigned long long distance)
-{
-       _distance = distance;
-
-       return;
-}
-
-unsigned long long UwbNode::getDistance()
-{
-       return _distance;
-}
-
-void UwbNode::setPanId(int id)
-{
-       _pan_id = id;
-
-       return;
-}
-
-int UwbNode::getPanId()
-{
-       return _pan_id;
-}
-
-void UwbNode::setNodeId(unsigned long long id)
-{
-       _node_id = id;
-
-       return;
-}
-
-unsigned long long UwbNode::getNodeId()
-{
-       return _node_id;
-}
-
-int UwbNode::getX()
-{
-       return _x;
-}
-
-void UwbNode::setX(int x)
-{
-       _x = x;
-
-       return;
-}
-
-int UwbNode::getY()
-{
-       return _y;
-}
-
-void UwbNode::setY(int y)
-{
-       _y = y;
-
-       return;
-}
-
-int UwbNode::getZ()
-{
-       return _z;
-}
-
-void UwbNode::setZ(int z)
-{
-       _z = z;
-
-       return;
-}
-
-bool UwbNode::getIsRemote()
-{
-       return _is_remote;
-}
-
-void UwbNode::setIsRemote(bool is_remote)
-{
-       _is_remote = is_remote;
-
-       return;
-}
index 3aab122..4fe836c 100644 (file)
@@ -14,8 +14,6 @@
  * limitations under the License.
  */
 
-#include <dlfcn.h>
-
 #include <uwb-log-def.h>
 
 #include <UwbPluginManager.h>
@@ -24,65 +22,69 @@ using namespace UwbManagerNamespace;
 
 UwbPluginManager::~UwbPluginManager()
 {
-       int res;
        __UWB_LOG_FUNC_ENTER__;
 
-       if (_dl_handle) {
-               res = dlclose(_dl_handle);
-               if (res != 0)
-                       UWB_LOGE("dlclose failed, [%d] : %s", errno, dlerror());        // LCOV_EXCL_LINE
+       this->_plugins.clear();
 
-               _dl_handle = nullptr;
-       }
        __UWB_LOG_FUNC_EXIT__;
 }
 
-int UwbPluginManager::load(const std::string lib_path_str)
+int UwbPluginManager::load(std::shared_ptr<UwbPlugin> plugin)
 {
-       int res;
        __UWB_LOG_FUNC_ENTER__;
 
-       if (_dl_handle) {
-               res = dlclose(_dl_handle);
-               if (res != 0)
-                       UWB_LOGE("dlclose failed, [%d] : %s", errno, dlerror());        // LCOV_EXCL_LINE
-               _dl_handle = nullptr;
+       if (plugin == nullptr){
+               __UWB_LOG_FUNC_EXIT__;
+               return -1;
        }
 
-       _dl_handle = dlopen(lib_path_str.c_str(), RTLD_LAZY);
-       if (_dl_handle == NULL) {
+       void *dl_handle = nullptr;
+       dl_handle = dlopen(plugin->getPluginPath().c_str(), RTLD_LAZY);
+       if (dl_handle == nullptr) {
                UWB_LOGE("dlopen failed, [%d] : %s", errno, dlerror());         // LCOV_EXCL_LINE
                __UWB_LOG_FUNC_EXIT__;
                return -1;
        }
 
+       void *symbol_table = nullptr;
+       symbol_table = dlsym(dl_handle, this->_func_tbl_symbol.c_str());
+       if (symbol_table == nullptr) {
+               UWB_LOGE("dlsym failed, [%d] : %s", errno, dlerror());  // LCOV_EXCL_LINE
+               dlclose(dl_handle);
+               __UWB_LOG_FUNC_EXIT__;
+               return -1;
+       }
+
+       plugin->init(symbol_table);
+       this->_plugins[plugin] = dl_handle;
+
        __UWB_LOG_FUNC_EXIT__;
        return 0;
 }
 
-void UwbPluginManager::unload(void)
+int UwbPluginManager::unload(std::shared_ptr<UwbPlugin> plugin)
 {
-       int res;
        __UWB_LOG_FUNC_ENTER__;
 
-       if (_dl_handle) {
-               res = dlclose(_dl_handle);
-               if (res != 0)
-                       UWB_LOGE("dlclose failed, [%d] : %s", errno, dlerror());        // LCOV_EXCL_LINE
-               _dl_handle = nullptr;
+       if (plugin == nullptr){
+               __UWB_LOG_FUNC_EXIT__;
+               return -1;
        }
-       __UWB_LOG_FUNC_EXIT__;
-}
 
-void *UwbPluginManager::get_symbol(const std::string symbol_str)
-{
-       void * ret;
-       __UWB_LOG_FUNC_ENTER__;
+       plugin->deinit();
 
-       ret = dlsym(_dl_handle, symbol_str.c_str());
-       if (!ret)
-               UWB_LOGE("dlsym failed, [%d] : %s", errno, dlerror());  // LCOV_EXCL_LINE
+       auto itr = this->_plugins.find(plugin);
+       if (itr == this->_plugins.end()) {
+               __UWB_LOG_FUNC_EXIT__;
+               return -1;
+       }
+
+       void *dl_handle = itr->second;
+       if (dl_handle)
+               dlclose(dl_handle);
+
+       this->_plugins.erase(plugin);
 
        __UWB_LOG_FUNC_EXIT__;
-       return ret;
+       return 0;
 }
diff --git a/src/UwbPosition.cpp b/src/UwbPosition.cpp
new file mode 100644 (file)
index 0000000..255b39a
--- /dev/null
@@ -0,0 +1,288 @@
+/*
+ * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include <math.h>
+
+#include <algorithm>
+
+#include <uwb-log-def.h>
+
+#include <UwbPosition.h>
+
+using namespace UwbManagerNamespace;
+
+UwbPosition::~UwbPosition()
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+       _node_list.clear();
+
+       __UWB_LOG_FUNC_EXIT__;
+       return;
+}
+
+int UwbPosition::updateUwbOwnNode()
+{
+       if (this->_range_plugin == nullptr)
+               return 0;
+
+       uwb_hpi_node_s *own_node;
+       int res = this->_range_plugin->getOwnNode(&own_node);
+       if (res != 0 || !own_node)
+               return -1;
+
+       this->setOwnNode(Node(own_node));
+       free(own_node);
+
+       return 0;
+}
+
+static void __foreach_node(gpointer data, gpointer user_data)
+{
+       uwb_hpi_node_s *node = (uwb_hpi_node_s *)data;
+       UwbPosition *position = (UwbPosition *)user_data;
+
+       if (!node || !position)
+               return;
+
+       Node uwb_node(node);
+
+       position->addNode(uwb_node);
+       return;
+}
+
+static void __destroy_node(gpointer data)
+{
+       if (data != NULL) {
+               uwb_hpi_node_s *node = (uwb_hpi_node_s *)data;
+               free(node);
+       }
+}
+
+int UwbPosition::updateUwbNodes(void)
+{
+       if (this->_range_plugin == nullptr)
+               return 0;
+
+       uwb_hpi_network_s *network_info = nullptr;
+       int res = this->_range_plugin->getNetworkInfo(&network_info);
+       if (res != 0 || !network_info)
+               return -1;
+
+       UWB_LOGD("panid : 0x%x, count : %d", network_info->pan_id, network_info->remote_node_count);
+
+       this->clearNodes();
+
+       g_slist_foreach(network_info->remote_node_list, __foreach_node, this);
+
+       g_slist_free_full(network_info->remote_node_list, __destroy_node);
+       free(network_info);
+
+       return 0;
+}
+
+/* TODO: How to handle if real position is origin */
+bool UwbPosition::hasOwnPosition(void)
+{
+       return !(this->_own_node.getX() == 0 &&
+                       this->_own_node.getY() == 0 &&
+                       this->_own_node.getZ() == 0);
+}
+
+static bool cmp_dist(const std::unique_ptr<Node> &up_node_src,
+               const std::unique_ptr<Node> &up_node_dst)
+{
+       return up_node_src->getDistance() < up_node_dst->getDistance();
+}
+
+int UwbPosition::trilaterate(void)
+{
+       Node *nodes[3] = {nullptr,};
+
+       int has_distance = 0;
+       auto current = this->_node_list.begin();
+       while (true) {
+               current = std::find_if(current, this->_node_list.end(),
+                               [&has_distance, &nodes](const std::unique_ptr<Node> &elem)
+                               { if (elem->getDistance() > 0) {
+                                       nodes[has_distance] = elem.get();
+                                       has_distance++;
+                                       return true;
+                               } else
+                                       return false;
+                               });
+               if (current == this->_node_list.end() || has_distance > 2)
+                       break;
+               current++;
+       }
+
+       if (has_distance < 3) {
+               UWB_LOGI("Own position is not computable");
+               return 0;
+       }
+
+       double a = (-2.0 * nodes[0]->getX() + 2.0 * nodes[1]->getX());
+       double b = (-2.0 * nodes[0]->getY() + 2.0 * nodes[1]->getY());
+       double c = pow(nodes[0]->getDistance(), 2) - pow(nodes[1]->getDistance(), 2)
+                       - pow(nodes[0]->getX(), 2) + pow(nodes[1]->getX(), 2)
+                       - pow(nodes[0]->getY(), 2) + pow(nodes[1]->getY(), 2);
+       double d = (-2.0 * nodes[1]->getX() + 2.0 * nodes[2]->getX());
+       double e = (-2.0 * nodes[1]->getY() + 2.0 * nodes[2]->getY());
+       double f = pow(nodes[1]->getDistance(), 2) - pow(nodes[2]->getDistance(), 2)
+                       - pow(nodes[1]->getX(), 2) + pow(nodes[2]->getX(), 2)
+                       - pow(nodes[1]->getY(), 2) + pow(nodes[2]->getY(), 2);
+
+       double divider1 = (e * a - b * d);
+       double divider2 = (b * d - a * e);
+       if (abs(divider1) < this->EPS || abs(divider2) < this->EPS) {
+               UWB_LOGI("Invalid divider");
+               return -1;
+       }
+
+       this->_own_node.setX((c * e - f * b) / (e * a - b * d));
+       this->_own_node.setY((c * d - a * f) / (b * d - a * e));
+       this->_own_node.setIsCalculated(true);
+
+       UWB_LOGI("calculated x : %d y : %d",
+                       this->_own_node.getX(), this->_own_node.getY());
+
+       return 0;
+}
+
+int UwbPosition::calculatePosition(void)
+{
+       this->_node_list.sort(cmp_dist);
+
+       if (this->hasOwnPosition()) {
+               this->_own_node.setIsCalculated(false);
+               UWB_LOGI("Has own position");
+               return 0;
+       }
+
+       return this->trilaterate();
+}
+
+int UwbPosition::update(void)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+       int ret = this->updateUwbOwnNode();
+       if (ret != 0) {
+               UWB_LOGI("Failed to update own node");
+               return -1;
+       }
+
+       ret = this->updateUwbNodes();
+       if (ret != 0) {
+               UWB_LOGI("Failed to update nodes");
+               return -1;
+       }
+
+       ret = this->calculatePosition();
+       if (ret != 0) {
+               UWB_LOGI("Failed to calculate position");
+               return -1;
+       }
+
+       __UWB_LOG_FUNC_EXIT__;
+       return 0;
+}
+
+void UwbPosition::setOwnNode(const Node &node)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+       this->_own_node = node;
+
+       UWB_LOGI("Node updated %llu", this->_own_node.getNodeId());
+
+       __UWB_LOG_FUNC_EXIT__;
+       return;
+}
+
+void UwbPosition::setPosition(int x, int y, int z)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+       int ret = this->updateUwbOwnNode();
+       if (ret != 0) {
+               UWB_LOGI("Failed to update own node");
+               return;
+       }
+
+       this->_range_plugin->setPosition(this->_own_node.getNodeId(), x, y, z);
+
+       __UWB_LOG_FUNC_EXIT__;
+       return;
+}
+
+
+void UwbPosition::clearNodes(void)
+{
+       this->_node_list.clear();
+
+       return;
+}
+
+Node UwbPosition::getOwnNode()
+{
+       return this->_own_node;
+}
+
+int UwbPosition::addNode(const Node &node)
+{
+       /* TODO: How to handle memory allocation error ?
+        * std::nothrow
+        * ClassA *a = new(std::nothrow) ClassA();
+        * if (a == nullptr)
+        *      return;
+        * or
+        *      try {
+        *              ClassA* a = new ClassA();
+        *      } catch(std::bad_allocation& ba) {
+        *      return;
+        *      }
+        *      */
+
+       this->_node_list.emplace_back((Node *)new Node(node));
+
+       return 0;
+}
+
+Node *UwbPosition::getNode(unsigned long long node_id)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+       Node *result_node = nullptr;
+       for (auto &elem : this->_node_list) {
+               result_node = elem.get();
+               if (result_node->getNodeId() == node_id)
+                       break;
+               result_node = nullptr;
+       }
+       __UWB_LOG_FUNC_EXIT__;
+       return result_node;
+}
+
+int UwbPosition::removeNode(unsigned long long node_id)
+{
+       __UWB_LOG_FUNC_ENTER__;
+
+       this->_node_list.erase(std::remove_if(this->_node_list.begin(), this->_node_list.end(),
+                       [node_id](const std::unique_ptr<Node> &node) {return node->getNodeId() == node_id;}));
+
+       __UWB_LOG_FUNC_EXIT__;
+       return 0;
+}
old mode 100755 (executable)
new mode 100644 (file)
index b682625..8553114
 #include <uwb-log-def.h>
 
 #include <UwbRangePlugin.h>
-#include <UwbDbusManager.h>
+//#include <UwbDbusManager.h>
 
 using namespace UwbManagerNamespace;
 
 void UwbRangePlugin::messageReceivedCb(uint16_t node_id, unsigned char *message, int message_length)
 {
        UWB_LOGI("Call signal emit method in dbus class"); // LCOV_EXCL_LINE
-       UwbDbusManager::emitMessageReceivedSignal(node_id, message, message_length);
+       //UwbDbusManager::emitMessageReceivedSignal(node_id, message, message_length);
 }
 
 void UwbRangePlugin::positionChangedCb(uint16_t node_id, int x, int y, int z)
 {
        UWB_LOGI("Call signal emit method in dbus class"); // LCOV_EXCL_LINE
-       UwbDbusManager::emitPositionChangedSignal(node_id, x, y, z);
+       //UwbDbusManager::emitPositionChangedSignal(node_id, x, y, z);
 }
 
-int UwbRangePlugin::init(UwbPluginManager *plugin_manager)
+int UwbRangePlugin::init(void *uwb_plugin_load)
 {
-       int (*uwb_plugin_load)(uwb_hpi_ops_s *interfaces);
+       int (*load_plugin)(uwb_hpi_ops_s *interfaces) = (int (*)(uwb_hpi_ops_s *))uwb_plugin_load;
 
-       uwb_plugin_load =
-                       (int (*)(uwb_hpi_ops_s*))plugin_manager->get_symbol("uwb_plugin_load");
-       if (uwb_plugin_load == NULL)
+       if (load_plugin == NULL)
                return -1;
 
-       if (uwb_plugin_load(&ops) < 0) {
+       if (load_plugin(&ops) < 0) {
                UWB_LOGE("onload failed"); // LCOV_EXCL_LINE
                return -1;
        }
@@ -58,6 +56,11 @@ int UwbRangePlugin::deinit(void)
        return uwb_hpi_deinit(&ops);
 }
 
+std::string UwbRangePlugin::getPluginPath(void)
+{
+       return this->_plugin_path;
+}
+
 int UwbRangePlugin::test(void)
 {
        return uwb_hpi_test(&ops);
@@ -73,6 +76,16 @@ int UwbRangePlugin::factoryReset(void)
        return uwb_hpi_factory_reset(&ops);
 }
 
+int UwbRangePlugin::enableNetwork(void)
+{
+       return uwb_hpi_enable_network(&ops);
+}
+
+int UwbRangePlugin::disableNetwork(void)
+{
+       return uwb_hpi_disable_network(&ops);
+}
+
 int UwbRangePlugin::getOwnNode(uwb_hpi_node_s **own_node)
 {
        return uwb_hpi_get_own_node(&ops, own_node);
@@ -93,7 +106,7 @@ int UwbRangePlugin::getConfigurations(uint16_t node_id, GVariant **configuration
        return uwb_hpi_get_configurations(&ops, node_id, configurations);
 }
 
-int UwbRangePlugin::setPosition(uint16_t node_id, int x, int y, int z)
+int UwbRangePlugin::setPosition(uint64_t node_id, int x, int y, int z)
 {
        return uwb_hpi_set_position(&ops, node_id, x, y, z);
 }
index 97a1b8d..9bc80a4 100755 (executable)
  * limitations under the License.
  */
 
-#include <UwbDbusManager.h>
-#include <UwbIfaceHandler.h>
-#include <UwbPluginManager.h>
-#include <UwbRangePlugin.h>
-#include <UwbManager.h>
+#include <memory>
+
+#include <uwb-log-def.h>
 
-#define DWM1001_PLUGIN_PATH "/usr/lib/uwb-plugin-dwm1001.so"
-#define DWM1001_PLUGIN_64BIT_PATH "/usr/lib64/uwb-plugin-dwm1001.so"
+#include <UwbRangePlugin.h>
+#include <UwbPluginManager.h>
+#include <UwbConfig.h>
+#include <UwbNetwork.h>
+#include <UwbPosition.h>
+#include <LocationManager.h>
+#include <UwbDbusManager.h>
+#include <UwbDbusIfaceAdapter.h>
 
 using namespace UwbManagerNamespace;
 
 GMainLoop *main_loop;
 
+static void __signal_handler(
+               int signo, siginfo_t *info, void *data)
+{
+       /* TODO: clear MQTT and UWB resources */
+       if (SIGTERM == signo || SIGSYS == signo || SIGINT == signo)
+               g_main_loop_quit(main_loop);
+}
+
+
+static void __set_signal_handler()
+{
+       struct sigaction sa;
+
+       memset(&sa, 0, sizeof(sa));
+       sa.sa_sigaction = __signal_handler;
+       sa.sa_flags = SA_SIGINFO;
+       sigaction(SIGINT, &sa, NULL);
+       sigaction(SIGTERM, &sa, NULL);
+}
+
+static void __set_device_control_handler(UwbRangePlugin *range_plugin,
+               UwbDbusIfaceAdapter &dbus_adapter)
+{
+       auto test_handler = std::bind(&UwbRangePlugin::test,
+                       range_plugin);
+       dbus_adapter.setTest(test_handler);
+
+       auto reset_handler = std::bind(&UwbRangePlugin::reset,
+                       range_plugin);
+       dbus_adapter.setReset(reset_handler);
+
+       auto factory_reset_handler = std::bind(&UwbRangePlugin::factoryReset,
+                       range_plugin);
+       dbus_adapter.setFactoryReset(factory_reset_handler);
+
+       using namespace std::placeholders;
+       auto send_message_handler = std::bind(&UwbRangePlugin::sendMessage,
+                       range_plugin, _1, _2);
+       dbus_adapter.setSendMessage(send_message_handler);
+
+       auto send_message_to_handler = std::bind(&UwbRangePlugin::sendMessageTo,
+                       range_plugin, _1, _2, _3);
+       dbus_adapter.setSendMessageTo(send_message_to_handler);
+}
+
+static void __set_configuration_handler(UwbConfig *config,
+               UwbDbusIfaceAdapter &dbus_adapter)
+{
+
+       auto set_configurations_handler = std::bind(&UwbConfig::setConfigurations,
+                       config, std::placeholders::_1);
+       dbus_adapter.setSetConfigurations(set_configurations_handler);
+
+       auto get_configurations_handler = std::bind(&UwbConfig::getConfigurations,
+                       config);
+       dbus_adapter.setGetConfigurations(get_configurations_handler);
+}
+
+static void __set_position_handler(UwbPosition *position,
+               UwbDbusIfaceAdapter &dbus_adapter)
+{
+       using namespace std::placeholders;
+       auto set_position_handler = std::bind(&UwbPosition::setPosition,
+                       position, _1, _2, _3);
+       dbus_adapter.setSetPosition(set_position_handler);
+}
+
+static void __set_network_handler(UwbNetwork *network,
+               UwbDbusIfaceAdapter &dbus_adapter)
+{
+       auto enable_network_handler = std::bind(&UwbNetwork::enable,
+                       network);
+       dbus_adapter.setEnableNetwork(enable_network_handler);
+
+       auto disable_network_handler = std::bind(&UwbNetwork::disable,
+                       network);
+       dbus_adapter.setDisableNetwork(disable_network_handler);
+}
+
+static void __set_location_handler(LocationManager *location_mgr,
+               UwbDbusIfaceAdapter &dbus_adapter)
+{
+       using namespace std::placeholders;
+       auto start_location_engine_handler = std::bind(&LocationManager::start,
+                       location_mgr, _1, _2);
+       dbus_adapter.setStartLocationEngine(start_location_engine_handler);
+
+       auto stop_location_engine_handler = std::bind(&LocationManager::stop,
+                       location_mgr);
+       dbus_adapter.setStopLocationEngine(stop_location_engine_handler);
+
+       auto get_own_node_handler = std::bind(&LocationManager::getCurrentPosition,
+                       location_mgr);
+       dbus_adapter.setGetOwnNode(get_own_node_handler);
+
+       auto get_nodes_handler = std::bind(&LocationManager::getNodeMap,
+                       location_mgr);
+       dbus_adapter.setGetNetworkInfo(get_nodes_handler);
+}
+
+static void __set_dbus_signal(UwbDbusManager *dbus_manager, LocationManager &location_mgr)
+{
+       using namespace std::placeholders;
+
+       auto emit_position_updated = std::bind(&UwbDbusManager::emitPositionUpdatedSignal,
+                       dbus_manager, _1);
+       location_mgr.setPositionUpdatedCallback(emit_position_updated);
+
+       auto emit_node_added = std::bind(&UwbDbusManager::emitNodeAddedSignal,
+                       dbus_manager, _1);
+       location_mgr.setNodeAddedCallback(emit_node_added);
+
+       auto emit_node_updated = std::bind(&UwbDbusManager::emitNodeUpdatedSignal,
+                       dbus_manager, _1);
+       location_mgr.setNodeUpdatedCallback(emit_node_updated);
+
+       auto emit_node_removed = std::bind(&UwbDbusManager::emitNodeRemovedSignal,
+                       dbus_manager, _1);
+       location_mgr.setNodeRemovedCallback(emit_node_removed);
+}
+
 int main(int argc, char *argv[])
 {
-       UwbPluginManager *plugin_manager = new UwbPluginManager();
-       UwbRangePlugin *range_plugin = new UwbRangePlugin();
-       UwbManager *manager = new UwbManager(nullptr, range_plugin);
-       UwbIfaceHandler *iface_handler = new UwbIfaceHandler(manager);
-       UwbDbusManager *dbus_manager = new UwbDbusManager();
-
-#if defined(TIZEN_ARCH_64)
-       plugin_manager->load(DWM1001_PLUGIN_64BIT_PATH);
-#else
-       plugin_manager->load(DWM1001_PLUGIN_PATH);
-#endif
-       range_plugin->init(plugin_manager);
-       manager->setDefaultConfigurations();
-       dbus_manager->init(iface_handler);
+       __UWB_LOG_FUNC_ENTER__;
+
+       std::shared_ptr<UwbManagerNamespace::UwbRangePlugin> range_plugin =
+                               std::make_shared<UwbManagerNamespace::UwbRangePlugin>();
+
+       UwbManagerNamespace::UwbPluginManager plugin_manager;
+       int ret = plugin_manager.load(range_plugin);
+       if (ret != 0) {
+               __UWB_LOG_FUNC_EXIT__;
+               return -1;
+       }
+
+       UwbManagerNamespace::UwbConfig uwb_config(range_plugin);
+       UwbManagerNamespace::UwbNetwork uwb_network(range_plugin);
+       std::shared_ptr<UwbManagerNamespace::UwbPosition> uwb_position =
+                               std::make_shared<UwbManagerNamespace::UwbPosition>(range_plugin);
+       UwbManagerNamespace::LocationManager location_manager(uwb_position);
+
+       ret = uwb_config.loadConfiguration();
+       if (ret != 0) {
+               __UWB_LOG_FUNC_EXIT__;
+               return -1;
+       }
+
+       UwbManagerNamespace::UwbDbusManager dbus_manager;
+       UwbManagerNamespace::UwbDbusIfaceAdapter dbus_adapter;
+       dbus_manager.init();
+
+       __set_device_control_handler(range_plugin.get(), dbus_adapter);
+       __set_configuration_handler(&uwb_config, dbus_adapter);
+       __set_network_handler(&uwb_network, dbus_adapter);
+       __set_position_handler(uwb_position.get(), dbus_adapter);
+       __set_location_handler(&location_manager, dbus_adapter);
+       __set_dbus_signal(&dbus_manager, location_manager);
+
+       auto dbus_acquired_cb =  std::bind(&UwbDbusIfaceAdapter::init,
+                       &dbus_adapter, std::placeholders::_1, std::placeholders::_2);
+       dbus_manager.setBusAcquiredCallback(dbus_acquired_cb);
+
+       __set_signal_handler();
 
        main_loop = g_main_loop_new(NULL, FALSE);
        g_main_loop_run(main_loop);
+       g_main_loop_unref(main_loop);
 
-       dbus_manager->deinit();
-       plugin_manager->unload();
-
-       delete iface_handler;
-       delete dbus_manager;
-       delete range_plugin;
-       delete plugin_manager;
+       dbus_manager.deinit();
+       uwb_network.disable();
+       plugin_manager.unload(range_plugin);
 
        return 0;
 }