From b2b63f7e67d2aeb3ce2a1d7ff2c4cdc81f3bcc74 Mon Sep 17 00:00:00 2001 From: "minsuk1.choi" Date: Fri, 20 Mar 2015 16:04:55 +0900 Subject: [PATCH] Implement: Notification Manager - Resource Hosting Problem: Not implemented How: resource hosting feature added. All review comments fixed. Change-Id: I5e980f4c16519ba30a6c10313c50ab436fc99810 Signed-off-by: minsuk1.choi Reviewed-on: https://gerrit.iotivity.org/gerrit/489 Tested-by: jenkins-iotivity Reviewed-by: Uze Choi --- service/SConscript | 2 +- .../NotificationManager/include/HostingConfig.h | 66 -- .../NotificationManager/include/HostingHandler.h | 67 -- .../NotificationManager/include/HostingInterface.h | 48 - .../include/NotificationManager.h | 83 -- .../include/OICPlatformConfig.h | 51 - .../include/RegistrationManager.h | 56 - .../NotificationManager/include/ResourceManager.h | 76 -- .../include/VirtualRepresentation.h | 82 -- .../NotificationManager/include/hosting.h | 67 ++ .../NotificationManager/include/virtualResource.h | 248 ++++ .../NotificationManager/src/HostingHandler.cpp | 220 ---- .../NotificationManager/src/HostingInterface.cpp | 148 --- .../src/NotificationManager.cpp | 162 --- .../NotificationManager/src/OICPlatformConfig.cpp | 80 -- .../src/RegistrationManager.cpp | 109 -- .../NotificationManager/src/ResourceManager.cpp | 232 ---- .../src/VirtualRepresentation.cpp | 231 ---- .../NotificationManager/src/hosting.c | 1250 ++++++++++++++++++++ .../NotificationManager/src/linux/main.cpp | 66 -- .../NotificationManager/src/virtualResource.c | 411 +++++++ service/notification-manager/SConscript | 15 +- .../SampleApp/linux/SConscript | 10 +- .../SampleApp/linux/notificationManager/main.c | 97 ++ .../linux/sampleConsumer/SampleConsumer.cpp | 310 ++--- .../linux/sampleProvider/SampleProvider.cpp | 139 ++- 26 files changed, 2354 insertions(+), 1972 deletions(-) delete mode 100644 service/notification-manager/NotificationManager/include/HostingConfig.h delete mode 100644 service/notification-manager/NotificationManager/include/HostingHandler.h delete mode 100644 service/notification-manager/NotificationManager/include/HostingInterface.h delete mode 100644 service/notification-manager/NotificationManager/include/NotificationManager.h delete mode 100644 service/notification-manager/NotificationManager/include/OICPlatformConfig.h delete mode 100644 service/notification-manager/NotificationManager/include/RegistrationManager.h delete mode 100644 service/notification-manager/NotificationManager/include/ResourceManager.h delete mode 100644 service/notification-manager/NotificationManager/include/VirtualRepresentation.h create mode 100755 service/notification-manager/NotificationManager/include/hosting.h create mode 100755 service/notification-manager/NotificationManager/include/virtualResource.h delete mode 100644 service/notification-manager/NotificationManager/src/HostingHandler.cpp delete mode 100644 service/notification-manager/NotificationManager/src/HostingInterface.cpp delete mode 100644 service/notification-manager/NotificationManager/src/NotificationManager.cpp delete mode 100644 service/notification-manager/NotificationManager/src/OICPlatformConfig.cpp delete mode 100644 service/notification-manager/NotificationManager/src/RegistrationManager.cpp delete mode 100644 service/notification-manager/NotificationManager/src/ResourceManager.cpp delete mode 100644 service/notification-manager/NotificationManager/src/VirtualRepresentation.cpp create mode 100755 service/notification-manager/NotificationManager/src/hosting.c delete mode 100644 service/notification-manager/NotificationManager/src/linux/main.cpp create mode 100644 service/notification-manager/NotificationManager/src/virtualResource.c create mode 100644 service/notification-manager/SampleApp/linux/notificationManager/main.c mode change 100644 => 100755 service/notification-manager/SampleApp/linux/sampleProvider/SampleProvider.cpp diff --git a/service/SConscript b/service/SConscript index cfd6f83..aa33776 100644 --- a/service/SConscript +++ b/service/SConscript @@ -20,6 +20,6 @@ if target_os not in targets_csdk_only: SConscript('protocol-plugin/SConscript') # Build notification manager project -# SConscript('notification-manager/SConscript') + SConscript('notification-manager/SConscript') #else: # SConscript('notification-manager/SampleApp/arduino/SConscript') diff --git a/service/notification-manager/NotificationManager/include/HostingConfig.h b/service/notification-manager/NotificationManager/include/HostingConfig.h deleted file mode 100644 index fa55ad2..0000000 --- a/service/notification-manager/NotificationManager/include/HostingConfig.h +++ /dev/null @@ -1,66 +0,0 @@ -//****************************************************************** -// -// Copyright 2014 Samsung Electronics 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. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= - -#ifndef HOSTINGCONFIG_H_ -#define HOSTINGCONFIG_H_ - -#include "NotificationManager.h" - - -enum class HostingMode -{ - None, - ManualMode, - AutomaticMode, -}; - -enum class AutomaticMethod -{ - None, - NetworkStatusChange, - Timer, - DeviceStatus -}; - -enum class NotifyMethod -{ - Frequence, - Equalization, - Granularity, - None -}; - -enum class NotifyFrequency -{ - OnTime, - Periodically, - None -}; - - -struct HostingConfig -{ - HostingMode hostingMode; - AutomaticMethod automaticMethod; - NotifyMethod notifyMethod; - NotifyFrequency frequency; -}; - -#endif /* HOSTINGCONFIG_H_ */ diff --git a/service/notification-manager/NotificationManager/include/HostingHandler.h b/service/notification-manager/NotificationManager/include/HostingHandler.h deleted file mode 100644 index 3f2170f..0000000 --- a/service/notification-manager/NotificationManager/include/HostingHandler.h +++ /dev/null @@ -1,67 +0,0 @@ -//****************************************************************** -// -// Copyright 2014 Samsung Electronics 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. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= - -#ifndef HOSTINGHANDLER_H_ -#define HOSTINGHANDLER_H_ - -#include "NotificationManager.h" - -class HostingHandler -{ - public: - - static void initialize(); - static void initialize(HostingConfig cfg); - static HostingHandler *getInstance(); - - void setHostingConfig(HostingConfig cfg); - - void changeHostingMode(HostingMode hostingMode, AutomaticMethod autoMethod = AutomaticMethod::None); - void changeAutomaticHostingMethod(AutomaticMethod autoMethod); - void changeNotifiyMethod(NotifyMethod notifyMethod); - void changeNotifyFrequencyType(NotifyFrequency notifyFrequency); - - private: - - HostingHandler(); - ~HostingHandler(); - - static HostingHandler *s_instance; - static mutex s_mutexForCreation; - - HostingConfig hostingCfg; - - static std::function< void(bool isHosting) > s_findHostingCandidate; - static std::function< void(std::string) > s_addExtraStr; - static std::function< void(std::shared_ptr< OCResource > resource) > s_startHosting; - static std::function< void(OCResourceHandle resourceHandle) > s_notify; - - void startFindHost(); - void onObserve(AttributeMap &AttMap, OCResourceHandle resourceHandle); - void onFoundCandidate(std::shared_ptr< OCResource > resource); - - void runAutomaticHosting(AutomaticMethod autoMethod); - void stopAutomaticHosting(); - - void notifyFrequence(OCResourceHandle resourceHandle); - -}; - -#endif /* HOSTINGHANDLER_H_ */ diff --git a/service/notification-manager/NotificationManager/include/HostingInterface.h b/service/notification-manager/NotificationManager/include/HostingInterface.h deleted file mode 100644 index 7af558f..0000000 --- a/service/notification-manager/NotificationManager/include/HostingInterface.h +++ /dev/null @@ -1,48 +0,0 @@ -//****************************************************************** -// -// Copyright 2014 Samsung Electronics 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. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= - -#ifndef HOSTINGINTERFACE_H_ -#define HOSTINGINTERFACE_H_ - -#include "NotificationManager.h" - -using namespace OC; -using namespace OCPlatform; - -class HostingInterface -{ - - public: - HostingInterface(); - ~HostingInterface(); - - int setOnFoundHostingCandidate( - std::function< void(std::shared_ptr< OCResource > resource) > func); - int setOnObserve(std::function< void(AttributeMap &inputAttMap, OCResourceHandle resourceHandle) > - func); - - int setFindHosting(std::function< void(bool isHosting) > &func); - int setStartHosting(std::function< void(std::shared_ptr< OCResource > resource) > &func); - int setNotifyObservers(std::function< void(OCResourceHandle resourceHandle) > &func); - int setAddExtraStr(std::function< void(std::string) > &func); - -}; - -#endif /* HOSTINGINTERFACE_H_ */ diff --git a/service/notification-manager/NotificationManager/include/NotificationManager.h b/service/notification-manager/NotificationManager/include/NotificationManager.h deleted file mode 100644 index e4909de..0000000 --- a/service/notification-manager/NotificationManager/include/NotificationManager.h +++ /dev/null @@ -1,83 +0,0 @@ -//****************************************************************** -// -// Copyright 2014 Samsung Electronics 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. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= - -#ifndef NOTIFICATIONMANAGER_H_ -#define NOTIFICATIONMANAGER_H_ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "OICPlatformConfig.h" -#include "HostingConfig.h" -#include "ResourceManager.h" -#include "RegistrationManager.h" -#include "VirtualRepresentation.h" -#include "HostingHandler.h" -#include "HostingInterface.h" - -#include -#include -#include -#include -#include -#include -#include - -#define IN -#define OUT - -using namespace OC; -using namespace OCPlatform; - -const std::string VIRTURL_TAG = "/virtual"; - -class NotificationManager -{ - - private: - - NotificationManager(); - NotificationManager(HostingConfig cfg); - ~NotificationManager(); - - static NotificationManager *s_instance; - static mutex s_mutexForCreation; - - int getNetInfo(IN int &sck, IN struct ifreq *item, OUT std::string &ip_addres); - bool scanAndGetNetworkInterface(OUT std::string &ip_addres); - - public: - - static void initialize(); - static void initialize(HostingConfig cfg); - static NotificationManager *getInstance(); - - void registerHostingEventListener(); - -}; - -#endif /* NOTIFICATIONMANAGER_H_ */ diff --git a/service/notification-manager/NotificationManager/include/OICPlatformConfig.h b/service/notification-manager/NotificationManager/include/OICPlatformConfig.h deleted file mode 100644 index fffd71c..0000000 --- a/service/notification-manager/NotificationManager/include/OICPlatformConfig.h +++ /dev/null @@ -1,51 +0,0 @@ -//****************************************************************** -// -// Copyright 2014 Samsung Electronics 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. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -#ifndef OICPLATFORMCONFIG_H_ -#define OICPLATFORMCONFIG_H_ - -#include "OCApi.h" -#include "OCPlatform.h" -#include "OCResource.h" -#include "OCResourceRequest.h" -#include "OCResourceResponse.h" -#include "ocstack.h" - -using namespace OC; -using namespace OCPlatform; - -class OICPlatformConfig -{ - private: - - OICPlatformConfig(); - ~OICPlatformConfig(); - - static OICPlatformConfig *s_instance; - static mutex s_mutexForCreation; - static PlatformConfig s_cfg; - - public: - - void initialize(); - static OICPlatformConfig *getInstance(); - void setIP(std::string ipaddress); -}; - -#endif /* OICPLATFORMCONFIG_H_ */ diff --git a/service/notification-manager/NotificationManager/include/RegistrationManager.h b/service/notification-manager/NotificationManager/include/RegistrationManager.h deleted file mode 100644 index 2ffc57d..0000000 --- a/service/notification-manager/NotificationManager/include/RegistrationManager.h +++ /dev/null @@ -1,56 +0,0 @@ -//****************************************************************** -// -// Copyright 2014 Samsung Electronics 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. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= - -#ifndef REGISTRATIONMANAGER_H_ -#define REGISTRATIONMANAGER_H_ - -#include "NotificationManager.h" - -using namespace OC; -using namespace OCPlatform; - -class OICPlatformConfig; -class VirtualRepresentation; - -class RegistrationManager -{ - - private: - RegistrationManager(); - ~RegistrationManager(); - - static RegistrationManager *s_instance; - static mutex s_mutexForCreation; - - public: - - static RegistrationManager *getInstance(); - - bool registerNMResource(VirtualRepresentation &resourceObject , - std::shared_ptr< OCResource > resource); - - int addResource(); - int removeResource(); - int updateResource(); - bool unregisterResource(); - -}; - -#endif /* REGISTRATIONMANAGER_H_ */ diff --git a/service/notification-manager/NotificationManager/include/ResourceManager.h b/service/notification-manager/NotificationManager/include/ResourceManager.h deleted file mode 100644 index bd8c257..0000000 --- a/service/notification-manager/NotificationManager/include/ResourceManager.h +++ /dev/null @@ -1,76 +0,0 @@ -//****************************************************************** -// -// Copyright 2014 Samsung Electronics 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. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= - -#ifndef RESOURCEMANAGER_H_ -#define RESOURCEMANAGER_H_ - -#include "NotificationManager.h" - -using namespace OC; -using namespace OCPlatform; - - -class OICPlatformConfig; -class VirtualRepresentation; - -class ResourceManager -{ - - private: - ResourceManager(); - ~ResourceManager(); - - static ResourceManager *s_instance; - static mutex s_mutexForCreation; - static std::list< VirtualRepresentation > s_resourceList; - static std::string s_extraStr; - - void foundResourceforhosting(std::shared_ptr< OCResource > resource); - - void checkResourceDBPolicy(); - void saveResourceDB(); - - public: - - std::function< void(std::shared_ptr< OCResource > resource) > m_onFoundforHosting; - std::function< void(AttributeMap &inputAttMap, OCResourceHandle resourceHandle) > m_onObserve; - std::function< void(OCResourceHandle resourceHandle) > m_notify; - - static ResourceManager *getInstance(); - - void findNMResource(bool isHosting); - - void onFoundforHostingDefault(std::shared_ptr< OCResource > resource); - void onObserveDefault(AttributeMap &inputAttMap, OCResourceHandle resourceHandle); - void notifyObserversDefault(OCResourceHandle resourceHandle); - - void startHosting(std::shared_ptr< OCResource > resource); - void notifyObservers(OCResourceHandle resourceHandle); - - VirtualRepresentation findVirtualRepresentation(std::string uri); - AttributeMap copyAttributeMap(AttributeMap &inputAttMap); - bool isEmptyAttributeMap(AttributeMap &inputAttMap); - void printAttributeMap(AttributeMap &inputAttMap); - - void addExtraStr(std::string str); - std::string getExtraStr(); -}; - -#endif /* RESOURCEMANAGER_H_ */ diff --git a/service/notification-manager/NotificationManager/include/VirtualRepresentation.h b/service/notification-manager/NotificationManager/include/VirtualRepresentation.h deleted file mode 100644 index aa9d131..0000000 --- a/service/notification-manager/NotificationManager/include/VirtualRepresentation.h +++ /dev/null @@ -1,82 +0,0 @@ -//****************************************************************** -// -// Copyright 2014 Samsung Electronics 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. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= - -#ifndef VIRTUALREPRESENTATION_H_ -#define VIRTUALREPRESENTATION_H_ - -#include "NotificationManager.h" - -#define SUCCESS_RESPONSE 0 - -using namespace OC; -using namespace OCPlatform; -using namespace std; - -class ResourceManager; - -class VirtualRepresentation -{ - - private: - std::string m_virtualUri; - std::string m_originHostIP; - std::string m_resourceTypeName; - std::string m_resourceInterface; - uint8_t m_resourceProperty; - - OCResourceHandle m_resourceHandle; - - static AttributeMap s_attributeMap; - static std::mutex s_mutexAttributeMap; - static std::condition_variable s_conditionAttributeMap; - static bool m_isReadyAttributeMap; - - int getRepresentation(OCRepresentation &oc); - - public: - - std::string getUri(); - std::string getHostIP(); - std::string getResourceTypeName(); - std::string getResourceInterface(); - uint8_t getResourceProperty(); - OCResourceHandle getResourceHandle(); - - int setUri(std::string uri); - int setHostIP(std::string ip); - int setResourceTypeName(std::string typeName); - int setResourceInterface(std::string interface); - int setResourceProperty(uint8_t property); - int setResourceHandle(OCResourceHandle &handle); - - public: - VirtualRepresentation(); - virtual ~VirtualRepresentation(); - - std::string addVirtualTag(std::string uri); - - OCEntityHandlerResult entityHandler(const std::shared_ptr request , - const std::shared_ptr response); - void onObserve(const HeaderOptions &headerOption, const OCRepresentation &rep , - const int eCode , const int sequenceNumber); - -}; - -#endif /* VIRTUALREPRESENTATION_H_ */ diff --git a/service/notification-manager/NotificationManager/include/hosting.h b/service/notification-manager/NotificationManager/include/hosting.h new file mode 100755 index 0000000..a291638 --- /dev/null +++ b/service/notification-manager/NotificationManager/include/hosting.h @@ -0,0 +1,67 @@ +//****************************************************************** +// +// Copyright 2015 Samsung Electronics 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. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef _HOSTING_H_ +#define _HOSTING_H_ + +// Standard API +#include +#include +#include + +// Iotivity Base CAPI +#include "ocstack.h" +#include "ocsocket.h" +#include "logger.h" + + +#define HOSTING_TAG PCF("Hosting") + +/** + * + * Start resource coordinator + * + * @brief create mirrorResourceList and discover coordinatee candidate. + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_INVALID_CALLBACK - invalid callback function pointer + * OC_STACK_INVALID_METHOD - invalid resource method + * OC_STACK_INVALID_URI - invalid required or reference URI + * OC_STACK_INVALID_QUERY - number of resource types specified for filtering presence + * notifications exceeds @ref MAX_PRESENCE_FILTERS. + * OC_STACK_ERROR - otherwise error(initialized value) + */ +OCStackResult OICStartCoordinate(); + +/** + * + * stop resource coordinator + * + * @brief delete mirrorResourceList used while coordinating + * + * @return + * OC_STACK_ERROR - otherwise error(initialized value) + */ +OCStackResult OICStopCoordinate(); + + + +#endif diff --git a/service/notification-manager/NotificationManager/include/virtualResource.h b/service/notification-manager/NotificationManager/include/virtualResource.h new file mode 100755 index 0000000..6844dbd --- /dev/null +++ b/service/notification-manager/NotificationManager/include/virtualResource.h @@ -0,0 +1,248 @@ +//****************************************************************** +// +// Copyright 2015 Samsung Electronics 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. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef _VIRTUAL_RESOURCE_H_ +#define _VIRTUAL_RESOURCE_H_ + +#include +#include +#include + +#include "ocstack.h" +#include "ocsocket.h" +#include "logger.h" + +#include "cJSON.h" +#define TAG PCF("virtualResource") + +//----------------------------------------------------------------------------- +// Typedefs +//----------------------------------------------------------------------------- + +/** +* Resource Coordinating Parameter Type +*/ +typedef enum +{ + OIC_SOURCE_ADDRESS = 0, + OIC_MIRROR_ADDRESS = 1, + OIC_REQUEST_HANDLE = 0, + OIC_MIRROR_HANDLE = 1, + OIC_NONE = 255 +} OICResourceCoordinatorParamType; + +/** +* Property of Mirror Resource +*/ +typedef struct MirrorResourceProperty +{ + int countResourceType; + int countInterface; + char **resourceType; + char **resourceInterfaceName; +} MirrorResourceProperty; + +/** +* Mirror Resource Object +*/ +typedef struct MirrorResource +{ + OCDoHandle resourceHandle[2]; // OIC_REQUEST_HANDLE = 0, OIC_VIRTUAL_HANDLE = 1 + char *address[2]; // OIC_SOURCE_ADDRESS = 0, OIC_VIRTUAL_ADDRESS = 1 + cJSON *rep; + char *uri; + MirrorResourceProperty prop; + + unsigned char isAliveCheck; + + struct MirrorResource *next; + + /* + * for multiple resource + */ +// virtualRepresentation rep2; + +} MirrorResource; + +/** +* Mirror Resource List +*/ +typedef struct MirrorResourceList +{ + struct MirrorResource *headerNode; + struct MirrorResource *tailNode; +} MirrorResourceList; + +//----------------------------------------------------------------------------- +// Function prototypes +//----------------------------------------------------------------------------- + +/** +* Create an empty mirror resource list +* +* @return +* pointer to empty Mirror resource list +*/ +MirrorResourceList *createMirrorResourceList(); + +/** +* Create an empty mirror resource. +* +* @return +* pointer to empty mirror resource +*/ +MirrorResource *createMirrorResource(); + +/** +* Insert the mirror resource in the mirror resource list +* +* @param mirrorResourceList - pointer to the target mirror resource list that mirror resource will be inserted +* @param mirrorResource - pointer to mirror resource list to be inserted +* @return +* OIC_HOSTING_INVALID_PARAM - if list or vResource is null +* OIC_HOSTING_OK - successfully inserted +*/ +OCStackResult insertMirrorResource(MirrorResourceList *mirrorResourceList, + MirrorResource *mirrorResource); + +/** +* Delete the mirror resource from the mirror resource list +* +* @param mirrorResourceList - pointer to the target mirror resource list that mirror resource will be deleted +* @param mirrorResource - pointer to mirror resource list to be deleted +* @return +* OIC_HOSTING_INVALID_PARAM - if mirrorResourceList or mirrorResource is null +* OIC_HOSTING_ERROR - mirror resource delete process error +* OIC_HOSTING_OK - successfully deleted +*/ +OCStackResult deleteMirrorResourceFromList(MirrorResourceList *mirrorResourceList, + MirrorResource *mirrorResource); + +/** +* Destroy mirror resource +* +* @param mirrorResource - pointer to mirror resource to be destroyed +* @return +* OIC_HOSTING_INVALID_PARAM - if mirrorResource is null +* OIC_HOSTING_OK - successfully destroyed +*/ +OCStackResult destroyMirrorResource(MirrorResource *mirrorResource); + +/** +* Destroy mirror resource list +* +* @param mirrorResourceList - pointer to mirror resource list to be destroyed +* @return +* OIC_HOSTING_INVALID_PARAM - if mirrorResourceList is null +* OIC_HOSTING_OK - successfully destroyed +*/ +OCStackResult destroyMirrorResourceList(MirrorResourceList *mirrorResourceList); + +/** +* Find mirror resource using handle +* +* @param mirrorResourceList - pointer to the target mirror resource list that mirror resource will be found +* @param handle - handle value to be found +* @param paramType - handle type to be found +* +* NOTE: every parameter(handle and type) will be compared +* +* @return +* pointer to the found mirror resource +* NULL - mirror resource not found +*/ +MirrorResource *findMirrorResourceUsingHandle(MirrorResourceList *mirrorResourceList, + OCResourceHandle handle, OICResourceCoordinatorParamType paramType); + +/* + * find virtual resource using address function 사용하는지 확인 필요. + */ +//virtualResource *findvResourceUsingAddress(virtualResourceList *list, +// const char *Address, OICResourceHostingParamType type, const char *subData); + +/** +* Find mirror resource using Address and URI +* +* @param mirrorResourceList - pointer to the target mirror resource list that mirror resource will be found +* @param address - pointer to address to be found +* @param paramType - address type to be found +* @param uri - pointer to uri to be found +* +* NOTE: every parameter(address, type and uri) will be compared +* +* @return +* pointer to the found mirror resource +* NULL - invalid input parameter or mirror resource not found +*/ +MirrorResource *findMirrorResourceUsingAddressAndURI(MirrorResourceList *mirrorResourceList, + const char *address, OICResourceCoordinatorParamType paramType, const char *uri); + +/** +* Find mirror resource list using Address and Hosting Parameter Type +* +* @param mirrorResourceList - pointer to the target mirror resource list that mirror resource will be found +* @param address - pointer to address to be found +* @param paramType - address type to be found +* +* NOTE: every parameter(address, type and uri) will be compared +* +* @return +* pointer to the found mirror resource +* NULL - invalid input parameter or mirror resource list not found +*/ +MirrorResourceList *findMirrorResourceListUsingAddress(MirrorResourceList *mirrorResourceList, + const char *address, OICResourceCoordinatorParamType paramType); + +/** +* Copy mirror resource +* +* @param sourceMirrorResource - pointer to source mirror resource +* +* @return +* pointer to the copied mirror resource +*/ +MirrorResource *cloneMirrorResource(MirrorResource *sourceMirrorResource); + +/** +* Eject mirror resource from mirror resource list +* +* @param mirrorResourceList - pointer to the target mirror resource list that mirror resource will be found +* @param mirrorResource - pointer to mirror resource to be ejected +* +* @return +* OIC_HOSTING_INVALID_PARAM - mirrorResourceList or mirrorResource is null +* OIC_HOSTING_OK - ejected successfully +* OIC_HOSTING_ERROR - cannot found mirror resource from mirrorResourceList same with mirrorResource +*/ +OCStackResult ejectMirrorResource(MirrorResourceList *mirrorResourceList, + MirrorResource *mirrorResource); + +/** +* Print mirror resources from mirror resource list +* +* @param mirrorResourceList - pointer to the mirror resource list that mirror resource will be printed +* +* @return +* OIC_HOSTING_INVALID_PARAM - mirrorResourceList is null or mirrorResourceList is empty +* OIC_HOSTING_OK - print successfully +*/ +OCStackResult printMirrorResourceList(MirrorResourceList *mirrorResourceList); + +#endif diff --git a/service/notification-manager/NotificationManager/src/HostingHandler.cpp b/service/notification-manager/NotificationManager/src/HostingHandler.cpp deleted file mode 100644 index fc7696a..0000000 --- a/service/notification-manager/NotificationManager/src/HostingHandler.cpp +++ /dev/null @@ -1,220 +0,0 @@ -//****************************************************************** -// -// Copyright 2014 Samsung Electronics 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. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= - -#include "HostingHandler.h" - -HostingHandler *HostingHandler::s_instance = NULL; -mutex HostingHandler::s_mutexForCreation; - -std::function< void(bool isHosting) > HostingHandler::s_findHostingCandidate; -std::function< void(std::shared_ptr< OCResource > resource) > HostingHandler::s_startHosting; -std::function< void(OCResourceHandle resourceHandle) > HostingHandler::s_notify; -std::function< void(std::string) > HostingHandler::s_addExtraStr; - -HostingHandler::HostingHandler() -{ - -} - -HostingHandler::~HostingHandler() -{ - -} - -HostingHandler *HostingHandler::getInstance() -{ - if (!s_instance) - { - s_mutexForCreation.lock(); - if (!s_instance) - { - s_instance = new HostingHandler(); - } - s_mutexForCreation.unlock(); - } - - return s_instance; -} - -void HostingHandler::initialize() -{ - // Create Hosting Handler instance - HostingHandler *ptr = HostingHandler::getInstance(); - - // Registration interface about hosting - HostingInterface hostingInterface; - - hostingInterface.setFindHosting(ptr->s_findHostingCandidate); - hostingInterface.setStartHosting(ptr->s_startHosting); - hostingInterface.setNotifyObservers(ptr->s_notify); - hostingInterface.setAddExtraStr(ptr->s_addExtraStr); - - hostingInterface.setOnFoundHostingCandidate( - std::function< void(std::shared_ptr< OCResource > resource) >( - std::bind(&HostingHandler::onFoundCandidate , HostingHandler::getInstance() , - std::placeholders::_1))); - hostingInterface.setOnObserve( - std::function< void(AttributeMap &inputAttMap, OCResourceHandle resourceHandle) >( - std::bind(&HostingHandler::onObserve , HostingHandler::getInstance() , std::placeholders::_1, - std::placeholders::_2))); - - ptr->s_addExtraStr("virtual"); - ptr->startFindHost(); -} - -void HostingHandler::initialize(HostingConfig cfg) -{ - // Create Hosting Handler instance - HostingHandler *ptr = HostingHandler::getInstance(); - - // Registration interface about hosting - HostingInterface hostingInterface; - - hostingInterface.setFindHosting(ptr->s_findHostingCandidate); - hostingInterface.setStartHosting(ptr->s_startHosting); - hostingInterface.setNotifyObservers(ptr->s_notify); - hostingInterface.setAddExtraStr(ptr->s_addExtraStr); - - hostingInterface.setOnFoundHostingCandidate( - std::function< void(std::shared_ptr< OCResource > resource) >( - std::bind(&HostingHandler::onFoundCandidate , HostingHandler::getInstance() , - std::placeholders::_1))); - hostingInterface.setOnObserve( - std::function< void(AttributeMap &inputAttMap, OCResourceHandle resourceHandle) >( - std::bind(&HostingHandler::onObserve , HostingHandler::getInstance() , std::placeholders::_1, - std::placeholders::_2))); - - // Set Hosting Config - ptr->setHostingConfig(cfg); - ptr->changeHostingMode(ptr->hostingCfg.hostingMode); - - ptr->s_addExtraStr("virtual"); - ptr->startFindHost(); -} - -void HostingHandler::setHostingConfig(HostingConfig cfg) -{ - hostingCfg.automaticMethod = cfg.automaticMethod; - hostingCfg.frequency = cfg.frequency; - hostingCfg.hostingMode = cfg.hostingMode; - hostingCfg.notifyMethod = cfg.notifyMethod; -} - -void HostingHandler::changeHostingMode(HostingMode hostingMode, AutomaticMethod autoMethod) -{ - if (hostingCfg.hostingMode != hostingMode) - { - hostingCfg.hostingMode = hostingMode; - if (hostingCfg.hostingMode == HostingMode::AutomaticMode) - { - runAutomaticHosting(autoMethod); - } - else - { - stopAutomaticHosting(); - } - } -} - -void HostingHandler::runAutomaticHosting(AutomaticMethod autoMethod) -{ - // TODO Triggering from Event Listener. - if (hostingCfg.automaticMethod != autoMethod) - { - hostingCfg.automaticMethod = autoMethod; - switch (hostingCfg.automaticMethod) - { - case AutomaticMethod::None: - break; - case AutomaticMethod::Timer: - case AutomaticMethod::DeviceStatus: - case AutomaticMethod::NetworkStatusChange: - default: - break; - } - } -} - -void HostingHandler::stopAutomaticHosting() -{ - if (hostingCfg.automaticMethod != AutomaticMethod::None) - { -// TODO - } -} - -void HostingHandler::changeAutomaticHostingMethod(AutomaticMethod autoMethod) -{ -// TODO -} -void HostingHandler::changeNotifiyMethod(NotifyMethod notifyMethod) -{ -// TODO -} -void HostingHandler::changeNotifyFrequencyType(NotifyFrequency notifyFrequency) -{ -// TODO -} - -void HostingHandler::startFindHost() -{ - if (hostingCfg.hostingMode != HostingMode::None) - { - s_findHostingCandidate(true); - } -} - -void HostingHandler::onFoundCandidate(std::shared_ptr< OCResource > resource) -{ - // TODO - // Condition of Hosting - s_startHosting(resource); -} - -void HostingHandler::onObserve(AttributeMap &AttMap, OCResourceHandle resourceHandle) -{ - - switch (hostingCfg.notifyMethod) - { - case NotifyMethod::None: - break; - case NotifyMethod::Equalization: - case NotifyMethod::Granularity: - case NotifyMethod::Frequence: - default: - notifyFrequence(resourceHandle); - break; - } -} - -void HostingHandler::notifyFrequence(OCResourceHandle resourceHandle) -{ - - switch (hostingCfg.frequency) - { - case NotifyFrequency::None: - break; - case NotifyFrequency::Periodically: - case NotifyFrequency::OnTime: - default: - s_notify(resourceHandle); - break; - } -} diff --git a/service/notification-manager/NotificationManager/src/HostingInterface.cpp b/service/notification-manager/NotificationManager/src/HostingInterface.cpp deleted file mode 100644 index 638c026..0000000 --- a/service/notification-manager/NotificationManager/src/HostingInterface.cpp +++ /dev/null @@ -1,148 +0,0 @@ -//****************************************************************** -// -// Copyright 2014 Samsung Electronics 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. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= - -#include "HostingInterface.h" - -HostingInterface::HostingInterface() -{ - -} - -HostingInterface::~HostingInterface() -{ - // TODO Auto-generated destructor stub -} - -int HostingInterface::setOnFoundHostingCandidate( - std::function< void(std::shared_ptr< OCResource > resource) > func) -{ - if (func != NULL) - { - try - { - ResourceManager::getInstance()->m_onFoundforHosting = func; - } - catch (exception &e) - { - return false; - } - } - else - { - ResourceManager::getInstance()->m_onFoundforHosting = std::function < - void(std::shared_ptr< OCResource > resource) > ( - std::bind(&ResourceManager::onFoundforHostingDefault , ResourceManager::getInstance() , - std::placeholders::_1)); - } - - return true; -} - -int HostingInterface::setOnObserve( - std::function< void(AttributeMap &inputAttMap, OCResourceHandle resourceHandle) > func) -{ - if (func != NULL) - { - try - { - ResourceManager::getInstance()->m_onObserve = func; - } - catch (exception &e) - { - return false; - } - } - else - { - ResourceManager::getInstance()->m_onObserve = std::function < - void(AttributeMap & inputAttMap, OCResourceHandle resourceHandle) > ( - std::bind(&ResourceManager::onObserveDefault , ResourceManager::getInstance() , - std::placeholders::_1, std::placeholders::_2)); - } - - return true; -} - -int HostingInterface::setNotifyObservers(std::function< void(OCResourceHandle resourceHandle) > - &func) -{ - try - { - func = std::function< void(OCResourceHandle resourceHandle) >( - std::bind(&ResourceManager::notifyObservers , ResourceManager::getInstance() , - std::placeholders::_1)); - } - catch (exception &e) - { - return false; - } - - return true; -} - -int HostingInterface::setStartHosting( - std::function< void(std::shared_ptr< OCResource > resource) > &func) -{ - try - { - func = std::function< void(std::shared_ptr< OCResource > resource) >( - std::bind(&ResourceManager::startHosting , ResourceManager::getInstance() , - std::placeholders::_1)); - } - catch (exception &e) - { - return false; - } - - return true; -} - -int HostingInterface::setFindHosting(std::function< void(bool isHosting) > &func) -{ - try - { - func = std::function< void(bool isHosting) >( - std::bind(&ResourceManager::findNMResource , - ResourceManager::getInstance() , - std::placeholders::_1)); - } - catch (exception &e) - { - return false; - } - - return true; -} - -int HostingInterface::setAddExtraStr(std::function< void(std::string) > &func) -{ - try - { - func = std::function< void(std::string str) >( - std::bind(&ResourceManager::addExtraStr , ResourceManager::getInstance() , - std::placeholders::_1)); - } - catch (exception &e) - { - return false; - } - - return true; -} diff --git a/service/notification-manager/NotificationManager/src/NotificationManager.cpp b/service/notification-manager/NotificationManager/src/NotificationManager.cpp deleted file mode 100644 index 8f1d391..0000000 --- a/service/notification-manager/NotificationManager/src/NotificationManager.cpp +++ /dev/null @@ -1,162 +0,0 @@ -//****************************************************************** -// -// Copyright 2014 Samsung Electronics 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. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= - -#include "NotificationManager.h" - -NotificationManager *NotificationManager::s_instance = NULL; -mutex NotificationManager::s_mutexForCreation; - -NotificationManager::NotificationManager() -{ - -} - -NotificationManager::NotificationManager(HostingConfig cfg) -{ - -} - -NotificationManager::~NotificationManager() -{ - -} - -void NotificationManager::initialize() -{ - // find local ip address - std::string ipAddress; - NotificationManager::getInstance()->scanAndGetNetworkInterface(ipAddress); - - // set ip address - OICPlatformConfig::getInstance()->setIP(ipAddress); - - // initialize hosting handler - HostingHandler::initialize(); -} - -void NotificationManager::initialize(HostingConfig cfg) -{ - // find local ip address - std::string ipAddress; - NotificationManager::getInstance()->scanAndGetNetworkInterface(ipAddress); - - // set ip address - OICPlatformConfig::getInstance()->setIP(ipAddress); - - // initialize hosting handler - HostingHandler::initialize(cfg); -} - -void NotificationManager::registerHostingEventListener() -{ - // TODO : Initial HostingEventListener (v1.0) -} - -NotificationManager *NotificationManager::getInstance() -{ - if (!s_instance) - { - s_mutexForCreation.lock(); - if (!s_instance) - { - s_instance = new NotificationManager(); - } - s_mutexForCreation.unlock(); - } - - return s_instance; -} - -int NotificationManager::getNetInfo(IN int &sck, IN struct ifreq *item, OUT std::string &ip_addres) -{ - struct ifreq temp_ifr; - memset(&temp_ifr, 0, sizeof(temp_ifr)); - strcpy(temp_ifr.ifr_name, item->ifr_name); - - if (ioctl(sck, SIOCGIFFLAGS, &temp_ifr)) - { - return -1; - } - - if (!((temp_ifr.ifr_flags & IFF_UP) && (temp_ifr.ifr_flags & IFF_RUNNING))) - { - return -1; - } - - std::string ip(inet_ntoa(((struct sockaddr_in *) &item->ifr_addr)->sin_addr)); - if (ip.empty()) - { - return -1; - } - - if (ip.find("127.0.0") == 0) - { - return -1; - } - - ip_addres = ip; - return 0; -} - -bool NotificationManager::scanAndGetNetworkInterface(OUT std::string &ip_addres) -{ - while (1) - { - char buf[1024] = { 0, }; - struct ifconf ifc; - struct ifreq *ifr; - int sck; - int interfaces; - int i; - - sck = socket(AF_INET, SOCK_DGRAM, 0); - if (sck < 0) - { - usleep(10); - continue; - } - - ifc.ifc_len = sizeof(buf); - ifc.ifc_buf = buf; - if (ioctl(sck, SIOCGIFCONF, &ifc) < 0) - { - printf( "SIOCGIFCONF Failed "); - close(sck); - usleep(10); - continue; - } - - ifr = ifc.ifc_req; - interfaces = ifc.ifc_len / sizeof(struct ifreq); - - for (i = 0; i < interfaces; i++) - { - if ( getNetInfo(sck, &ifr[i], ip_addres) == 0 ) - { - return 0; - } - continue; - } - close(sck); - usleep(10); - } - - return 0; -} diff --git a/service/notification-manager/NotificationManager/src/OICPlatformConfig.cpp b/service/notification-manager/NotificationManager/src/OICPlatformConfig.cpp deleted file mode 100644 index 0dd4ed5..0000000 --- a/service/notification-manager/NotificationManager/src/OICPlatformConfig.cpp +++ /dev/null @@ -1,80 +0,0 @@ -//****************************************************************** -// -// Copyright 2014 Samsung Electronics 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. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= - -#include "OICPlatformConfig.h" - - -OICPlatformConfig *OICPlatformConfig::s_instance = NULL; -mutex OICPlatformConfig::s_mutexForCreation; -//OCPlatform *OICPlatformConfig::s_nmOCPlatform = NULL; -PlatformConfig OICPlatformConfig::s_cfg; -//(ServiceType::InProc, ModeType::Both,"", 5683, QualityOfService::NonConfirmable); - -OICPlatformConfig::OICPlatformConfig() -{ - // TODO Auto-generated constructor stub - -} - -OICPlatformConfig::~OICPlatformConfig() -{ - // TODO Auto-generated destructor stub -} - - -OICPlatformConfig *OICPlatformConfig::getInstance() -{ - if (!s_instance) - { - s_mutexForCreation.lock(); - if (!s_instance) - { - s_instance = new OICPlatformConfig(); - Configure(s_cfg); - } - s_mutexForCreation.unlock(); - } - - return s_instance; -} - -//void OICPlatformConfig::getOCPlatform() -//{ -//// if(!s_nmOCPlatform) -//// { -//// if(s_cfg.ipAddress.empty()) -//// { -//// return NULL; -//// } -//// s_nmOCPlatform = new OCPlatform(s_cfg); -//// Configure(s_cfg); -//// } -//// return s_nmOCPlatform; -//} - -void OICPlatformConfig::initialize() -{ - -} - -void OICPlatformConfig::setIP(std::string ipaddress) -{ - s_cfg.ipAddress = ipaddress; -} diff --git a/service/notification-manager/NotificationManager/src/RegistrationManager.cpp b/service/notification-manager/NotificationManager/src/RegistrationManager.cpp deleted file mode 100644 index c019b6b..0000000 --- a/service/notification-manager/NotificationManager/src/RegistrationManager.cpp +++ /dev/null @@ -1,109 +0,0 @@ -//****************************************************************** -// -// Copyright 2014 Samsung Electronics 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. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= - -#include "RegistrationManager.h" - -RegistrationManager *RegistrationManager::s_instance = NULL; -mutex RegistrationManager::s_mutexForCreation; - -RegistrationManager::RegistrationManager() -{ -} - -RegistrationManager::~RegistrationManager() -{ -} - -RegistrationManager *RegistrationManager::getInstance() -{ - if (!s_instance) - { - s_mutexForCreation.lock(); - if (s_instance) - { - s_instance = new RegistrationManager(); - } - s_mutexForCreation.unlock(); - } - - return s_instance; -} - -int RegistrationManager::addResource() -{ - return 0; -} - -int RegistrationManager::removeResource() -{ - return 0; -} - -int RegistrationManager::updateResource() -{ - return 0; -} - -bool RegistrationManager::registerNMResource(VirtualRepresentation &resourceObject , - std::shared_ptr< OCResource > resource) -{ - std::string uri = resourceObject.getUri(); - std::string type = resourceObject.getResourceTypeName(); - std::string interface = resourceObject.getResourceInterface(); - - OCResourceHandle resourceHandle; - - OCStackResult result; - result = registerResource(resourceHandle , uri , type , - interface , - std::function < - OCEntityHandlerResult(const std::shared_ptr< OCResourceRequest > request , - const std::shared_ptr< OCResourceResponse > response) > ( - std::bind(&VirtualRepresentation::entityHandler , resourceObject , - std::placeholders::_1 , std::placeholders::_2)) , - resourceObject.getResourceProperty()); - - resourceObject.setResourceHandle(resourceHandle); - - if (OC_STACK_OK != result) - { - return false; - } - else - { - QueryParamsMap queryParmaMap; - resource->observe(ObserveType::Observe , queryParmaMap , - std::function < - void(const HeaderOptions headerOption, - const OCRepresentation & rep , const int &eCode , - const int &sequenceNumber) > ( - std::bind(&VirtualRepresentation::onObserve , resourceObject , - std::placeholders::_1 , std::placeholders::_2 , - std::placeholders::_3 , std::placeholders::_4))); - } - - return true; -} - -bool RegistrationManager::unregisterResource() -{ - return true; -} - diff --git a/service/notification-manager/NotificationManager/src/ResourceManager.cpp b/service/notification-manager/NotificationManager/src/ResourceManager.cpp deleted file mode 100644 index 8e35655..0000000 --- a/service/notification-manager/NotificationManager/src/ResourceManager.cpp +++ /dev/null @@ -1,232 +0,0 @@ -//****************************************************************** -// -// Copyright 2014 Samsung Electronics 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. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= - -#include "ResourceManager.h" - -ResourceManager *ResourceManager::s_instance = NULL; -mutex ResourceManager::s_mutexForCreation; -std::list< VirtualRepresentation > ResourceManager::s_resourceList; - -std::string ResourceManager::s_extraStr; - -ResourceManager::ResourceManager() -{ - m_onFoundforHosting = NULL; - m_onObserve = NULL; - m_notify = NULL; -} - -ResourceManager::~ResourceManager() -{ -} - -ResourceManager *ResourceManager::getInstance() -{ - if (!s_instance) - { - s_mutexForCreation.lock(); - if (!s_instance) - { - s_instance = new ResourceManager(); - } - s_mutexForCreation.unlock(); - } - return s_instance; -} - -VirtualRepresentation ResourceManager::findVirtualRepresentation(std::string uri) -{ - - VirtualRepresentation retObject; - - for (auto it = s_resourceList.begin() ; it != s_resourceList.end() ; it++) - { - if (it->getUri().compare(uri) == 0) - { - retObject = *it; - return retObject; - } - } - - return retObject; -} - -void ResourceManager::findNMResource(bool isHosting) -{ - if (isHosting) - { - findResource("" , "coap://224.0.1.187/oc/core", - std::function< void(std::shared_ptr< OCResource > resource) >( - std::bind(&ResourceManager::foundResourceforhosting , ResourceManager::getInstance() , - std::placeholders::_1))); - } -} - -void ResourceManager::foundResourceforhosting(std::shared_ptr< OCResource > resource) -{ - try - { - if (resource) - { - if (resource->uri().find("/a/NM") != std::string::npos) - { - ResourceManager::getInstance()->m_onFoundforHosting(resource); - } - } - else - { - // TODO - } - - } - catch (std::exception &e) - { - } -} - -void ResourceManager::startHosting(std::shared_ptr< OCResource > resource) -{ - - cout << "start hosting" << endl; - VirtualRepresentation tmp = findVirtualRepresentation( resource->uri() ); - - if ( !tmp.getUri().empty() ) - { - return; - } - - VirtualRepresentation resourceObject; - resourceObject.setUri(resource->uri()); - - std::cout << "resourceObject uri: " << resourceObject.getUri() << std::endl; - - std::string resourceHostIP; - std::string resourceType; - std::string resourceInterface; - uint8_t resourceProperty; - - resourceHostIP = resource->host(); - resourceType = *(resource->getResourceTypes().data()); - resourceInterface = *(resource->getResourceInterfaces().data()); - resourceProperty = (OC_DISCOVERABLE | resource->isObservable()); - - resourceObject.setHostIP(resourceHostIP); - resourceObject.setResourceTypeName(resourceType); - resourceObject.setResourceInterface(resourceInterface); - resourceObject.setResourceProperty(resourceProperty); - - RegistrationManager::getInstance()->registerNMResource(resourceObject , resource); - - s_resourceList.push_back(resourceObject); - -} - -void ResourceManager::notifyObservers(OCResourceHandle resourceHandle) -{ - OCStackResult result = OC_STACK_OK; - - result = notifyAllObservers(resourceHandle); - - if (OC_STACK_NO_OBSERVERS == result) - { - // No observers. - // TODO - } -} - -AttributeMap ResourceManager::copyAttributeMap(AttributeMap &inputAttMap) -{ - - AttributeMap retAttMap; - - retAttMap = inputAttMap; -// for(auto it = inputAttMap.begin() ; it != inputAttMap.end() ; ++it) -// { -// AttributeValues tmpVal; -// -// for(auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr) -// { -// std::string tmpStr; -// -// tmpStr.append(*valueItr); -// -// tmpVal.push_back(tmpStr); -// } -// retAttMap[it->first] = tmpVal; -// -// } - return retAttMap; -} - -bool ResourceManager::isEmptyAttributeMap(AttributeMap &inputAttMap) -{ - for (auto it = inputAttMap.begin() ; it != inputAttMap.end() ; ++it) - { - if (inputAttMap.find(it->first) == inputAttMap.end()) - { - return true; - } - } - return false; -} - -void ResourceManager::onFoundforHostingDefault(std::shared_ptr< OCResource > resource) -{ - ResourceManager::getInstance()->startHosting(resource); -} -void ResourceManager::onObserveDefault(AttributeMap &inputAttMap , OCResourceHandle resourceHandle) -{ - ResourceManager::getInstance()->notifyObservers(resourceHandle); -} - -void ResourceManager::printAttributeMap(AttributeMap &inputAttMap) -{ - for (auto it = inputAttMap.begin() ; it != inputAttMap.end() ; ++it) - { - std::cout << "\tAttribute name: " << it->first << " value: "; - - for (auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr) - { - std::cout << "\t" << *valueItr << " "; - } - - std::cout << std::endl; - } -} - -void ResourceManager::addExtraStr(std::string str) -{ - s_extraStr = str; -} - -std::string ResourceManager::getExtraStr() -{ - return s_extraStr; -} - -void ResourceManager::checkResourceDBPolicy() -{ - -} - -void ResourceManager::saveResourceDB() -{ - -} diff --git a/service/notification-manager/NotificationManager/src/VirtualRepresentation.cpp b/service/notification-manager/NotificationManager/src/VirtualRepresentation.cpp deleted file mode 100644 index 313d61f..0000000 --- a/service/notification-manager/NotificationManager/src/VirtualRepresentation.cpp +++ /dev/null @@ -1,231 +0,0 @@ -//****************************************************************** -// -// Copyright 2014 Samsung Electronics 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. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= - -#include "VirtualRepresentation.h" - -AttributeMap VirtualRepresentation::s_attributeMap; - -std::mutex VirtualRepresentation::s_mutexAttributeMap; -std::condition_variable VirtualRepresentation::s_conditionAttributeMap; -bool VirtualRepresentation::m_isReadyAttributeMap = true; - -int g_num = 0; - -VirtualRepresentation::VirtualRepresentation() -{ - m_resourceHandle = NULL; - m_resourceProperty = 0x00; -} - -VirtualRepresentation::~VirtualRepresentation() -{ -} - -std::string VirtualRepresentation::addVirtualTag(std::string uri) -{ - std::string ret = uri; - return ret.append(VIRTURL_TAG + std::to_string(g_num++)); -} - -OCResourceHandle VirtualRepresentation::getResourceHandle() -{ - return m_resourceHandle; -} - -std::string VirtualRepresentation::getUri() -{ - return m_virtualUri; -} - -std::string VirtualRepresentation::getHostIP() -{ - return m_originHostIP; -} - -std::string VirtualRepresentation::getResourceTypeName() -{ - return m_resourceTypeName; -} - -std::string VirtualRepresentation::getResourceInterface() -{ - return m_resourceInterface; -} - -uint8_t VirtualRepresentation::getResourceProperty() -{ - return m_resourceProperty; -} - -int VirtualRepresentation::setUri(std::string uri) -{ - m_virtualUri = addVirtualTag(uri); - return true; -} - -int VirtualRepresentation::setHostIP(std::string ip) -{ - m_originHostIP = ip; - return true; -} - -int VirtualRepresentation::setResourceTypeName(std::string typeName) -{ - m_resourceTypeName = typeName; - return true; -} - -int VirtualRepresentation::setResourceInterface(std::string interface) -{ - m_resourceInterface = interface; - return true; -} - -int VirtualRepresentation::setResourceProperty(uint8_t property) -{ - m_resourceProperty = property; - return true; -} - -int VirtualRepresentation::setResourceHandle(OCResourceHandle &handle) -{ - m_resourceHandle = handle; - return true; -} - -int VirtualRepresentation::getRepresentation(OCRepresentation &oc) -{ - oc.setAttributeMap(s_attributeMap); - oc.setUri(this->getUri().c_str()); - return true; -} - -OCEntityHandlerResult VirtualRepresentation::entityHandler(const std::shared_ptr - request , const std::shared_ptr response) -{ - if (request) - { - std::string requestType = request->getRequestType(); - int requestFlag = request->getRequestHandlerFlag(); - - if (requestFlag == RequestHandlerFlag::InitFlag) - { - } - - else if (requestFlag == RequestHandlerFlag::RequestFlag) - { - if ( (requestType == "GET") && response ) - { - - std::unique_lock< std::mutex > lck(s_mutexAttributeMap); - while (!m_isReadyAttributeMap) - { - s_conditionAttributeMap.wait(lck); - } - m_isReadyAttributeMap = false; - - OCRepresentation rep; - getRepresentation(rep); - - response->setErrorCode(200); - response->setResourceRepresentation(rep , DEFAULT_INTERFACE); - - m_isReadyAttributeMap = true; - s_conditionAttributeMap.notify_all(); - } - else if (requestType == "PUT") - { - // TODO - } - else if (requestType == "POST") - { - // TODO - } - else if (requestType == "DELETE") - { - // TODO - } - else - { - // TODO - } - } - else if (requestFlag == RequestHandlerFlag::InitFlag) - { - // TODO - } - else if (requestFlag == RequestHandlerFlag::ObserverFlag) - { - // TODO - cout << "requestFlag == RequestHandlerFlag::ObserverFlag\n"; - } - else - { - // requestFlag is not [Request, Init, Observer] - // TODO - } - } - else - { - // Param(request) is empty. - // TODO - } - return OC_EH_OK; -} - -void VirtualRepresentation::onObserve(const HeaderOptions &headerOption, - const OCRepresentation &rep , const int eCode , const int sequenceNumber) -{ - if (eCode == SUCCESS_RESPONSE) - { - AttributeMap inputAttributeMap = rep.getAttributeMap(); - if (ResourceManager::getInstance()->isEmptyAttributeMap(inputAttributeMap)) - { - return; - } - VirtualRepresentation tmpObj = *this; - if (!tmpObj.getUri().empty()) - { - AttributeMap tmpAttMap = ResourceManager::getInstance()->copyAttributeMap(inputAttributeMap); - { - std::unique_lock< std::mutex > lck(s_mutexAttributeMap); - while (!m_isReadyAttributeMap) - { - s_conditionAttributeMap.wait(lck); - } - m_isReadyAttributeMap = false; - s_attributeMap = tmpAttMap; - m_isReadyAttributeMap = true; - s_conditionAttributeMap.notify_all(); - } - - if (ResourceManager::getInstance()->m_onObserve) - { - ResourceManager::getInstance()->m_onObserve(inputAttributeMap, tmpObj.getResourceHandle()); - } - } - } - else - { - // Check the error. - // TODO - } - cout << "VirtualRepresentation::onObserve Out\n"; -} diff --git a/service/notification-manager/NotificationManager/src/hosting.c b/service/notification-manager/NotificationManager/src/hosting.c new file mode 100755 index 0000000..f65b4ec --- /dev/null +++ b/service/notification-manager/NotificationManager/src/hosting.c @@ -0,0 +1,1250 @@ +//****************************************************************** +// +// Copyright 2014 Samsung Electronics 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. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +// Hosting Header +#include "hosting.h" +#include "virtualResource.h" + +// External Lib +#include "cJSON.h" + +/* + * internal function + */ +/////////////////////////////////////////////////////////////////////////////////////////////////// +static MirrorResourceList *s_mirrorResourceList = NULL; + +#define OIC_COORDINATING_FLAG "/hosting" +#define OIC_STRING_MAX_VALUE 100 + +#define OC_DEFAULT_ADDRESS "224.0.1.187" +#define OC_DEFAULT_PORT "5683" +#define OC_COORDINATING_QUERY "/oc/core?rt=Resource.Hosting" +#define OC_PRESENCE_URI "/oc/presence" +#define DEFAULT_CONTEXT_VALUE 0x99 + +/* + * Presence Func for hosting + */ + +/** + * + * request presence for coordinating + * + * @param[in] originResourceAddr - pointer of address string of original resource + * + * @return + * OC_STACK_OK + * OC_STACK_ERROR + */ +OCStackResult requestPresence(char *originResourceAddr); + +/** + * + * callback function that call when response of presence request received + * + * @param[in] originResourceAddr - pointer of address string of original resource + * + * @return + * OC_STACK_OK + * OC_STACK_ERROR + */ +OCStackApplicationResult requestPresenceCB(void *context, OCDoHandle handle, + OCClientResponse *clientResponse); + +/** + * + * build mirror resource list by clientResponse + * + * @param[in] handle - not using... + * @param[in] clientResponse - client response that mirror resources are stored + * + * @return + * pointer of result MirrorResourceList + */ +MirrorResourceList *buildMirrorResourceList(OCDoHandle handle, OCClientResponse *clientResponse); + +/** + * + * build mirror resource by JSON payload + * + * @param[in] ocArray_sub - pointer of json payload string + * + * @return + * pointer of result MirrorResource + */ +MirrorResource *buildMirrorResource(cJSON *ocArray_sub); + +/** + * + * This method is used when setting queryUri, registering callback function and starting OCDoResource() Function in order to find Coordinatee Candidate + * + * @brief discover coordinatee candidate + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_INVALID_CALLBACK - invalid callback function pointer + * OC_STACK_INVALID_METHOD - invalid resource method + * OC_STACK_INVALID_URI - invalid required or reference URI + * OC_STACK_INVALID_QUERY - number of resource types specified for filtering presence + * notifications exceeds @ref MAX_PRESENCE_FILTERS. + * OC_STACK_ERROR - otherwise error(initialized value) + */ +int requestCoordinateeCandidateDiscovery(char *address); + +/** + * + * This method is used to add a coordinator resource callback method in mirrorResourceList when host resource discovered. + * + * @param[in] context + * Context for callback method + * @param[in] handle + * Handle to an @ref OCDoResource invocation. + * @param[in] clientResponse + * Response from queries to remote servers. Queries are made by calling the @ref OCDoResource API. + * + * @brief callback for receiving response of discoverCoordinateeCandidate() + * + * @return + * PRINT("Callback Context for DISCOVER query recvd successfully\n") - context is DEFAULT_CONTEXT_VALUE + * call the buildMirrorResource() method - clientResponse is not NULL && clientResponse->result is OC_STACK_OK + * OC_STACK_KEEP_TRANSACTION - otherwise case + */ +OCStackApplicationResult requestCoordinateeCandidateDiscoveryCB(void *context, OCDoHandle handle, + OCClientResponse *clientResponse); + +/** + * + * This method is used when setting queryUri, registering callback function and starting OCDoResource() Function in order to request resource coordination + * + * @brief + * + * @param[in] mirrorResource + * mirrorResource for using in order to request resource coordination + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_INVALID_CALLBACK - invalid callback function pointer + * OC_STACK_INVALID_METHOD - invalid resource method + * OC_STACK_INVALID_URI - invalid required or reference URI + * OC_STACK_INVALID_QUERY - number of resource types specified for filtering presence + * notifications exceeds @ref MAX_PRESENCE_FILTERS. + * OC_STACK_ERROR - otherwise error(initialized value) + */ +OCStackResult requestResourceObservation(MirrorResource *mirrorResource); + +/** + * + * This method is used to handle callback of requestCoordination method. + * + * @param[in] context + * Context for callback method + * @param[in] handle + * Handle to update mirror resource and check errorResponse + * @param[in] clientResponse + * Response from queries to remote servers. Queries are made by calling the @ref OCDoResource API. + * + * @brief callback when receiving response of coordinating requestion. + * + * @todo diverge return value + * + * @return + * + * OC_STACK_KEEP_TRANSACTION - otherwise case + */ +OCStackApplicationResult requestResourceObservationCB(void *context, OCDoHandle handle, + OCClientResponse *clientResponse); + +/** + * + * This method is used to check resource validation and delete resource if it is not exist(not alive). + * + * @brief check mirror resource is alive + * + * @param[in] requestHandle + * Handle to check mirror resource + * + * @return + * + * OC_STACK_DELETE_TRANSACTION - otherwise case + */ +OCStackApplicationResult checkResourceValidation(OCDoHandle requestHandle); + +/** + * + * register Mirror resource in the base resource list + * + * @param[in] requestHandle + * Handle to check mirror resource + * + * @return + * OC_STACK_OK + * OC_STACK_ERROR + */ +OCStackResult registerMirrorResource(MirrorResource *node); + +/** + * + * update resource + * + * @param[in] sourceHandle - handle of source resource + * @param[in] payload - pointer of json payload string that update items stored + * + * @return + * pointer of mirror resource. return NULL if there is any error. + */ +MirrorResource *updateMirrorResource(OCDoHandle sourceHandle, const char *payload); + +/** + * + * build response payload + * + * @param[in] ehRequest - pointer of handler of entity handler request that to be responded + * + * @return + * OC_STACK_OK + * OC_STACK_ERROR + */ +char *buildResponsePayload (OCEntityHandlerRequest *ehRequest); + +/** + * + * handle "Get" request + * + * @param[in] ehRequest - pointer of handler of entity handler request + * @param[out] payload - pointer of payload to be responded + * @param[in] maxPayloadSize - size of payload + * + * @return + * OC_EH_OK - success to copy response payload + * OC_EH_ERROR - error to copy response payload + */ +OCEntityHandlerResult handleGetRequest (OCEntityHandlerRequest *ehRequest, + char *payload, uint16_t maxPayloadSize); + +/** + * + * handle request for non-existing resource + * + * @param[in] ehRequest - pointer of handler of entity handler request + * @param[out] payload - pointer of payload to be responded + * @param[in] maxPayloadSize - size of payload + * + * @return + * OC_EH_RESOURCE_DELETED - resource deleted + */ +OCEntityHandlerResult handleNonExistingResourceRequest(OCEntityHandlerRequest *ehRequest, + char *payload, uint16_t maxPayloadSize); + +/** + * + * callback function that called when source resource changed + * + * @param[in] flag - entity handler flag + * @param[in] entityHandlerRequest - pointer of entity handler request + * + * @return + * OC_EH_OK + * OC_EH_ERROR + */ +OCEntityHandlerResult resourceEntityHandlerCB (OCEntityHandlerFlag flag, + OCEntityHandlerRequest *entityHandlerRequest); + +/** + * + * request that address is alive + * + * @param[in] address - pointer of address string + * + * @return + * OC_STACK_OK + * OC_STACK_ERROR + */ +OCStackResult requestIsAlive(const char *address); + +/** + * + * get string value of OCStackResult code + * + * @param[in] result - OCStringResult code + * + * @return + * pointer of result string value + */ +const char *getResultString(OCStackResult result); + +/* + * for Lite Device Side + */ + +/** + * + * register resource as coordinatable + * + * @param[in] handle - resource handle + * @param[in] resourceTypeName - resource type name + * @param[in] resourceInterfaceName - resource interface name + * @param[in] resourceUri - resource URI + * @param[in] entityHandler - entity handler + * @param[in] resourceProperties - resource properties + * + * @return + * pointer of result string value + */ +OCStackResult registerResourceAsCoordinatable(OCResourceHandle *handle, + const char *resourceTypeName, const char *resourceInterfaceName, + const char *resourceUri, OCEntityHandler entityHandler, uint8_t resourceProperties); + +/////////////////////////////////////////////////////////////////////////////////////////////////// + + +OCStackResult registerResourceAsCoordinatable(OCResourceHandle *handle, + const char *resourceTypeName, + const char *resourceInterfaceName, + const char *resourceUri, + OCEntityHandler entityHandler, + uint8_t resourceProperties) +{ + + char *coordinatingURI = (char *)malloc(sizeof(char) * (strlen(resourceUri) + strlen( + OIC_COORDINATING_FLAG))); + sprintf(coordinatingURI, "%s%s", resourceUri, OIC_COORDINATING_FLAG); + + OC_LOG_V(DEBUG, HOSTING_TAG, "requiedUri+coordinatingFlag = %s\n", coordinatingURI); + + OCStackResult result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName, + coordinatingURI, entityHandler, resourceProperties); + + return result; +} + +/* + * for Hosting Device Side + */ +OCStackResult OICStartCoordinate() +{ + int result = OC_STACK_ERROR; + + s_mirrorResourceList = createMirrorResourceList(); +// result = discoverCoordinateeCandidate(NULL); + result = requestPresence(OC_DEFAULT_ADDRESS); + + return result; +} + +OCStackResult OICStopCoordinate() +{ + OCStackResult result = OC_STACK_ERROR; + + destroyMirrorResourceList(s_mirrorResourceList); + + return result; +} + +int requestCoordinateeCandidateDiscovery(char *sourceResourceAddress) +{ + OCStackResult result; + OCCallbackData cbData; + OCDoHandle handle; + + /* Start a discovery query*/ + char queryUri[OIC_STRING_MAX_VALUE] = { '\0' }; + if (sourceResourceAddress == NULL) + { + sprintf(queryUri, "coap://%s:%s%s", OC_DEFAULT_ADDRESS, OC_DEFAULT_PORT , OC_COORDINATING_QUERY); + } + else + { + sprintf(queryUri, "coap://%s%s", sourceResourceAddress , OC_COORDINATING_QUERY); + } + + cbData.cb = requestCoordinateeCandidateDiscoveryCB; + cbData.context = (void *)DEFAULT_CONTEXT_VALUE; + cbData.cd = NULL; + + result = OCDoResource(&handle, OC_REST_GET, queryUri, OIC_COORDINATING_FLAG, 0, OC_LOW_QOS, &cbData, + NULL, 0); + if (result != OC_STACK_OK) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "OCStack resource error\n"); + } + OC_LOG_V(DEBUG, HOSTING_TAG, "Host Resource Finding...\n"); + return result; +} + +OCStackResult requestPresence(char *sourceResourceAddress) +{ + OCStackResult result = OC_STACK_OK; + OCCallbackData cbData; + OCDoHandle handle; + + if (sourceResourceAddress == NULL) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "SourceResourceAddress is not available.\n"); + result = OC_STACK_ERROR; + return result; + } + + cbData.cb = requestPresenceCB; + cbData.context = (void *)DEFAULT_CONTEXT_VALUE; + cbData.cd = NULL; + + char queryUri[OIC_STRING_MAX_VALUE] = { '\0' }; + sprintf(queryUri, "coap://%s%s", sourceResourceAddress , OC_PRESENCE_URI); + OC_LOG_V(DEBUG, HOSTING_TAG, "initializePresenceForCoordinating Query : %s\n", queryUri); + + result = OCDoResource(&handle, OC_REST_PRESENCE, queryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0); + + if (result != OC_STACK_OK) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "initializePresenceForCoordinating error\n"); + return result; + } + // Need presenceHandle manager + + OC_LOG_V(DEBUG, HOSTING_TAG, "Success initializePresenceForCoordinating\n"); + + return result; +} + +OCStackApplicationResult requestPresenceCB(void *context, OCDoHandle handle, + OCClientResponse *clientResponse) +{ + uint8_t remoteIpAddress[4]; + uint16_t remotePortNumber; + char address[OIC_STRING_MAX_VALUE] = { '\0' }; + + if (context == (void *) DEFAULT_CONTEXT_VALUE) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "\tCallback Context for presence CB recv successfully\n"); + } + if (clientResponse) + { + OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddress, + remoteIpAddress + 1, remoteIpAddress + 2, remoteIpAddress + 3); + OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNumber); + OC_LOG_V(DEBUG, HOSTING_TAG, "\tStackResult: %s\n", getResultString(clientResponse->result)); + OC_LOG_V(DEBUG, HOSTING_TAG, "\tStackResult: %d\n", clientResponse->result); + OC_LOG_V(DEBUG, HOSTING_TAG, + "\tPresence Device =============> Presence %s @ %d.%d.%d.%d:%d\n", + clientResponse->resJSONPayload, remoteIpAddress[0], remoteIpAddress[1], + remoteIpAddress[2], remoteIpAddress[3], remotePortNumber); + + sprintf(address, "%d.%d.%d.%d:%d", remoteIpAddress[0], remoteIpAddress[1], + remoteIpAddress[2], remoteIpAddress[3], remotePortNumber); + if (clientResponse->result == OC_STACK_OK) + { + requestCoordinateeCandidateDiscovery(address); + } + //delete logic +// else if(clientResponse->result == OC_STACK_PRESENCE_STOPPED + if (clientResponse->result == OC_STACK_PRESENCE_STOPPED + || clientResponse->result == OC_STACK_PRESENCE_TIMEOUT + || clientResponse->result == OC_STACK_PRESENCE_DO_NOT_HANDLE) + { + requestIsAlive(address); + } + + } + return OC_STACK_KEEP_TRANSACTION; +} + +OCStackApplicationResult requestCoordinateeCandidateDiscoveryCB(void *ctx, OCDoHandle handle, + OCClientResponse *clientResponse) +{ + OC_LOG_V(DEBUG, HOSTING_TAG, "Found Host Resource\n"); + OCStackResult ret; + + if (ctx == (void *) DEFAULT_CONTEXT_VALUE) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "Callback Context for DISCOVER query recvd successfully\n"); + } + if (clientResponse && clientResponse->result == OC_STACK_OK) + { + //TODO: checkError + + MirrorResourceList *vList = buildMirrorResourceList(handle, clientResponse); + if (vList != NULL) + { + + if (vList->headerNode == NULL) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "This Discover Response is empty\n"); + return OC_STACK_KEEP_TRANSACTION; + } + + // register All of VirtualResource + char *address = vList->headerNode->address[OIC_SOURCE_ADDRESS]; + while (vList->headerNode) + { + MirrorResource *mirrorResource = vList->headerNode; + ret = ejectMirrorResource(vList, mirrorResource); + mirrorResource->next = NULL; + OC_LOG_V(DEBUG, HOSTING_TAG, "register virtual resource uri : %s\n", mirrorResource->uri); + if (ret != OC_STACK_OK) + { + continue; + } + + ret = registerMirrorResource(mirrorResource); + if (ret != OC_STACK_OK) + { + continue; + } + + ret = insertMirrorResource(s_mirrorResourceList, mirrorResource); + if (ret != OC_STACK_OK) + { + OCDeleteResource(mirrorResource->resourceHandle[OIC_MIRROR_HANDLE]); + continue; + } + printMirrorResourceList(s_mirrorResourceList); + + ret = requestResourceObservation(mirrorResource); + if (ret != OC_STACK_OK) + { + OCDeleteResource(mirrorResource->resourceHandle[OIC_MIRROR_HANDLE]); + deleteMirrorResourceFromList(s_mirrorResourceList, mirrorResource); + continue; + } + } + destroyMirrorResourceList(vList); + if (ret != OC_STACK_OK) + { + return OC_STACK_KEEP_TRANSACTION; + } + } + } + return OC_STACK_KEEP_TRANSACTION; +} + +MirrorResourceList *buildMirrorResourceList(OCDoHandle handle, OCClientResponse *clientResponse) +{ + + cJSON *discoveryJson = cJSON_CreateObject(); + discoveryJson = cJSON_Parse((char *)clientResponse->resJSONPayload); + + cJSON *ocArray = cJSON_GetObjectItem(discoveryJson, "oc"); + char *ocArray_str = cJSON_PrintUnformatted(ocArray); + + if ( strstr(ocArray_str, "[{}") == ocArray_str ) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "invalid payload : %s\n", ocArray_str); + cJSON_Delete(discoveryJson); + return NULL; + } + + MirrorResourceList *retList = createMirrorResourceList(); + + uint8_t remoteIpAddr[4]; + uint16_t remotePortNum; + + OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr, + remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3); + OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNum); + + char sourceaddr[OIC_STRING_MAX_VALUE] = {'\0'}; + sprintf(sourceaddr, "%d.%d.%d.%d:%d", remoteIpAddr[0], remoteIpAddr[1], + remoteIpAddr[2], remoteIpAddr[3], remotePortNum); + + OC_LOG_V(DEBUG, HOSTING_TAG, "Host Device =============> Discovered %s @ %s\n", + clientResponse->resJSONPayload, sourceaddr); + + int i = 0; + int arraySize = cJSON_GetArraySize(ocArray); + for (i = 0; i < arraySize; ++i) + { + cJSON *ocArray_sub = cJSON_GetArrayItem(ocArray, i); + MirrorResource *mirrorResource = buildMirrorResource(ocArray_sub); + + if (mirrorResource == NULL) + { + continue; + } + mirrorResource->address[OIC_SOURCE_ADDRESS] = (char *)malloc(sizeof(char) * OIC_STRING_MAX_VALUE); + sprintf(mirrorResource->address[OIC_SOURCE_ADDRESS], "%s", sourceaddr); + + mirrorResource->address[OIC_MIRROR_ADDRESS] = (char *)malloc(sizeof(char) * OIC_STRING_MAX_VALUE); + sprintf(mirrorResource->address[OIC_MIRROR_ADDRESS], "0.0.0.0:00"); + + if (OC_STACK_OK != insertMirrorResource(retList, mirrorResource)) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "buildVirtualResourceList : insert resource fail\n"); + } + } + + cJSON_Delete(discoveryJson); + return retList; +} + +MirrorResource *buildMirrorResource(cJSON *ocArray_sub) +{ + + char temp[OIC_STRING_MAX_VALUE] = {'\0'}; + strcpy(temp, cJSON_GetObjectItem(ocArray_sub, "href")->valuestring); + + if ( strstr(temp, OIC_COORDINATING_FLAG) ) + { + + uint8_t remoteIpAddr[4]; + uint16_t remotePortNum; + + MirrorResource *mirrorResource = createMirrorResource(); + + mirrorResource->uri = (char *)malloc(sizeof(char) * OIC_STRING_MAX_VALUE); + strncpy(mirrorResource->uri, temp, strlen(temp) - strlen(OIC_COORDINATING_FLAG)); + mirrorResource->uri[strlen(temp) - strlen(OIC_COORDINATING_FLAG)] = '\0'; + OC_LOG_V(DEBUG, HOSTING_TAG, "VirtualResource URI : %s\n", mirrorResource->uri); + + cJSON *inArray_sub = cJSON_GetObjectItem(ocArray_sub, "prop"); + + cJSON *tmpJSON; + int sizetemp; + int k = 0; + + tmpJSON = cJSON_GetObjectItem(inArray_sub, "rt"); + sizetemp = cJSON_GetArraySize(tmpJSON); + mirrorResource->prop.countResourceType = sizetemp; + mirrorResource->prop.resourceType = (char **)malloc(sizeof(char *)*sizetemp); + for (k = 0; k < sizetemp; ++k) + { + mirrorResource->prop.resourceType[k] = (char *)malloc(sizeof(char) * OIC_STRING_MAX_VALUE); + memset(mirrorResource->prop.resourceType[k], '\0', OIC_STRING_MAX_VALUE); + strcpy(mirrorResource->prop.resourceType[k], cJSON_GetArrayItem(tmpJSON, k)->valuestring); + } + + tmpJSON = cJSON_GetObjectItem(inArray_sub, "if"); + sizetemp = cJSON_GetArraySize(tmpJSON); + mirrorResource->prop.countInterface = sizetemp; + mirrorResource->prop.resourceInterfaceName = (char **)malloc(sizeof(char *)*sizetemp); + for (k = 0; k < sizetemp; ++k) + { + mirrorResource->prop.resourceInterfaceName[k] = (char *)malloc(sizeof(char) * OIC_STRING_MAX_VALUE); + memset(mirrorResource->prop.resourceInterfaceName[k], '\0', OIC_STRING_MAX_VALUE); + strcpy(mirrorResource->prop.resourceInterfaceName[k], cJSON_GetArrayItem(tmpJSON, k)->valuestring); + } + return mirrorResource; + } + else + { + return NULL; + } +} + +OCStackResult registerMirrorResource(MirrorResource *mirrorResource) +{ + OCStackResult result = OC_STACK_ERROR; + + MirrorResource *foundMirrorResource = findMirrorResourceUsingAddressAndURI(s_mirrorResourceList, + mirrorResource->address[OIC_MIRROR_ADDRESS], OIC_MIRROR_ADDRESS, mirrorResource->uri); + if (foundMirrorResource != NULL) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "Already registered resource\n"); + goto RETURN_ERR; + } + + result = OCCreateResource(&(mirrorResource->resourceHandle[OIC_MIRROR_HANDLE]), + mirrorResource->prop.resourceType[0], + mirrorResource->prop.resourceInterfaceName[0], + mirrorResource->uri, + resourceEntityHandlerCB, + OC_DISCOVERABLE | OC_OBSERVABLE); + + printf("mirror resource uri : %s\n", mirrorResource->uri); + + if (result != OC_STACK_OK) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "error return = %s\n", getResultString(result)); + mirrorResource->next = NULL; + destroyMirrorResource(mirrorResource); + goto RETURN_ERR; + } + + if (mirrorResource->prop.countResourceType > 1) + { + int i = 0; + for (i = 1; i < mirrorResource->prop.countResourceType; ++i) + { + result = OCBindResourceTypeToResource(mirrorResource->resourceHandle[OIC_MIRROR_HANDLE], + mirrorResource->prop.resourceType[i]); + if (result != OC_STACK_OK) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "Virtual Resource Registration Fail : BindResourceType\n"); + OCDeleteResource(mirrorResource->resourceHandle[OIC_MIRROR_HANDLE]); + mirrorResource->next = NULL; + destroyMirrorResource(mirrorResource); + goto RETURN_ERR; + } + } + } + + if (mirrorResource->prop.countInterface > 1) + { + int i = 0; + for (i = 1; i < mirrorResource->prop.countInterface; ++i) + { + result = OCBindResourceInterfaceToResource(mirrorResource->resourceHandle[OIC_MIRROR_HANDLE], + mirrorResource->prop.resourceInterfaceName[i]); + if (result != OC_STACK_OK) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "Virtual Resource Registration Fail : BindResourceInterfaceName\n"); + OCDeleteResource(mirrorResource->resourceHandle[OIC_MIRROR_HANDLE]); + mirrorResource->next = NULL; + destroyMirrorResource(mirrorResource); + goto RETURN_ERR; + } + } + } + + OC_LOG_V(DEBUG, HOSTING_TAG, "Mirror Resource Registration Success\n"); + OC_LOG_V(DEBUG, HOSTING_TAG, "Mirror Resource uri : %s\n", mirrorResource->uri); + OC_LOG_V(DEBUG, HOSTING_TAG, "Mirror Resource source address : %s\n", + mirrorResource->address[OIC_SOURCE_ADDRESS]); + OC_LOG_V(DEBUG, HOSTING_TAG, "Mirror Resource virtual address : %s\n", + mirrorResource->address[OIC_MIRROR_ADDRESS]); + return result; + +RETURN_ERR: + OC_LOG_V(DEBUG, HOSTING_TAG, "Mirror Resource Registration Fail\n"); + return result; +} + +OCStackResult requestResourceObservation(MirrorResource *mirrorResource) +{ + OCStackResult result; + OCCallbackData cbData; + + cbData.cb = requestResourceObservationCB; + cbData.context = (void *)DEFAULT_CONTEXT_VALUE; + cbData.cd = NULL; + + char query[OIC_STRING_MAX_VALUE] = {'\0'}; + sprintf(query, "coap://%s%s%s", mirrorResource->address[OIC_SOURCE_ADDRESS], mirrorResource->uri, + OIC_COORDINATING_FLAG); + + result = OCDoResource(&mirrorResource->resourceHandle[OIC_REQUEST_HANDLE], OC_REST_OBSERVE, query, + 0, NULL, + OC_HIGH_QOS, &cbData, NULL, 0); + + if (result != OC_STACK_OK) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "OCDoResource returns error %s with method %d\n", + getResultString(result), OC_REST_OBSERVE); + } + + return result; +} + +OCStackApplicationResult requestResourceObservationCB(void *context, OCDoHandle handle, + OCClientResponse *clientResponse) +{ + if (context == (void *)DEFAULT_CONTEXT_VALUE) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "Callback Context for OBS query recvd successfully\n"); + } + + if (clientResponse && clientResponse->result != OC_STACK_OK) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "observeCB result error = %s\n", + getResultString(clientResponse->result)); + return checkResourceValidation(handle); + } + + else if (clientResponse && clientResponse->result == OC_STACK_OK) + { + OC_LOG_V(DEBUG, HOSTING_TAG, + "<=============\nCallback Context for OBSERVE notification recvd successfully\n"); + OC_LOG_V(DEBUG, HOSTING_TAG, "SEQUENCE NUMBER: %d\n", clientResponse->sequenceNumber); + OC_LOG_V(DEBUG, HOSTING_TAG, "JSON = %s \n=============> Obs Response\n", + clientResponse->resJSONPayload); + + MirrorResource *foundMirrorResource = findMirrorResourceUsingHandle(s_mirrorResourceList, + handle, OIC_REQUEST_HANDLE); + if (foundMirrorResource == NULL) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "Cannot found Mirror Resource : Fail\n"); + return OC_STACK_DELETE_TRANSACTION; + } + + if (foundMirrorResource->isAliveCheck) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "This response is Alive Check : Keep resource %s%s\n", + foundMirrorResource->address[OIC_SOURCE_ADDRESS], foundMirrorResource->uri); + deleteMirrorResourceFromList(s_mirrorResourceList, foundMirrorResource); + return OC_STACK_KEEP_TRANSACTION; + } + + foundMirrorResource = updateMirrorResource(handle, clientResponse->resJSONPayload); + + if ( OC_STACK_OK != OCNotifyAllObservers(foundMirrorResource->resourceHandle[OIC_MIRROR_HANDLE], + OC_HIGH_QOS) ) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "Notify Mirror Resource's Subscriber : Fail\n"); + } + else + { + OC_LOG_V(DEBUG, HOSTING_TAG, "Notify Mirror Resource's Subscriber : Success\n"); + } + + if (clientResponse->sequenceNumber == OC_OBSERVE_REGISTER) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "This also serves as a registration confirmation\n"); + } + else if (clientResponse->sequenceNumber == OC_OBSERVE_DEREGISTER) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "This also serves as a deregistration confirmation\n"); + return OC_STACK_DELETE_TRANSACTION; + } + else if (clientResponse->sequenceNumber == OC_OBSERVE_NO_OPTION) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "This also tells you that registration/deregistration failed\n"); + return OC_STACK_DELETE_TRANSACTION; + } + } + return OC_STACK_KEEP_TRANSACTION; +} + +OCStackApplicationResult checkResourceValidation(OCDoHandle handle) +{ + MirrorResource *foundMirrorResource = findMirrorResourceUsingHandle(s_mirrorResourceList, + handle, OIC_REQUEST_HANDLE); + + if (foundMirrorResource == NULL) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "Not found any error mirror resource.\n"); + return OC_STACK_DELETE_TRANSACTION; + } + + if (foundMirrorResource->isAliveCheck) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "This response is Alive Check : Expired resource %s%s\n", + foundMirrorResource->address[OIC_SOURCE_ADDRESS], foundMirrorResource->uri); + MirrorResource *deletedMirrorResource = findMirrorResourceUsingAddressAndURI(s_mirrorResourceList, + foundMirrorResource->uri, OIC_SOURCE_ADDRESS, foundMirrorResource->address[OIC_SOURCE_ADDRESS]); + if (deletedMirrorResource) + { + OCDeleteResource(deletedMirrorResource->resourceHandle[OIC_MIRROR_HANDLE]); + deleteMirrorResourceFromList(s_mirrorResourceList, deletedMirrorResource); + } + } + else + { + OC_LOG_V(DEBUG, HOSTING_TAG, "This response is Expired resource %s%s\n", + foundMirrorResource->address[OIC_SOURCE_ADDRESS], foundMirrorResource->uri); + OCDeleteResource(foundMirrorResource->resourceHandle[OIC_MIRROR_HANDLE]); + } + deleteMirrorResourceFromList(s_mirrorResourceList, foundMirrorResource); + return OC_STACK_DELETE_TRANSACTION; +} + +MirrorResource *updateMirrorResource(OCDoHandle handle, const char *payload) +{ + MirrorResource *foundMirrorResource = findMirrorResourceUsingHandle( + s_mirrorResourceList, handle, OIC_REQUEST_HANDLE); + + if (!foundMirrorResource) + { + // TODO + OC_LOG_V(DEBUG, HOSTING_TAG, "Cannot found Mirror Resource.\n"); + return NULL; + } + + cJSON *observeJson = cJSON_CreateObject(); + observeJson = cJSON_Parse(payload); + + cJSON *ocArray = cJSON_GetObjectItem(observeJson, "oc"); + int arraySize = cJSON_GetArraySize(ocArray); + + cJSON *ocArray_sub = cJSON_GetArrayItem(ocArray, 0); + + cJSON *tempData = cJSON_GetObjectItem(ocArray_sub, "rep"); + char *temp = cJSON_PrintUnformatted(tempData); + + cJSON *repData = cJSON_Parse(temp); + + free(temp); + cJSON_Delete(observeJson); + + if (foundMirrorResource->rep) + { + cJSON_Delete(foundMirrorResource->rep); + foundMirrorResource->rep = NULL; + } + foundMirrorResource->rep = repData; + + cJSON *json = cJSON_CreateObject(); + + char nodeData[OIC_STRING_MAX_VALUE] = {'\0'}; + sprintf(nodeData, "%s", foundMirrorResource->uri); + cJSON_AddStringToObject(json, "href", nodeData); + + cJSON *nodeRep = cJSON_Parse(cJSON_PrintUnformatted(foundMirrorResource->rep)); + cJSON_AddItemToObject(json, "rep", nodeRep); + OC_LOG_V(DEBUG, HOSTING_TAG, "It will notify resource : %s\n", cJSON_PrintUnformatted(json)); + + cJSON_Delete(json); + + return foundMirrorResource; +} + +char *buildResponsePayload (OCEntityHandlerRequest *entityHandlerRequest) +{ + MirrorResource *mirrorResource = findMirrorResourceUsingHandle(s_mirrorResourceList, + entityHandlerRequest->resource, OIC_MIRROR_HANDLE); + if (!mirrorResource) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "Cannot found Mirror Resource.\n"); + return NULL; + } + + OC_LOG_V(DEBUG, HOSTING_TAG, "node's uri : %s\n", mirrorResource->uri); + OC_LOG_V(DEBUG, HOSTING_TAG, "node's source address : %s\n", mirrorResource->address[0]); + OC_LOG_V(DEBUG, HOSTING_TAG, "node's mirror address : %s\n", mirrorResource->address[1]); + OC_LOG_V(DEBUG, HOSTING_TAG, "node's rep : %s\n", cJSON_PrintUnformatted(mirrorResource->rep)); + + cJSON *jsonObject = cJSON_CreateObject(); + + char uriString[OIC_STRING_MAX_VALUE] = {'\0'}; + sprintf(uriString, "%s", mirrorResource->uri); + cJSON_AddStringToObject(jsonObject, "href", uriString); + + cJSON *itemRep = cJSON_Parse(cJSON_PrintUnformatted(mirrorResource->rep)); + cJSON_AddItemToObject(jsonObject, "rep", itemRep); + OC_LOG_V(DEBUG, HOSTING_TAG, "Will response resource : %s\n", cJSON_PrintUnformatted(jsonObject)); + + char *jsonResponse = cJSON_Print(jsonObject); + cJSON_Delete(jsonObject); + + return jsonResponse; +} + +OCEntityHandlerResult +resourceEntityHandlerCB (OCEntityHandlerFlag entifyHandlerFlag, + OCEntityHandlerRequest *entityHandlerRequest) +{ + OC_LOG_V(DEBUG, HOSTING_TAG, "Inside device default entity handler - flags: 0x%x\n", + entifyHandlerFlag); + + OCEntityHandlerResult entityHandlerResult = OC_EH_OK; + OCEntityHandlerResponse entityHandlerResponse; + char payload[MAX_RESPONSE_LENGTH] = {0}; + + // Validate pointer + if (!entityHandlerRequest) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "Invalid request pointer\n"); + return OC_EH_ERROR; + } + + // Initialize certain response fields + entityHandlerResponse.numSendVendorSpecificHeaderOptions = 0; + memset(entityHandlerResponse.sendVendorSpecificHeaderOptions, 0, + sizeof entityHandlerResponse.sendVendorSpecificHeaderOptions); + memset(entityHandlerResponse.resourceUri, 0, sizeof entityHandlerResponse.resourceUri); + + if (entifyHandlerFlag & OC_INIT_FLAG) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "Flag includes OC_INIT_FLAG\n"); + } + if (entifyHandlerFlag & OC_REQUEST_FLAG) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "Flag includes OC_REQUEST_FLAG\n"); + if (entityHandlerRequest->resource == NULL) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "Received request from client to a non-existing resource\n"); + entityHandlerResult = handleNonExistingResourceRequest(entityHandlerRequest, payload, + sizeof(payload) - 1); + } + else if (OC_REST_GET == entityHandlerRequest->method) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "Received OC_REST_GET from client\n"); + entityHandlerResult = handleGetRequest (entityHandlerRequest, payload, sizeof(payload) - 1); + } + else if (OC_REST_PUT == entityHandlerRequest->method) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "Received OC_REST_PUT from client\n"); + } + else if (OC_REST_DELETE == entityHandlerRequest->method) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "Received OC_REST_DELETE from client\n"); + } + else + { + OC_LOG_V(DEBUG, HOSTING_TAG, "Received unsupported method %d from client\n", + entityHandlerRequest->method); + entityHandlerResult = OC_EH_ERROR; + } + + // If the result isn't an error or forbidden, send response + if (!((entityHandlerResult == OC_EH_ERROR) || (entityHandlerResult == OC_EH_FORBIDDEN))) + { + // Format the response. Note this requires some info about the request + entityHandlerResponse.requestHandle = entityHandlerRequest->requestHandle; + entityHandlerResponse.resourceHandle = entityHandlerRequest->resource; + entityHandlerResponse.ehResult = entityHandlerResult; + entityHandlerResponse.payload = (unsigned char *)payload; + entityHandlerResponse.payloadSize = strlen(payload); + // Indicate that response is NOT in a persistent buffer + entityHandlerResponse.persistentBufferFlag = 0; + + // Handle vendor specific options + if (entityHandlerRequest->rcvdVendorSpecificHeaderOptions && + entityHandlerRequest->numRcvdVendorSpecificHeaderOptions) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "Received vendor specific options\n"); + uint8_t i = 0; + OCHeaderOption *receivedVenderSpecificHeaderOptions = + entityHandlerRequest->rcvdVendorSpecificHeaderOptions; + for ( i = 0; i < entityHandlerRequest->numRcvdVendorSpecificHeaderOptions; i++) + { + if (((OCHeaderOption)receivedVenderSpecificHeaderOptions[i]).protocolID == OC_COAP_ID) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "Received option with OC_COAP_ID and ID %u with\n", + ((OCHeaderOption)receivedVenderSpecificHeaderOptions[i]).optionID ); + } + } + OCHeaderOption *sendVenderSpecificHeaderOptions = + entityHandlerResponse.sendVendorSpecificHeaderOptions; + uint8_t option2[] = {21, 22, 23, 24, 25, 26, 27, 28, 29, 30}; + uint8_t option3[] = {31, 32, 33, 34, 35, 36, 37, 38, 39, 40}; + sendVenderSpecificHeaderOptions[0].protocolID = OC_COAP_ID; + sendVenderSpecificHeaderOptions[0].optionID = 2248; + memcpy(sendVenderSpecificHeaderOptions[0].optionData, option2, sizeof(option2)); + sendVenderSpecificHeaderOptions[0].optionLength = 10; + sendVenderSpecificHeaderOptions[1].protocolID = OC_COAP_ID; + sendVenderSpecificHeaderOptions[1].optionID = 2600; + memcpy(sendVenderSpecificHeaderOptions[1].optionData, option3, sizeof(option3)); + sendVenderSpecificHeaderOptions[1].optionLength = 10; + entityHandlerResponse.numSendVendorSpecificHeaderOptions = 2; + } + + // Send the response + if (OCDoResponse(&entityHandlerResponse) != OC_STACK_OK) + { + OC_LOG(ERROR, HOSTING_TAG, "Error sending response"); + entityHandlerResult = OC_EH_ERROR; + } + } + } + if (entifyHandlerFlag & OC_OBSERVE_FLAG) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "Flag includes OC_OBSERVE_FLAG\n"); + if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "Received OC_OBSERVE_REGISTER from client\n"); + } + else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "Received OC_OBSERVE_DEREGISTER from client\n"); + } + } + + return entityHandlerResult; +} +OCEntityHandlerResult handleGetRequest (OCEntityHandlerRequest *entityHandlerRequest, + char *payload, uint16_t maxPayloadSize) +{ + OC_LOG_V(DEBUG, HOSTING_TAG, "ProcessGetRequest in....\n"); + + OCEntityHandlerResult entityHandlerResult; + char *responsePayload = buildResponsePayload(entityHandlerRequest); + + if (maxPayloadSize > strlen ((char *)responsePayload)) + { + strncpy(payload, responsePayload, strlen((char *)responsePayload)); + entityHandlerResult = OC_EH_OK; + } + else + { + OC_LOG_V(DEBUG, HOSTING_TAG, "Response buffer: %d bytes is too small\n", maxPayloadSize); + entityHandlerResult = OC_EH_ERROR; + } + + free(responsePayload); + + return entityHandlerResult; +} +OCEntityHandlerResult handleNonExistingResourceRequest(OCEntityHandlerRequest *entityHandlerRequest, + char *payload, uint16_t maxPayloadSize) +{ + OC_LOG_V(INFO, HOSTING_TAG, "\n\nExecuting %s ", __func__); + + const char *responsePayload = NULL; + responsePayload = "{App determines payload: The resource does not exist.}"; + + if ( (entityHandlerRequest != NULL) && + (maxPayloadSize > strlen ((char *)responsePayload)) ) + { + strncpy((char *)payload, responsePayload, strlen((char *)responsePayload)); + } + else + { + OC_LOG_V (INFO, HOSTING_TAG, "Response buffer: %d bytes is too small", + maxPayloadSize); + } + + return OC_EH_RESOURCE_DELETED; +} + +OCStackResult requestIsAlive(const char *address) +{ + MirrorResourceList *requestMirrorResourceList = findMirrorResourceListUsingAddress( + s_mirrorResourceList, address, OIC_SOURCE_ADDRESS); + + if (requestMirrorResourceList == NULL) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "Cannot found any mirror resource1\n"); + return OC_STACK_ERROR; + } + + if (requestMirrorResourceList->headerNode == NULL) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "Cannot found any mirror resource2\n"); + return OC_STACK_ERROR; + } + + MirrorResource *mirrorResource = requestMirrorResourceList->headerNode; + while (mirrorResource) + { + MirrorResource *currentMirrorResource = mirrorResource; + mirrorResource = mirrorResource->next; + if (OC_STACK_OK != ejectMirrorResource(requestMirrorResourceList, currentMirrorResource)) + { + continue; + } + + OCCallbackData cbData; + + cbData.cb = requestResourceObservationCB; + cbData.context = (void *)DEFAULT_CONTEXT_VALUE; + cbData.cd = NULL; + + char query[OIC_STRING_MAX_VALUE] = {'\0'}; + sprintf(query, "coap://%s%s", address, currentMirrorResource->uri); + + currentMirrorResource->resourceHandle[OIC_REQUEST_HANDLE] = NULL; + currentMirrorResource->isAliveCheck = 1; + insertMirrorResource(s_mirrorResourceList, currentMirrorResource); + OC_LOG_V(DEBUG, HOSTING_TAG, "Check Alive IP : %s, URI : %s\n", + currentMirrorResource->address[OIC_SOURCE_ADDRESS], currentMirrorResource->uri); + OCStackResult result = OCDoResource(¤tMirrorResource->resourceHandle[OIC_REQUEST_HANDLE], + OC_REST_GET, query, 0, NULL, OC_HIGH_QOS, &cbData, NULL, 0); + if (result != OC_STACK_OK) + { + OC_LOG_V(DEBUG, HOSTING_TAG, "OCDoResource returns error %s with method %d\n", + getResultString(result), OC_REST_OBSERVE); + deleteMirrorResourceFromList(s_mirrorResourceList, currentMirrorResource); + } + } + destroyMirrorResourceList(requestMirrorResourceList); + + return OC_STACK_OK; +} + +const char *getResultString(OCStackResult result) +{ + switch (result) + { + case OC_STACK_OK: + return "OC_STACK_OK"; + case OC_STACK_RESOURCE_CREATED: + return "OC_STACK_RESOURCE_CREATED"; + case OC_STACK_RESOURCE_DELETED: + return "OC_STACK_RESOURCE_DELETED"; + case OC_STACK_INVALID_URI: + return "OC_STACK_INVALID_URI"; + case OC_STACK_INVALID_QUERY: + return "OC_STACK_INVALID_QUERY"; + case OC_STACK_INVALID_IP: + return "OC_STACK_INVALID_IP"; + case OC_STACK_INVALID_PORT: + return "OC_STACK_INVALID_PORT"; + case OC_STACK_INVALID_CALLBACK: + return "OC_STACK_INVALID_CALLBACK"; + case OC_STACK_INVALID_METHOD: + return "OC_STACK_INVALID_METHOD"; + case OC_STACK_NO_MEMORY: + return "OC_STACK_NO_MEMORY"; + case OC_STACK_COMM_ERROR: + return "OC_STACK_COMM_ERROR"; + case OC_STACK_INVALID_PARAM: + return "OC_STACK_INVALID_PARAM"; + case OC_STACK_NOTIMPL: + return "OC_STACK_NOTIMPL"; + case OC_STACK_NO_RESOURCE: + return "OC_STACK_NO_RESOURCE"; + case OC_STACK_RESOURCE_ERROR: + return "OC_STACK_RESOURCE_ERROR"; + case OC_STACK_SLOW_RESOURCE: + return "OC_STACK_SLOW_RESOURCE"; + case OC_STACK_NO_OBSERVERS: + return "OC_STACK_NO_OBSERVERS"; + case OC_STACK_VIRTUAL_DO_NOT_HANDLE: + return "OC_STACK_VIRTUAL_DO_NOT_HANDLE"; + case OC_STACK_PRESENCE_STOPPED: + return "OC_STACK_PRESENCE_STOPPED"; + case OC_STACK_PRESENCE_TIMEOUT: + return "OC_STACK_PRESENCE_TIMEOUT"; + case OC_STACK_PRESENCE_DO_NOT_HANDLE: + return "OC_STACK_PRESENCE_DO_NOT_HANDLE"; + case OC_STACK_ERROR: + return "OC_STACK_ERROR"; + default: + return "UNKNOWN"; + } +} + +void getJsonArrayPair(cJSON *tempData) +{ + ////////////////////////////////////////////////////////////////////////////////////////////// + // Test + int countofrep = cJSON_GetArraySize(tempData); + OC_LOG_V(DEBUG, HOSTING_TAG, + "//////////////////////////////////////////////////////////////////////////\n"); + OC_LOG_V(DEBUG, HOSTING_TAG, "//Test\n"); + OC_LOG_V(DEBUG, HOSTING_TAG, "rep Size : %d\n", countofrep); + int i = 0; + for (i = 0; i < countofrep; ++i) + { + cJSON *arrayJSON = cJSON_GetArrayItem(tempData, i); + OC_LOG_V(DEBUG, HOSTING_TAG, "rep#%d's name : %s\n", i, arrayJSON->string); + + switch (arrayJSON->type) + { + case cJSON_False: + case cJSON_True: + OC_LOG_V(DEBUG, HOSTING_TAG, "rep#%d's value : %d\n", i, arrayJSON->valueint); + break; + case cJSON_Number: + OC_LOG_V(DEBUG, HOSTING_TAG, "rep#%d's value : %f\n", i, arrayJSON->valuedouble); + break; + case cJSON_String: + OC_LOG_V(DEBUG, HOSTING_TAG, "rep#%d's value : %s\n", i, arrayJSON->valuestring); + break; + case cJSON_NULL: + default: + OC_LOG_V(DEBUG, HOSTING_TAG, "rep#%d's value : NULL\n", i); + break; + } + } + OC_LOG_V(DEBUG, HOSTING_TAG, + "//////////////////////////////////////////////////////////////////////////\n"); + ////////////////////////////////////////////////////////////////////////////////////////////// +} diff --git a/service/notification-manager/NotificationManager/src/linux/main.cpp b/service/notification-manager/NotificationManager/src/linux/main.cpp deleted file mode 100644 index 473b366..0000000 --- a/service/notification-manager/NotificationManager/src/linux/main.cpp +++ /dev/null @@ -1,66 +0,0 @@ -//****************************************************************** -// -// Copyright 2014 Samsung Electronics 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. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= - -#include -#include "NotificationManager.h" - -using namespace OC; - -int main(void) -{ - - std::cout << endl; - std::cout << "========================================================" << endl; - std::cout << "Start Notification Manager : Hosting v0.5\n"; - - - HostingConfig cfg; - cfg.hostingMode = HostingMode::ManualMode; - cfg.automaticMethod = AutomaticMethod::None; - cfg.notifyMethod = NotifyMethod::Frequence; - cfg.frequency = NotifyFrequency::OnTime; - - NotificationManager::initialize(cfg); - - while (true) - { - char signal; - cin >> signal; - - switch (signal) - { - case 'q': - case 'Q': - std::cout << endl; - std::cout << "========================================================" << endl; - std::cout << "End Notification Manager : Hosting v0.5\n"; - return true; - default: - break; - } - - } - - std::cout << endl; - std::cout << "========================================================" << endl; - std::cout << "End Notification Manager : Hosting v0.5\n"; - - return true; -} diff --git a/service/notification-manager/NotificationManager/src/virtualResource.c b/service/notification-manager/NotificationManager/src/virtualResource.c new file mode 100644 index 0000000..12ac417 --- /dev/null +++ b/service/notification-manager/NotificationManager/src/virtualResource.c @@ -0,0 +1,411 @@ +//****************************************************************** +// +// Copyright 2015 Samsung Electronics 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. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "virtualResource.h" + + +MirrorResourceList *createMirrorResourceList() +{ + MirrorResourceList *mirrorResourceList = (MirrorResourceList *)malloc(sizeof(MirrorResourceList)); + if (!mirrorResourceList) + { + OC_LOG_V(DEBUG, VR_TAG, "Virtual Resource List Creation Fail.\n"); + } + else + { + mirrorResourceList->headerNode = NULL; + mirrorResourceList->tailNode = NULL; + } + + return mirrorResourceList; +} + +MirrorResource *createMirrorResource() +{ + + MirrorResource *mirrorResource = (MirrorResource *)malloc(sizeof(MirrorResource)); + + if (!mirrorResource) + { + OC_LOG_V(DEBUG, VR_TAG, "Virtual Resource List Creation Fail.\n"); + } + else + { + mirrorResource->resourceHandle[OIC_REQUEST_HANDLE] = NULL; + mirrorResource->resourceHandle[OIC_MIRROR_HANDLE] = NULL; + mirrorResource->address[OIC_SOURCE_ADDRESS] = NULL; + mirrorResource->address[OIC_MIRROR_ADDRESS] = NULL; + + mirrorResource->rep = NULL; + mirrorResource->uri = NULL; + mirrorResource->next = NULL; + + mirrorResource->prop.countResourceType = 0; + mirrorResource->prop.resourceType = NULL; + mirrorResource->prop.countInterface = 0; + mirrorResource->prop.resourceInterfaceName = NULL; + + mirrorResource->isAliveCheck = 0; + } + + return mirrorResource; +} + +OCStackResult destroyMirrorResourceList(MirrorResourceList *mirrorResourceList) +{ + + OC_LOG_V(DEBUG, VR_TAG, "enter destroyVirtualResourceList\n"); + + if (mirrorResourceList) + { + while (mirrorResourceList->headerNode) + { + deleteMirrorResourceFromList(mirrorResourceList, mirrorResourceList->headerNode); + } + + free(mirrorResourceList); + } + else + { + return OC_STACK_INVALID_PARAM; + } + + return OC_STACK_OK; +} + +OCStackResult destroyMirrorResource(MirrorResource *mirrorResource) +{ + + OC_LOG_V(DEBUG, VR_TAG, "\n\n\n\nenter destroy virtual resource.\n"); + + if (mirrorResource) + { + if (mirrorResource->next) + { + mirrorResource->next = NULL; + } + if (mirrorResource->rep) + { + cJSON_Delete(mirrorResource->rep); + } + if (mirrorResource->uri) + { + free(mirrorResource->uri); + } + if (mirrorResource->address[OIC_SOURCE_ADDRESS]) + { + free(mirrorResource->address[OIC_SOURCE_ADDRESS]); + } + if (mirrorResource->address[OIC_MIRROR_ADDRESS]) + { + free(mirrorResource->address[OIC_MIRROR_ADDRESS]); + } + if (mirrorResource->prop.resourceType) + { + int i = 0; + for (i = 0; i < mirrorResource->prop.countResourceType; ++i) + { + free(mirrorResource->prop.resourceType[i]); + mirrorResource->prop.resourceType[i] = NULL; + } + free(mirrorResource->prop.resourceType); + mirrorResource->prop.countResourceType = 0; + } + if (mirrorResource->prop.resourceInterfaceName) + { + int i = 0; + for (i = 0; i < mirrorResource->prop.countInterface; ++i) + { + free(mirrorResource->prop.resourceInterfaceName[i]); + mirrorResource->prop.resourceInterfaceName[i] = NULL; + } + free(mirrorResource->prop.resourceInterfaceName); + mirrorResource->prop.countInterface = 0; + } + + + free(mirrorResource); + } + else + { + return OC_STACK_INVALID_PARAM; + } + + return OC_STACK_OK; + +} + +OCStackResult insertMirrorResource(MirrorResourceList *mirrorResourceList, + MirrorResource *mirrorResource) +{ + if (mirrorResourceList == NULL || mirrorResource == NULL) + { + return OC_STACK_INVALID_PARAM; + } + + if (mirrorResourceList->headerNode == NULL) + { + mirrorResourceList->headerNode = mirrorResource; + mirrorResourceList->tailNode = mirrorResource; + } + else + { + mirrorResourceList->tailNode->next = mirrorResource; + mirrorResourceList->tailNode = mirrorResource; + } + + return OC_STACK_OK; +} + +MirrorResource *findMirrorResourceUsingAddressAndURI(MirrorResourceList *mirrorResourceList, + const char *address, OICResourceCoordinatorParamType paramType, const char *uri) +{ + if (mirrorResourceList->headerNode == NULL) + { + OC_LOG_V(DEBUG, VR_TAG, "Find Virtual Resource : Empty Virtual Resource List.\n"); + return NULL; + } + if (mirrorResourceList == NULL || address == NULL) + { + OC_LOG_V(DEBUG, VR_TAG, "Find Virtual Resource : invalid parameter.\n"); + return NULL; + } + + MirrorResource *tempMirrorResource = mirrorResourceList->headerNode; + while (tempMirrorResource != NULL) + { + OC_LOG_V(DEBUG, VR_TAG, "node's uri = %s\n", tempMirrorResource->uri); + if (strcmp(tempMirrorResource->address[paramType], address) == 0) // if(It is Same) + { + if (strcmp(tempMirrorResource->uri, uri) == 0) // if(It is Same) + { + return tempMirrorResource; + } + } + tempMirrorResource = tempMirrorResource->next; + } + + return NULL; +} + +MirrorResource *findMirrorResourceUsingHandle(MirrorResourceList *mirrorResourceList, + OCResourceHandle handle, OICResourceCoordinatorParamType paramType) +{ + if (mirrorResourceList == NULL || handle == NULL) + { + OC_LOG_V(DEBUG, VR_TAG, "Find Virtual Resource : invalid parameter.\n"); + return NULL; + } + if (mirrorResourceList->headerNode == NULL) + { + OC_LOG_V(DEBUG, VR_TAG, "Find Virtual Resource : Empty Virtual Resource List.\n"); + return NULL; + } + + MirrorResource *tempMirrorResource = mirrorResourceList->headerNode; + while (tempMirrorResource != NULL) + { + if (tempMirrorResource->resourceHandle[paramType] == handle) + { + return tempMirrorResource; + } + tempMirrorResource = tempMirrorResource->next; + } + + return NULL; +} + +OCStackResult deleteMirrorResourceFromList(MirrorResourceList *mirrorResourceList, + MirrorResource *mirrorResource) +{ + + OC_LOG_V(DEBUG, VR_TAG, "\n\n\n\nenter delete virtual resource.\n"); + + if (mirrorResourceList == NULL || mirrorResource == NULL) + { + OC_LOG_V(DEBUG, VR_TAG, "Delete Virtual Resource : invalid parameter.\n"); + return OC_STACK_INVALID_PARAM; + } + if (mirrorResourceList->headerNode == NULL) + { + OC_LOG_V(DEBUG, VR_TAG, "Delete Virtual Resource : Empty Virtual Resource List.\n"); + return OC_STACK_ERROR; + } + + if (mirrorResource == mirrorResourceList->headerNode) + { + mirrorResourceList->headerNode = mirrorResourceList->headerNode->next; + mirrorResource->next = NULL; + return destroyMirrorResource(mirrorResource); + } + + MirrorResource *preNode = mirrorResourceList->headerNode; + MirrorResource *curNode = preNode->next; + while (curNode != NULL) + { + if (curNode == mirrorResource) + { + if (curNode == mirrorResourceList->tailNode) + { + mirrorResourceList->tailNode = preNode; + preNode->next = NULL; + } + else + { + preNode->next = curNode->next; + } + mirrorResource->next = NULL; + return destroyMirrorResource(mirrorResource); + } + preNode = curNode; + curNode = curNode->next; + } + + return OC_STACK_ERROR; +} + +OCStackResult ejectMirrorResource(MirrorResourceList *mirrorResourceList, + MirrorResource *mirrorResource) +{ + if (mirrorResourceList == NULL || mirrorResource == NULL) + { + OC_LOG_V(DEBUG, VR_TAG, "Eject Virtual Resource : invalid parameter.\n"); + return OC_STACK_INVALID_PARAM; + } + if (mirrorResourceList->headerNode == NULL) + { + OC_LOG_V(DEBUG, VR_TAG, "Eject Virtual Resource : Empty Virtual Resource List.\n"); + } + + if (mirrorResource == mirrorResourceList->headerNode) + { + mirrorResourceList->headerNode = mirrorResourceList->headerNode->next; + return OC_STACK_OK; + } + + MirrorResource *preNode = mirrorResourceList->headerNode; + MirrorResource *curNode = preNode->next; + while (curNode != NULL) + { + if (curNode == mirrorResource) + { + preNode->next = curNode->next; + return OC_STACK_OK; + } + preNode = curNode; + curNode = curNode->next; + } + + return OC_STACK_ERROR; + +} + +MirrorResource *cloneMirrorResource(MirrorResource *sourceMirrorResource) +{ + MirrorResource *clonedMirrorResource = createMirrorResource(); + + int sizeofstr = 0; + int i = 0; + +// retNode->resourceHandle[OIC_REQUEST_HANDLE] = sourceNode->resourceHandle[OIC_REQUEST_HANDLE]; +// retNode->resourceHandle[OIC_VIRTUAL_HANDLE] = sourceNode->resourceHandle[OIC_VIRTUAL_HANDLE]; + clonedMirrorResource->rep = cJSON_Parse(cJSON_PrintUnformatted(sourceMirrorResource->rep)); + + sizeofstr = strlen(sourceMirrorResource->uri) + 1; + clonedMirrorResource->uri = (char *)malloc(sizeof(char) * sizeofstr); + memset(clonedMirrorResource->uri, '\0', sizeofstr); + strcpy(clonedMirrorResource->uri, sourceMirrorResource->uri); + + for (i = OIC_SOURCE_ADDRESS; i < OIC_MIRROR_ADDRESS; ++i) + { + sizeofstr = strlen(sourceMirrorResource->address[i]) + 1; + clonedMirrorResource->address[i] = (char *)malloc(sizeof(char) * sizeofstr); + memset(clonedMirrorResource->address[i], '\0', sizeofstr); + strcpy(clonedMirrorResource->address[i], sourceMirrorResource->address[i]); + } + + // copy prop ?? + + return clonedMirrorResource; +} + +MirrorResourceList *findMirrorResourceListUsingAddress(MirrorResourceList *mirrorResourceList, + const char *address, OICResourceCoordinatorParamType paramType) +{ + + MirrorResource *tempNode = mirrorResourceList->headerNode; + int i = 0; + while (tempNode != NULL) + { + OC_LOG_V(DEBUG, VR_TAG, "%d's uri = %s\n", i++, tempNode->uri); + tempNode = tempNode->next; + } + + if (mirrorResourceList == NULL || address == NULL) + { + OC_LOG_V(DEBUG, VR_TAG, "Find Virtual Resource List : invalid parameter.\n"); + return NULL; + } + if (mirrorResourceList->headerNode == NULL) + { + OC_LOG_V(DEBUG, VR_TAG, "Find Virtual Resource List : Empty Virtual Resource List.\n"); + return NULL; + } + + MirrorResourceList *resultMirrorResourceList = createMirrorResourceList(); + MirrorResource *mirrorResource = mirrorResourceList->headerNode; + while (mirrorResource != NULL) + { + if (strcmp(mirrorResource->address[paramType], address) == 0) // if(It is Same) + { + insertMirrorResource(resultMirrorResourceList, cloneMirrorResource(mirrorResource)); + } + mirrorResource = mirrorResource->next; + } + + return resultMirrorResourceList; +} + + +OCStackResult printMirrorResourceList(MirrorResourceList *mirrorResourceList) +{ + + if (mirrorResourceList == NULL) + { + OC_LOG_V(DEBUG, VR_TAG, "print Virtual Resource list : invalid parameter.\n"); + return OC_STACK_INVALID_PARAM; + } + if (mirrorResourceList->headerNode == NULL) + { + OC_LOG_V(DEBUG, VR_TAG, "print Virtual Resource list : Empty Virtual Resource List.\n"); + return OC_STACK_INVALID_PARAM; + } + OC_LOG_V(DEBUG, VR_TAG, "\n\n==============================================================\n"); + MirrorResource *mirrorResource = mirrorResourceList->headerNode; + int i = 0; + while (mirrorResource != NULL) + { + OC_LOG_V(DEBUG, VR_TAG, "%d's uri = %s\n", i++, mirrorResource->uri); + mirrorResource = mirrorResource->next; + } + OC_LOG_V(DEBUG, VR_TAG, "\n==============================================================\n\n"); + + return OC_STACK_OK; +} diff --git a/service/notification-manager/SConscript b/service/notification-manager/SConscript index e5b7f17..ec2ddfa 100644 --- a/service/notification-manager/SConscript +++ b/service/notification-manager/SConscript @@ -13,6 +13,8 @@ target_os = env.get('TARGET_OS') # Build flags ###################################################################### notimgr_env.AppendUnique(CPPPATH = ['NotificationManager/include']) +notimgr_env.AppendUnique(CPPPATH = ['../../extlibs/cjson']) +notimgr_env.AppendUnique(CPPPATH = ['../../resource/csdk/logger/include']) notimgr_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'coap']) if target_os not in ['windows', 'winrt']: @@ -23,7 +25,7 @@ if target_os == 'linux': if target_os == 'android': notimgr_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions']) - notimgr_env.AppendUnique(LIBS = ['gnustl_shared']) + notimgr_env.AppendUnique(LIBS = ['gnustl_static']) if not env.get('RELEASE'): notimgr_env.AppendUnique(LIBS = ['log']) @@ -33,15 +35,12 @@ if target_os == 'android': ###################################################################### NOTI_SRC_DIR = 'NotificationManager/src/' notimgr_src = [ - NOTI_SRC_DIR + 'LinuxMain.cpp', - NOTI_SRC_DIR + 'NotificationManager.cpp', - NOTI_SRC_DIR + 'RegistrationManager.cpp', - NOTI_SRC_DIR + 'ResourceManager.cpp', - NOTI_SRC_DIR + 'VirtualRepresentation.cpp'] + NOTI_SRC_DIR + 'hosting.c', + NOTI_SRC_DIR + 'virtualResource.c'] -notificationmanager = notimgr_env.Program('noti_manager', notimgr_src) +notificationsdk = notimgr_env.StaticLibrary('NOTISDKLibrary', notimgr_src) -notimgr_env.InstallTarget(notificationmanager, 'notificationmanager') +notimgr_env.InstallTarget(notificationsdk, 'libNMSDK') # Go to build sample apps SConscript('SampleApp/SConscript') diff --git a/service/notification-manager/SampleApp/linux/SConscript b/service/notification-manager/SampleApp/linux/SConscript index b824757..95c5a7d 100644 --- a/service/notification-manager/SampleApp/linux/SConscript +++ b/service/notification-manager/SampleApp/linux/SConscript @@ -12,11 +12,17 @@ notimgr_env = lib_env.Clone() # Build flags ###################################################################### notimgr_env.AppendUnique(CPPPATH = ['../../NotificationManager/include']) -notimgr_env.AppendUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'coap', 'pthread']) +notimgr_env.AppendUnique(CPPPATH = ['../../../../extlibs/cjson']) +notimgr_env.AppendUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'coap', 'pthread','NOTISDKLibrary']) notimgr_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0']) ###################################################################### # Source files and Targets ###################################################################### sampleprovider = notimgr_env.Program('sampleprovider', 'sampleProvider/SampleProvider.cpp') -sampleconsumer = notimgr_env.Program('sampleconsumer', 'sampleConsumer/SampleConsumer.cpp') \ No newline at end of file +sampleconsumer = notimgr_env.Program('sampleconsumer', 'sampleConsumer/SampleConsumer.cpp') +notificationmanager = notimgr_env.Program('notificationmanager', 'notificationManager/main.c') + +#notimgr_env.InstallTarget(sampleprovider, 'sampleprovider') +#notimgr_env.InstallTarget(sampleconsumer, 'sampleconsumer') +#notimgr_env.InstallTarget(notificationmanager, 'notificationmanager') diff --git a/service/notification-manager/SampleApp/linux/notificationManager/main.c b/service/notification-manager/SampleApp/linux/notificationManager/main.c new file mode 100644 index 0000000..ce1debb --- /dev/null +++ b/service/notification-manager/SampleApp/linux/notificationManager/main.c @@ -0,0 +1,97 @@ +//****************************************************************** +// +// Copyright 2015 Samsung Electronics 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. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include +#include + +#include "hosting.h" + +int g_quitFlag = 0; + +void handleSigInt(int signum); + +/* +* This method is an entry point of Resource Hosting Manager. +* This function should be run only on the device that it could be host device. +*/ +int main() +{ + + uint8_t interfaceAddress[20] = {0}; + uint8_t *coordinatingAddress = NULL; + uint8_t interfaceName[] = "eth0"; + + printf("OCResourceHosting is starting...\n"); + + if ( OCGetInterfaceAddress(interfaceName, sizeof(interfaceName), AF_INET, interfaceAddress, + sizeof(interfaceAddress)) == ERR_SUCCESS) + { + printf("Starting OIC resource hosting on address %s\n", interfaceAddress); + coordinatingAddress = interfaceAddress; + } + + if (OCInit((char *) coordinatingAddress, USE_RANDOM_PORT, OC_CLIENT_SERVER) != OC_STACK_OK) + { + printf("OCStack init error\n"); + return 0; + } + + OICStartCoordinate(); + + signal(SIGINT, handleSigInt); + while (!g_quitFlag) + { + if (OCProcess() != OC_STACK_OK) + { + OICStopCoordinate(); + printf("OCStack process error\n"); + return 0; + } + + sleep(2); + } + + OICStopCoordinate(); + + printf("Exiting occlient main loop...\n"); + + if (OCStop() != OC_STACK_OK) + { + printf("OCStack stop error\n"); + } + + return 0; + +} + +/* +* This is a signal handling function for SIGINT(CTRL+C). +* A Resource Coordinator handle the SIGINT signal for safe exit. +* +* @param[in] signal +* signal number of caught signal. +*/ +void handleSigInt(int signum) +{ + if (signum == SIGINT) + { + g_quitFlag = 1; + } +} diff --git a/service/notification-manager/SampleApp/linux/sampleConsumer/SampleConsumer.cpp b/service/notification-manager/SampleApp/linux/sampleConsumer/SampleConsumer.cpp index 74b8180..f413428 100644 --- a/service/notification-manager/SampleApp/linux/sampleConsumer/SampleConsumer.cpp +++ b/service/notification-manager/SampleApp/linux/sampleConsumer/SampleConsumer.cpp @@ -1,6 +1,6 @@ //****************************************************************** // -// Copyright 2014 Samsung Electronics All Rights Reserved. +// Copyright 2015 Samsung Electronics All Rights Reserved. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // @@ -26,38 +26,33 @@ #include #include "OCPlatform.h" #include "OCApi.h" - +#include using namespace OC; const int SUCCESS_RESPONSE = OC_STACK_OK; -static ObserveType OBSERVE_TYPE_TO_USE = ObserveType::Observe; -std::shared_ptr< OCResource > g_curResource; +#define OBSERVE 1 +#define GET 2 +#define PUT 3 +#define DELETE 4 +std::shared_ptr< OCResource > g_curResource; +std::mutex curResourceLock; OCStackResult nmfindResource(const std::string &host , const std::string &resourceName); void onObserve(const HeaderOptions &headerOption , const OCRepresentation &rep , const int &eCode, const int &sequenceNumber); +void onPut(const HeaderOptions &headerOption, const OCRepresentation &rep, const int eCode); +void onGet(const HeaderOptions &headerOption , const OCRepresentation &rep , const int eCode); +void onDelete(const HeaderOptions &headerOption , const int eCode); + + void findResourceCandidate() { try { - nmfindResource("" , "coap://224.0.1.187/oc/core?rt=NotificationManager.Hosting"); + nmfindResource("" , "coap://224.0.1.187/oc/core?rt=Resource.Hosting"); std::cout << "Finding Resource... " << std::endl; - while (true) - { - char signal; - cin >> signal; - - switch (signal) - { - case 'q': - case 'Q': - exit(-1); - default: - break; - } - } } catch (OCException &e) @@ -67,10 +62,61 @@ void findResourceCandidate() void startObserve(std::shared_ptr< OCResource > resource) { + if (resource == NULL) + { + std::cout << "startObserve() error : resource == null" << std::endl; + return; + } + + QueryParamsMap test; + if (OC_STACK_OK != resource->observe(ObserveType::Observe , test , &onObserve)) + std::cout << "To Fail resource observe() process" << std::endl; +} + +void startGet(std::shared_ptr< OCResource > resource) +{ + + if (resource == NULL) + { + std::cout << "startObserve() error : resource == null" << std::endl; + return; + } + + QueryParamsMap test; + std::cout << "URI :" << resource->uri() << std::endl; + if (OC_STACK_OK != resource->get(test, &onGet)) + std::cout << "To Fail resource get() process" << std::endl; +} + +void startPut(std::shared_ptr< OCResource > resource) +{ + if (resource == NULL) + { + std::cout << "startObserve() error : resource == null" << std::endl; + return; + } + g_curResource = resource; + OCRepresentation rep; + rep.setValue("temperature", 25); + rep.setValue("humidity", 10); QueryParamsMap test; - resource->observe(ObserveType::Observe , test , &onObserve); + if (OC_STACK_OK != resource->put(rep, test, &onPut)) + std::cout << "To Fail resource put() process" << std::endl; +} + +void startDelete(std::shared_ptr< OCResource > resource) +{ + if (resource == NULL) + { + std::cout << "startObserve() error : resource == null" << std::endl; + return; + } + + g_curResource = resource; + if (OC_STACK_OK != resource->deleteResource(&onDelete)) + std::cout << "To Fail resource delete() process" << std::endl; } int observe_count() @@ -83,40 +129,16 @@ void onObserve(const HeaderOptions &headerOption , const OCRepresentation &rep , const int &sequenceNumber) { std::cout << "onObserve" << std::endl; -// if(eCode == SUCCESS_RESPONSE) - if (eCode <= OC_STACK_RESOURCE_DELETED) - { - - AttributeMap attributeMap = rep.getAttributeMap(); - - for (auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it) - { - if (attributeMap.find(it->first) == attributeMap.end()) - { - return; - } - } - - if (rep.getUri().empty()) - { - cout << "uri is null\n"; - return; - } + if (eCode <= OC_STACK_OK) + { std::cout << std::endl; std::cout << "========================================================" << std::endl; std::cout << "Receive OBSERVE RESULT:" << std::endl; + std::cout << "\tUri: " << rep.getUri() << std::endl; std::cout << "\tSequenceNumber: " << sequenceNumber << std::endl; - for (auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it) - { - std::cout << "\tAttribute name: " << it->first << " value: "; - for (auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr) - { - std::cout << "\t" << *valueItr << " "; - } - - std::cout << std::endl; - } + std::cout << "\tTemperature : " << rep.getValue("temperature") << std::endl; + std::cout << "\tHumidity : " << rep.getValue("humidity") << std::endl; if (observe_count() > 30) { @@ -140,12 +162,24 @@ void foundResource(std::shared_ptr< OCResource > resource) { std::string resourceURI; std::string hostAddress; + + std::cout << "foundResource" << std::endl; + try { + /*std::lock_guard lock(curResourceLock); + if (g_curResource) + { + std::cout << "Found another resource, ignoring" << std::endl; + return; + }*/ + + std::cout << "mutex lock passed" << std::endl; + if (resource) { -// if(resource->uri().find("/a/NM/TempHumSensor/virtual") != std::string::npos) - if (resource->uri().find("/a/NM/TempHumSensor") != std::string::npos) + std::cout << resource->uri() << std::endl; + if (resource->uri() == "/a/TempHumSensor") { std::cout << std::endl; std::cout << "========================================================" << std::endl; @@ -157,7 +191,7 @@ void foundResource(std::shared_ptr< OCResource > resource) hostAddress = resource->host(); std::cout << "\tHost address of the resource: " << hostAddress << std::endl; - startObserve(resource); + g_curResource = resource; } } else @@ -184,101 +218,65 @@ void getRepresentation(std::shared_ptr< OCResource > resource) } } -void onPut(const OCRepresentation &rep , const int eCode) +void onPut(const HeaderOptions &headerOption, const OCRepresentation &rep, const int eCode) { - if (eCode == SUCCESS_RESPONSE) + try { - std::cout << "PUT request was successful" << std::endl; + if (eCode == OC_STACK_OK) + { + std::cout << "PUT request was successful" << std::endl; + int humidity; + int temperature; + rep.getValue("temperature", temperature); + rep.getValue("humidity", humidity); - AttributeMap attributeMap = rep.getAttributeMap(); - for (auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it) + std::cout << "\t temperature: " << temperature << std::endl; + std::cout << "\t humidity: " << humidity << std::endl; + } + else { - std::cout << "\tAttribute name: " << it->first << " value: "; - for (auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr) - { - std::cout << "\t" << *valueItr << " "; - } - - std::cout << std::endl; + std::cout << "onPut Response error: " << eCode << std::endl; + std::exit(-1); } + } + catch (std::exception &e) + { + std::cout << "Exception: " << e.what() << " in onPut" << std::endl; + } +} - std::vector< OCRepresentation > children = rep.getChildren(); - - for (auto oit = children.begin() ; oit != children.end() ; ++oit) +//callback hadnler on DELETE request +void onDelete(const HeaderOptions &headerOption , const int eCode) +{ + try + { + if (eCode == OC_STACK_RESOURCE_DELETED) { - attributeMap = oit->getAttributeMap(); - - for (auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it) - { - std::cout << "\tAttribute name: " << it->first << " value: "; - for (auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr) - { - std::cout << "\t" << *valueItr << " "; - } - - std::cout << std::endl; - } + std::cout << "DELETE request was successful" << std::endl; + } + else + { + std::cout << "onDelete Response error: " << eCode << std::endl; + std::exit(-1); } - - if (OBSERVE_TYPE_TO_USE == ObserveType::Observe) - std::cout << std::endl << "Observe is used." << std::endl << std::endl; - else if (OBSERVE_TYPE_TO_USE == ObserveType::ObserveAll) - std::cout << std::endl << "ObserveAll is used." << std::endl << std::endl; - - QueryParamsMap test; - - g_curResource->observe(ObserveType::Observe , test , &onObserve); - } - else + catch (std::exception &e) { - std::cout << "onPut Response error: " << eCode << std::endl; - std::exit(-1); + std::cout << "Exception: " << e.what() << " in onDelete" << std::endl; } } // callback handler on GET request void onGet(const HeaderOptions &headerOption , const OCRepresentation &rep , const int eCode) { + std::cout << "GET request was successful1" << std::endl; if (eCode == SUCCESS_RESPONSE) { std::cout << "GET request was successful" << std::endl; - - AttributeMap attributeMap = rep.getAttributeMap(); - - std::cout << "Resource URI: " << rep.getUri() << std::endl; - - for (auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it) - { - std::cout << "\tAttribute name: " << it->first << " value: "; - for (auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr) - { - std::cout << "\t" << *valueItr << " "; - } - - std::cout << std::endl; - } - - std::vector< OCRepresentation > children = rep.getChildren(); - - for (auto oit = children.begin() ; oit != children.end() ; ++oit) - { - std::cout << "Child Resource URI: " << oit->getUri() << std::endl; - - attributeMap = oit->getAttributeMap(); - - for (auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it) - { - std::cout << "\tAttribute name: " << it->first << " value: "; - for (auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr) - { - std::cout << "\t" << *valueItr << " "; - } - - std::cout << std::endl; - } - } + std::cout << "Resource URI: " << rep.getUri().c_str() << std::endl; + std::cout << "\tTemperature : " << rep.getValue("temperature") << std::endl; + std::cout << "\tHumidity : " << rep.getValue("humidity") << std::endl; } else { @@ -306,29 +304,22 @@ void PrintUsage() std::cout << " ObserveType : 2 - ObserveAll" << std::endl; } -int main(int argc , char *argv[]) +void PRINT() { + std::cout << std::endl; + std::cout << "********************************************" << std::endl; + std::cout << "* method Type : 1 - Observe *" << std::endl; + std::cout << "* method Type : 2 - Get *" << std::endl; + std::cout << "* method Type : 3 - Put *" << std::endl; + std::cout << "* method Type : 4 - Delete *" << std::endl; + std::cout << "********************************************" << std::endl; + std::cout << std::endl; +} - if (argc == 1) - { - OBSERVE_TYPE_TO_USE = ObserveType::Observe; - } - else if (argc == 2) - { - int value = atoi(argv[1]); - if (value == 1) - OBSERVE_TYPE_TO_USE = ObserveType::Observe; - else if (value == 2) - OBSERVE_TYPE_TO_USE = ObserveType::ObserveAll; - else - OBSERVE_TYPE_TO_USE = ObserveType::Observe; - } - else - { - PrintUsage(); - return -1; - } +int main(int argc , char *argv[]) +{ + int in; PlatformConfig cfg; OCPlatform::Configure(cfg); @@ -336,6 +327,31 @@ int main(int argc , char *argv[]) std::cout << "Created Platform..." << std::endl; findResourceCandidate(); + while (1) + { + PRINT(); + + std::cin >> in; + switch (in) + { + case OBSERVE: + startObserve(g_curResource); + break; + case GET: + startGet(g_curResource); + break; + case PUT: + startPut(g_curResource); + break; + case DELETE: + startDelete(g_curResource); + break; + default: + std::cout << "Invalid input, please try again" << std::endl; + break; + } + } + return 0; } diff --git a/service/notification-manager/SampleApp/linux/sampleProvider/SampleProvider.cpp b/service/notification-manager/SampleApp/linux/sampleProvider/SampleProvider.cpp old mode 100644 new mode 100755 index a943b2f..f7079eb --- a/service/notification-manager/SampleApp/linux/sampleProvider/SampleProvider.cpp +++ b/service/notification-manager/SampleApp/linux/sampleProvider/SampleProvider.cpp @@ -1,6 +1,6 @@ //****************************************************************** // -// Copyright 2014 Samsung Electronics All Rights Reserved. +// Copyright 2015 Samsung Electronics All Rights Reserved. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // @@ -21,6 +21,7 @@ #include #include +#include #include "OCPlatform.h" #include "OCApi.h" @@ -30,14 +31,17 @@ using namespace OC; using namespace std; +using namespace OC::OCPlatform; int g_Observation = 0; +int gQuitFlag = 0; pthread_cond_t m_cond = PTHREAD_COND_INITIALIZER; pthread_mutex_t m_mutex = PTHREAD_MUTEX_INITIALIZER; -OCEntityHandlerResult entityHandler(std::shared_ptr< OCResourceRequest > request , - std::shared_ptr< OCResourceResponse > response); + + +OCEntityHandlerResult entityHandler(std::shared_ptr< OCResourceRequest > request); class TempHumidResource { @@ -45,10 +49,9 @@ class TempHumidResource int m_temp; int m_humid; - std::string m_uri; OCResourceHandle m_resourceHandle; - + ObservationIds m_interestedObservers; OCRepresentation m_Rep; public: @@ -59,8 +62,8 @@ class TempHumidResource void createResource() { - std::string resourceURI = "/a/NM/TempHumSensor"; - std::string resourceTypeName = "NotificationManager.Hosting"; + std::string resourceURI = "/a/TempHumSensor/hosting"; + std::string resourceTypeName = "Resource.Hosting"; std::string resourceInterface = DEFAULT_INTERFACE; m_uri = resourceURI; @@ -109,7 +112,6 @@ class TempHumidResource OCRepresentation post(OCRepresentation &rep) { static int first = 1; - // for the first time it tries to create a resource if (first) { @@ -160,15 +162,20 @@ class TempHumidResource OCRepresentation get() { - cout << "resource get\n"; m_Rep.setValue("temperature", m_temp); m_Rep.setValue("humidity", m_humid); - - cout << "resource get : done\n"; - return m_Rep; } - + OCStackResult deleteDeviceResource() + { + OCStackResult result = OCPlatform::unregisterResource(m_resourceHandle); + if (OC_STACK_OK != result) + { + throw std::runtime_error( + std::string("Device Resource failed to unregister/delete") + std::to_string(result)); + } + return result; + } }; TempHumidResource myResource; @@ -210,10 +217,11 @@ void *ChangeLightRepresentation(void *param) return NULL; } -OCEntityHandlerResult entityHandler(std::shared_ptr< OCResourceRequest > request , - std::shared_ptr< OCResourceResponse > response) +OCEntityHandlerResult entityHandler(std::shared_ptr< OCResourceRequest > request) { cout << "Sample Provider entityHandler\n"; + + OCEntityHandlerResult ehResult = OC_EH_ERROR; if (request) { cout << "flag : request\n"; @@ -228,28 +236,23 @@ OCEntityHandlerResult entityHandler(std::shared_ptr< OCResourceRequest > request if (requestFlag == RequestHandlerFlag::RequestFlag) { cout << "\t\trequestFlag : Request\n"; + auto pResponse = std::make_shared(); + pResponse->setRequestHandle(request->getRequestHandle()); + pResponse->setResourceHandle(request->getResourceHandle()); + if (requestType == "GET") { cout << "\t\trequestType : GET\n"; - try - { - if (response) - { - OCRepresentation rep = myResource.get(); - cout << rep.getJSONRepresentation() << endl; - response->setErrorCode(200); - response->setResourceRepresentation(rep, DEFAULT_INTERFACE); - } - else - { - cout << "response is null\n"; - } - } - catch (exception &e) + + pResponse->setErrorCode(200); + pResponse->setResponseResult(OC_EH_OK); + pResponse->setResourceRepresentation(myResource.get()); + if (OC_STACK_OK == OCPlatform::sendResponse(pResponse)) { - cout << e.what() << endl; + ehResult = OC_EH_OK; } } + else if (requestType == "PUT") { cout << "\t\t\trequestType : PUT\n"; @@ -257,23 +260,61 @@ OCEntityHandlerResult entityHandler(std::shared_ptr< OCResourceRequest > request OCRepresentation rep = request->getResourceRepresentation(); myResource.put(rep); - if (response) + if (pResponse) + { + pResponse->setErrorCode(200); + pResponse->setResourceRepresentation(myResource.get()); + } + if (OC_STACK_OK == OCPlatform::sendResponse(pResponse)) { - response->setErrorCode(200); - response->setResourceRepresentation(myResource.get()); + ehResult = OC_EH_OK; } } + else if (requestType == "POST") { + cout << "\t\t\trequestType : POST\n"; } + else if (requestType == "DELETE") { + cout << "\t\trequestType : DELETE\n"; + cout << "DeviceResource Delete Request" << std::endl; + + if (myResource.deleteDeviceResource() == OC_STACK_OK) + { + cout << "\tSuccess DELETE\n"; + pResponse->setErrorCode(200); + pResponse->setResponseResult(OC_EH_RESOURCE_DELETED); + ehResult = OC_EH_OK; + } + else + { + pResponse->setResponseResult(OC_EH_ERROR); + ehResult = OC_EH_ERROR; + } + + OCPlatform::sendResponse(pResponse); } } - else if (requestFlag & RequestHandlerFlag::ObserverFlag) + if (requestFlag & RequestHandlerFlag::ObserverFlag) { pthread_t threadId; + ObservationInfo observationInfo = request->getObservationInfo(); + if (ObserveAction::ObserveRegister == observationInfo.action) + { + myResource.m_interestedObservers.push_back(observationInfo.obsId); + } + else if (ObserveAction::ObserveUnregister == observationInfo.action) + { + myResource.m_interestedObservers.erase(std::remove( + myResource.m_interestedObservers.begin(), + myResource.m_interestedObservers.end(), + observationInfo.obsId), + myResource.m_interestedObservers.end()); + } + cout << request->getResourceUri() << endl; cout << request->getResourceRepresentation().getUri() << endl; @@ -290,6 +331,7 @@ OCEntityHandlerResult entityHandler(std::shared_ptr< OCResourceRequest > request pthread_create(&threadId , NULL , ChangeLightRepresentation , (void *) NULL); startedThread = 1; } + ehResult = OC_EH_OK; } } else @@ -297,7 +339,22 @@ OCEntityHandlerResult entityHandler(std::shared_ptr< OCResourceRequest > request std::cout << "Request invalid" << std::endl; } - return OC_EH_OK; + return ehResult; +} + +void quitProcess() +{ + stopPresence(); + exit(0); +} + +void handleSigInt(int signum) +{ + if (signum == SIGINT) + { + std::cout << " handleSigInt in" << std::endl; + quitProcess(); + } } int main() @@ -318,9 +375,11 @@ int main() try { + startPresence(30); myResource.createResource(); + signal(SIGINT, handleSigInt); while (true) { bool end = false; @@ -330,6 +389,7 @@ int main() cout << "2. Temp is down" << endl; cout << "3. This Program will be ended." << endl; cout << "========================================================" << endl; + cin >> number; switch (number) @@ -353,12 +413,14 @@ int main() case 3: { cout << "Bye!" << endl; + stopPresence(); end = true; + quitProcess(); break; } default: { - cout << "You type wrong number. Try again!" << endl; + cout << "Invalid input. Please try again." << endl; break; } } @@ -372,4 +434,7 @@ int main() { cout << "main exception : " << e.what() << endl; } + + } + -- 2.7.4