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.mi.def";
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_INIT_FLAG)
514 OC_LOG (INFO, TAG, "Flag includes OC_INIT_FLAG");
516 if (flag & OC_REQUEST_FLAG)
518 OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
520 if (entityHandlerRequest->resource == NULL)
522 OC_LOG (INFO, TAG, "Received request from client to a non-existing resource");
523 ehResult = ProcessNonExistingResourceRequest(entityHandlerRequest,
524 payload, sizeof(payload) - 1);
526 else if (OC_REST_GET == entityHandlerRequest->method)
528 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
529 ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
531 else if (OC_REST_PUT == entityHandlerRequest->method)
533 OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
534 ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
536 else if (OC_REST_DELETE == entityHandlerRequest->method)
538 OC_LOG (INFO, TAG, "Received OC_REST_DELETE from client");
539 ehResult = ProcessDeleteRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
543 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
544 entityHandlerRequest->method);
545 ehResult = OC_EH_ERROR;
547 // If the result isn't an error or forbidden, send response
548 if (!((ehResult == OC_EH_ERROR) || (ehResult == OC_EH_FORBIDDEN)))
550 // Format the response. Note this requires some info about the request
551 response.requestHandle = entityHandlerRequest->requestHandle;
552 response.resourceHandle = entityHandlerRequest->resource;
553 response.ehResult = ehResult;
554 response.payload = payload;
555 response.payloadSize = strlen(payload);
556 // Indicate that response is NOT in a persistent buffer
557 response.persistentBufferFlag = 0;
560 if (OCDoResponse(&response) != OC_STACK_OK)
562 OC_LOG(ERROR, TAG, "Error sending response");
563 ehResult = OC_EH_ERROR;
567 if (flag & OC_OBSERVE_FLAG)
569 OC_LOG(INFO, TAG, "Flag includes OC_OBSERVE_FLAG");
570 if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
572 OC_LOG (INFO, TAG, "Received OC_OBSERVE_REGISTER from client");
574 else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
576 OC_LOG (INFO, TAG, "Received OC_OBSERVE_DEREGISTER from client");
583 OCEntityHandlerResult
584 OCNOPEntityHandlerCb (OCEntityHandlerFlag flag,
585 OCEntityHandlerRequest *entityHandlerRequest)
587 // This is callback is associated with the 2 presence notification
588 // resources. They are non-operational.
592 OCEntityHandlerResult
593 OCEntityHandlerCb (OCEntityHandlerFlag flag,
594 OCEntityHandlerRequest *entityHandlerRequest)
596 OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
598 OCEntityHandlerResult ehResult = OC_EH_OK;
599 OCEntityHandlerResponse response;
600 char payload[MAX_RESPONSE_LENGTH] = {0};
603 if (!entityHandlerRequest)
605 OC_LOG (ERROR, TAG, "Invalid request pointer");
609 // Initialize certain response fields
610 response.numSendVendorSpecificHeaderOptions = 0;
611 memset(response.sendVendorSpecificHeaderOptions,
612 0, sizeof response.sendVendorSpecificHeaderOptions);
613 memset(response.resourceUri, 0, sizeof response.resourceUri);
615 if (flag & OC_INIT_FLAG)
617 OC_LOG (INFO, TAG, "Flag includes OC_INIT_FLAG");
619 if (flag & OC_REQUEST_FLAG)
621 OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
623 if (OC_REST_GET == entityHandlerRequest->method)
625 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
626 ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
628 else if (OC_REST_PUT == entityHandlerRequest->method)
630 OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
631 ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
633 else if (OC_REST_POST == entityHandlerRequest->method)
635 OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
636 ehResult = ProcessPostRequest (entityHandlerRequest, &response, payload, sizeof(payload) - 1);
638 else if (OC_REST_DELETE == entityHandlerRequest->method)
640 OC_LOG (INFO, TAG, "Received OC_REST_DELETE from client");
641 ehResult = ProcessDeleteRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
645 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
646 entityHandlerRequest->method);
647 ehResult = OC_EH_ERROR;
649 // If the result isn't an error or forbidden, send response
650 if (!((ehResult == OC_EH_ERROR) || (ehResult == OC_EH_FORBIDDEN)))
652 // Format the response. Note this requires some info about the request
653 response.requestHandle = entityHandlerRequest->requestHandle;
654 response.resourceHandle = entityHandlerRequest->resource;
655 response.ehResult = ehResult;
656 response.payload = payload;
657 response.payloadSize = strlen(payload);
658 // Indicate that response is NOT in a persistent buffer
659 response.persistentBufferFlag = 0;
661 // Handle vendor specific options
662 if(entityHandlerRequest->rcvdVendorSpecificHeaderOptions &&
663 entityHandlerRequest->numRcvdVendorSpecificHeaderOptions)
665 OC_LOG (INFO, TAG, "Received vendor specific options");
667 OCHeaderOption * rcvdOptions =
668 entityHandlerRequest->rcvdVendorSpecificHeaderOptions;
669 for( i = 0; i < entityHandlerRequest->numRcvdVendorSpecificHeaderOptions; i++)
671 if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
673 OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
674 ((OCHeaderOption)rcvdOptions[i]).optionID );
676 OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
677 MAX_HEADER_OPTION_DATA_LENGTH);
680 OCHeaderOption * sendOptions = response.sendVendorSpecificHeaderOptions;
681 uint8_t option2[] = {21,22,23,24,25,26,27,28,29,30};
682 uint8_t option3[] = {31,32,33,34,35,36,37,38,39,40};
683 sendOptions[0].protocolID = OC_COAP_ID;
684 sendOptions[0].optionID = 2248;
685 memcpy(sendOptions[0].optionData, option2, sizeof(option2));
686 sendOptions[0].optionLength = 10;
687 sendOptions[1].protocolID = OC_COAP_ID;
688 sendOptions[1].optionID = 2600;
689 memcpy(sendOptions[1].optionData, option3, sizeof(option3));
690 sendOptions[1].optionLength = 10;
691 response.numSendVendorSpecificHeaderOptions = 2;
695 if (OCDoResponse(&response) != OC_STACK_OK)
697 OC_LOG(ERROR, TAG, "Error sending response");
698 ehResult = OC_EH_ERROR;
702 if (flag & OC_OBSERVE_FLAG)
704 OC_LOG(INFO, TAG, "Flag includes OC_OBSERVE_FLAG");
706 if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
708 OC_LOG (INFO, TAG, "Received OC_OBSERVE_REGISTER from client");
709 ProcessObserveRegister (entityHandlerRequest);
711 else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
713 OC_LOG (INFO, TAG, "Received OC_OBSERVE_DEREGISTER from client");
714 ProcessObserveDeregister (entityHandlerRequest);
721 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
722 void handleSigInt(int signum)
724 if (signum == SIGINT)
730 void *ChangeLightRepresentation (void *param)
733 OCStackResult result = OC_STACK_ERROR;
736 uint8_t numNotifies = (SAMPLE_MAX_NUM_OBSERVATIONS)/2;
737 OCObservationId obsNotify[numNotifies];
743 if (gLightUnderObservation)
745 OC_LOG_V(INFO, TAG, " =====> Notifying stack of new power level %d\n", Light.power);
746 if (gObserveNotifyType == 1)
748 // Notify list of observers. Alternate observers on the list will be notified.
750 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; (i=i+2))
752 if (interestedObservers[i].valid == true)
754 obsNotify[j] = interestedObservers[i].observationId;
759 cJSON *json = cJSON_CreateObject();
761 cJSON_AddStringToObject(json,"href",gResourceUri);
762 cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
763 cJSON_AddBoolToObject(format, "state", Light.state);
764 cJSON_AddNumberToObject(format, "power", Light.power);
765 char * obsResp = cJSON_Print(json);
767 result = OCNotifyListOfObservers (Light.handle, obsNotify, j,
771 else if (gObserveNotifyType == 0)
773 // Notifying all observers
774 result = OCNotifyAllObservers (Light.handle, OC_NA_QOS);
775 if (OC_STACK_NO_OBSERVERS == result)
778 "=======> No more observers exist, stop sending observations");
779 gLightUnderObservation = 0;
784 OC_LOG (ERROR, TAG, "Incorrect notification type selected");
788 if(stopPresenceCount > 0)
790 OC_LOG_V(INFO, TAG, "================ Counting down to stop presence %d", stopPresenceCount);
792 if(!stopPresenceCount--)
794 OC_LOG(INFO, TAG, "================ stopping presence");
803 void *presenceNotificationGenerator(void *param)
807 OCDoHandle presenceNotificationHandles[numPresenceResources];
808 OCStackResult res = OC_STACK_OK;
810 std::array<std::string, numPresenceResources> presenceNotificationResources { {
811 std::string("core.fan"),
812 std::string("core.led") } };
813 std::array<std::string, numPresenceResources> presenceNotificationUris { {
814 std::string("/a/fan"),
815 std::string("/a/led") } };
817 for(int i=0; i<numPresenceResources; i++)
819 if(res == OC_STACK_OK)
822 res = OCCreateResource(&presenceNotificationHandles[i],
823 presenceNotificationResources.at(i).c_str(),
825 presenceNotificationUris.at(i).c_str(),
826 OCNOPEntityHandlerCb,
827 OC_DISCOVERABLE|OC_OBSERVABLE);
829 if(res != OC_STACK_OK)
831 OC_LOG_V(ERROR, TAG, "\"Presence Notification Generator\" failed to create resource "
832 "%s with result %s.", presenceNotificationResources.at(i).c_str(),
836 OC_LOG_V(INFO, TAG, PCF("Created %s for presence notification"),
837 presenceNotificationUris[i].c_str());
840 for(int i=0; i<numPresenceResources; i++)
842 if(res == OC_STACK_OK)
844 res = OCDeleteResource(presenceNotificationHandles[i]);
846 if(res != OC_STACK_OK)
848 OC_LOG_V(ERROR, TAG, "\"Presence Notification Generator\" failed to delete "\
849 "resource %s.", presenceNotificationResources.at(i).c_str());
852 OC_LOG_V(INFO, TAG, PCF("Deleted %s for presence notification"),
853 presenceNotificationUris[i].c_str());
859 static void PrintUsage()
861 OC_LOG(INFO, TAG, "Usage : ocserver -o <0|1>");
862 OC_LOG(INFO, TAG, "-o 0 : Notify all observers");
863 OC_LOG(INFO, TAG, "-o 1 : Notify list of observers");
866 int main(int argc, char* argv[])
869 pthread_t threadId_presence;
872 while ((opt = getopt(argc, argv, "o:")) != -1)
877 gObserveNotifyType = atoi(optarg);
885 if ((gObserveNotifyType != 0) && (gObserveNotifyType != 1))
891 OC_LOG(DEBUG, TAG, "OCServer is starting...");
893 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
895 OC_LOG(ERROR, TAG, "OCStack init error");
899 if (OCStartPresence(0) != OC_STACK_OK)
901 OC_LOG(ERROR, TAG, "OCStack presence/discovery error");
906 OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandlerCb);
908 OCStackResult deviceResult = SetDeviceInfo(contentType, dateOfManufacture, deviceName,
909 deviceUUID, firmwareVersion, hostName, manufacturerName,
910 manufacturerUrl, modelNumber, platformVersion, supportUrl, version);
912 if (deviceResult != OC_STACK_OK)
914 OC_LOG(INFO, TAG, "Device Registration failed!");
918 deviceResult = OCSetDeviceInfo(deviceInfo);
920 if (deviceResult != OC_STACK_OK)
922 OC_LOG(INFO, TAG, "Device Registration failed!");
927 * Declare and create the example resource: Light
929 createLightResource(gResourceUri, &Light);
931 // Initialize observations data structure for the resource
932 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
934 interestedObservers[i].valid = false;
938 * Create a thread for changing the representation of the Light
940 pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)NULL);
943 * Create a thread for generating changes that cause presence notifications
944 * to be sent to clients
948 pthread_create(&threadId_presence, NULL, presenceNotificationGenerator, (void *)NULL);
951 // Break from loop with Ctrl-C
952 OC_LOG(INFO, TAG, "Entering ocserver main loop...");
954 signal(SIGINT, handleSigInt);
957 if (OCProcess() != OC_STACK_OK)
959 OC_LOG(ERROR, TAG, "OCStack process error");
967 * Cancel the Light thread and wait for it to terminate
969 pthread_cancel(threadId);
970 pthread_join(threadId, NULL);
971 pthread_cancel(threadId_presence);
972 pthread_join(threadId_presence, NULL);
974 OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
976 if (OCStop() != OC_STACK_OK)
978 OC_LOG(ERROR, TAG, "OCStack process error");
984 int createLightResource (char *uri, LightResource *lightResource)
988 OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
992 lightResource->state = false;
993 lightResource->power= 0;
994 OCStackResult res = OCCreateResource(&(lightResource->handle),
999 OC_DISCOVERABLE|OC_OBSERVABLE);
1000 OC_LOG_V(INFO, TAG, "Created Light resource with result: %s", getResult(res));
1005 void DeleteDeviceInfo()
1007 free(deviceInfo.contentType);
1008 free(deviceInfo.dateOfManufacture);
1009 free(deviceInfo.deviceName);
1010 free(deviceInfo.deviceUUID);
1011 free(deviceInfo.firmwareVersion);
1012 free(deviceInfo.hostName);
1013 free(deviceInfo.manufacturerName);
1014 free(deviceInfo.manufacturerUrl);
1015 free(deviceInfo.modelNumber);
1016 free(deviceInfo.platformVersion);
1017 free(deviceInfo.supportUrl);
1018 free(deviceInfo.version);
1021 bool DuplicateString(char** targetString, const char* sourceString)
1029 *targetString = (char *) malloc(strlen(sourceString) + 1);
1033 strncpy(*targetString, sourceString, (strlen(sourceString) + 1));
1040 OCStackResult SetDeviceInfo(const char *contentType, const char *dateOfManufacture,
1041 const char *deviceName, const char *deviceUUID, const char *firmwareVersion,
1042 const char *hostName, const char *manufacturerName, const char *manufacturerUrl,
1043 const char *modelNumber, const char *platformVersion, const char *supportUrl,
1044 const char *version)
1047 bool success = true;
1049 if(manufacturerName != NULL && (strlen(manufacturerName) > MAX_MANUFACTURER_NAME_LENGTH))
1051 return OC_STACK_INVALID_PARAM;
1054 if(manufacturerUrl != NULL && (strlen(manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH))
1056 return OC_STACK_INVALID_PARAM;
1059 if(!DuplicateString(&deviceInfo.contentType, contentType))
1064 if(!DuplicateString(&deviceInfo.dateOfManufacture, dateOfManufacture))
1069 if(!DuplicateString(&deviceInfo.deviceName, deviceName))
1074 if(!DuplicateString(&deviceInfo.deviceUUID, deviceUUID))
1079 if(!DuplicateString(&deviceInfo.firmwareVersion, firmwareVersion))
1084 if(!DuplicateString(&deviceInfo.hostName, hostName))
1089 if(!DuplicateString(&deviceInfo.manufacturerName, manufacturerName))
1094 if(!DuplicateString(&deviceInfo.manufacturerUrl, manufacturerUrl))
1099 if(!DuplicateString(&deviceInfo.modelNumber, modelNumber))
1104 if(!DuplicateString(&deviceInfo.platformVersion, platformVersion))
1109 if(!DuplicateString(&deviceInfo.supportUrl, supportUrl))
1114 if(!DuplicateString(&deviceInfo.version, version))
1125 return OC_STACK_ERROR;