6811e9464f760cb99c0b38f92f2f792ba38f05f7
[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<OCRepresentation> m_reps;
55
56 public:
57     /// Constructor
58     GarageResource(): m_name("John's Garage"), m_state(false), m_garageUri("/a/garage") {
59         // Initialize representation
60         m_garageRep.setUri(m_garageUri);
61
62         m_garageRep.setValue("state", m_state);
63         m_garageRep.setValue("name", m_name);
64
65         // For demonstration purpose we are setting x to nullptr here.
66         // In reality it may happen else where.
67         int* x = nullptr;
68
69         // Check for nullptr and set null for that attribute
70         if(x == nullptr)
71         {
72             m_garageRep.setNULL("nullAttribute");
73         }
74
75         std::vector<bool> lightStates;
76         std::vector<int>  lightPowers;
77
78         for(int i = 0; i <= 9; i++)
79         {
80             lightStates.push_back(i % 2 == 0);
81             lightPowers.push_back(i);
82         }
83
84         m_lightRep.setValue("states", lightStates);
85         m_lightRep.setValue("powers", lightPowers);
86
87         // Storing another representation within a representation
88         m_garageRep.setValue("light", m_lightRep);
89
90         OCRepresentation rep1;
91         int value1 = 5;
92         rep1.setValue("key1", value1);
93         OCRepresentation rep2;
94         int value2 = 10;
95         rep2.setValue("key2", value2);
96
97         m_reps.push_back(rep1);
98         m_reps.push_back(rep2);
99
100         // storing array of representations
101         m_garageRep.setValue("reps", m_reps);
102     }
103
104     /* Note that this does not need to be a member function: for classes you do not have
105     access to, you can accomplish this with a free function: */
106
107     /// This function internally calls registerResource API.
108     void createResource(OC::OCPlatform& platform)
109     {
110         std::string resourceURI = m_garageUri; // URI of the resource
111         std::string resourceTypeName = "core.garage"; // resource type name.
112         std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
113
114         // OCResourceProperty is defined ocstack.h
115         uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
116
117         // This will internally create and register the resource.
118         OCStackResult result = platform.registerResource(
119                                     m_resourceHandle, resourceURI, resourceTypeName,
120                                     resourceInterface, &entityHandler, resourceProperty);
121
122         if (OC_STACK_OK != result)
123         {
124             cout << "Resource creation was unsuccessful\n";
125         }
126     }
127
128     OCResourceHandle getHandle()
129     {
130         return m_resourceHandle;
131     }
132
133     // Puts representation.
134     // Gets values from the representation and
135     // updates the internal state
136     void put(OCRepresentation& rep)
137     {
138         try {
139             if (rep.getValue("state", m_state))
140             {
141                 cout << "\t\t\t\t" << "state: " << m_state << endl;
142             }
143             else
144             {
145                 cout << "\t\t\t\t" << "state not found in the representation" << endl;
146             }
147         }
148         catch (exception& e)
149         {
150             cout << e.what() << endl;
151         }
152
153     }
154
155     // gets the updated representation.
156     // Updates the representation with latest internal state before
157     // sending out.
158     OCRepresentation get()
159     {
160         m_garageRep.setValue("state", m_state);
161
162         return m_garageRep;
163     }
164
165 };
166
167 // Create the instance of the resource class (in this case instance of class 'GarageResource').
168 GarageResource myGarage;
169
170 void entityHandler(std::shared_ptr<OCResourceRequest> request,
171                    std::shared_ptr<OCResourceResponse> response)
172 {
173     cout << "\tIn Server CPP entity handler:\n";
174
175     if(request)
176     {
177         // Get the request type and request flag
178         std::string requestType = request->getRequestType();
179         int requestFlag = request->getRequestHandlerFlag();
180
181         if(requestFlag & RequestHandlerFlag::InitFlag)
182         {
183             cout << "\t\trequestFlag : Init\n";
184
185             // entity handler to perform resource initialization operations
186         }
187         if(requestFlag & RequestHandlerFlag::RequestFlag)
188         {
189             cout << "\t\trequestFlag : Request\n";
190
191             // If the request type is GET
192             if(requestType == "GET")
193             {
194                 cout << "\t\t\trequestType : GET\n";
195
196                 if(response)
197                 {
198                     // TODO Error Code
199                     response->setErrorCode(200);
200
201                     response->setResourceRepresentation(myGarage.get());
202                 }
203             }
204             else if(requestType == "PUT")
205             {
206                 cout << "\t\t\trequestType : PUT\n";
207
208                 OCRepresentation rep = request->getResourceRepresentation();
209
210                 // Do related operations related to PUT request
211
212                 // Update the lightResource
213                 myGarage.put(rep);
214
215                 if(response)
216                 {
217                     // TODO Error Code
218                     response->setErrorCode(200);
219
220                     response->setResourceRepresentation(myGarage.get());
221                 }
222
223             }
224             else if(requestType == "POST")
225             {
226                 // POST request operations
227             }
228             else if(requestType == "DELETE")
229             {
230                 // DELETE request operations
231             }
232         }
233         if(requestFlag & RequestHandlerFlag::ObserverFlag)
234         {
235             // OBSERVE operations
236         }
237     }
238     else
239     {
240         std::cout << "Request invalid" << std::endl;
241     }
242 }
243
244 int main(int argc, char* argv[1])
245 {
246     // Create PlatformConfig object
247     PlatformConfig cfg {
248         OC::ServiceType::InProc,
249         OC::ModeType::Server,
250         "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
251         0,         // Uses randomly available port
252         OC::QualityOfService::NonConfirmable
253     };
254
255     // Create a OCPlatform instance.
256     // Note: Platform creation is synchronous call.
257     try
258     {
259         OCPlatform platform(cfg);
260
261         // Invoke createResource function of class light.
262         myGarage.createResource(platform);
263
264         // Perform app tasks
265         while(true)
266         {
267             // some tasks
268         }
269     }
270     catch(OCException e)
271     {
272         //log(e.what());
273     }
274
275     // No explicit call to stop the platform.
276     // When OCPlatform destructor is invoked, internally we do platform cleanup
277 }