Merge branch 'master' into simulator
[platform/upstream/iotivity.git] / resource / csdk / stack / samples / linux / SimpleClientServer / ocserverslow.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 <sys/time.h>
28 #include <list>
29 #include "ocstack.h"
30 #include "oic_malloc.h"
31 #include "oic_string.h"
32 #include "logger.h"
33 #include "cJSON.h"
34 #include "ocserverslow.h"
35 #include "ocpayload.h"
36
37 volatile sig_atomic_t gQuitFlag = 0;
38
39 static std::list<OCEntityHandlerRequest *> gRequestList;
40 static constexpr unsigned int SLOW_RESPONSE_DELAY_SEC = 5;
41
42 static LEDResource LED;
43
44 static constexpr unsigned int SAMPLE_MAX_NUM_POST_INSTANCE = 2;
45 static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
46
47 //char *gResourceUri= const_cast<char *>("/a/led");
48 char *gResourceUri= (char *)"/a/led";
49
50 //This function takes the request as an input and returns the response
51 //in JSON format.
52 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
53 {
54     LEDResource *currLEDResource = &LED;
55
56     OC_LOG(INFO, TAG, "Entering constructResponse");
57
58     if (ehRequest->resource == gLedInstance[0].handle)
59     {
60         OC_LOG(INFO, TAG, "handle 0");
61         currLEDResource = &gLedInstance[0];
62         gResourceUri = const_cast<char *>("a/led/0");
63     }
64     else if (ehRequest->resource == gLedInstance[1].handle)
65     {
66         OC_LOG(INFO, TAG, "handle 1");
67         currLEDResource = &gLedInstance[1];
68         gResourceUri = const_cast<char *>("a/led/1");
69     }
70
71     if(OC_REST_PUT == ehRequest->method)
72     {
73         if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
74         {
75             OC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
76             return nullptr;
77         }
78
79         OCRepPayload *putPayload = reinterpret_cast<OCRepPayload*> (ehRequest->payload);
80
81         int64_t power;
82         bool state;
83
84         if (OCRepPayloadGetPropBool(putPayload, "state", &state))
85         {
86             currLEDResource->state = state;
87         }
88         if (OCRepPayloadGetPropInt (putPayload, "power", &power))
89         {
90             currLEDResource->power = power;
91         }
92     }
93
94     OCRepPayload *response = OCRepPayloadCreate();
95
96     if (!response)
97     {
98         OC_LOG_V(ERROR, TAG, "Memory allocation for response payload failed.");
99     }
100
101     OCRepPayloadSetUri (response, gResourceUri);
102     OCRepPayloadSetPropBool(response, "state", currLEDResource->state);
103     OCRepPayloadSetPropInt(response, "power", currLEDResource->power);
104
105     return response;
106 }
107
108 void ProcessGetPutRequest (OCEntityHandlerRequest *ehRequest)
109 {
110     OC_LOG(INFO, TAG, "Entering ProcessGetPutRequest");
111
112     OCRepPayload *getResp = constructResponse(ehRequest);
113
114     if(!getResp)
115     {
116         OC_LOG(ERROR, TAG, "Failed to construct response");
117         return;
118     }
119
120     OCEntityHandlerResponse response;
121
122     // Format the response.  Note this requires some info about the request
123     response.requestHandle = ehRequest->requestHandle;
124     response.resourceHandle = ehRequest->resource;
125     response.ehResult = OC_EH_OK;
126     response.payload = reinterpret_cast<OCPayload*> (getResp);
127     response.numSendVendorSpecificHeaderOptions = 0;
128     memset(response.sendVendorSpecificHeaderOptions,
129             0, sizeof response.sendVendorSpecificHeaderOptions);
130     memset(response.resourceUri, 0, sizeof(response.resourceUri));
131     // Indicate that response is NOT in a persistent buffer
132     response.persistentBufferFlag = 0;
133
134     // Send the response
135     if (OCDoResponse(&response) != OC_STACK_OK)
136     {
137         OC_LOG(ERROR, TAG, "Error sending response");
138     }
139
140     free(getResp);
141 }
142
143 OCEntityHandlerRequest *CopyRequest(OCEntityHandlerRequest *entityHandlerRequest)
144 {
145     OC_LOG(INFO, TAG, "Copying received request for slow response");
146
147     OCEntityHandlerRequest *copyOfRequest =
148             (OCEntityHandlerRequest *)OICMalloc(sizeof(OCEntityHandlerRequest));
149
150     if (copyOfRequest)
151     {
152         // Do shallow copy
153         memcpy(copyOfRequest, entityHandlerRequest, sizeof(OCEntityHandlerRequest));
154
155
156         if (copyOfRequest->query)
157         {
158             copyOfRequest->query = OICStrdup(entityHandlerRequest->query);
159             if(!copyOfRequest->query)
160             {
161                 OC_LOG(ERROR, TAG, "Copy failed due to allocation failure");
162                 OICFree(copyOfRequest);
163                 return NULL;
164             }
165         }
166
167         if (entityHandlerRequest->payload)
168         {
169             copyOfRequest->payload = reinterpret_cast<OCPayload*>
170                     (OCRepPayloadClone ((OCRepPayload*) entityHandlerRequest->payload));
171         }
172
173         // Ignore vendor specific header options for example
174         copyOfRequest->numRcvdVendorSpecificHeaderOptions = 0;
175         copyOfRequest->rcvdVendorSpecificHeaderOptions = NULL;
176     }
177
178     if (copyOfRequest)
179     {
180         OC_LOG(INFO, TAG, "Copied client request");
181     }
182     else
183     {
184         OC_LOG(ERROR, TAG, "Error copying client request");
185     }
186     return copyOfRequest;
187 }
188
189 OCEntityHandlerResult OCEntityHandlerCb (OCEntityHandlerFlag flag,
190         OCEntityHandlerRequest *entityHandlerRequest, void* callbackParam)
191 {
192     OCEntityHandlerResult result = OC_EH_ERROR;
193     OCEntityHandlerRequest *request = NULL;
194
195     OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
196
197     if (flag & OC_REQUEST_FLAG)
198     {
199         OC_LOG(INFO, TAG, "Flag includes OC_REQUEST_FLAG");
200         if (entityHandlerRequest)
201         {
202             OC_LOG_V (INFO, TAG, "request query %s from client",
203                                         entityHandlerRequest->query);
204             OC_LOG_PAYLOAD (INFO, TAG, entityHandlerRequest->payload);
205
206             // Make deep copy of received request and queue it for slow processing
207             request = CopyRequest(entityHandlerRequest);
208
209             if (request)
210             {
211
212                 OC_LOG(INFO, TAG, "Scheduling slow response for received request");
213                 gRequestList.push_back(request);
214                 // Indicate to the stack that this is a slow response
215                 result = OC_EH_SLOW;
216                 // Start the slow response alarm
217                 alarm(SLOW_RESPONSE_DELAY_SEC);
218             }
219             else
220             {
221                 OC_LOG(ERROR, TAG, "Error queuing request for slow response");
222                 // Indicate to the stack that this is a slow response
223                 result = OC_EH_ERROR;
224             }
225         }
226         else
227         {
228             OC_LOG(ERROR, TAG, "Invalid request");
229             result = OC_EH_ERROR;
230         }
231     }
232     return result;
233 }
234
235 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
236 void handleSigInt(int signum)
237 {
238     if (signum == SIGINT)
239     {
240         gQuitFlag = 1;
241     }
242 }
243
244 // SIGINT alarm handler:  alarm set by entity handler.  Does
245 // slow response when fired
246 void AlarmHandler(int sig)
247 {
248     if (sig == SIGALRM)
249     {
250         OC_LOG (INFO, TAG, "Server starting slow response");
251         if (gRequestList.empty())
252         {
253             OC_LOG (INFO, TAG, "No requests to service");
254             return;
255         }
256
257         // Get the request from the list
258         OCEntityHandlerRequest *entityHandlerRequest = gRequestList.front();
259         gRequestList.pop_front();
260         if (entityHandlerRequest->method == OC_REST_GET)
261         {
262             OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
263             ProcessGetPutRequest (entityHandlerRequest);
264         }
265         else if (entityHandlerRequest->method == OC_REST_PUT)
266         {
267             OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
268             ProcessGetPutRequest (entityHandlerRequest);
269         }
270         else
271         {
272             OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
273                     entityHandlerRequest->method);
274         }
275         // Free the request
276         OICFree(entityHandlerRequest->query);
277         OCPayloadDestroy(entityHandlerRequest->payload);
278         OICFree(entityHandlerRequest);
279
280         // If there are more requests in list, re-arm the alarm signal
281         if (gRequestList.empty())
282         {
283             alarm(SLOW_RESPONSE_DELAY_SEC);
284         }
285     }
286 }
287
288 int main(int argc, char* argv[])
289 {
290     OC_LOG(DEBUG, TAG, "OCServer is starting...");
291
292     if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
293     {
294         OC_LOG(ERROR, TAG, "OCStack init error");
295         return 0;
296     }
297
298     // Declare and create the example resource: LED
299     createLEDResource(gResourceUri, &LED, false, 42);
300
301     // Initialize slow response alarm
302     signal(SIGALRM, AlarmHandler);
303
304     // Break from loop with Ctrl-C
305     OC_LOG(INFO, TAG, "Entering ocserver main loop...");
306     signal(SIGINT, handleSigInt);
307
308     while (!gQuitFlag)
309     {
310         if (OCProcess() != OC_STACK_OK)
311         {
312             OC_LOG(ERROR, TAG, "OCStack process error");
313             return 0;
314         }
315         sleep(2);
316     }
317
318     OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
319
320     // Free requests
321     if (!gRequestList.empty())
322     {
323         for (auto iter = gRequestList.begin(); iter != gRequestList.end(); ++iter)
324         {
325             OICFree((*iter)->query);
326             OCPayloadDestroy((*iter)->payload);
327             OICFree(*iter);
328         }
329         gRequestList.clear();
330     }
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