2c3cfdb8a55fceacb40e532d2d2342add66a16b8
[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,
224                    void* /*callbackParam*/)
225 {
226     OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
227
228     OCEntityHandlerResult ehResult = OC_EH_ERROR;
229     OCEntityHandlerResponse response = { 0, 0, OC_EH_ERROR, 0, 0, { },{ 0 }, false };
230
231     // Validate pointer
232     if (!entityHandlerRequest)
233     {
234         OC_LOG (ERROR, TAG, "Invalid request pointer");
235         return OC_EH_ERROR;
236     }
237
238     OCRepPayload* payload = nullptr;
239
240     if (flag & OC_REQUEST_FLAG)
241     {
242         OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
243         if (entityHandlerRequest)
244         {
245             if (OC_REST_GET == entityHandlerRequest->method)
246             {
247                 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
248                 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
249             }
250             else if (OC_REST_PUT == entityHandlerRequest->method)
251             {
252                 OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
253                 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
254             }
255             else if (OC_REST_POST == entityHandlerRequest->method)
256             {
257                 OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
258                 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
259             }
260             else
261             {
262                 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
263                         entityHandlerRequest->method);
264             }
265
266             if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
267             {
268                 // Format the response.  Note this requires some info about the request
269                 response.requestHandle = entityHandlerRequest->requestHandle;
270                 response.resourceHandle = entityHandlerRequest->resource;
271                 response.ehResult = ehResult;
272                 response.payload = reinterpret_cast<OCPayload*>(payload);
273                 response.numSendVendorSpecificHeaderOptions = 0;
274                 memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
275                 memset(response.resourceUri, 0, sizeof(response.resourceUri));
276                 // Indicate that response is NOT in a persistent buffer
277                 response.persistentBufferFlag = 0;
278
279                 // Send the response
280                 if (OCDoResponse(&response) != OC_STACK_OK)
281                 {
282                     OC_LOG(ERROR, TAG, "Error sending response");
283                     ehResult = OC_EH_ERROR;
284                 }
285             }
286         }
287     }
288
289     OCPayloadDestroy(response.payload);
290     return ehResult;
291 }
292
293 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
294 void handleSigInt(int signum)
295 {
296     if (signum == SIGINT)
297     {
298         gQuitFlag = 1;
299     }
300 }
301
302 int main(int /*argc*/, char* /*argv*/[])
303 {
304     OC_LOG(DEBUG, TAG, "OCServer is starting...");
305     if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
306     {
307         OC_LOG(ERROR, TAG, "OCStack init error");
308         return 0;
309     }
310
311     /*
312      * Declare and create the example resource: LED
313      */
314     createLEDResource(gResourceUri, &LED, false, 0);
315
316     // Break from loop with Ctrl-C
317     OC_LOG(INFO, TAG, "Entering ocserver main loop...");
318     signal(SIGINT, handleSigInt);
319     while (!gQuitFlag)
320     {
321         if (OCProcess() != OC_STACK_OK)
322         {
323             OC_LOG(ERROR, TAG, "OCStack process error");
324             return 0;
325         }
326
327         sleep(2);
328     }
329
330     OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
331
332     if (OCStop() != OC_STACK_OK)
333     {
334         OC_LOG(ERROR, TAG, "OCStack process error");
335     }
336
337     return 0;
338 }
339
340 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
341 {
342     if (!uri)
343     {
344         OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
345         return -1;
346     }
347
348     ledResource->state = resourceState;
349     ledResource->power= resourcePower;
350     OCStackResult res = OCCreateResource(&(ledResource->handle),
351             "core.led",
352             OC_RSRVD_INTERFACE_DEFAULT,
353             uri,
354             OCEntityHandlerCb,
355             NULL,
356             OC_DISCOVERABLE|OC_OBSERVABLE);
357     OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
358
359     return 0;
360 }
361