Imported Upstream version 0.9.2
[platform/upstream/iotivity.git] / resource / csdk / stack / samples / linux / SimpleClientServer / ocserverbasicops.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 <stdio.h>
22 #include <string.h>
23 #include <stdlib.h>
24 #include <unistd.h>
25 #include <signal.h>
26 #include <pthread.h>
27 #include "ocstack.h"
28 #include "logger.h"
29 #include "ocserverbasicops.h"
30 #include "ocpayload.h"
31
32 //string length of "/a/led/" + std::numeric_limits<int>::digits10 + '\0'"
33 // 7 + 9 + 1 = 17
34 const int URI_MAXSIZE = 17;
35
36 volatile sig_atomic_t gQuitFlag = 0;
37
38 static LEDResource LED;
39 // This variable determines instance number of the LED resource.
40 // Used by POST method to create a new instance of LED resource.
41 static int gCurrLedInstance = 0;
42 #define SAMPLE_MAX_NUM_POST_INSTANCE 2
43 static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
44
45 char *gResourceUri= (char *)"/a/led";
46
47 OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
48 {
49     OCRepPayload* payload = OCRepPayloadCreate();
50     if(!payload)
51     {
52         OC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
53         return nullptr;
54     }
55
56     OCRepPayloadSetUri(payload, uri);
57     OCRepPayloadSetPropBool(payload, "state", state);
58     OCRepPayloadSetPropInt(payload, "power", power);
59
60     return payload;
61 }
62
63 //This function takes the request as an input and returns the response
64 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
65 {
66     if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
67     {
68         OC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
69         return nullptr;
70     }
71
72     OCRepPayload* input = reinterpret_cast<OCRepPayload*>(ehRequest->payload);
73
74     LEDResource *currLEDResource = &LED;
75
76     if (ehRequest->resource == gLedInstance[0].handle)
77     {
78         currLEDResource = &gLedInstance[0];
79         gResourceUri = (char *) "/a/led/0";
80     }
81     else if (ehRequest->resource == gLedInstance[1].handle)
82     {
83         currLEDResource = &gLedInstance[1];
84         gResourceUri = (char *) "/a/led/1";
85     }
86
87     if(OC_REST_PUT == ehRequest->method)
88     {
89         // Get pointer to query
90         int64_t pow;
91         if(OCRepPayloadGetPropInt(input, "power", &pow))
92         {
93             currLEDResource->power =pow;
94         }
95
96         bool state;
97         if(OCRepPayloadGetPropBool(input, "state", &state))
98         {
99             currLEDResource->state = state;
100         }
101     }
102
103     return getPayload(gResourceUri, currLEDResource->power, currLEDResource->state);
104 }
105
106 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
107         OCRepPayload **payload)
108 {
109     OCEntityHandlerResult ehResult;
110     OCRepPayload *getResp = constructResponse(ehRequest);
111
112     if(getResp)
113     {
114         *payload = getResp;
115         ehResult = OC_EH_OK;
116      }
117     else
118     {
119         ehResult = OC_EH_ERROR;
120     }
121
122     return ehResult;
123 }
124
125 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
126         OCRepPayload **payload)
127 {
128     OCEntityHandlerResult ehResult;
129     OCRepPayload *putResp = constructResponse(ehRequest);
130
131     if(putResp)
132     {
133         *payload = putResp;
134         ehResult = OC_EH_OK;
135     }
136     else
137     {
138         ehResult = OC_EH_ERROR;
139     }
140
141     return ehResult;
142 }
143
144 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
145         OCEntityHandlerResponse *response, OCRepPayload **payload)
146 {
147     OCRepPayload *respPLPost_led = nullptr;
148     OCEntityHandlerResult ehResult = OC_EH_OK;
149
150     /*
151      * The entity handler determines how to process a POST request.
152      * Per the REST paradigm, POST can also be used to update representation of existing
153      * resource or create a new resource.
154      * In the sample below, if the POST is for /a/led then a new instance of the LED
155      * resource is created with default representation (if representation is included in
156      * POST payload it can be used as initial values) as long as the instance is
157      * lesser than max new instance count. Once max instance count is reached, POST on
158      * /a/led updated the representation of /a/led (just like PUT)
159      */
160
161     if (ehRequest->resource == LED.handle)
162     {
163         if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
164         {
165             // Create new LED instance
166             char newLedUri[URI_MAXSIZE ];
167             snprintf(newLedUri, URI_MAXSIZE, "/a/led/%d", gCurrLedInstance);
168
169             respPLPost_led = OCRepPayloadCreate();
170             OCRepPayloadSetUri(respPLPost_led, gResourceUri);
171             OCRepPayloadSetPropString(respPLPost_led, "createduri", newLedUri);
172
173             if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
174             {
175                 OC_LOG (INFO, TAG, "Created new LED instance");
176                 gLedInstance[gCurrLedInstance].state = 0;
177                 gLedInstance[gCurrLedInstance].power = 0;
178                 gCurrLedInstance++;
179                 strncpy ((char *)response->resourceUri, newLedUri, MAX_URI_LENGTH);
180                 ehResult = OC_EH_RESOURCE_CREATED;
181             }
182         }
183         else
184         {
185             respPLPost_led = constructResponse(ehRequest);
186         }
187     }
188     else
189     {
190         for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
191         {
192             if (ehRequest->resource == gLedInstance[i].handle)
193             {
194                 if (i == 0)
195                 {
196                     respPLPost_led = constructResponse(ehRequest);
197                     break;
198                 }
199                 else if (i == 1)
200                 {
201                     respPLPost_led = constructResponse(ehRequest);
202                 }
203             }
204         }
205     }
206
207     if ((respPLPost_led != NULL))
208     {
209         *payload = respPLPost_led;
210         ehResult = OC_EH_OK;
211     }
212     else
213     {
214         OC_LOG_V (INFO, TAG, "Payload was NULL");
215         ehResult = OC_EH_ERROR;
216     }
217
218     return ehResult;
219 }
220
221 OCEntityHandlerResult
222 OCEntityHandlerCb (OCEntityHandlerFlag flag,
223         OCEntityHandlerRequest *entityHandlerRequest,void* callbackParam)
224 {
225     OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
226
227     OCEntityHandlerResult ehResult = OC_EH_ERROR;
228     OCEntityHandlerResponse response;
229
230     // Validate pointer
231     if (!entityHandlerRequest)
232     {
233         OC_LOG (ERROR, TAG, "Invalid request pointer");
234         return OC_EH_ERROR;
235     }
236
237     OCRepPayload* payload = nullptr;
238
239     if (flag & OC_REQUEST_FLAG)
240     {
241         OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
242         if (entityHandlerRequest)
243         {
244             if (OC_REST_GET == entityHandlerRequest->method)
245             {
246                 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
247                 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
248             }
249             else if (OC_REST_PUT == entityHandlerRequest->method)
250             {
251                 OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
252                 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
253             }
254             else if (OC_REST_POST == entityHandlerRequest->method)
255             {
256                 OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
257                 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
258             }
259             else
260             {
261                 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
262                         entityHandlerRequest->method);
263             }
264
265             if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
266             {
267                 // Format the response.  Note this requires some info about the request
268                 response.requestHandle = entityHandlerRequest->requestHandle;
269                 response.resourceHandle = entityHandlerRequest->resource;
270                 response.ehResult = ehResult;
271                 response.payload = reinterpret_cast<OCPayload*>(payload);
272                 response.numSendVendorSpecificHeaderOptions = 0;
273                 memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
274                 memset(response.resourceUri, 0, sizeof(response.resourceUri));
275                 // Indicate that response is NOT in a persistent buffer
276                 response.persistentBufferFlag = 0;
277
278                 // Send the response
279                 if (OCDoResponse(&response) != OC_STACK_OK)
280                 {
281                     OC_LOG(ERROR, TAG, "Error sending response");
282                     ehResult = OC_EH_ERROR;
283                 }
284             }
285         }
286     }
287
288     OCPayloadDestroy(response.payload);
289     return ehResult;
290 }
291
292 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
293 void handleSigInt(int signum)
294 {
295     if (signum == SIGINT)
296     {
297         gQuitFlag = 1;
298     }
299 }
300
301 int main(int argc, char* argv[])
302 {
303     OC_LOG(DEBUG, TAG, "OCServer is starting...");
304     if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
305     {
306         OC_LOG(ERROR, TAG, "OCStack init error");
307         return 0;
308     }
309
310     /*
311      * Declare and create the example resource: LED
312      */
313     createLEDResource(gResourceUri, &LED, false, 0);
314
315     // Break from loop with Ctrl-C
316     OC_LOG(INFO, TAG, "Entering ocserver main loop...");
317     signal(SIGINT, handleSigInt);
318     while (!gQuitFlag)
319     {
320         if (OCProcess() != OC_STACK_OK)
321         {
322             OC_LOG(ERROR, TAG, "OCStack process error");
323             return 0;
324         }
325
326         sleep(2);
327     }
328
329     OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
330
331     if (OCStop() != OC_STACK_OK)
332     {
333         OC_LOG(ERROR, TAG, "OCStack process error");
334     }
335
336     return 0;
337 }
338
339 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
340 {
341     if (!uri)
342     {
343         OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
344         return -1;
345     }
346
347     ledResource->state = resourceState;
348     ledResource->power= resourcePower;
349     OCStackResult res = OCCreateResource(&(ledResource->handle),
350             "core.led",
351             OC_RSRVD_INTERFACE_DEFAULT,
352             uri,
353             OCEntityHandlerCb,
354             NULL,
355             OC_DISCOVERABLE|OC_OBSERVABLE);
356     OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
357
358     return 0;
359 }
360