Imported Upstream version 0.9.2
[platform/upstream/iotivity.git] / examples / OICMiddle / Client.cpp
1 //******************************************************************
2 //
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
4 //
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
6 //
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
10 //
11 //      http://www.apache.org/licenses/LICENSE-2.0
12 //
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18 //
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20
21 #include <map>
22 #include <stdexcept>
23
24 #include "WrapResource.h"
25 #include "Client.h"
26
27 MiddleClient::MiddleClient()
28 {
29     m_findCB = bind(&MiddleClient::foundOCResource, this, placeholders::_1);
30 }
31
32 bool MiddleClient::init()
33 {
34     findResources();
35     return true;
36 }
37
38 void MiddleClient::findResources()
39 {
40     m_resourceMap.clear();
41
42     OC::OCPlatform::findResource("", OC_RSRVD_WELL_KNOWN_URI, CT_DEFAULT, m_findCB);
43 }
44
45 void MiddleClient::foundOCResource(shared_ptr<OCResource> resource)
46 {
47     WrapResource *wres;
48     string resourceID = formatResourceID(resource);
49
50     m_mutexFoundCB.lock();
51
52     try {
53         wres = m_resourceMap.at(resourceID);
54     } catch (const std::out_of_range) {
55         wres = new WrapResource(resourceID, resource);
56         m_resourceMap[resourceID] = wres;
57     }
58
59     m_mutexFoundCB.unlock();
60
61     wres->findTypes();
62 }
63
64 /*
65  *  I need a unique ID, so I concatenate the host string and resource uri
66  *  It's arbitrary and sufficient.
67  */
68 string MiddleClient::formatResourceID(std::shared_ptr<OCResource> resource)
69 {
70     if(!resource)
71     {
72         throw invalid_argument("Invalid resource object in formatResourceID");
73     }
74
75     return resource->sid() + resource->uri();
76 }
77
78 void MiddleClient::addResource(WrapResource *wres)
79 {
80     if(!wres)
81     {
82         throw invalid_argument("Invalid WrapResource object in addResource");
83     }
84
85     string resourceID = wres->getResourceID();
86     try {
87         m_resourceMap[resourceID];
88     } catch (const std::out_of_range) {
89         m_resourceMap[resourceID] = wres;
90     }
91 }