From: Jay Sharma Date: Thu, 9 Jul 2015 15:54:13 +0000 (+0530) Subject: Sample Client and Server Application X-Git-Tag: 0.9.2-RC1^2~51 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=54ad793606cbb73fa24f71212c71dbe284bf1aa6;p=contrib%2Fiotivity.git Sample Client and Server Application - Sample client using the Resource Client APIs (Resource Broker & Resource Cache) - Sample Server using Server Builder APIs Change-Id: Ibdafb01f8a9c40c52d9a9175c5e5ddd4c5a43eb6 Signed-off-by: Jay Sharma Reviewed-on: https://gerrit.iotivity.org/gerrit/1607 Tested-by: jenkins-iotivity Reviewed-by: Uze Choi --- diff --git a/service/resource-manipulation/examples/SConscript b/service/resource-manipulation/examples/SConscript new file mode 100644 index 0000000..c023f3f --- /dev/null +++ b/service/resource-manipulation/examples/SConscript @@ -0,0 +1,8 @@ +## +# Examples build script +## +Import('env') + +target_os = env.get('TARGET_OS') +if target_os == 'linux': + SConscript('linux/SConscript') diff --git a/service/resource-manipulation/examples/linux/SConscript b/service/resource-manipulation/examples/linux/SConscript new file mode 100644 index 0000000..7014693 --- /dev/null +++ b/service/resource-manipulation/examples/linux/SConscript @@ -0,0 +1,70 @@ +#****************************************************************** +# +# 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. +# +#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +## +# linux sample app build script (Sample Client & Sample Server) +## +Import('env') + +# Add third party libraries +lib_env = env.Clone() +SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env') + +ResourceClient_env = lib_env.Clone() +ResourceServer_env = lib_env.Clone() + +###################################################################### +# ##### Resource Client ##### +###################################################################### + +ResourceClient_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x']) +ResourceClient_env.AppendUnique(LIBS = ['ResourceClient','ResourceCache', 'ResourceBroker', 'ExpiryTimer','service_common','oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap', 'pthread']) +ResourceClient_env.AppendUnique(CPPPATH = ['../../modules/resourceBroker/include']) +ResourceClient_env.AppendUnique(CPPPATH = ['../../modules/resourceCache/include']) +ResourceClient_env.AppendUnique(CPPPATH = ['../../modules/common/primitiveResource/include']) +ResourceClient_env.AppendUnique(CPPPATH = ['../../include']) + + +###################################################################### +# ##### Resource Server ##### +###################################################################### + +ResourceServer_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x']) +ResourceServer_env.AppendUnique(LIBS = ['libserver_builder', 'libservice_common','oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap', 'pthread']) +ResourceServer_env.AppendUnique(CPPPATH = ['../../modules/common/primitiveResource/include']) +ResourceServer_env.AppendUnique(CPPPATH = ['../../modules/serverBuilder/include']) + +if env.get('SECURED') == '1': + ResourceClient_env.AppendUnique(LIBS = ['tinydtls']) + ResourceServer_env.AppendUnique(LIBS = ['tinydtls']) + +if 'rt' in ResourceClient_env.get('LIBS'): + ResourceClient_env.Append(LIBS = ['rt']) +if 'rt' in ResourceServer_env.get('LIBS'): + ResourceServer_env.Append(LIBS = ['rt']) + +#################################################################### +# Source files and Targets +#################################################################### +sampleResourceClient = ResourceClient_env.Program('sampleResourceClient', 'SampleResourceClient.cpp') +sampleResourceServer = ResourceServer_env.Program('sampleResourceServer', 'SampleResourceServer.cpp') + +ResourceClient_env.InstallTarget(sampleResourceClient, 'sampleResourceClient') +ResourceServer_env.InstallTarget(sampleResourceServer, 'sampleResourceServer') diff --git a/service/resource-manipulation/examples/linux/SampleResourceClient.cpp b/service/resource-manipulation/examples/linux/SampleResourceClient.cpp new file mode 100644 index 0000000..219428d --- /dev/null +++ b/service/resource-manipulation/examples/linux/SampleResourceClient.cpp @@ -0,0 +1,306 @@ +#include + +#include "ResourceClient.h" +#include "ResourceAttributes.h" +#include "OCPlatform.h" + +using namespace std; +using namespace OC; +using namespace OIC::Service; + +std::shared_ptr resource; +ResourceAttributes resourceAttributes; +bool startCachingFlag; +bool isReady; + +//callback function for discoverResource() +void OnResourceDiscovered(std::shared_ptr foundResource) +{ + + cout << "\nOnResourceDiscovered callback" << std::endl; + + std::string resourceURI = foundResource->getUri(); + std::string hostAddress = foundResource->getAddress(); + + cout << "\tResource URI : " << resourceURI << std::endl; + cout << "\tResource Host : " << hostAddress << std::endl; + + resource = foundResource; + isReady = true; +} + +//callback for StartWatching() +void OnResourceStateChanged(ResourceState resourceState) +{ + + cout << "\nOnResourceStateChanged callback" << std::endl; + + if (resourceState == ResourceState::NOT_WATCHING) + cout << "State changed to : NOT_WATCHING" << std::endl; + else if (resourceState == ResourceState::ALIVE) + cout << "State changed to : ALIVE" << std::endl; + else if (resourceState == ResourceState::REQUESTED) + cout << "State changed to : REQUESTED" << std::endl; + else if (resourceState == ResourceState::LOST_SIGNAL) + cout << "State changed to : LOST_SIGNAL" << std::endl; + else if (resourceState == ResourceState::DESTROYED) + cout << "State changed to : DESTROYED" << std::endl; +} + +//callback for startCaching() [uptodate] +void OnCacheUpdated(const ResourceAttributes atttribute ) +{ + cout << "\nOnCacheUpdated callback" << std::endl; + if (atttribute.empty()) + { + std::cout << "Attribute is Empty" << std::endl; + } + else + { + ResourceAttributes::const_iterator iter = atttribute.begin(); + for (unsigned int i = 0; i < atttribute.size(); ++i) + { + std::cout << "key : " << iter->key() << "\nvalue : " << iter->value().toString() << std::endl; + ++iter; + } + } + +} +//callback for getRemoteAttributes() +void OnRemoteAttributesReceivedCallback(const ResourceAttributes &atttribute) +{ + + std::cout << "\nOnRemoteAttributesReceivedCallback callback" << std::endl; + if (atttribute.empty()) + { + std::cout << "Got empty attribute " << std::endl; + } + else + { + resourceAttributes = atttribute; + ResourceAttributes::const_iterator iter = atttribute.begin(); + for (unsigned int i = 0; i < atttribute.size(); ++i) + { + std::cout << "key : " << iter->key() << "\nvalue : " << iter->value().toString() << std::endl; + ++iter; + } + } +} + +//callback for setRemoteAttributes() +void OnRemoteAttributesSetCallback(const ResourceAttributes &atttribute) +{ + + std::cout << "\nOnRemoteAttributesSetCallback callback" << std::endl; + if (atttribute.empty()) + { + std::cout << "Got empty attribute " << std::endl; + } + else + { + resourceAttributes = atttribute; + ResourceAttributes::const_iterator iter = atttribute.begin(); + for (unsigned int i = 0; i < atttribute.size(); ++i) + { + std::cout << "key : " << iter->key() << "\nvalue : " << iter->value().toString() << std::endl; + ++iter; + } + } +} + +int main() +{ + + DiscoveryManager *discoveryManagerInstance = DiscoveryManager::getInstance(); + bool cachingFlag = false; + + //configuring the platform + PlatformConfig config + { + OC::ServiceType::InProc, ModeType::Client, "0.0.0.0", 0, OC::QualityOfService::LowQos + }; + OCPlatform::Configure(config); + + std::cout << "\nPlatform configured successfully" << std::endl; + std::string uri = ""; + std::string address = ""; + std::string rt = "core.TemperatureSensor"; + + try + { + uri = OC_MULTICAST_DISCOVERY_URI + uri + "?rt=" + rt; + //discover the resource in the network + discoveryManagerInstance->discoverResource(address, uri , CT_DEFAULT, &OnResourceDiscovered); + } + catch (InvalidParameterException e) + { + cout << "Exeception in discoverResource" << e.what() << std::endl; + } + + bool isRun = true; + int userInput; + while (isRun) + { + while (isReady) + { + cout << endl; + cout << "1 :: Start Hosting" << endl; + cout << "2 :: Stop Hosting" << endl; + cout << "3 :: Get Attribute" << endl; + cout << "4 :: Set Attribute" << endl; + cout << "5 :: Start caching (No update to Application)" << endl; + cout << "6 :: Start caching (Update the application when data change)" << + endl; //look for the datachange on server + cout << "7 :: Get Resource cache State" << endl; + cout << "8 :: Get Cached Attributes" << endl; + cout << "9 :: Get Cached Attribute" << endl; + cout << "10 :: Stop caching" << endl; + cout << "11 :: QUIT" << endl; + + cin >> userInput; + + if (userInput == 1) + { + try + { + resource->startWatching(&OnResourceStateChanged); + cout << "\n\n********** Hosting Started ***********" << std::endl; + } + catch (InvalidParameterException e) + { + cout << "Exeception in startWatching :: " << e.what() << std::endl; + } + } + else if (userInput == 2) + { + resource->stopWatching(); + cout << "\n\n****** Hosting stopped******" << std::endl; + } + else if (userInput == 3) + { + resource->getRemoteAttributes(&OnRemoteAttributesReceivedCallback); + } + else if (userInput == 4) + { + int temperatureValue; + if (0 == resourceAttributes.size()) + { + cout << "\n***First Get the Attributes from Remote Device : press 3 to get attributes***" << + std::endl; + } + else + { + ResourceAttributes::const_iterator iter = resourceAttributes.begin(); + for (unsigned int i = 0; i < resourceAttributes.size(); ++i) + { + if ( iter->key() == "Temperature") + { + cout << "Enter the value you want to set :"; + cin >> temperatureValue; + resourceAttributes["Temperature"] = temperatureValue; + resource->setRemoteAttributes(resourceAttributes, &OnRemoteAttributesSetCallback); + } + ++iter; + } + } + } + else if (userInput == 5) + { + if (false == cachingFlag) + { + resource->startCaching(); + cout << "********** caching Started ***********" << std::endl; + cachingFlag = true; + } + else + { + cout << "*** Already Started... To start it again first stop it : press 10 ***" << std::endl; + } + } + else if (userInput == 6) + { + try + { + if (false == cachingFlag) + { + resource->startCaching(&OnCacheUpdated); + cout << "********** caching Started ***********" << std::endl; + } + else + { + cout << "*** Already Started... To start it again first stop it : press 10 ***" << std::endl; + } + } + catch (InvalidParameterException e) + { + cout << "Exeception in startCaching :: " << e.what() << std::endl; + } + } + else if (userInput == 7) + { + + CacheState state = resource->getResourceCacheState(); + if (state == CacheState ::READY) + cout << "Current Cache State : " << "CACHE_STATE ::READY" << std::endl; + else if (state == CacheState ::READY_YET) + cout << "Current Cache State : " << "CACHE_STATE ::READY_YET" << std::endl; + else if (state == CacheState ::LOST_SIGNAL) + cout << "Current Cache State : " << "CACHE_STATE ::LOST_SIGNAL" << std::endl; + else if (state == CacheState ::DESTROYED) + cout << "Current Cache State : " << "CACHE_STATE ::DESTROYED" << std::endl; + else if (state == CacheState ::UPDATING) + cout << "Current Cache State : " << "CACHE_STATE ::UPDATING" << std::endl; + else if (state == CacheState ::NONE) + cout << "Current Cache State : " << "CACHE_STATE ::NONE" << std::endl; + } + else if (userInput == 8) + { + ResourceAttributes atttribute = resource->getCachedAttributes(); + if (atttribute.empty()) + { + cout << "Received cached attribute is empty" << std::endl; + } + else + { + ResourceAttributes::const_iterator iter = atttribute.begin(); + for (unsigned int i = 0; i < atttribute.size(); ++i) + { + std::cout << "\nkey : " << iter->key() << "\nvalue : " << iter->value().toString() << std::endl; + ++iter; + } + } + } + else if (userInput == 9) + { + std::string key = "Temperature"; + try + { + ResourceAttributes::Value valueObj = resource->getCachedAttribute(key); + int value = valueObj.get< int >(); + cout << "\nkey : " << key << "\nValue : " << value << std::endl; + } + catch (BadGetException e) + { + cout << "Exeception in getCachedAttribute BadGetException:: " << e.what() << std::endl; + } + } + else if (userInput == 10) + { + resource->stopCaching(); + cachingFlag = false; + cout << "****** Caching stopped ******" << std::endl; + } + else if (userInput == 11) + { + isReady = false; + isRun = false; + } + else + { + cout << "*** Please enter the number between 1-11 ***" << std::endl; + } + } + } + return 0; +} + diff --git a/service/resource-manipulation/examples/linux/SampleResourceServer.cpp b/service/resource-manipulation/examples/linux/SampleResourceServer.cpp new file mode 100644 index 0000000..7da312c --- /dev/null +++ b/service/resource-manipulation/examples/linux/SampleResourceServer.cpp @@ -0,0 +1,225 @@ +/****************************************************************** + * + * 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 "PrimitiveResource.h" +#include "ResourceObject.h" +#include "OCPlatform.h" +#include "OCApi.h" + +using namespace std; +using namespace OC; +using namespace OC::OCPlatform; +using namespace OIC::Service; + +std::string resourceUri = "/a/TempHumSensor"; +std::string resourceType = "core.TemperatureSensor"; +std::string resourceInterface = "oic.if."; +std::string attributeKey = "Temperature"; +ResourceObject::Ptr server; + +//display the menu on the screen +void displayMenu() +{ + std::cout << "=====================================================================\n\n"; + std::cout << " 1 - Creation of Resource [Auto control for requests]" << std::endl; + std::cout << " 2 - Creation of Resource [Developer control for Get and Set requests]" <getAttributes(); + ResourceAttributes::const_iterator iter = attr.begin(); + for (unsigned int i = 0; i < attr.size(); ++i) + { + std::cout << "\nkey : " << iter->key() << "\nvalue : " << iter->value().toString() << std::endl; + ++iter; + } + return PrimitiveGetResponse::create(attr); +} + +//hander for set request (if developer choose second option for resource Creation) +PrimitiveSetResponse RequestHandlerForSet(const PrimitiveRequest &request, + ResourceAttributes &attrs) +{ + cout << "\nRecieved a Set request from Client" << std::endl; + ResourceAttributes::const_iterator iter = attrs.begin(); + for (unsigned int i = 0; i < attrs.size(); ++i) + { + std::cout << "\nkey : " << iter->key() << "\nvalue : " << iter->value().toString() << std::endl; + ++iter; + } + return PrimitiveSetResponse::create(attrs); +} + +int main(void) +{ + + int userInput; + int initialTemperature = 0; + int temperatureInput; + bool flag = true; + startPresence(3); + + displayMenu(); + + //userInput for creation of Resource + std::cin >> userInput; + std::cin.clear(); + std::cin.ignore (std::numeric_limits::max(), '\n'); + try + { + while (flag) + { + + switch (userInput) + { + + case 1: + //Creation of Resource & Auto control for all requests from Client + { + //creation of Resource + server = ResourceObject::Builder(resourceUri, resourceType, + resourceInterface).setDiscoverable(true).setObservable(false).build(); + std::cout << "Resource created successfully " << std::endl; + + //setting attribute for the Created Resource + server->setAttribute(attributeKey, initialTemperature); + flag = false; + break; + } + + case 2: + //Creation of Resource & setting get and set handler for handling get and set request from client in application + { + server = ResourceObject::Builder(resourceUri, resourceType, + resourceInterface).setDiscoverable(true).setObservable(false).build(); + std::cout << "Resource created successfully " << std::endl; + + //setting attribute for the Created Resource + server->setAttribute(attributeKey, initialTemperature); + + //setting handler for handling get request from the client + server->setGetRequestHandler(RequestHandlerForGet); + + // setting handler for handling set request from the client + server->setSetRequestHandler(RequestHandlerForSet); + flag = false; + break; + } + case 3: + return 0; + default : + std::cout << "Invalid Input" << std::endl; + break; + } + } + + while (true) + { + bool end = false; + cout << endl; + cout << "========================================================" << endl; + cout << "1. Increase Temperature by 10 degree" << endl; + cout << "2. Decrease Temperature by 10 degree" << endl; + cout << "3. Stop the Sensor" << endl; + cout << "========================================================" << endl; + + //user Input for increasing/decreasing the temperature + cin >> temperatureInput; + if (std::cin.fail()) + { + std::cin.clear(); + std::cin.ignore(std::numeric_limits::max(), '\n'); + std::cout << "Invalid input type, please try again" << std::endl; + continue; + } + + switch (temperatureInput) + { + case 1: + { + ResourceObject::LockGuard lock(*server); + ResourceAttributes attrs = server->getAttributes(); + + attrs[attributeKey] = (server->getAttribute(attributeKey) + 10); + server->setAttribute(attributeKey, attrs[attributeKey]); + cout << "\nTemperature increased by 10 degree" << endl; + + //getting the current attribute and priniting it on the console + attrs = server->getAttributes(); + cout << "\nCurrent Temperature : "; + ResourceAttributes::const_iterator iter = attrs.begin(); + for (unsigned int i = 0; i < attrs.size(); ++i) + { + std::cout << iter->value().toString() << std::endl; + ++iter; + } + break; + } + case 2: + { + ResourceObject::LockGuard lock(*server); + ResourceAttributes attrs = server->getAttributes(); + attrs[attributeKey] = (server->getAttribute(attributeKey) - 10); + server->setAttribute(attributeKey, attrs[attributeKey]); + cout << "\nTemperature decreased by 10 degree" << endl; + + //getting the current attribute and priniting it on the console + attrs = server->getAttributes(); + cout << "\nCurrent Temperature : "; + ResourceAttributes::const_iterator iter = attrs.begin(); + for (unsigned int i = 0; i < attrs.size(); ++i) + { + std::cout << iter->value().toString() << std::endl; + ++iter; + } + break; + } + case 3: + { + cout << "Stopping the Resource" << endl; + end = true; + break; + } + default: + { + cout << "Invalid input. Please try again." << endl; + break; + } + } + if (end == true) + { + break; + } + } + } + catch (exception &e) + { + cout << "main exception : " << e.what() << endl; + } +} + +