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 // Entity handler should check for resourceTypeName and ResourceInterface in order to GET
84 // the existence of a known resource
85 const char *resourceTypeName = "core.light";
86 const char *resourceInterface = OC_RSRVD_INTERFACE_DEFAULT;
88 OCDeviceInfo deviceInfo;
90 //This function takes the request as an input and returns the response
92 char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
94 cJSON *json = cJSON_CreateObject();
97 LightResource *currLightResource = &Light;
99 if (ehRequest->resource == gLightInstance[0].handle)
101 currLightResource = &gLightInstance[0];
102 gResourceUri = (char *) "a/light/0";
104 else if (ehRequest->resource == gLightInstance[1].handle)
106 currLightResource = &gLightInstance[1];
107 gResourceUri = (char *) "a/light/1";
110 if(OC_REST_PUT == ehRequest->method)
112 // Get cJSON pointer to query
113 cJSON *putJson = cJSON_Parse(ehRequest->reqJSONPayload);
117 OC_LOG_V(ERROR, TAG, "Failed to parse JSON: %s", ehRequest->reqJSONPayload);
121 // Get root of JSON payload, then the 1st resource.
122 cJSON* carrier = cJSON_GetObjectItem(putJson, "oc");
123 carrier = cJSON_GetArrayItem(carrier, 0);
124 carrier = cJSON_GetObjectItem(carrier, "rep");
126 cJSON* prop = cJSON_GetObjectItem(carrier,"power");
129 currLightResource->power =prop->valueint;
132 prop = cJSON_GetObjectItem(carrier,"state");
135 currLightResource->state = prop->valueint;
138 cJSON_Delete(putJson);
141 cJSON_AddStringToObject(json,"href",gResourceUri);
142 cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
143 cJSON_AddBoolToObject(format, "state", currLightResource->state);
144 cJSON_AddNumberToObject(format, "power", currLightResource->power);
146 jsonResponse = cJSON_Print(json);
153 * Very simple example of query parsing.
154 * The query may have multiple filters separated by '&'.
155 * It is upto the entity handler to parse the query for the individual filters,
156 * VALIDATE them and respond as it sees fit.
158 * This function only returns false if the query is exactly "power<X" and
159 * current power is greater than X. If X cannot be parsed for an int,
162 bool checkIfQueryForPowerPassed(char * query)
164 if (query && strncmp(query, "power<", strlen("power<")) == 0)
166 char * pointerToOperator = strstr(query, "<");
168 if (pointerToOperator)
170 int powerRequested = atoi(pointerToOperator + 1);
171 if (Light.power > powerRequested)
173 OC_LOG_V(INFO, TAG, "Current power: %d. Requested: <%d", Light.power
183 * Application should validate and process these as desired.
185 OCEntityHandlerResult ValidateQueryParams (OCEntityHandlerRequest *entityHandlerRequest)
187 OC_LOG_V(INFO, TAG, PCF("Received query %s"), entityHandlerRequest->query);
188 OC_LOG(INFO, TAG, PCF("Not processing query"));
192 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
193 char *payload, uint16_t maxPayloadSize)
195 OCEntityHandlerResult ehResult;
196 bool queryPassed = checkIfQueryForPowerPassed(ehRequest->query);
198 // Empty payload if the query has no match.
201 char *getResp = constructJsonResponse(ehRequest);
204 OC_LOG(ERROR, TAG, "constructJsonResponse failed");
208 if (maxPayloadSize > strlen (getResp))
210 strncpy(payload, getResp, strlen(getResp));
215 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
217 ehResult = OC_EH_ERROR;
230 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
231 char *payload, uint16_t maxPayloadSize)
233 OCEntityHandlerResult ehResult;
234 char *putResp = constructJsonResponse(ehRequest);
238 OC_LOG(ERROR, TAG, "Failed to construct Json response");
242 if (maxPayloadSize > strlen ((char *)putResp))
244 strncpy(payload, putResp, strlen((char *)putResp));
249 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
251 ehResult = OC_EH_ERROR;
259 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
260 OCEntityHandlerResponse *response, char *payload, uint16_t maxPayloadSize)
262 OCEntityHandlerResult ehResult = OC_EH_OK;
263 char *respPLPost_light = NULL;
268 * The entity handler determines how to process a POST request.
269 * Per the REST paradigm, POST can also be used to update representation of existing
270 * resource or create a new resource.
271 * In the sample below, if the POST is for /a/light then a new instance of the Light
272 * resource is created with default representation (if representation is included in
273 * POST payload it can be used as initial values) as long as the instance is
274 * lesser than max new instance count. Once max instance count is reached, POST on
275 * /a/light updated the representation of /a/light (just like PUT)
278 if (ehRequest->resource == Light.handle)
280 if (gCurrLightInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
282 // Create new Light instance
283 char newLightUri[URI_MAXSIZE];
284 snprintf(newLightUri, URI_MAXSIZE, "/a/light/%d", gCurrLightInstance);
286 json = cJSON_CreateObject();
287 cJSON_AddStringToObject(json,"href",gResourceUri);
288 cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
289 cJSON_AddStringToObject(format, "createduri", (char *) newLightUri);
291 if (0 == createLightResource (newLightUri, &gLightInstance[gCurrLightInstance]))
293 OC_LOG (INFO, TAG, "Created new Light instance\n");
294 gLightInstance[gCurrLightInstance].state = 0;
295 gLightInstance[gCurrLightInstance].power = 0;
296 gCurrLightInstance++;
297 respPLPost_light = cJSON_Print(json);
298 strncpy ((char *)response->resourceUri, newLightUri, MAX_URI_LENGTH);
299 ehResult = OC_EH_RESOURCE_CREATED;
306 // Update repesentation of /a/light
309 respPLPost_light = constructJsonResponse(ehRequest);
314 for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
316 if (ehRequest->resource == gLightInstance[i].handle)
318 gLightInstance[i].state = true;
319 gLightInstance[i].power = 22;
322 respPLPost_light = constructJsonResponse(ehRequest);
327 respPLPost_light = constructJsonResponse(ehRequest);
333 if ((respPLPost_light != NULL) && (maxPayloadSize > strlen ((char *)respPLPost_light)))
335 strncpy(payload, respPLPost_light, strlen((char *)respPLPost_light));
339 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
341 ehResult = OC_EH_ERROR;
344 free(respPLPost_light);
348 OCEntityHandlerResult ProcessDeleteRequest (OCEntityHandlerRequest *ehRequest,
349 char *payload, uint16_t maxPayloadSize)
351 if(ehRequest == NULL)
353 OC_LOG(INFO, TAG, "The ehRequest is NULL");
356 OCEntityHandlerResult ehResult = OC_EH_OK;
358 OC_LOG_V(INFO, TAG, "\n\nExecuting %s for resource %d ", __func__, ehRequest->resource);
361 * In the sample below, the application will:
362 * 1a. pass the delete request to the c stack
363 * 1b. internally, the c stack figures out what needs to be done and does it accordingly
364 * (e.g. send observers notification, remove observers...)
365 * 1c. the c stack returns with the result whether the request is fullfilled.
366 * 2. optionally, app removes observers out of its array 'interestedObservers'
369 const char* deleteResponse = NULL;
371 if ((ehRequest != NULL) && (ehRequest->resource == Light.handle))
373 //Step 1: Ask stack to do the work.
374 OCStackResult result = OCDeleteResource(ehRequest->resource);
376 if (result == OC_STACK_OK)
378 OC_LOG (INFO, TAG, "\n\nDelete Resource operation succeeded.");
380 deleteResponse = responsePayloadDeleteOk;
382 //Step 2: clear observers who wanted to observe this resource at the app level.
383 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
385 if (interestedObservers[i].resourceHandle == ehRequest->resource)
387 interestedObservers[i].valid = false;
388 interestedObservers[i].observationId = 0;
389 interestedObservers[i].resourceHandle = NULL;
393 else if (result == OC_STACK_NO_RESOURCE)
395 OC_LOG(INFO, TAG, "\n\nThe resource doesn't exist or it might have been deleted.");
396 deleteResponse = responsePayloadResourceDoesNotExist;
397 ehResult = OC_EH_RESOURCE_DELETED;
401 OC_LOG(INFO, TAG, "\n\nEncountered error from OCDeleteResource().");
402 deleteResponse = responsePayloadDeleteNotOK;
403 ehResult = OC_EH_ERROR;
406 else if (ehRequest->resource != Light.handle)
408 //Let's this app not supporting DELETE on some resources so
409 //consider the DELETE request is received for a non-support resource.
410 OC_LOG_V(INFO, TAG, "\n\nThe request is received for a non-support resource.");
411 deleteResponse = responsePayloadDeleteResourceNotSupported;
412 ehResult = OC_EH_FORBIDDEN;
415 if (maxPayloadSize > strlen ((char *)deleteResponse))
417 strncpy(payload, deleteResponse, strlen((char *)deleteResponse));
421 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
423 ehResult = OC_EH_ERROR;
429 OCEntityHandlerResult ProcessNonExistingResourceRequest(OCEntityHandlerRequest *ehRequest,
430 char *payload, uint16_t maxPayloadSize)
432 OC_LOG_V(INFO, TAG, "\n\nExecuting %s ", __func__);
434 const char* response = NULL;
435 response = responsePayloadResourceDoesNotExist;
437 if ( (ehRequest != NULL) &&
438 (maxPayloadSize > strlen ((char *)response)) )
440 strncpy((char *)payload, response, strlen((char *)response));
444 OC_LOG_V (ERROR, TAG, "Response buffer: %d bytes is too small",
448 return OC_EH_RESOURCE_NOT_FOUND;
451 void ProcessObserveRegister (OCEntityHandlerRequest *ehRequest)
453 OC_LOG_V (INFO, TAG, "Received observation registration request with observation Id %d",
454 ehRequest->obsInfo.obsId);
455 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
457 if (interestedObservers[i].valid == false)
459 interestedObservers[i].observationId = ehRequest->obsInfo.obsId;
460 interestedObservers[i].valid = true;
461 gLightUnderObservation = 1;
467 void ProcessObserveDeregister (OCEntityHandlerRequest *ehRequest)
469 bool clientStillObserving = false;
471 OC_LOG_V (INFO, TAG, "Received observation deregistration request for observation Id %d",
472 ehRequest->obsInfo.obsId);
473 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
475 if (interestedObservers[i].observationId == ehRequest->obsInfo.obsId)
477 interestedObservers[i].valid = false;
479 if (interestedObservers[i].valid == true)
481 // Even if there is one single client observing we continue notifying entity handler
482 clientStillObserving = true;
485 if (clientStillObserving == false)
486 gLightUnderObservation = 0;
489 OCEntityHandlerResult
490 OCDeviceEntityHandlerCb (OCEntityHandlerFlag flag,
491 OCEntityHandlerRequest *entityHandlerRequest, char* uri)
493 OC_LOG_V (INFO, TAG, "Inside device default entity handler - flags: 0x%x, uri: %s", flag, uri);
495 OCEntityHandlerResult ehResult = OC_EH_OK;
496 OCEntityHandlerResponse response;
497 char payload[MAX_RESPONSE_LENGTH] = {0};
500 if (!entityHandlerRequest)
502 OC_LOG (ERROR, TAG, "Invalid request pointer");
505 // Initialize certain response fields
506 response.numSendVendorSpecificHeaderOptions = 0;
507 memset(response.sendVendorSpecificHeaderOptions, 0,
508 sizeof response.sendVendorSpecificHeaderOptions);
509 memset(response.resourceUri, 0, sizeof response.resourceUri);
512 if (flag & OC_REQUEST_FLAG)
514 OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
516 if (entityHandlerRequest->resource == NULL)
518 OC_LOG (INFO, TAG, "Received request from client to a non-existing resource");
519 ehResult = ProcessNonExistingResourceRequest(entityHandlerRequest,
520 payload, sizeof(payload) - 1);
522 else if (OC_REST_GET == entityHandlerRequest->method)
524 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
525 ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
527 else if (OC_REST_PUT == entityHandlerRequest->method)
529 OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
530 ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
532 else if (OC_REST_DELETE == entityHandlerRequest->method)
534 OC_LOG (INFO, TAG, "Received OC_REST_DELETE from client");
535 ehResult = ProcessDeleteRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
539 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
540 entityHandlerRequest->method);
541 ehResult = OC_EH_ERROR;
543 // If the result isn't an error or forbidden, send response
544 if (!((ehResult == OC_EH_ERROR) || (ehResult == OC_EH_FORBIDDEN)))
546 // Format the response. Note this requires some info about the request
547 response.requestHandle = entityHandlerRequest->requestHandle;
548 response.resourceHandle = entityHandlerRequest->resource;
549 response.ehResult = ehResult;
550 response.payload = payload;
551 response.payloadSize = strlen(payload);
552 // Indicate that response is NOT in a persistent buffer
553 response.persistentBufferFlag = 0;
556 if (OCDoResponse(&response) != OC_STACK_OK)
558 OC_LOG(ERROR, TAG, "Error sending response");
559 ehResult = OC_EH_ERROR;
563 if (flag & OC_OBSERVE_FLAG)
565 OC_LOG(INFO, TAG, "Flag includes OC_OBSERVE_FLAG");
566 if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
568 OC_LOG (INFO, TAG, "Received OC_OBSERVE_REGISTER from client");
570 else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
572 OC_LOG (INFO, TAG, "Received OC_OBSERVE_DEREGISTER from client");
579 OCEntityHandlerResult
580 OCNOPEntityHandlerCb (OCEntityHandlerFlag flag,
581 OCEntityHandlerRequest *entityHandlerRequest)
583 // This is callback is associated with the 2 presence notification
584 // resources. They are non-operational.
588 OCEntityHandlerResult
589 OCEntityHandlerCb (OCEntityHandlerFlag flag,
590 OCEntityHandlerRequest *entityHandlerRequest)
592 OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
594 OCEntityHandlerResult ehResult = OC_EH_OK;
595 OCEntityHandlerResponse response;
596 char payload[MAX_RESPONSE_LENGTH] = {0};
599 if (!entityHandlerRequest)
601 OC_LOG (ERROR, TAG, "Invalid request pointer");
605 // Initialize certain response fields
606 response.numSendVendorSpecificHeaderOptions = 0;
607 memset(response.sendVendorSpecificHeaderOptions,
608 0, sizeof response.sendVendorSpecificHeaderOptions);
609 memset(response.resourceUri, 0, sizeof response.resourceUri);
611 if (flag & OC_REQUEST_FLAG)
613 OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
615 if (OC_REST_GET == entityHandlerRequest->method)
617 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
618 ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
620 else if (OC_REST_PUT == entityHandlerRequest->method)
622 OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
623 ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
625 else if (OC_REST_POST == entityHandlerRequest->method)
627 OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
628 ehResult = ProcessPostRequest (entityHandlerRequest, &response, payload, sizeof(payload) - 1);
630 else if (OC_REST_DELETE == entityHandlerRequest->method)
632 OC_LOG (INFO, TAG, "Received OC_REST_DELETE from client");
633 ehResult = ProcessDeleteRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
637 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
638 entityHandlerRequest->method);
639 ehResult = OC_EH_ERROR;
641 // If the result isn't an error or forbidden, send response
642 if (!((ehResult == OC_EH_ERROR) || (ehResult == OC_EH_FORBIDDEN)))
644 // Format the response. Note this requires some info about the request
645 response.requestHandle = entityHandlerRequest->requestHandle;
646 response.resourceHandle = entityHandlerRequest->resource;
647 response.ehResult = ehResult;
648 response.payload = payload;
649 response.payloadSize = strlen(payload);
650 // Indicate that response is NOT in a persistent buffer
651 response.persistentBufferFlag = 0;
653 // Handle vendor specific options
654 if(entityHandlerRequest->rcvdVendorSpecificHeaderOptions &&
655 entityHandlerRequest->numRcvdVendorSpecificHeaderOptions)
657 OC_LOG (INFO, TAG, "Received vendor specific options");
659 OCHeaderOption * rcvdOptions =
660 entityHandlerRequest->rcvdVendorSpecificHeaderOptions;
661 for( i = 0; i < entityHandlerRequest->numRcvdVendorSpecificHeaderOptions; i++)
663 if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
665 OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
666 ((OCHeaderOption)rcvdOptions[i]).optionID );
668 OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
669 MAX_HEADER_OPTION_DATA_LENGTH);
672 OCHeaderOption * sendOptions = response.sendVendorSpecificHeaderOptions;
673 uint8_t option2[] = {21,22,23,24,25,26,27,28,29,30};
674 uint8_t option3[] = {31,32,33,34,35,36,37,38,39,40};
675 sendOptions[0].protocolID = OC_COAP_ID;
676 sendOptions[0].optionID = 2248;
677 memcpy(sendOptions[0].optionData, option2, sizeof(option2));
678 sendOptions[0].optionLength = 10;
679 sendOptions[1].protocolID = OC_COAP_ID;
680 sendOptions[1].optionID = 2600;
681 memcpy(sendOptions[1].optionData, option3, sizeof(option3));
682 sendOptions[1].optionLength = 10;
683 response.numSendVendorSpecificHeaderOptions = 2;
687 if (OCDoResponse(&response) != OC_STACK_OK)
689 OC_LOG(ERROR, TAG, "Error sending response");
690 ehResult = OC_EH_ERROR;
694 if (flag & OC_OBSERVE_FLAG)
696 OC_LOG(INFO, TAG, "Flag includes OC_OBSERVE_FLAG");
698 if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
700 OC_LOG (INFO, TAG, "Received OC_OBSERVE_REGISTER from client");
701 ProcessObserveRegister (entityHandlerRequest);
703 else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
705 OC_LOG (INFO, TAG, "Received OC_OBSERVE_DEREGISTER from client");
706 ProcessObserveDeregister (entityHandlerRequest);
713 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
714 void handleSigInt(int signum)
716 if (signum == SIGINT)
722 void *ChangeLightRepresentation (void *param)
725 OCStackResult result = OC_STACK_ERROR;
728 uint8_t numNotifies = (SAMPLE_MAX_NUM_OBSERVATIONS)/2;
729 OCObservationId obsNotify[numNotifies];
735 if (gLightUnderObservation)
737 OC_LOG_V(INFO, TAG, " =====> Notifying stack of new power level %d\n", Light.power);
738 if (gObserveNotifyType == 1)
740 // Notify list of observers. Alternate observers on the list will be notified.
742 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; (i=i+2))
744 if (interestedObservers[i].valid == true)
746 obsNotify[j] = interestedObservers[i].observationId;
751 cJSON *json = cJSON_CreateObject();
753 cJSON_AddStringToObject(json,"href",gResourceUri);
754 cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
755 cJSON_AddBoolToObject(format, "state", Light.state);
756 cJSON_AddNumberToObject(format, "power", Light.power);
757 char * obsResp = cJSON_Print(json);
759 result = OCNotifyListOfObservers (Light.handle, obsNotify, j,
763 else if (gObserveNotifyType == 0)
765 // Notifying all observers
766 result = OCNotifyAllObservers (Light.handle, OC_NA_QOS);
767 if (OC_STACK_NO_OBSERVERS == result)
770 "=======> No more observers exist, stop sending observations");
771 gLightUnderObservation = 0;
776 OC_LOG (ERROR, TAG, "Incorrect notification type selected");
780 if(stopPresenceCount > 0)
782 OC_LOG_V(INFO, TAG, "================ Counting down to stop presence %d", stopPresenceCount);
784 if(!stopPresenceCount--)
786 OC_LOG(INFO, TAG, "================ stopping presence");
795 void *presenceNotificationGenerator(void *param)
799 OCDoHandle presenceNotificationHandles[numPresenceResources];
800 OCStackResult res = OC_STACK_OK;
802 std::array<std::string, numPresenceResources> presenceNotificationResources { {
803 std::string("core.fan"),
804 std::string("core.led") } };
805 std::array<std::string, numPresenceResources> presenceNotificationUris { {
806 std::string("/a/fan"),
807 std::string("/a/led") } };
809 for(int i=0; i<numPresenceResources; i++)
811 if(res == OC_STACK_OK)
814 res = OCCreateResource(&presenceNotificationHandles[i],
815 presenceNotificationResources.at(i).c_str(),
816 OC_RSRVD_INTERFACE_DEFAULT,
817 presenceNotificationUris.at(i).c_str(),
818 OCNOPEntityHandlerCb,
819 OC_DISCOVERABLE|OC_OBSERVABLE);
821 if(res != OC_STACK_OK)
823 OC_LOG_V(ERROR, TAG, "\"Presence Notification Generator\" failed to create resource "
824 "%s with result %s.", presenceNotificationResources.at(i).c_str(),
828 OC_LOG_V(INFO, TAG, PCF("Created %s for presence notification"),
829 presenceNotificationUris[i].c_str());
832 for(int i=0; i<numPresenceResources; i++)
834 if(res == OC_STACK_OK)
836 res = OCDeleteResource(presenceNotificationHandles[i]);
838 if(res != OC_STACK_OK)
840 OC_LOG_V(ERROR, TAG, "\"Presence Notification Generator\" failed to delete "\
841 "resource %s.", presenceNotificationResources.at(i).c_str());
844 OC_LOG_V(INFO, TAG, PCF("Deleted %s for presence notification"),
845 presenceNotificationUris[i].c_str());
851 static void PrintUsage()
853 OC_LOG(INFO, TAG, "Usage : ocserver -o <0|1>");
854 OC_LOG(INFO, TAG, "-o 0 : Notify all observers");
855 OC_LOG(INFO, TAG, "-o 1 : Notify list of observers");
858 int main(int argc, char* argv[])
861 pthread_t threadId_presence;
864 while ((opt = getopt(argc, argv, "o:")) != -1)
869 gObserveNotifyType = atoi(optarg);
877 if ((gObserveNotifyType != 0) && (gObserveNotifyType != 1))
883 OC_LOG(DEBUG, TAG, "OCServer is starting...");
885 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
887 OC_LOG(ERROR, TAG, "OCStack init error");
891 if (OCStartPresence(0) != OC_STACK_OK)
893 OC_LOG(ERROR, TAG, "OCStack presence/discovery error");
898 OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandlerCb);
900 OCStackResult deviceResult = SetDeviceInfo(contentType, dateOfManufacture, deviceName,
901 deviceUUID, firmwareVersion, hostName, manufacturerName,
902 manufacturerUrl, modelNumber, platformVersion, supportUrl, version);
904 if (deviceResult != OC_STACK_OK)
906 OC_LOG(INFO, TAG, "Device Registration failed!");
910 deviceResult = OCSetDeviceInfo(deviceInfo);
912 if (deviceResult != OC_STACK_OK)
914 OC_LOG(INFO, TAG, "Device Registration failed!");
919 * Declare and create the example resource: Light
921 createLightResource(gResourceUri, &Light);
923 // Initialize observations data structure for the resource
924 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
926 interestedObservers[i].valid = false;
930 * Create a thread for changing the representation of the Light
932 pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)NULL);
935 * Create a thread for generating changes that cause presence notifications
936 * to be sent to clients
940 pthread_create(&threadId_presence, NULL, presenceNotificationGenerator, (void *)NULL);
943 // Break from loop with Ctrl-C
944 OC_LOG(INFO, TAG, "Entering ocserver main loop...");
946 signal(SIGINT, handleSigInt);
949 if (OCProcess() != OC_STACK_OK)
951 OC_LOG(ERROR, TAG, "OCStack process error");
959 * Cancel the Light thread and wait for it to terminate
961 pthread_cancel(threadId);
962 pthread_join(threadId, NULL);
963 pthread_cancel(threadId_presence);
964 pthread_join(threadId_presence, NULL);
966 OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
968 if (OCStop() != OC_STACK_OK)
970 OC_LOG(ERROR, TAG, "OCStack process error");
976 int createLightResource (char *uri, LightResource *lightResource)
980 OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
984 lightResource->state = false;
985 lightResource->power= 0;
986 OCStackResult res = OCCreateResource(&(lightResource->handle),
988 OC_RSRVD_INTERFACE_DEFAULT,
991 OC_DISCOVERABLE|OC_OBSERVABLE);
992 OC_LOG_V(INFO, TAG, "Created Light resource with result: %s", getResult(res));
997 void DeleteDeviceInfo()
999 free(deviceInfo.contentType);
1000 free(deviceInfo.dateOfManufacture);
1001 free(deviceInfo.deviceName);
1002 free(deviceInfo.deviceUUID);
1003 free(deviceInfo.firmwareVersion);
1004 free(deviceInfo.hostName);
1005 free(deviceInfo.manufacturerName);
1006 free(deviceInfo.manufacturerUrl);
1007 free(deviceInfo.modelNumber);
1008 free(deviceInfo.platformVersion);
1009 free(deviceInfo.supportUrl);
1010 free(deviceInfo.version);
1013 bool DuplicateString(char** targetString, const char* sourceString)
1021 *targetString = (char *) malloc(strlen(sourceString) + 1);
1025 strncpy(*targetString, sourceString, (strlen(sourceString) + 1));
1032 OCStackResult SetDeviceInfo(const char *contentType, const char *dateOfManufacture,
1033 const char *deviceName, const char *deviceUUID, const char *firmwareVersion,
1034 const char *hostName, const char *manufacturerName, const char *manufacturerUrl,
1035 const char *modelNumber, const char *platformVersion, const char *supportUrl,
1036 const char *version)
1039 bool success = true;
1041 if(manufacturerName != NULL && (strlen(manufacturerName) > MAX_MANUFACTURER_NAME_LENGTH))
1043 return OC_STACK_INVALID_PARAM;
1046 if(manufacturerUrl != NULL && (strlen(manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH))
1048 return OC_STACK_INVALID_PARAM;
1051 if(!DuplicateString(&deviceInfo.contentType, contentType))
1056 if(!DuplicateString(&deviceInfo.dateOfManufacture, dateOfManufacture))
1061 if(!DuplicateString(&deviceInfo.deviceName, deviceName))
1066 if(!DuplicateString(&deviceInfo.deviceUUID, deviceUUID))
1071 if(!DuplicateString(&deviceInfo.firmwareVersion, firmwareVersion))
1076 if(!DuplicateString(&deviceInfo.hostName, hostName))
1081 if(!DuplicateString(&deviceInfo.manufacturerName, manufacturerName))
1086 if(!DuplicateString(&deviceInfo.manufacturerUrl, manufacturerUrl))
1091 if(!DuplicateString(&deviceInfo.modelNumber, modelNumber))
1096 if(!DuplicateString(&deviceInfo.platformVersion, platformVersion))
1101 if(!DuplicateString(&deviceInfo.supportUrl, supportUrl))
1106 if(!DuplicateString(&deviceInfo.version, version))
1117 return OC_STACK_ERROR;