New APIs : hasAttribute, numberOfAttributes, erase in OCRepresentation.
[platform/upstream/iotivity.git] / examples / garageserver.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 ///
22 /// This sample provides using varous json types in the representation.
23 ///
24
25 #include <functional>
26
27 #include <pthread.h>
28
29 #include "OCPlatform.h"
30 #include "OCApi.h"
31
32 using namespace OC;
33 using namespace std;
34
35 // Forward declaring the entityHandler
36 void entityHandler(std::shared_ptr<OCResourceRequest> request,
37                    std::shared_ptr<OCResourceResponse> response);
38
39 /// This class represents a single resource named 'lightResource'. This resource has
40
41 class GarageResource
42 {
43 public:
44     /// Access this property from a TB client
45     std::string m_name;
46     bool m_state;
47     std::string m_garageUri;
48     OCResourceHandle m_resourceHandle;
49     OCRepresentation m_garageRep;
50     ObservationIds m_interestedObservers;
51
52     // array of lights representation with in GarageResource
53     OCRepresentation m_lightRep;
54     std::vector<bool> m_lightStates;
55     std::vector<int> m_lightPowers;
56
57 public:
58     /// Constructor
59     GarageResource(): m_name("John's Garage"), m_state(false), m_garageUri("/a/garage") {
60         // Initialize representation
61         m_garageRep.setUri(m_garageUri);
62
63         m_garageRep.setValue("state", m_state);
64         m_garageRep.setValue("name", m_name);
65
66         for(int i = 0; i <= 9; i++)
67         {
68             m_lightStates.push_back(i % 2 == 0);
69             m_lightPowers.push_back(i);
70         }
71
72         m_lightRep.setValue("states", m_lightStates);
73         m_lightRep.setValue("powers", m_lightPowers);
74
75         // Storing another representation within a representation
76         m_garageRep.setValue("light", m_lightRep);
77     }
78
79     /* Note that this does not need to be a member function: for classes you do not have
80     access to, you can accomplish this with a free function: */
81
82     /// This function internally calls registerResource API.
83     void createResource(OC::OCPlatform& platform)
84     {
85         std::string resourceURI = m_garageUri; // URI of the resource
86         std::string resourceTypeName = "core.garage"; // resource type name.
87         std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
88
89         // OCResourceProperty is defined ocstack.h
90         uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
91
92         // This will internally create and register the resource.
93         OCStackResult result = platform.registerResource(
94                                     m_resourceHandle, resourceURI, resourceTypeName,
95                                     resourceInterface, &entityHandler, resourceProperty);
96
97         if (OC_STACK_OK != result)
98         {
99             cout << "Resource creation was unsuccessful\n";
100         }
101     }
102
103     OCResourceHandle getHandle()
104     {
105         return m_resourceHandle;
106     }
107
108     // Puts representation.
109     // Gets values from the representation and
110     // updates the internal state
111     void put(OCRepresentation& rep)
112     {
113         try {
114             if (rep.getValue("state", m_state))
115             {
116                 cout << "\t\t\t\t" << "state: " << m_state << endl;
117             }
118             else
119             {
120                 cout << "\t\t\t\t" << "state not found in the representation" << endl;
121             }
122         }
123         catch (exception& e)
124         {
125             cout << e.what() << endl;
126         }
127
128     }
129
130     // gets the updated representation.
131     // Updates the representation with latest internal state before
132     // sending out.
133     OCRepresentation get()
134     {
135         m_garageRep.setValue("state", m_state);
136
137         return m_garageRep;
138     }
139
140 };
141
142 // Create the instance of the resource class (in this case instance of class 'GarageResource').
143 GarageResource myGarage;
144
145 void entityHandler(std::shared_ptr<OCResourceRequest> request,
146                    std::shared_ptr<OCResourceResponse> response)
147 {
148     cout << "\tIn Server CPP entity handler:\n";
149
150     if(request)
151     {
152         // Get the request type and request flag
153         std::string requestType = request->getRequestType();
154         int requestFlag = request->getRequestHandlerFlag();
155
156         if(requestFlag & RequestHandlerFlag::InitFlag)
157         {
158             cout << "\t\trequestFlag : Init\n";
159
160             // entity handler to perform resource initialization operations
161         }
162         if(requestFlag & RequestHandlerFlag::RequestFlag)
163         {
164             cout << "\t\trequestFlag : Request\n";
165
166             // If the request type is GET
167             if(requestType == "GET")
168             {
169                 cout << "\t\t\trequestType : GET\n";
170
171                 if(response)
172                 {
173                     // TODO Error Code
174                     response->setErrorCode(200);
175
176                     response->setResourceRepresentation(myGarage.get());
177                 }
178             }
179             else if(requestType == "PUT")
180             {
181                 cout << "\t\t\trequestType : PUT\n";
182
183                 OCRepresentation rep = request->getResourceRepresentation();
184
185                 // Do related operations related to PUT request
186
187                 // Update the lightResource
188                 myGarage.put(rep);
189
190                 if(response)
191                 {
192                     // TODO Error Code
193                     response->setErrorCode(200);
194
195                     response->setResourceRepresentation(myGarage.get());
196                 }
197
198             }
199             else if(requestType == "POST")
200             {
201                 // POST request operations
202             }
203             else if(requestType == "DELETE")
204             {
205                 // DELETE request operations
206             }
207         }
208         if(requestFlag & RequestHandlerFlag::ObserverFlag)
209         {
210             // OBSERVE operations
211         }
212     }
213     else
214     {
215         std::cout << "Request invalid" << std::endl;
216     }
217 }
218
219 int main(int argc, char* argv[1])
220 {
221     // Create PlatformConfig object
222     PlatformConfig cfg {
223         OC::ServiceType::InProc,
224         OC::ModeType::Server,
225         "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
226         0,         // Uses randomly available port
227         OC::QualityOfService::NonConfirmable
228     };
229
230     // Create a OCPlatform instance.
231     // Note: Platform creation is synchronous call.
232     try
233     {
234         OCPlatform platform(cfg);
235
236         // Invoke createResource function of class light.
237         myGarage.createResource(platform);
238
239         // Perform app tasks
240         while(true)
241         {
242             // some tasks
243         }
244     }
245     catch(OCException e)
246     {
247         //log(e.what());
248     }
249
250     // No explicit call to stop the platform.
251     // When OCPlatform destructor is invoked, internally we do platform cleanup
252 }