1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
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
11 // http://www.apache.org/licenses/LICENSE-2.0
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.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
33 #include "ocserverslow.h"
35 volatile sig_atomic_t gQuitFlag = 0;
37 static std::list<OCEntityHandlerRequest *> gRequestList;
38 static constexpr unsigned int SLOW_RESPONSE_DELAY_SEC = 5;
40 static LEDResource LED;
42 static constexpr unsigned int SAMPLE_MAX_NUM_POST_INSTANCE = 2;
43 static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
45 //char *gResourceUri= const_cast<char *>("/a/led");
46 char *gResourceUri= (char *)"/a/led";
48 //This function takes the request as an input and returns the response
50 char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
52 cJSON *json = cJSON_CreateObject();
56 OC_LOG(ERROR, TAG, "CreateObject result in null for json");
62 LEDResource *currLEDResource = &LED;
64 OC_LOG(INFO, TAG, "Entering constructJsonResponse");
66 if (ehRequest->resource == gLedInstance[0].handle)
68 OC_LOG(INFO, TAG, "handle 0");
69 currLEDResource = &gLedInstance[0];
70 gResourceUri = const_cast<char *>("a/led/0");
72 else if (ehRequest->resource == gLedInstance[1].handle)
74 OC_LOG(INFO, TAG, "handle 1");
75 currLEDResource = &gLedInstance[1];
76 gResourceUri = const_cast<char *>("a/led/1");
79 if(OC_REST_PUT == ehRequest->method)
81 cJSON *putJson = cJSON_Parse((char *)ehRequest->reqJSONPayload);
85 OC_LOG(ERROR, TAG, "CreateObject result in null for putJson");
90 currLEDResource->state = ( !strcmp(cJSON_GetObjectItem(putJson,"state")->valuestring ,
92 currLEDResource->power = cJSON_GetObjectItem(putJson,"power")->valuedouble;
93 cJSON_Delete(putJson);
96 cJSON_AddStringToObject(json,"href",gResourceUri);
97 format = cJSON_CreateObject();
101 OC_LOG(ERROR, TAG, "CreateObject result in null for format");
106 cJSON_AddItemToObject(json, "rep", format);
107 cJSON_AddStringToObject(format, "state", (char *) (currLEDResource->state ? "on":"off"));
108 cJSON_AddNumberToObject(format, "power", currLEDResource->power);
110 OC_LOG(INFO, TAG, "Before constructJsonResponse print");
111 jsonResponse = cJSON_Print(json);
112 OC_LOG(INFO, TAG, "Before constructJsonResponse delete");
115 OC_LOG(INFO, TAG, "Before constructJsonResponse return");
119 void ProcessGetRequest (OCEntityHandlerRequest *ehRequest)
121 OC_LOG(INFO, TAG, "Entering ProcessGetRequest");
122 char *getResp = constructJsonResponse(ehRequest);
126 OC_LOG(ERROR, TAG, "Failed to constructJsonResponse");
129 OC_LOG(INFO, TAG, "After constructJsonResponse");
130 OCEntityHandlerResponse response;
132 // Format the response. Note this requires some info about the request
133 response.requestHandle = ehRequest->requestHandle;
134 response.resourceHandle = ehRequest->resource;
135 response.ehResult = OC_EH_OK;
136 response.payload = getResp;
137 response.payloadSize = strlen(getResp) + 1;
138 response.numSendVendorSpecificHeaderOptions = 0;
139 memset(response.sendVendorSpecificHeaderOptions,
140 0, sizeof response.sendVendorSpecificHeaderOptions);
141 memset(response.resourceUri, 0, sizeof(response.resourceUri));
142 // Indicate that response is NOT in a persistent buffer
143 response.persistentBufferFlag = 0;
146 if (OCDoResponse(&response) != OC_STACK_OK)
148 OC_LOG(ERROR, TAG, "Error sending response");
154 OCEntityHandlerRequest *CopyRequest(OCEntityHandlerRequest *entityHandlerRequest)
156 OC_LOG(INFO, TAG, "Copying received request for slow response");
157 OCEntityHandlerRequest *request =
158 (OCEntityHandlerRequest *)OCMalloc(sizeof(OCEntityHandlerRequest));
162 memcpy(request, entityHandlerRequest, sizeof(OCEntityHandlerRequest));
163 // Do deep copy of query
165 (char * )OCMalloc(strlen((const char *)entityHandlerRequest->query) + 1);
168 strcpy((char *)request->query, (const char *)entityHandlerRequest->query);
170 // Copy the request payload
171 request->reqJSONPayload = (char * )OCMalloc(
172 strlen((const char *)entityHandlerRequest->reqJSONPayload) + 1);
173 if (request->reqJSONPayload)
175 strcpy((char *)request->reqJSONPayload,
176 (const char *)entityHandlerRequest->reqJSONPayload);
178 // Ignore vendor specific header options for example
179 request->numRcvdVendorSpecificHeaderOptions = 0;
180 request->rcvdVendorSpecificHeaderOptions = NULL;
184 OCFree(request->query);
198 OC_LOG(INFO, TAG, "Copied client request");
202 OC_LOG(ERROR, TAG, "Error copying client request");
207 OCEntityHandlerResult
208 OCEntityHandlerCb (OCEntityHandlerFlag flag,
209 OCEntityHandlerRequest *entityHandlerRequest)
211 OCEntityHandlerResult result = OC_EH_ERROR;
212 OCEntityHandlerRequest *request = NULL;
214 OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
215 if (flag & OC_REQUEST_FLAG)
217 OC_LOG(INFO, TAG, "Flag includes OC_REQUEST_FLAG");
218 if (entityHandlerRequest)
220 OC_LOG_V (INFO, TAG, "request query %s from client",
221 entityHandlerRequest->query);
222 OC_LOG_V (INFO, TAG, "request payload %s from client",
223 entityHandlerRequest->reqJSONPayload);
224 // Make deep copy of received request and queue it for slow processing
225 request = CopyRequest(entityHandlerRequest);
229 OC_LOG(INFO, TAG, "Scheduling slow response for received request");
230 gRequestList.push_back(request);
231 // Indicate to the stack that this is a slow response
233 // Start the slow response alarm
234 alarm(SLOW_RESPONSE_DELAY_SEC);
238 OC_LOG(ERROR, TAG, "Error queuing request for slow response");
239 // Indicate to the stack that this is a slow response
240 result = OC_EH_ERROR;
245 OC_LOG(ERROR, TAG, "Invalid request");
246 result = OC_EH_ERROR;
252 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
253 void handleSigInt(int signum)
255 if (signum == SIGINT)
261 // SIGINT alarm handler: alarm set by entity handler. Does
262 // slow response when fired
263 void AlarmHandler(int sig)
267 OC_LOG (INFO, TAG, "Server starting slow response");
268 if (gRequestList.empty())
270 OC_LOG (INFO, TAG, "No requests to service");
274 // Get the request from the list
275 OCEntityHandlerRequest *entityHandlerRequest = gRequestList.front();
276 gRequestList.pop_front();
277 if (entityHandlerRequest->method == OC_REST_GET)
279 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
280 ProcessGetRequest (entityHandlerRequest);
284 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
285 entityHandlerRequest->method);
288 OCFree(entityHandlerRequest->query);
289 OCFree(entityHandlerRequest->reqJSONPayload);
290 OCFree(entityHandlerRequest);
292 // If there are more requests in list, re-arm the alarm signal
293 if (gRequestList.empty())
295 alarm(SLOW_RESPONSE_DELAY_SEC);
300 int main(int argc, char* argv[])
302 OC_LOG(DEBUG, TAG, "OCServer is starting...");
304 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
306 OC_LOG(ERROR, TAG, "OCStack init error");
311 * Declare and create the example resource: LED
313 createLEDResource(gResourceUri, &LED, false, 0);
315 // Initialize slow response alarm
316 signal(SIGALRM, AlarmHandler);
318 // Break from loop with Ctrl-C
319 OC_LOG(INFO, TAG, "Entering ocserver main loop...");
320 signal(SIGINT, handleSigInt);
324 if (OCProcess() != OC_STACK_OK)
326 OC_LOG(ERROR, TAG, "OCStack process error");
333 OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
336 if (!gRequestList.empty())
338 for (auto iter = gRequestList.begin(); iter != gRequestList.end(); ++iter)
340 OCFree((*iter)->query);
341 OCFree((*iter)->reqJSONPayload);
344 gRequestList.clear();
347 if (OCStop() != OC_STACK_OK)
349 OC_LOG(ERROR, TAG, "OCStack process error");
355 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
359 OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
363 ledResource->state = resourceState;
364 ledResource->power= resourcePower;
365 OCStackResult res = OCCreateResource(&(ledResource->handle),
367 OC_RSRVD_INTERFACE_DEFAULT,
370 OC_DISCOVERABLE|OC_OBSERVABLE);
371 OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));