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 *dateOfManufacture = "myDateOfManufacture";
71 const char *deviceName = "myDeviceName";
72 const char *deviceUUID = "myDeviceUUID";
73 const char *firmwareVersion = "myFirmwareVersion";
74 const char *manufacturerName = "myName";
75 const char *operatingSystemVersion = "myOS";
76 const char *hardwareVersion = "myHardwareVersion";
77 const char* platformID = "myPlatformID";
78 const char *manufacturerUrl = "myManufacturerUrl";
79 const char *modelNumber = "myModelNumber";
80 const char *platformVersion = "myPlatformVersion";
81 const char *supportUrl = "mySupportUrl";
82 const char *version = "myVersion";
83 const char *systemTime = "2015-05-15T11.04";
85 // Entity handler should check for resourceTypeName and ResourceInterface in order to GET
86 // the existence of a known resource
87 const char *resourceTypeName = "core.light";
88 const char *resourceInterface = OC_RSRVD_INTERFACE_DEFAULT;
90 OCPlatformInfo platformInfo;
91 OCDeviceInfo deviceInfo;
93 //This function takes the request as an input and returns the response
95 char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
97 cJSON *json = cJSON_CreateObject();
100 LightResource *currLightResource = &Light;
102 if (ehRequest->resource == gLightInstance[0].handle)
104 currLightResource = &gLightInstance[0];
105 gResourceUri = (char *) "a/light/0";
107 else if (ehRequest->resource == gLightInstance[1].handle)
109 currLightResource = &gLightInstance[1];
110 gResourceUri = (char *) "a/light/1";
113 if(OC_REST_PUT == ehRequest->method)
115 // Get cJSON pointer to query
116 cJSON *putJson = cJSON_Parse(ehRequest->reqJSONPayload);
120 OC_LOG_V(ERROR, TAG, "Failed to parse JSON: %s", ehRequest->reqJSONPayload);
124 // Get root of JSON payload, then the 1st resource.
125 cJSON* carrier = cJSON_GetObjectItem(putJson, "oic");
126 carrier = cJSON_GetArrayItem(carrier, 0);
127 carrier = cJSON_GetObjectItem(carrier, "rep");
129 cJSON* prop = cJSON_GetObjectItem(carrier,"power");
132 currLightResource->power =prop->valueint;
135 prop = cJSON_GetObjectItem(carrier,"state");
138 currLightResource->state = prop->valueint;
141 cJSON_Delete(putJson);
144 cJSON_AddStringToObject(json,"href",gResourceUri);
145 cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
146 cJSON_AddBoolToObject(format, "state", currLightResource->state);
147 cJSON_AddNumberToObject(format, "power", currLightResource->power);
149 jsonResponse = cJSON_Print(json);
156 * Very simple example of query parsing.
157 * The query may have multiple filters separated by ';'.
158 * It is upto the entity handler to parse the query for the individual filters,
159 * VALIDATE them and respond as it sees fit.
161 * This function only returns false if the query is exactly "power<X" and
162 * current power is greater than X. If X cannot be parsed for an int,
165 bool checkIfQueryForPowerPassed(char * query)
167 if (query && strncmp(query, "power<", strlen("power<")) == 0)
169 char * pointerToOperator = strstr(query, "<");
171 if (pointerToOperator)
173 int powerRequested = atoi(pointerToOperator + 1);
174 if (Light.power > powerRequested)
176 OC_LOG_V(INFO, TAG, "Current power: %d. Requested: <%d", Light.power
186 * Application should validate and process these as desired.
188 OCEntityHandlerResult ValidateQueryParams (OCEntityHandlerRequest *entityHandlerRequest)
190 OC_LOG_V(INFO, TAG, PCF("Received query %s"), entityHandlerRequest->query);
191 OC_LOG(INFO, TAG, PCF("Not processing query"));
195 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
196 char *payload, uint16_t maxPayloadSize)
198 OCEntityHandlerResult ehResult;
199 bool queryPassed = checkIfQueryForPowerPassed(ehRequest->query);
201 // Empty payload if the query has no match.
204 char *getResp = constructJsonResponse(ehRequest);
207 OC_LOG(ERROR, TAG, "constructJsonResponse failed");
211 if (maxPayloadSize > strlen (getResp))
213 strncpy(payload, getResp, strlen(getResp));
218 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
220 ehResult = OC_EH_ERROR;
233 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
234 char *payload, uint16_t maxPayloadSize)
236 OCEntityHandlerResult ehResult;
237 char *putResp = constructJsonResponse(ehRequest);
241 OC_LOG(ERROR, TAG, "Failed to construct Json response");
245 if (maxPayloadSize > strlen ((char *)putResp))
247 strncpy(payload, putResp, strlen((char *)putResp));
252 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
254 ehResult = OC_EH_ERROR;
262 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
263 OCEntityHandlerResponse *response, char *payload, uint16_t maxPayloadSize)
265 OCEntityHandlerResult ehResult = OC_EH_OK;
266 char *respPLPost_light = NULL;
271 * The entity handler determines how to process a POST request.
272 * Per the REST paradigm, POST can also be used to update representation of existing
273 * resource or create a new resource.
274 * In the sample below, if the POST is for /a/light then a new instance of the Light
275 * resource is created with default representation (if representation is included in
276 * POST payload it can be used as initial values) as long as the instance is
277 * lesser than max new instance count. Once max instance count is reached, POST on
278 * /a/light updated the representation of /a/light (just like PUT)
281 if (ehRequest->resource == Light.handle)
283 if (gCurrLightInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
285 // Create new Light instance
286 char newLightUri[URI_MAXSIZE];
287 snprintf(newLightUri, URI_MAXSIZE, "/a/light/%d", gCurrLightInstance);
289 json = cJSON_CreateObject();
290 cJSON_AddStringToObject(json,"href",gResourceUri);
291 cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
292 cJSON_AddStringToObject(format, "createduri", (char *) newLightUri);
294 if (0 == createLightResource (newLightUri, &gLightInstance[gCurrLightInstance]))
296 OC_LOG (INFO, TAG, "Created new Light instance\n");
297 gLightInstance[gCurrLightInstance].state = 0;
298 gLightInstance[gCurrLightInstance].power = 0;
299 gCurrLightInstance++;
300 respPLPost_light = cJSON_Print(json);
301 strncpy ((char *)response->resourceUri, newLightUri, MAX_URI_LENGTH);
302 ehResult = OC_EH_RESOURCE_CREATED;
309 // Update repesentation of /a/light
312 respPLPost_light = constructJsonResponse(ehRequest);
317 for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
319 if (ehRequest->resource == gLightInstance[i].handle)
321 gLightInstance[i].state = true;
322 gLightInstance[i].power = 22;
325 respPLPost_light = constructJsonResponse(ehRequest);
330 respPLPost_light = constructJsonResponse(ehRequest);
336 if ((respPLPost_light != NULL) && (maxPayloadSize > strlen ((char *)respPLPost_light)))
338 strncpy(payload, respPLPost_light, strlen((char *)respPLPost_light));
342 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
344 ehResult = OC_EH_ERROR;
347 free(respPLPost_light);
351 OCEntityHandlerResult ProcessDeleteRequest (OCEntityHandlerRequest *ehRequest,
352 char *payload, uint16_t maxPayloadSize)
354 if(ehRequest == NULL)
356 OC_LOG(INFO, TAG, "The ehRequest is NULL");
359 OCEntityHandlerResult ehResult = OC_EH_OK;
361 OC_LOG_V(INFO, TAG, "\n\nExecuting %s for resource %d ", __func__, ehRequest->resource);
364 * In the sample below, the application will:
365 * 1a. pass the delete request to the c stack
366 * 1b. internally, the c stack figures out what needs to be done and does it accordingly
367 * (e.g. send observers notification, remove observers...)
368 * 1c. the c stack returns with the result whether the request is fullfilled.
369 * 2. optionally, app removes observers out of its array 'interestedObservers'
372 const char* deleteResponse = NULL;
374 if ((ehRequest != NULL) && (ehRequest->resource == Light.handle))
376 //Step 1: Ask stack to do the work.
377 OCStackResult result = OCDeleteResource(ehRequest->resource);
379 if (result == OC_STACK_OK)
381 OC_LOG (INFO, TAG, "\n\nDelete Resource operation succeeded.");
383 deleteResponse = responsePayloadDeleteOk;
385 //Step 2: clear observers who wanted to observe this resource at the app level.
386 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
388 if (interestedObservers[i].resourceHandle == ehRequest->resource)
390 interestedObservers[i].valid = false;
391 interestedObservers[i].observationId = 0;
392 interestedObservers[i].resourceHandle = NULL;
396 else if (result == OC_STACK_NO_RESOURCE)
398 OC_LOG(INFO, TAG, "\n\nThe resource doesn't exist or it might have been deleted.");
399 deleteResponse = responsePayloadResourceDoesNotExist;
400 ehResult = OC_EH_RESOURCE_DELETED;
404 OC_LOG(INFO, TAG, "\n\nEncountered error from OCDeleteResource().");
405 deleteResponse = responsePayloadDeleteNotOK;
406 ehResult = OC_EH_ERROR;
409 else if (ehRequest->resource != Light.handle)
411 //Let's this app not supporting DELETE on some resources so
412 //consider the DELETE request is received for a non-support resource.
413 OC_LOG_V(INFO, TAG, "\n\nThe request is received for a non-support resource.");
414 deleteResponse = responsePayloadDeleteResourceNotSupported;
415 ehResult = OC_EH_FORBIDDEN;
418 if (maxPayloadSize > strlen ((char *)deleteResponse))
420 strncpy(payload, deleteResponse, strlen((char *)deleteResponse));
424 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
426 ehResult = OC_EH_ERROR;
432 OCEntityHandlerResult ProcessNonExistingResourceRequest(OCEntityHandlerRequest *ehRequest,
433 char *payload, uint16_t maxPayloadSize)
435 OC_LOG_V(INFO, TAG, "\n\nExecuting %s ", __func__);
437 const char* response = NULL;
438 response = responsePayloadResourceDoesNotExist;
440 if ( (ehRequest != NULL) &&
441 (maxPayloadSize > strlen ((char *)response)) )
443 strncpy((char *)payload, response, strlen((char *)response));
447 OC_LOG_V (ERROR, TAG, "Response buffer: %d bytes is too small",
451 return OC_EH_RESOURCE_NOT_FOUND;
454 void ProcessObserveRegister (OCEntityHandlerRequest *ehRequest)
456 OC_LOG_V (INFO, TAG, "Received observation registration request with observation Id %d",
457 ehRequest->obsInfo.obsId);
458 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
460 if (interestedObservers[i].valid == false)
462 interestedObservers[i].observationId = ehRequest->obsInfo.obsId;
463 interestedObservers[i].valid = true;
464 gLightUnderObservation = 1;
470 void ProcessObserveDeregister (OCEntityHandlerRequest *ehRequest)
472 bool clientStillObserving = false;
474 OC_LOG_V (INFO, TAG, "Received observation deregistration request for observation Id %d",
475 ehRequest->obsInfo.obsId);
476 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
478 if (interestedObservers[i].observationId == ehRequest->obsInfo.obsId)
480 interestedObservers[i].valid = false;
482 if (interestedObservers[i].valid == true)
484 // Even if there is one single client observing we continue notifying entity handler
485 clientStillObserving = true;
488 if (clientStillObserving == false)
489 gLightUnderObservation = 0;
492 OCEntityHandlerResult
493 OCDeviceEntityHandlerCb (OCEntityHandlerFlag flag,
494 OCEntityHandlerRequest *entityHandlerRequest, char* uri)
496 OC_LOG_V (INFO, TAG, "Inside device default entity handler - flags: 0x%x, uri: %s", flag, uri);
498 OCEntityHandlerResult ehResult = OC_EH_OK;
499 OCEntityHandlerResponse response;
500 char payload[MAX_RESPONSE_LENGTH] = {0};
503 if (!entityHandlerRequest)
505 OC_LOG (ERROR, TAG, "Invalid request pointer");
508 // Initialize certain response fields
509 response.numSendVendorSpecificHeaderOptions = 0;
510 memset(response.sendVendorSpecificHeaderOptions, 0,
511 sizeof response.sendVendorSpecificHeaderOptions);
512 memset(response.resourceUri, 0, sizeof response.resourceUri);
515 if (flag & OC_REQUEST_FLAG)
517 OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
519 if (entityHandlerRequest->resource == NULL)
521 OC_LOG (INFO, TAG, "Received request from client to a non-existing resource");
522 ehResult = ProcessNonExistingResourceRequest(entityHandlerRequest,
523 payload, sizeof(payload) - 1);
525 else if (OC_REST_GET == entityHandlerRequest->method)
527 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
528 ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
530 else if (OC_REST_PUT == entityHandlerRequest->method)
532 OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
533 ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
535 else if (OC_REST_DELETE == entityHandlerRequest->method)
537 OC_LOG (INFO, TAG, "Received OC_REST_DELETE from client");
538 ehResult = ProcessDeleteRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
542 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
543 entityHandlerRequest->method);
544 ehResult = OC_EH_ERROR;
546 // If the result isn't an error or forbidden, send response
547 if (!((ehResult == OC_EH_ERROR) || (ehResult == OC_EH_FORBIDDEN)))
549 // Format the response. Note this requires some info about the request
550 response.requestHandle = entityHandlerRequest->requestHandle;
551 response.resourceHandle = entityHandlerRequest->resource;
552 response.ehResult = ehResult;
553 response.payload = payload;
554 response.payloadSize = strlen(payload);
555 // Indicate that response is NOT in a persistent buffer
556 response.persistentBufferFlag = 0;
559 if (OCDoResponse(&response) != OC_STACK_OK)
561 OC_LOG(ERROR, TAG, "Error sending response");
562 ehResult = OC_EH_ERROR;
566 if (flag & OC_OBSERVE_FLAG)
568 OC_LOG(INFO, TAG, "Flag includes OC_OBSERVE_FLAG");
569 if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
571 OC_LOG (INFO, TAG, "Received OC_OBSERVE_REGISTER from client");
573 else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
575 OC_LOG (INFO, TAG, "Received OC_OBSERVE_DEREGISTER from client");
582 OCEntityHandlerResult
583 OCNOPEntityHandlerCb (OCEntityHandlerFlag flag,
584 OCEntityHandlerRequest *entityHandlerRequest)
586 // This is callback is associated with the 2 presence notification
587 // resources. They are non-operational.
591 OCEntityHandlerResult
592 OCEntityHandlerCb (OCEntityHandlerFlag flag,
593 OCEntityHandlerRequest *entityHandlerRequest)
595 OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
597 OCEntityHandlerResult ehResult = OC_EH_OK;
598 OCEntityHandlerResponse response;
599 char payload[MAX_RESPONSE_LENGTH] = {0};
602 if (!entityHandlerRequest)
604 OC_LOG (ERROR, TAG, "Invalid request pointer");
608 // Initialize certain response fields
609 response.numSendVendorSpecificHeaderOptions = 0;
610 memset(response.sendVendorSpecificHeaderOptions,
611 0, sizeof response.sendVendorSpecificHeaderOptions);
612 memset(response.resourceUri, 0, sizeof response.resourceUri);
614 if (flag & OC_REQUEST_FLAG)
616 OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
618 if (OC_REST_GET == entityHandlerRequest->method)
620 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
621 ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
623 else if (OC_REST_PUT == entityHandlerRequest->method)
625 OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
626 ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
628 else if (OC_REST_POST == entityHandlerRequest->method)
630 OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
631 ehResult = ProcessPostRequest (entityHandlerRequest, &response, payload, sizeof(payload) - 1);
633 else if (OC_REST_DELETE == entityHandlerRequest->method)
635 OC_LOG (INFO, TAG, "Received OC_REST_DELETE from client");
636 ehResult = ProcessDeleteRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
640 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
641 entityHandlerRequest->method);
642 ehResult = OC_EH_ERROR;
644 // If the result isn't an error or forbidden, send response
645 if (!((ehResult == OC_EH_ERROR) || (ehResult == OC_EH_FORBIDDEN)))
647 // Format the response. Note this requires some info about the request
648 response.requestHandle = entityHandlerRequest->requestHandle;
649 response.resourceHandle = entityHandlerRequest->resource;
650 response.ehResult = ehResult;
651 response.payload = payload;
652 response.payloadSize = strlen(payload);
653 // Indicate that response is NOT in a persistent buffer
654 response.persistentBufferFlag = 0;
656 // Handle vendor specific options
657 if(entityHandlerRequest->rcvdVendorSpecificHeaderOptions &&
658 entityHandlerRequest->numRcvdVendorSpecificHeaderOptions)
660 OC_LOG (INFO, TAG, "Received vendor specific options");
662 OCHeaderOption * rcvdOptions =
663 entityHandlerRequest->rcvdVendorSpecificHeaderOptions;
664 for( i = 0; i < entityHandlerRequest->numRcvdVendorSpecificHeaderOptions; i++)
666 if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
668 OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
669 ((OCHeaderOption)rcvdOptions[i]).optionID );
671 OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
672 MAX_HEADER_OPTION_DATA_LENGTH);
675 OCHeaderOption * sendOptions = response.sendVendorSpecificHeaderOptions;
676 uint8_t option2[] = {21,22,23,24,25,26,27,28,29,30};
677 uint8_t option3[] = {31,32,33,34,35,36,37,38,39,40};
678 sendOptions[0].protocolID = OC_COAP_ID;
679 sendOptions[0].optionID = 2248;
680 memcpy(sendOptions[0].optionData, option2, sizeof(option2));
681 sendOptions[0].optionLength = 10;
682 sendOptions[1].protocolID = OC_COAP_ID;
683 sendOptions[1].optionID = 2600;
684 memcpy(sendOptions[1].optionData, option3, sizeof(option3));
685 sendOptions[1].optionLength = 10;
686 response.numSendVendorSpecificHeaderOptions = 2;
690 if (OCDoResponse(&response) != OC_STACK_OK)
692 OC_LOG(ERROR, TAG, "Error sending response");
693 ehResult = OC_EH_ERROR;
697 if (flag & OC_OBSERVE_FLAG)
699 OC_LOG(INFO, TAG, "Flag includes OC_OBSERVE_FLAG");
701 if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
703 OC_LOG (INFO, TAG, "Received OC_OBSERVE_REGISTER from client");
704 ProcessObserveRegister (entityHandlerRequest);
706 else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
708 OC_LOG (INFO, TAG, "Received OC_OBSERVE_DEREGISTER from client");
709 ProcessObserveDeregister (entityHandlerRequest);
716 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
717 void handleSigInt(int signum)
719 if (signum == SIGINT)
725 void *ChangeLightRepresentation (void *param)
728 OCStackResult result = OC_STACK_ERROR;
731 uint8_t numNotifies = (SAMPLE_MAX_NUM_OBSERVATIONS)/2;
732 OCObservationId obsNotify[numNotifies];
738 if (gLightUnderObservation)
740 OC_LOG_V(INFO, TAG, " =====> Notifying stack of new power level %d\n", Light.power);
741 if (gObserveNotifyType == 1)
743 // Notify list of observers. Alternate observers on the list will be notified.
745 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; (i=i+2))
747 if (interestedObservers[i].valid == true)
749 obsNotify[j] = interestedObservers[i].observationId;
754 cJSON *json = cJSON_CreateObject();
756 cJSON_AddStringToObject(json,"href",gResourceUri);
757 cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
758 cJSON_AddBoolToObject(format, "state", Light.state);
759 cJSON_AddNumberToObject(format, "power", Light.power);
760 char * obsResp = cJSON_Print(json);
762 result = OCNotifyListOfObservers (Light.handle, obsNotify, j,
766 else if (gObserveNotifyType == 0)
768 // Notifying all observers
769 result = OCNotifyAllObservers (Light.handle, OC_NA_QOS);
770 if (OC_STACK_NO_OBSERVERS == result)
773 "=======> No more observers exist, stop sending observations");
774 gLightUnderObservation = 0;
779 OC_LOG (ERROR, TAG, "Incorrect notification type selected");
783 if(stopPresenceCount > 0)
785 OC_LOG_V(INFO, TAG, "================ Counting down to stop presence %d", stopPresenceCount);
787 if(!stopPresenceCount--)
789 OC_LOG(INFO, TAG, "================ stopping presence");
798 void *presenceNotificationGenerator(void *param)
802 OCDoHandle presenceNotificationHandles[numPresenceResources];
803 OCStackResult res = OC_STACK_OK;
805 std::array<std::string, numPresenceResources> presenceNotificationResources { {
806 std::string("core.fan"),
807 std::string("core.led") } };
808 std::array<std::string, numPresenceResources> presenceNotificationUris { {
809 std::string("/a/fan"),
810 std::string("/a/led") } };
812 for(int i=0; i<numPresenceResources; i++)
814 if(res == OC_STACK_OK)
817 res = OCCreateResource(&presenceNotificationHandles[i],
818 presenceNotificationResources.at(i).c_str(),
819 OC_RSRVD_INTERFACE_DEFAULT,
820 presenceNotificationUris.at(i).c_str(),
821 OCNOPEntityHandlerCb,
822 OC_DISCOVERABLE|OC_OBSERVABLE);
824 if(res != OC_STACK_OK)
826 OC_LOG_V(ERROR, TAG, "\"Presence Notification Generator\" failed to create resource "
827 "%s with result %s.", presenceNotificationResources.at(i).c_str(),
831 OC_LOG_V(INFO, TAG, PCF("Created %s for presence notification"),
832 presenceNotificationUris[i].c_str());
835 for(int i=0; i<numPresenceResources; i++)
837 if(res == OC_STACK_OK)
839 res = OCDeleteResource(presenceNotificationHandles[i]);
841 if(res != OC_STACK_OK)
843 OC_LOG_V(ERROR, TAG, "\"Presence Notification Generator\" failed to delete "\
844 "resource %s.", presenceNotificationResources.at(i).c_str());
847 OC_LOG_V(INFO, TAG, PCF("Deleted %s for presence notification"),
848 presenceNotificationUris[i].c_str());
854 int createLightResource (char *uri, LightResource *lightResource)
858 OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
862 lightResource->state = false;
863 lightResource->power= 0;
864 OCStackResult res = OCCreateResource(&(lightResource->handle),
869 OC_DISCOVERABLE|OC_OBSERVABLE);
870 OC_LOG_V(INFO, TAG, "Created Light resource with result: %s", getResult(res));
875 void DeletePlatformInfo()
877 free (platformInfo.platformID);
878 free (platformInfo.manufacturerName);
879 free (platformInfo.manufacturerUrl);
880 free (platformInfo.modelNumber);
881 free (platformInfo.dateOfManufacture);
882 free (platformInfo.platformVersion);
883 free (platformInfo.operatingSystemVersion);
884 free (platformInfo.hardwareVersion);
885 free (platformInfo.firmwareVersion);
886 free (platformInfo.supportUrl);
887 free (platformInfo.systemTime);
890 void DeleteDeviceInfo()
892 free (deviceInfo.deviceName);
895 bool DuplicateString(char** targetString, const char* sourceString)
903 *targetString = (char *) malloc(strlen(sourceString) + 1);
907 strncpy(*targetString, sourceString, (strlen(sourceString) + 1));
914 OCStackResult SetPlatformInfo(const char* platformID, const char *manufacturerName,
915 const char *manufacturerUrl, const char *modelNumber, const char *dateOfManufacture,
916 const char *platformVersion, const char* operatingSystemVersion, const char* hardwareVersion,
917 const char *firmwareVersion, const char* supportUrl, const char* systemTime)
922 if(manufacturerName != NULL && (strlen(manufacturerName) > MAX_MANUFACTURER_NAME_LENGTH))
924 return OC_STACK_INVALID_PARAM;
927 if(manufacturerUrl != NULL && (strlen(manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH))
929 return OC_STACK_INVALID_PARAM;
932 if(!DuplicateString(&platformInfo.platformID, platformID))
937 if(!DuplicateString(&platformInfo.manufacturerName, manufacturerName))
942 if(!DuplicateString(&platformInfo.manufacturerUrl, manufacturerUrl))
947 if(!DuplicateString(&platformInfo.modelNumber, modelNumber))
952 if(!DuplicateString(&platformInfo.dateOfManufacture, dateOfManufacture))
957 if(!DuplicateString(&platformInfo.platformVersion, platformVersion))
962 if(!DuplicateString(&platformInfo.operatingSystemVersion, operatingSystemVersion))
967 if(!DuplicateString(&platformInfo.hardwareVersion, hardwareVersion))
972 if(!DuplicateString(&platformInfo.firmwareVersion, firmwareVersion))
977 if(!DuplicateString(&platformInfo.supportUrl, supportUrl))
982 if(!DuplicateString(&platformInfo.systemTime, systemTime))
992 DeletePlatformInfo();
993 return OC_STACK_ERROR;
996 OCStackResult SetDeviceInfo(const char* deviceName)
998 if(!DuplicateString(&deviceInfo.deviceName, deviceName))
1000 return OC_STACK_ERROR;
1005 static void PrintUsage()
1007 OC_LOG(INFO, TAG, "Usage : ocserver -o <0|1>");
1008 OC_LOG(INFO, TAG, "-o 0 : Notify all observers");
1009 OC_LOG(INFO, TAG, "-o 1 : Notify list of observers");
1012 int main(int argc, char* argv[])
1015 pthread_t threadId_presence;
1018 while ((opt = getopt(argc, argv, "o:")) != -1)
1023 gObserveNotifyType = atoi(optarg);
1031 if ((gObserveNotifyType != 0) && (gObserveNotifyType != 1))
1037 OC_LOG(DEBUG, TAG, "OCServer is starting...");
1039 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
1041 OC_LOG(ERROR, TAG, "OCStack init error");
1044 #ifdef WITH_PRESENCE
1045 if (OCStartPresence(0) != OC_STACK_OK)
1047 OC_LOG(ERROR, TAG, "OCStack presence/discovery error");
1052 OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandlerCb);
1054 OCStackResult registrationResult =
1055 SetPlatformInfo(platformID, manufacturerName, manufacturerUrl, modelNumber,
1056 dateOfManufacture, platformVersion, operatingSystemVersion, hardwareVersion,
1057 firmwareVersion, supportUrl, systemTime);
1059 if (registrationResult != OC_STACK_OK)
1061 OC_LOG(INFO, TAG, "Platform info setting failed locally!");
1062 exit (EXIT_FAILURE);
1065 registrationResult = OCSetPlatformInfo(platformInfo);
1067 if (registrationResult != OC_STACK_OK)
1069 OC_LOG(INFO, TAG, "Platform Registration failed!");
1070 exit (EXIT_FAILURE);
1073 registrationResult = SetDeviceInfo(deviceName);
1075 if (registrationResult != OC_STACK_OK)
1077 OC_LOG(INFO, TAG, "Device info setting failed locally!");
1078 exit (EXIT_FAILURE);
1081 registrationResult = OCSetDeviceInfo(deviceInfo);
1083 if (registrationResult != OC_STACK_OK)
1085 OC_LOG(INFO, TAG, "Device Registration failed!");
1086 exit (EXIT_FAILURE);
1090 * Declare and create the example resource: Light
1092 createLightResource(gResourceUri, &Light);
1094 // Initialize observations data structure for the resource
1095 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
1097 interestedObservers[i].valid = false;
1101 * Create a thread for changing the representation of the Light
1103 pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)NULL);
1106 * Create a thread for generating changes that cause presence notifications
1107 * to be sent to clients
1110 #ifdef WITH_PRESENCE
1111 pthread_create(&threadId_presence, NULL, presenceNotificationGenerator, (void *)NULL);
1114 // Break from loop with Ctrl-C
1115 OC_LOG(INFO, TAG, "Entering ocserver main loop...");
1117 DeletePlatformInfo();
1120 signal(SIGINT, handleSigInt);
1124 if (OCProcess() != OC_STACK_OK)
1126 OC_LOG(ERROR, TAG, "OCStack process error");
1134 * Cancel the Light thread and wait for it to terminate
1136 pthread_cancel(threadId);
1137 pthread_join(threadId, NULL);
1138 pthread_cancel(threadId_presence);
1139 pthread_join(threadId_presence, NULL);
1141 OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
1143 if (OCStop() != OC_STACK_OK)
1145 OC_LOG(ERROR, TAG, "OCStack process error");