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 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
35 //string length of "/a/light/" + std::numeric_limits<int>::digits10 + '\0'"
37 const int URI_MAXSIZE = 19;
39 static int gObserveNotifyType = 3;
42 int gLightUnderObservation = 0;
44 static LightResource Light;
45 // This variable determines instance number of the Light resource.
46 // Used by POST method to create a new instance of Light resource.
47 static int gCurrLightInstance = 0;
49 static LightResource gLightInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
51 Observers interestedObservers[SAMPLE_MAX_NUM_OBSERVATIONS];
54 static int stopPresenceCount = 10;
55 #define numPresenceResources (2)
58 //TODO: Follow the pattern used in constructJsonResponse() when the payload is decided.
59 const char responsePayloadDeleteOk[] =
60 "{App determines payload: Delete Resource operation succeeded.}";
61 const char responsePayloadDeleteNotOK[] =
62 "{App determines payload: Delete Resource operation failed.}";
63 const char responsePayloadResourceDoesNotExist[] =
64 "{App determines payload: The resource does not exist.}";
65 const char responsePayloadDeleteResourceNotSupported[] =
66 "{App determines payload: The request is received for a non-support resource.}";
69 char *gResourceUri= (char *)"/a/light";
70 const char *contentType = "myContentType";
71 const char *dateOfManufacture = "myDateOfManufacture";
72 const char *deviceName = "myDeviceName";
73 const char *deviceUUID = "myDeviceUUID";
74 const char *firmwareVersion = "myFirmwareVersion";
75 const char *hostName = "myHostName";
76 const char *manufacturerName = "myManufacturerNa";
77 const char *manufacturerUrl = "myManufacturerUrl";
78 const char *modelNumber = "myModelNumber";
79 const char *platformVersion = "myPlatformVersion";
80 const char *supportUrl = "mySupportUrl";
81 const char *version = "myVersion";
83 OCDeviceInfo deviceInfo;
85 //This function takes the request as an input and returns the response
87 char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
89 cJSON *json = cJSON_CreateObject();
92 LightResource *currLightResource = &Light;
94 if (ehRequest->resource == gLightInstance[0].handle)
96 currLightResource = &gLightInstance[0];
97 gResourceUri = (char *) "a/light/0";
99 else if (ehRequest->resource == gLightInstance[1].handle)
101 currLightResource = &gLightInstance[1];
102 gResourceUri = (char *) "a/light/1";
105 if(OC_REST_PUT == ehRequest->method)
107 // Get cJSON pointer to query
108 cJSON *putJson = cJSON_Parse((char *)ehRequest->reqJSONPayload);
110 // Get root of JSON payload, then the 1st resource.
111 cJSON* carrier = cJSON_GetObjectItem(putJson, "oc");
112 carrier = cJSON_GetArrayItem(carrier, 0);
113 carrier = cJSON_GetObjectItem(carrier, "rep");
115 cJSON* prop = cJSON_GetObjectItem(carrier,"power");
118 currLightResource->power =prop->valueint;
121 prop = cJSON_GetObjectItem(carrier,"state");
124 currLightResource->state = prop->valueint;
127 cJSON_Delete(putJson);
130 cJSON_AddStringToObject(json,"href",gResourceUri);
131 cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
132 cJSON_AddBoolToObject(format, "state", currLightResource->state);
133 cJSON_AddNumberToObject(format, "power", currLightResource->power);
135 jsonResponse = cJSON_Print(json);
141 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
142 char *payload, uint16_t maxPayloadSize)
144 OCEntityHandlerResult ehResult;
145 char *getResp = constructJsonResponse(ehRequest);
147 if (maxPayloadSize > strlen ((char *)getResp))
149 strncpy(payload, getResp, strlen((char *)getResp));
154 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
156 ehResult = OC_EH_ERROR;
164 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
165 char *payload, uint16_t maxPayloadSize)
167 OCEntityHandlerResult ehResult;
168 char *putResp = constructJsonResponse(ehRequest);
170 if (maxPayloadSize > strlen ((char *)putResp))
172 strncpy(payload, putResp, strlen((char *)putResp));
177 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
179 ehResult = OC_EH_ERROR;
187 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
188 OCEntityHandlerResponse *response, char *payload, uint16_t maxPayloadSize)
190 OCEntityHandlerResult ehResult = OC_EH_OK;
191 char *respPLPost_light = NULL;
196 * The entity handler determines how to process a POST request.
197 * Per the REST paradigm, POST can also be used to update representation of existing
198 * resource or create a new resource.
199 * In the sample below, if the POST is for /a/light then a new instance of the Light
200 * resource is created with default representation (if representation is included in
201 * POST payload it can be used as initial values) as long as the instance is
202 * lesser than max new instance count. Once max instance count is reached, POST on
203 * /a/light updated the representation of /a/light (just like PUT)
206 if (ehRequest->resource == Light.handle)
208 if (gCurrLightInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
210 // Create new Light instance
211 char newLightUri[URI_MAXSIZE];
212 snprintf(newLightUri, URI_MAXSIZE, "/a/light/%d", gCurrLightInstance);
214 json = cJSON_CreateObject();
215 cJSON_AddStringToObject(json,"href",gResourceUri);
216 cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
217 cJSON_AddStringToObject(format, "createduri", (char *) newLightUri);
219 if (0 == createLightResource (newLightUri, &gLightInstance[gCurrLightInstance]))
221 OC_LOG (INFO, TAG, "Created new Light instance\n");
222 gLightInstance[gCurrLightInstance].state = 0;
223 gLightInstance[gCurrLightInstance].power = 0;
224 gCurrLightInstance++;
225 respPLPost_light = cJSON_Print(json);
226 strncpy ((char *)response->resourceUri, newLightUri, MAX_URI_LENGTH);
227 ehResult = OC_EH_RESOURCE_CREATED;
234 // Update repesentation of /a/light
237 respPLPost_light = constructJsonResponse(ehRequest);
242 for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
244 if (ehRequest->resource == gLightInstance[i].handle)
246 gLightInstance[i].state = true;
247 gLightInstance[i].power = 22;
250 respPLPost_light = constructJsonResponse(ehRequest);
255 respPLPost_light = constructJsonResponse(ehRequest);
261 if ((respPLPost_light != NULL) && (maxPayloadSize > strlen ((char *)respPLPost_light)))
263 strncpy(payload, respPLPost_light, strlen((char *)respPLPost_light));
267 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
269 ehResult = OC_EH_ERROR;
272 free(respPLPost_light);
276 OCEntityHandlerResult ProcessDeleteRequest (OCEntityHandlerRequest *ehRequest,
277 char *payload, uint16_t maxPayloadSize)
279 if(ehRequest == NULL)
281 OC_LOG(INFO, TAG, "The ehRequest is NULL");
284 OCEntityHandlerResult ehResult = OC_EH_OK;
286 OC_LOG_V(INFO, TAG, "\n\nExecuting %s for resource %d ", __func__, ehRequest->resource);
289 * In the sample below, the application will:
290 * 1a. pass the delete request to the c stack
291 * 1b. internally, the c stack figures out what needs to be done and does it accordingly
292 * (e.g. send observers notification, remove observers...)
293 * 1c. the c stack returns with the result whether the request is fullfilled.
294 * 2. optionally, app removes observers out of its array 'interestedObservers'
297 const char* deleteResponse = NULL;
299 if ((ehRequest != NULL) && (ehRequest->resource == Light.handle))
301 //Step 1: Ask stack to do the work.
302 OCStackResult result = OCDeleteResource(ehRequest->resource);
304 if (result == OC_STACK_OK)
306 OC_LOG (INFO, TAG, "\n\nDelete Resource operation succeeded.");
308 deleteResponse = responsePayloadDeleteOk;
310 //Step 2: clear observers who wanted to observe this resource at the app level.
311 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
313 if (interestedObservers[i].resourceHandle == ehRequest->resource)
315 interestedObservers[i].valid = false;
316 interestedObservers[i].observationId = 0;
317 interestedObservers[i].resourceHandle = NULL;
321 else if (result == OC_STACK_NO_RESOURCE)
323 OC_LOG(INFO, TAG, "\n\nThe resource doesn't exist or it might have been deleted.");
324 deleteResponse = responsePayloadResourceDoesNotExist;
325 ehResult = OC_EH_RESOURCE_DELETED;
329 OC_LOG(INFO, TAG, "\n\nEncountered error from OCDeleteResource().");
330 deleteResponse = responsePayloadDeleteNotOK;
331 ehResult = OC_EH_ERROR;
334 else if (ehRequest->resource != Light.handle)
336 //Let's this app not supporting DELETE on some resources so
337 //consider the DELETE request is received for a non-support resource.
338 OC_LOG_V(INFO, TAG, "\n\nThe request is received for a non-support resource.");
339 deleteResponse = responsePayloadDeleteResourceNotSupported;
340 ehResult = OC_EH_FORBIDDEN;
343 if (maxPayloadSize > strlen ((char *)deleteResponse))
345 strncpy(payload, deleteResponse, strlen((char *)deleteResponse));
349 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
351 ehResult = OC_EH_ERROR;
357 OCEntityHandlerResult ProcessNonExistingResourceRequest(OCEntityHandlerRequest *ehRequest,
358 char *payload, uint16_t maxPayloadSize)
360 OC_LOG_V(INFO, TAG, "\n\nExecuting %s ", __func__);
362 const char* response = NULL;
363 response = responsePayloadResourceDoesNotExist;
365 if ( (ehRequest != NULL) &&
366 (maxPayloadSize > strlen ((char *)response)) )
368 strncpy((char *)payload, response, strlen((char *)response));
372 OC_LOG_V (ERROR, TAG, "Response buffer: %d bytes is too small",
376 return OC_EH_RESOURCE_NOT_FOUND;
379 void ProcessObserveRegister (OCEntityHandlerRequest *ehRequest)
381 OC_LOG_V (INFO, TAG, "Received observation registration request with observation Id %d",
382 ehRequest->obsInfo.obsId);
383 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
385 if (interestedObservers[i].valid == false)
387 interestedObservers[i].observationId = ehRequest->obsInfo.obsId;
388 interestedObservers[i].valid = true;
389 gLightUnderObservation = 1;
395 void ProcessObserveDeregister (OCEntityHandlerRequest *ehRequest)
397 bool clientStillObserving = false;
399 OC_LOG_V (INFO, TAG, "Received observation deregistration request for observation Id %d",
400 ehRequest->obsInfo.obsId);
401 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
403 if (interestedObservers[i].observationId == ehRequest->obsInfo.obsId)
405 interestedObservers[i].valid = false;
407 if (interestedObservers[i].valid == true)
409 // Even if there is one single client observing we continue notifying entity handler
410 clientStillObserving = true;
413 if (clientStillObserving == false)
414 gLightUnderObservation = 0;
417 OCEntityHandlerResult
418 OCDeviceEntityHandlerCb (OCEntityHandlerFlag flag,
419 OCEntityHandlerRequest *entityHandlerRequest, char* uri)
421 OC_LOG_V (INFO, TAG, "Inside device default entity handler - flags: 0x%x, uri: %s", flag, uri);
423 OCEntityHandlerResult ehResult = OC_EH_OK;
424 OCEntityHandlerResponse response;
425 char payload[MAX_RESPONSE_LENGTH] = {0};
428 if (!entityHandlerRequest)
430 OC_LOG (ERROR, TAG, "Invalid request pointer");
434 // Initialize certain response fields
435 response.numSendVendorSpecificHeaderOptions = 0;
436 memset(response.sendVendorSpecificHeaderOptions, 0,
437 sizeof response.sendVendorSpecificHeaderOptions);
438 memset(response.resourceUri, 0, sizeof response.resourceUri);
440 if (flag & OC_INIT_FLAG)
442 OC_LOG (INFO, TAG, "Flag includes OC_INIT_FLAG");
444 if (flag & OC_REQUEST_FLAG)
446 OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
447 if (entityHandlerRequest->resource == NULL)
449 OC_LOG (INFO, TAG, "Received request from client to a non-existing resource");
450 ehResult = ProcessNonExistingResourceRequest(entityHandlerRequest,
451 payload, sizeof(payload) - 1);
453 else if (OC_REST_GET == entityHandlerRequest->method)
455 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
456 ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
458 else if (OC_REST_PUT == entityHandlerRequest->method)
460 OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
461 ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
463 else if (OC_REST_DELETE == entityHandlerRequest->method)
465 OC_LOG (INFO, TAG, "Received OC_REST_DELETE from client");
466 ehResult = ProcessDeleteRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
470 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
471 entityHandlerRequest->method);
472 ehResult = OC_EH_ERROR;
475 // If the result isn't an error or forbidden, send response
476 if (!((ehResult == OC_EH_ERROR) || (ehResult == OC_EH_FORBIDDEN)))
478 // Format the response. Note this requires some info about the request
479 response.requestHandle = entityHandlerRequest->requestHandle;
480 response.resourceHandle = entityHandlerRequest->resource;
481 response.ehResult = ehResult;
482 response.payload = payload;
483 response.payloadSize = strlen(payload);
484 // Indicate that response is NOT in a persistent buffer
485 response.persistentBufferFlag = 0;
488 if (OCDoResponse(&response) != OC_STACK_OK)
490 OC_LOG(ERROR, TAG, "Error sending response");
491 ehResult = OC_EH_ERROR;
495 if (flag & OC_OBSERVE_FLAG)
497 OC_LOG(INFO, TAG, "Flag includes OC_OBSERVE_FLAG");
498 if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
500 OC_LOG (INFO, TAG, "Received OC_OBSERVE_REGISTER from client");
502 else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
504 OC_LOG (INFO, TAG, "Received OC_OBSERVE_DEREGISTER from client");
511 OCEntityHandlerResult
512 OCNOPEntityHandlerCb (OCEntityHandlerFlag flag,
513 OCEntityHandlerRequest *entityHandlerRequest)
515 // This is callback is associated with the 2 presence notification
516 // resources. They are non-operational.
520 OCEntityHandlerResult
521 OCEntityHandlerCb (OCEntityHandlerFlag flag,
522 OCEntityHandlerRequest *entityHandlerRequest)
524 OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
526 OCEntityHandlerResult ehResult = OC_EH_OK;
527 OCEntityHandlerResponse response;
528 char payload[MAX_RESPONSE_LENGTH] = {0};
531 if (!entityHandlerRequest)
533 OC_LOG (ERROR, TAG, "Invalid request pointer");
537 // Initialize certain response fields
538 response.numSendVendorSpecificHeaderOptions = 0;
539 memset(response.sendVendorSpecificHeaderOptions,
540 0, sizeof response.sendVendorSpecificHeaderOptions);
541 memset(response.resourceUri, 0, sizeof response.resourceUri);
543 if (flag & OC_INIT_FLAG)
545 OC_LOG (INFO, TAG, "Flag includes OC_INIT_FLAG");
547 if (flag & OC_REQUEST_FLAG)
549 OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
550 if (OC_REST_GET == entityHandlerRequest->method)
552 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
553 ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
555 else if (OC_REST_PUT == entityHandlerRequest->method)
557 OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
558 ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
560 else if (OC_REST_POST == entityHandlerRequest->method)
562 OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
563 ehResult = ProcessPostRequest (entityHandlerRequest,
564 &response, payload, sizeof(payload) - 1);
566 else if (OC_REST_DELETE == entityHandlerRequest->method)
568 OC_LOG (INFO, TAG, "Received OC_REST_DELETE from client");
569 ehResult = ProcessDeleteRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
573 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
574 entityHandlerRequest->method);
577 // If the result isn't an error or forbidden, send response
578 if (!((ehResult == OC_EH_ERROR) || (ehResult == OC_EH_FORBIDDEN)))
580 // Format the response. Note this requires some info about the request
581 response.requestHandle = entityHandlerRequest->requestHandle;
582 response.resourceHandle = entityHandlerRequest->resource;
583 response.ehResult = ehResult;
584 response.payload = payload;
585 response.payloadSize = strlen(payload);
586 // Indicate that response is NOT in a persistent buffer
587 response.persistentBufferFlag = 0;
589 // Handle vendor specific options
590 if(entityHandlerRequest->rcvdVendorSpecificHeaderOptions &&
591 entityHandlerRequest->numRcvdVendorSpecificHeaderOptions)
593 OC_LOG (INFO, TAG, "Received vendor specific options");
595 OCHeaderOption * rcvdOptions =
596 entityHandlerRequest->rcvdVendorSpecificHeaderOptions;
597 for( i = 0; i < entityHandlerRequest->numRcvdVendorSpecificHeaderOptions; i++)
599 if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
601 OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
602 ((OCHeaderOption)rcvdOptions[i]).optionID );
604 OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
605 MAX_HEADER_OPTION_DATA_LENGTH);
608 OCHeaderOption * sendOptions = response.sendVendorSpecificHeaderOptions;
609 uint8_t option2[] = {21,22,23,24,25,26,27,28,29,30};
610 uint8_t option3[] = {31,32,33,34,35,36,37,38,39,40};
611 sendOptions[0].protocolID = OC_COAP_ID;
612 sendOptions[0].optionID = 2248;
613 memcpy(sendOptions[0].optionData, option2, sizeof(option2));
614 sendOptions[0].optionLength = 10;
615 sendOptions[1].protocolID = OC_COAP_ID;
616 sendOptions[1].optionID = 2600;
617 memcpy(sendOptions[1].optionData, option3, sizeof(option3));
618 sendOptions[1].optionLength = 10;
619 response.numSendVendorSpecificHeaderOptions = 2;
623 if (OCDoResponse(&response) != OC_STACK_OK)
625 OC_LOG(ERROR, TAG, "Error sending response");
626 ehResult = OC_EH_ERROR;
630 if (flag & OC_OBSERVE_FLAG)
632 OC_LOG(INFO, TAG, "Flag includes OC_OBSERVE_FLAG");
634 if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
636 OC_LOG (INFO, TAG, "Received OC_OBSERVE_REGISTER from client");
637 ProcessObserveRegister (entityHandlerRequest);
639 else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
641 OC_LOG (INFO, TAG, "Received OC_OBSERVE_DEREGISTER from client");
642 ProcessObserveDeregister (entityHandlerRequest);
649 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
650 void handleSigInt(int signum)
652 if (signum == SIGINT)
658 void *ChangeLightRepresentation (void *param)
661 OCStackResult result = OC_STACK_ERROR;
664 uint8_t numNotifies = (SAMPLE_MAX_NUM_OBSERVATIONS)/2;
665 OCObservationId obsNotify[numNotifies];
671 if (gLightUnderObservation)
673 OC_LOG_V(INFO, TAG, " =====> Notifying stack of new power level %d\n", Light.power);
674 if (gObserveNotifyType == 1)
676 // Notify list of observers. Alternate observers on the list will be notified.
678 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; (i=i+2))
680 if (interestedObservers[i].valid == true)
682 obsNotify[j] = interestedObservers[i].observationId;
687 cJSON *json = cJSON_CreateObject();
689 cJSON_AddStringToObject(json,"href",gResourceUri);
690 cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
691 cJSON_AddBoolToObject(format, "state", Light.state);
692 cJSON_AddNumberToObject(format, "power", Light.power);
693 char * obsResp = cJSON_Print(json);
695 result = OCNotifyListOfObservers (Light.handle, obsNotify, j,
699 else if (gObserveNotifyType == 0)
701 // Notifying all observers
702 result = OCNotifyAllObservers (Light.handle, OC_NA_QOS);
703 if (OC_STACK_NO_OBSERVERS == result)
706 "=======> No more observers exist, stop sending observations");
707 gLightUnderObservation = 0;
712 OC_LOG (ERROR, TAG, "Incorrect notification type selected");
716 if(stopPresenceCount > 0)
718 OC_LOG_V(INFO, TAG, "================ Counting down to stop presence %d", stopPresenceCount);
720 if(!stopPresenceCount--)
722 OC_LOG(INFO, TAG, "================ stopping presence");
731 void *presenceNotificationGenerator(void *param)
735 OCDoHandle presenceNotificationHandles[numPresenceResources];
736 OCStackResult res = OC_STACK_OK;
738 std::array<std::string, numPresenceResources> presenceNotificationResources { {
739 std::string("core.fan"),
740 std::string("core.led") } };
741 std::array<std::string, numPresenceResources> presenceNotificationUris { {
742 std::string("/a/fan"),
743 std::string("/a/led") } };
745 for(int i=0; i<numPresenceResources; i++)
747 if(res == OC_STACK_OK)
750 res = OCCreateResource(&presenceNotificationHandles[i],
751 presenceNotificationResources.at(i).c_str(),
753 presenceNotificationUris.at(i).c_str(),
754 OCNOPEntityHandlerCb,
755 OC_DISCOVERABLE|OC_OBSERVABLE);
757 if(res != OC_STACK_OK)
759 OC_LOG_V(ERROR, TAG, "\"Presence Notification Generator\" failed to create resource "
760 "%s with result %s.", presenceNotificationResources.at(i).c_str(),
764 OC_LOG_V(INFO, TAG, PCF("Created %s for presence notification"),
765 presenceNotificationUris[i].c_str());
768 for(int i=0; i<numPresenceResources; i++)
770 if(res == OC_STACK_OK)
772 res = OCDeleteResource(presenceNotificationHandles[i]);
774 if(res != OC_STACK_OK)
776 OC_LOG_V(ERROR, TAG, "\"Presence Notification Generator\" failed to delete "\
777 "resource %s.", presenceNotificationResources.at(i).c_str());
780 OC_LOG_V(INFO, TAG, PCF("Deleted %s for presence notification"),
781 presenceNotificationUris[i].c_str());
787 static void PrintUsage()
789 OC_LOG(INFO, TAG, "Usage : ocserver -o <0|1>");
790 OC_LOG(INFO, TAG, "-o 0 : Notify all observers");
791 OC_LOG(INFO, TAG, "-o 1 : Notify list of observers");
794 int main(int argc, char* argv[])
797 pthread_t threadId_presence;
800 while ((opt = getopt(argc, argv, "o:")) != -1)
805 gObserveNotifyType = atoi(optarg);
813 if ((gObserveNotifyType != 0) && (gObserveNotifyType != 1))
819 OC_LOG(DEBUG, TAG, "OCServer is starting...");
821 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
823 OC_LOG(ERROR, TAG, "OCStack init error");
827 if (OCStartPresence(0) != OC_STACK_OK)
829 OC_LOG(ERROR, TAG, "OCStack presence/discovery error");
834 OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandlerCb);
836 OCStackResult deviceResult = SetDeviceInfo(contentType, dateOfManufacture, deviceName,
837 deviceUUID, firmwareVersion, hostName, manufacturerName,
838 manufacturerUrl, modelNumber, platformVersion, supportUrl, version);
840 if (deviceResult != OC_STACK_OK)
842 OC_LOG(INFO, TAG, "Device Registration failed!");
846 deviceResult = OCSetDeviceInfo(deviceInfo);
848 if (deviceResult != OC_STACK_OK)
850 OC_LOG(INFO, TAG, "Device Registration failed!");
855 * Declare and create the example resource: Light
857 createLightResource(gResourceUri, &Light);
859 // Initialize observations data structure for the resource
860 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
862 interestedObservers[i].valid = false;
866 * Create a thread for changing the representation of the Light
868 pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)NULL);
871 * Create a thread for generating changes that cause presence notifications
872 * to be sent to clients
876 pthread_create(&threadId_presence, NULL, presenceNotificationGenerator, (void *)NULL);
879 // Break from loop with Ctrl-C
880 OC_LOG(INFO, TAG, "Entering ocserver main loop...");
882 signal(SIGINT, handleSigInt);
885 if (OCProcess() != OC_STACK_OK)
887 OC_LOG(ERROR, TAG, "OCStack process error");
895 * Cancel the Light thread and wait for it to terminate
897 pthread_cancel(threadId);
898 pthread_join(threadId, NULL);
899 pthread_cancel(threadId_presence);
900 pthread_join(threadId_presence, NULL);
902 OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
904 if (OCStop() != OC_STACK_OK)
906 OC_LOG(ERROR, TAG, "OCStack process error");
912 int createLightResource (char *uri, LightResource *lightResource)
916 OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
920 lightResource->state = false;
921 lightResource->power= 0;
922 OCStackResult res = OCCreateResource(&(lightResource->handle),
927 OC_DISCOVERABLE|OC_OBSERVABLE);
928 OC_LOG_V(INFO, TAG, "Created Light resource with result: %s", getResult(res));
933 void DeleteDeviceInfo()
935 free(deviceInfo.contentType);
936 free(deviceInfo.dateOfManufacture);
937 free(deviceInfo.deviceName);
938 free(deviceInfo.deviceUUID);
939 free(deviceInfo.firmwareVersion);
940 free(deviceInfo.hostName);
941 free(deviceInfo.manufacturerName);
942 free(deviceInfo.manufacturerUrl);
943 free(deviceInfo.modelNumber);
944 free(deviceInfo.platformVersion);
945 free(deviceInfo.supportUrl);
946 free(deviceInfo.version);
949 bool DuplicateString(char** targetString, const char* sourceString)
957 *targetString = (char *) malloc(strlen(sourceString) + 1);
961 strncpy(*targetString, sourceString, (strlen(sourceString) + 1));
968 OCStackResult SetDeviceInfo(const char *contentType, const char *dateOfManufacture,
969 const char *deviceName, const char *deviceUUID, const char *firmwareVersion,
970 const char *hostName, const char *manufacturerName, const char *manufacturerUrl,
971 const char *modelNumber, const char *platformVersion, const char *supportUrl,
977 if(manufacturerName != NULL && (strlen(manufacturerName) > MAX_MANUFACTURER_NAME_LENGTH))
979 return OC_STACK_INVALID_PARAM;
982 if(manufacturerUrl != NULL && (strlen(manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH))
984 return OC_STACK_INVALID_PARAM;
987 if(!DuplicateString(&deviceInfo.contentType, contentType))
992 if(!DuplicateString(&deviceInfo.dateOfManufacture, dateOfManufacture))
997 if(!DuplicateString(&deviceInfo.deviceName, deviceName))
1002 if(!DuplicateString(&deviceInfo.deviceUUID, deviceUUID))
1007 if(!DuplicateString(&deviceInfo.firmwareVersion, firmwareVersion))
1012 if(!DuplicateString(&deviceInfo.hostName, hostName))
1017 if(!DuplicateString(&deviceInfo.manufacturerName, manufacturerName))
1022 if(!DuplicateString(&deviceInfo.manufacturerUrl, manufacturerUrl))
1027 if(!DuplicateString(&deviceInfo.modelNumber, modelNumber))
1032 if(!DuplicateString(&deviceInfo.platformVersion, platformVersion))
1037 if(!DuplicateString(&deviceInfo.supportUrl, supportUrl))
1042 if(!DuplicateString(&deviceInfo.version, version))
1053 return OC_STACK_ERROR;