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 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
30 #include "ocserverbasicops.h"
35 static LEDResource LED;
36 // This variable determines instance number of the LED resource.
37 // Used by POST method to create a new instance of LED resource.
38 static int gCurrLedInstance = 0;
39 #define SAMPLE_MAX_NUM_POST_INSTANCE 2
40 static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
42 char *gResourceUri= (char *)"/a/led";
44 //File containing Server's Identity and the PSK credentials
45 //of other devices which the server trusts
46 //This can be generated using 'gen_sec_bin' application
47 static char CRED_FILE[] = "server_cred.bin";
49 //This function takes the request as an input and returns the response
51 char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
53 cJSON *json = cJSON_CreateObject();
56 LEDResource *currLEDResource = &LED;
58 if (ehRequest->resource == gLedInstance[0].handle)
60 currLEDResource = &gLedInstance[0];
61 gResourceUri = (char *) "a/led/0";
63 else if (ehRequest->resource == gLedInstance[1].handle)
65 currLEDResource = &gLedInstance[1];
66 gResourceUri = (char *) "a/led/1";
69 if(OC_REST_PUT == ehRequest->method)
71 cJSON *putJson = cJSON_Parse(ehRequest->reqJSONPayload);
74 OC_LOG_V(ERROR, TAG, "Failed to parse JSON: %s", ehRequest->reqJSONPayload);
78 currLEDResource->state = ( !strcmp(cJSON_GetObjectItem(putJson,"state")->valuestring ,
80 currLEDResource->power = cJSON_GetObjectItem(putJson,"power")->valuedouble;
81 cJSON_Delete(putJson);
84 cJSON_AddStringToObject(json,"href",gResourceUri);
85 cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
86 cJSON_AddStringToObject(format, "state", (char *) (currLEDResource->state ? "on":"off"));
87 cJSON_AddNumberToObject(format, "power", currLEDResource->power);
89 jsonResponse = cJSON_Print(json);
94 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
95 char *payload, size_t maxPayloadSize)
97 OCEntityHandlerResult ehResult;
99 char *getResp = constructJsonResponse(ehRequest);
102 if (maxPayloadSize > strlen (getResp))
104 strcpy(payload, getResp);
109 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
111 ehResult = OC_EH_ERROR;
118 ehResult = OC_EH_ERROR;
124 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
125 char *payload, size_t maxPayloadSize)
127 OCEntityHandlerResult ehResult;
129 char *putResp = constructJsonResponse(ehRequest);
133 if (maxPayloadSize > strlen (putResp))
135 strcpy(payload, putResp);
140 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
142 ehResult = OC_EH_ERROR;
149 ehResult = OC_EH_ERROR;
155 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
156 char *payload, size_t maxPayloadSize)
158 char *respPLPost_led = NULL;
161 OCEntityHandlerResult ehResult;
164 * The entity handler determines how to process a POST request.
165 * Per the REST paradigm, POST can also be used to update representation of existing
166 * resource or create a new resource.
167 * In the sample below, if the POST is for /a/led then a new instance of the LED
168 * resource is created with default representation (if representation is included in
169 * POST payload it can be used as initial values) as long as the instance is
170 * lesser than max new instance count. Once max instance count is reached, POST on
171 * /a/led updated the representation of /a/led (just like PUT)
174 if (ehRequest->resource == LED.handle)
176 if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
178 // Create new LED instance
179 char newLedUri[15] = "/a/led/";
180 int newLedUriLength = strlen(newLedUri);
181 snprintf (newLedUri + newLedUriLength, sizeof(newLedUri)-newLedUriLength, "%d", gCurrLedInstance);
183 json = cJSON_CreateObject();
185 cJSON_AddStringToObject(json,"href",gResourceUri);
186 cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
187 cJSON_AddStringToObject(format, "createduri", (char *) newLedUri);
189 if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
191 OC_LOG (INFO, TAG, "Created new LED instance");
192 gLedInstance[gCurrLedInstance].state = 0;
193 gLedInstance[gCurrLedInstance].power = 0;
195 respPLPost_led = cJSON_Print(json);
202 respPLPost_led = constructJsonResponse(ehRequest);
207 for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
209 if (ehRequest->resource == gLedInstance[i].handle)
213 respPLPost_led = constructJsonResponse(ehRequest);
218 respPLPost_led = constructJsonResponse(ehRequest);
224 if ((respPLPost_led != NULL) && (maxPayloadSize > strlen (respPLPost_led)))
226 strcpy(payload, respPLPost_led);
231 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
233 ehResult = OC_EH_ERROR;
236 free(respPLPost_led);
241 OCEntityHandlerResult
242 OCEntityHandlerCb (OCEntityHandlerFlag flag,
243 OCEntityHandlerRequest *entityHandlerRequest)
245 OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
247 OCEntityHandlerResult ehResult = OC_EH_ERROR;
248 OCEntityHandlerResponse response;
249 char payload[MAX_RESPONSE_LENGTH] = {0};
251 if (flag & OC_REQUEST_FLAG)
253 OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
254 if (entityHandlerRequest)
256 if (OC_REST_GET == entityHandlerRequest->method)
258 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
259 ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload));
261 else if (OC_REST_PUT == entityHandlerRequest->method)
263 OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
264 ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload));
266 else if (OC_REST_POST == entityHandlerRequest->method)
268 OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
269 ehResult = ProcessPostRequest (entityHandlerRequest, payload, sizeof(payload));
273 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
274 entityHandlerRequest->method);
275 ehResult = OC_EH_ERROR;
278 if (ehResult == OC_EH_OK)
280 // Format the response. Note this requires some info about the request
281 response.requestHandle = entityHandlerRequest->requestHandle;
282 response.resourceHandle = entityHandlerRequest->resource;
283 response.ehResult = ehResult;
284 response.payload = payload;
285 response.payloadSize = strlen(payload);
286 response.numSendVendorSpecificHeaderOptions = 0;
287 memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
288 memset(response.resourceUri, 0, sizeof(response.resourceUri));
289 // Indicate that response is NOT in a persistent buffer
290 response.persistentBufferFlag = 0;
293 if (OCDoResponse(&response) != OC_STACK_OK)
295 OC_LOG(ERROR, TAG, "Error sending response");
296 ehResult = OC_EH_ERROR;
304 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
305 void handleSigInt(int signum)
307 if (signum == SIGINT)
313 int main(int argc, char* argv[])
315 struct timespec timeout;
317 OC_LOG(DEBUG, TAG, "OCServer is starting...");
319 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
321 OC_LOG(ERROR, TAG, "OCStack init error");
326 * Read DTLS PSK credentials from persistent storage and
327 * set in the OC stack.
329 if (SetCredentials(CRED_FILE) != OC_STACK_OK)
331 OC_LOG(ERROR, TAG, "SetCredentials failed");
335 * Declare and create the example resource: LED
337 createLEDResource(gResourceUri, &LED, false, 0);
340 timeout.tv_nsec = 100000000L;
342 // Break from loop with Ctrl-C
343 OC_LOG(INFO, TAG, "Entering ocserver main loop...");
344 signal(SIGINT, handleSigInt);
347 if (OCProcess() != OC_STACK_OK)
349 OC_LOG(ERROR, TAG, "OCStack process error");
352 nanosleep(&timeout, NULL);
355 OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
357 if (OCStop() != OC_STACK_OK)
359 OC_LOG(ERROR, TAG, "OCStack process error");
365 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
369 OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
373 ledResource->state = resourceState;
374 ledResource->power= resourcePower;
375 OCStackResult res = OCCreateResource(&(ledResource->handle),
377 OC_RSRVD_INTERFACE_DEFAULT,
380 OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
381 OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));