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((char *)ehRequest->reqJSONPayload);
115 // Get root of JSON payload, then the 1st resource.
116 cJSON* carrier = cJSON_GetObjectItem(putJson, "oc");
117 carrier = cJSON_GetArrayItem(carrier, 0);
118 carrier = cJSON_GetObjectItem(carrier, "rep");
120 cJSON* prop = cJSON_GetObjectItem(carrier,"power");
123 currLightResource->power =prop->valueint;
126 prop = cJSON_GetObjectItem(carrier,"state");
129 currLightResource->state = prop->valueint;
132 cJSON_Delete(putJson);
135 cJSON_AddStringToObject(json,"href",gResourceUri);
136 cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
137 cJSON_AddBoolToObject(format, "state", currLightResource->state);
138 cJSON_AddNumberToObject(format, "power", currLightResource->power);
140 jsonResponse = cJSON_Print(json);
147 * Very simple example of query parsing.
148 * The query may have multiple filters separated by '&'.
149 * It is upto the entity handler to parse the query for the individual filters,
150 * VALIDATE them and respond as it sees fit.
152 * This function only returns false if the query is exactly "power<X" and
153 * current power is greater than X. If X cannot be parsed for an int,
156 bool checkIfQueryForPowerPassed(char * query)
158 if (query && strncmp(query, "power<", strlen("power<")) == 0)
160 char * pointerToOperator = strstr(query, "<");
162 if (pointerToOperator)
164 int powerRequested = atoi(pointerToOperator + 1);
165 if (Light.power > powerRequested)
167 OC_LOG_V(INFO, TAG, "Current power: %d. Requested: <%d", Light.power
177 * Application should validate and process these as desired.
179 OCEntityHandlerResult ValidateQueryParams (OCEntityHandlerRequest *entityHandlerRequest)
181 OC_LOG_V(INFO, TAG, PCF("Received query %s"), entityHandlerRequest->query);
182 OC_LOG(INFO, TAG, PCF("Not processing query"));
186 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
187 char *payload, uint16_t maxPayloadSize)
189 OCEntityHandlerResult ehResult;
191 bool queryPassed = checkIfQueryForPowerPassed(ehRequest->query);
193 // Empty payload if the query has no match.
196 char *getResp = constructJsonResponse(ehRequest);
198 if (maxPayloadSize > strlen ((char *)getResp))
200 strncpy(payload, getResp, strlen((char *)getResp));
205 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
207 ehResult = OC_EH_ERROR;
220 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
221 char *payload, uint16_t maxPayloadSize)
223 OCEntityHandlerResult ehResult;
224 char *putResp = constructJsonResponse(ehRequest);
226 if (maxPayloadSize > strlen ((char *)putResp))
228 strncpy(payload, putResp, strlen((char *)putResp));
233 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
235 ehResult = OC_EH_ERROR;
243 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
244 OCEntityHandlerResponse *response, char *payload, uint16_t maxPayloadSize)
246 OCEntityHandlerResult ehResult = OC_EH_OK;
247 char *respPLPost_light = NULL;
252 * The entity handler determines how to process a POST request.
253 * Per the REST paradigm, POST can also be used to update representation of existing
254 * resource or create a new resource.
255 * In the sample below, if the POST is for /a/light then a new instance of the Light
256 * resource is created with default representation (if representation is included in
257 * POST payload it can be used as initial values) as long as the instance is
258 * lesser than max new instance count. Once max instance count is reached, POST on
259 * /a/light updated the representation of /a/light (just like PUT)
262 if (ehRequest->resource == Light.handle)
264 if (gCurrLightInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
266 // Create new Light instance
267 char newLightUri[URI_MAXSIZE];
268 snprintf(newLightUri, URI_MAXSIZE, "/a/light/%d", gCurrLightInstance);
270 json = cJSON_CreateObject();
271 cJSON_AddStringToObject(json,"href",gResourceUri);
272 cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
273 cJSON_AddStringToObject(format, "createduri", (char *) newLightUri);
275 if (0 == createLightResource (newLightUri, &gLightInstance[gCurrLightInstance]))
277 OC_LOG (INFO, TAG, "Created new Light instance\n");
278 gLightInstance[gCurrLightInstance].state = 0;
279 gLightInstance[gCurrLightInstance].power = 0;
280 gCurrLightInstance++;
281 respPLPost_light = cJSON_Print(json);
282 strncpy ((char *)response->resourceUri, newLightUri, MAX_URI_LENGTH);
283 ehResult = OC_EH_RESOURCE_CREATED;
290 // Update repesentation of /a/light
293 respPLPost_light = constructJsonResponse(ehRequest);
298 for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
300 if (ehRequest->resource == gLightInstance[i].handle)
302 gLightInstance[i].state = true;
303 gLightInstance[i].power = 22;
306 respPLPost_light = constructJsonResponse(ehRequest);
311 respPLPost_light = constructJsonResponse(ehRequest);
317 if ((respPLPost_light != NULL) && (maxPayloadSize > strlen ((char *)respPLPost_light)))
319 strncpy(payload, respPLPost_light, strlen((char *)respPLPost_light));
323 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
325 ehResult = OC_EH_ERROR;
328 free(respPLPost_light);
332 OCEntityHandlerResult ProcessDeleteRequest (OCEntityHandlerRequest *ehRequest,
333 char *payload, uint16_t maxPayloadSize)
335 if(ehRequest == NULL)
337 OC_LOG(INFO, TAG, "The ehRequest is NULL");
340 OCEntityHandlerResult ehResult = OC_EH_OK;
342 OC_LOG_V(INFO, TAG, "\n\nExecuting %s for resource %d ", __func__, ehRequest->resource);
345 * In the sample below, the application will:
346 * 1a. pass the delete request to the c stack
347 * 1b. internally, the c stack figures out what needs to be done and does it accordingly
348 * (e.g. send observers notification, remove observers...)
349 * 1c. the c stack returns with the result whether the request is fullfilled.
350 * 2. optionally, app removes observers out of its array 'interestedObservers'
353 const char* deleteResponse = NULL;
355 if ((ehRequest != NULL) && (ehRequest->resource == Light.handle))
357 //Step 1: Ask stack to do the work.
358 OCStackResult result = OCDeleteResource(ehRequest->resource);
360 if (result == OC_STACK_OK)
362 OC_LOG (INFO, TAG, "\n\nDelete Resource operation succeeded.");
364 deleteResponse = responsePayloadDeleteOk;
366 //Step 2: clear observers who wanted to observe this resource at the app level.
367 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
369 if (interestedObservers[i].resourceHandle == ehRequest->resource)
371 interestedObservers[i].valid = false;
372 interestedObservers[i].observationId = 0;
373 interestedObservers[i].resourceHandle = NULL;
377 else if (result == OC_STACK_NO_RESOURCE)
379 OC_LOG(INFO, TAG, "\n\nThe resource doesn't exist or it might have been deleted.");
380 deleteResponse = responsePayloadResourceDoesNotExist;
381 ehResult = OC_EH_RESOURCE_DELETED;
385 OC_LOG(INFO, TAG, "\n\nEncountered error from OCDeleteResource().");
386 deleteResponse = responsePayloadDeleteNotOK;
387 ehResult = OC_EH_ERROR;
390 else if (ehRequest->resource != Light.handle)
392 //Let's this app not supporting DELETE on some resources so
393 //consider the DELETE request is received for a non-support resource.
394 OC_LOG_V(INFO, TAG, "\n\nThe request is received for a non-support resource.");
395 deleteResponse = responsePayloadDeleteResourceNotSupported;
396 ehResult = OC_EH_FORBIDDEN;
399 if (maxPayloadSize > strlen ((char *)deleteResponse))
401 strncpy(payload, deleteResponse, strlen((char *)deleteResponse));
405 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
407 ehResult = OC_EH_ERROR;
413 OCEntityHandlerResult ProcessNonExistingResourceRequest(OCEntityHandlerRequest *ehRequest,
414 char *payload, uint16_t maxPayloadSize)
416 OC_LOG_V(INFO, TAG, "\n\nExecuting %s ", __func__);
418 const char* response = NULL;
419 response = responsePayloadResourceDoesNotExist;
421 if ( (ehRequest != NULL) &&
422 (maxPayloadSize > strlen ((char *)response)) )
424 strncpy((char *)payload, response, strlen((char *)response));
428 OC_LOG_V (ERROR, TAG, "Response buffer: %d bytes is too small",
432 return OC_EH_RESOURCE_NOT_FOUND;
435 void ProcessObserveRegister (OCEntityHandlerRequest *ehRequest)
437 OC_LOG_V (INFO, TAG, "Received observation registration request with observation Id %d",
438 ehRequest->obsInfo.obsId);
439 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
441 if (interestedObservers[i].valid == false)
443 interestedObservers[i].observationId = ehRequest->obsInfo.obsId;
444 interestedObservers[i].valid = true;
445 gLightUnderObservation = 1;
451 void ProcessObserveDeregister (OCEntityHandlerRequest *ehRequest)
453 bool clientStillObserving = false;
455 OC_LOG_V (INFO, TAG, "Received observation deregistration request for observation Id %d",
456 ehRequest->obsInfo.obsId);
457 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
459 if (interestedObservers[i].observationId == ehRequest->obsInfo.obsId)
461 interestedObservers[i].valid = false;
463 if (interestedObservers[i].valid == true)
465 // Even if there is one single client observing we continue notifying entity handler
466 clientStillObserving = true;
469 if (clientStillObserving == false)
470 gLightUnderObservation = 0;
473 OCEntityHandlerResult
474 OCDeviceEntityHandlerCb (OCEntityHandlerFlag flag,
475 OCEntityHandlerRequest *entityHandlerRequest, char* uri)
477 OC_LOG_V (INFO, TAG, "Inside device default entity handler - flags: 0x%x, uri: %s", flag, uri);
479 OCEntityHandlerResult ehResult = OC_EH_OK;
480 OCEntityHandlerResponse response;
481 char payload[MAX_RESPONSE_LENGTH] = {0};
484 if (!entityHandlerRequest)
486 OC_LOG (ERROR, TAG, "Invalid request pointer");
489 // Initialize certain response fields
490 response.numSendVendorSpecificHeaderOptions = 0;
491 memset(response.sendVendorSpecificHeaderOptions, 0,
492 sizeof response.sendVendorSpecificHeaderOptions);
493 memset(response.resourceUri, 0, sizeof response.resourceUri);
496 if (flag & OC_INIT_FLAG)
498 OC_LOG (INFO, TAG, "Flag includes OC_INIT_FLAG");
500 if (flag & OC_REQUEST_FLAG)
502 OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
504 if (entityHandlerRequest->resource == NULL)
506 OC_LOG (INFO, TAG, "Received request from client to a non-existing resource");
507 ehResult = ProcessNonExistingResourceRequest(entityHandlerRequest,
508 payload, sizeof(payload) - 1);
510 else if (OC_REST_GET == entityHandlerRequest->method)
512 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
513 ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
515 else if (OC_REST_PUT == entityHandlerRequest->method)
517 OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
518 ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
520 else if (OC_REST_DELETE == entityHandlerRequest->method)
522 OC_LOG (INFO, TAG, "Received OC_REST_DELETE from client");
523 ehResult = ProcessDeleteRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
527 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
528 entityHandlerRequest->method);
529 ehResult = OC_EH_ERROR;
531 // If the result isn't an error or forbidden, send response
532 if (!((ehResult == OC_EH_ERROR) || (ehResult == OC_EH_FORBIDDEN)))
534 // Format the response. Note this requires some info about the request
535 response.requestHandle = entityHandlerRequest->requestHandle;
536 response.resourceHandle = entityHandlerRequest->resource;
537 response.ehResult = ehResult;
538 response.payload = payload;
539 response.payloadSize = strlen(payload);
540 // Indicate that response is NOT in a persistent buffer
541 response.persistentBufferFlag = 0;
544 if (OCDoResponse(&response) != OC_STACK_OK)
546 OC_LOG(ERROR, TAG, "Error sending response");
547 ehResult = OC_EH_ERROR;
551 if (flag & OC_OBSERVE_FLAG)
553 OC_LOG(INFO, TAG, "Flag includes OC_OBSERVE_FLAG");
554 if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
556 OC_LOG (INFO, TAG, "Received OC_OBSERVE_REGISTER from client");
558 else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
560 OC_LOG (INFO, TAG, "Received OC_OBSERVE_DEREGISTER from client");
567 OCEntityHandlerResult
568 OCNOPEntityHandlerCb (OCEntityHandlerFlag flag,
569 OCEntityHandlerRequest *entityHandlerRequest)
571 // This is callback is associated with the 2 presence notification
572 // resources. They are non-operational.
576 OCEntityHandlerResult
577 OCEntityHandlerCb (OCEntityHandlerFlag flag,
578 OCEntityHandlerRequest *entityHandlerRequest)
580 OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
582 OCEntityHandlerResult ehResult = OC_EH_OK;
583 OCEntityHandlerResponse response;
584 char payload[MAX_RESPONSE_LENGTH] = {0};
587 if (!entityHandlerRequest)
589 OC_LOG (ERROR, TAG, "Invalid request pointer");
593 // Initialize certain response fields
594 response.numSendVendorSpecificHeaderOptions = 0;
595 memset(response.sendVendorSpecificHeaderOptions,
596 0, sizeof response.sendVendorSpecificHeaderOptions);
597 memset(response.resourceUri, 0, sizeof response.resourceUri);
599 if (flag & OC_INIT_FLAG)
601 OC_LOG (INFO, TAG, "Flag includes OC_INIT_FLAG");
603 if (flag & OC_REQUEST_FLAG)
605 OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
607 if (OC_REST_GET == entityHandlerRequest->method)
609 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
610 ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
612 else if (OC_REST_PUT == entityHandlerRequest->method)
614 OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
615 ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
617 else if (OC_REST_POST == entityHandlerRequest->method)
619 OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
620 ehResult = ProcessPostRequest (entityHandlerRequest, &response, payload, sizeof(payload) - 1);
622 else if (OC_REST_DELETE == entityHandlerRequest->method)
624 OC_LOG (INFO, TAG, "Received OC_REST_DELETE from client");
625 ehResult = ProcessDeleteRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
629 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
630 entityHandlerRequest->method);
631 ehResult = OC_EH_ERROR;
633 // If the result isn't an error or forbidden, send response
634 if (!((ehResult == OC_EH_ERROR) || (ehResult == OC_EH_FORBIDDEN)))
636 // Format the response. Note this requires some info about the request
637 response.requestHandle = entityHandlerRequest->requestHandle;
638 response.resourceHandle = entityHandlerRequest->resource;
639 response.ehResult = ehResult;
640 response.payload = payload;
641 response.payloadSize = strlen(payload);
642 // Indicate that response is NOT in a persistent buffer
643 response.persistentBufferFlag = 0;
645 // Handle vendor specific options
646 if(entityHandlerRequest->rcvdVendorSpecificHeaderOptions &&
647 entityHandlerRequest->numRcvdVendorSpecificHeaderOptions)
649 OC_LOG (INFO, TAG, "Received vendor specific options");
651 OCHeaderOption * rcvdOptions =
652 entityHandlerRequest->rcvdVendorSpecificHeaderOptions;
653 for( i = 0; i < entityHandlerRequest->numRcvdVendorSpecificHeaderOptions; i++)
655 if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
657 OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
658 ((OCHeaderOption)rcvdOptions[i]).optionID );
660 OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
661 MAX_HEADER_OPTION_DATA_LENGTH);
664 OCHeaderOption * sendOptions = response.sendVendorSpecificHeaderOptions;
665 uint8_t option2[] = {21,22,23,24,25,26,27,28,29,30};
666 uint8_t option3[] = {31,32,33,34,35,36,37,38,39,40};
667 sendOptions[0].protocolID = OC_COAP_ID;
668 sendOptions[0].optionID = 2248;
669 memcpy(sendOptions[0].optionData, option2, sizeof(option2));
670 sendOptions[0].optionLength = 10;
671 sendOptions[1].protocolID = OC_COAP_ID;
672 sendOptions[1].optionID = 2600;
673 memcpy(sendOptions[1].optionData, option3, sizeof(option3));
674 sendOptions[1].optionLength = 10;
675 response.numSendVendorSpecificHeaderOptions = 2;
679 if (OCDoResponse(&response) != OC_STACK_OK)
681 OC_LOG(ERROR, TAG, "Error sending response");
682 ehResult = OC_EH_ERROR;
686 if (flag & OC_OBSERVE_FLAG)
688 OC_LOG(INFO, TAG, "Flag includes OC_OBSERVE_FLAG");
690 if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
692 OC_LOG (INFO, TAG, "Received OC_OBSERVE_REGISTER from client");
693 ProcessObserveRegister (entityHandlerRequest);
695 else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
697 OC_LOG (INFO, TAG, "Received OC_OBSERVE_DEREGISTER from client");
698 ProcessObserveDeregister (entityHandlerRequest);
705 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
706 void handleSigInt(int signum)
708 if (signum == SIGINT)
714 void *ChangeLightRepresentation (void *param)
717 OCStackResult result = OC_STACK_ERROR;
720 uint8_t numNotifies = (SAMPLE_MAX_NUM_OBSERVATIONS)/2;
721 OCObservationId obsNotify[numNotifies];
727 if (gLightUnderObservation)
729 OC_LOG_V(INFO, TAG, " =====> Notifying stack of new power level %d\n", Light.power);
730 if (gObserveNotifyType == 1)
732 // Notify list of observers. Alternate observers on the list will be notified.
734 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; (i=i+2))
736 if (interestedObservers[i].valid == true)
738 obsNotify[j] = interestedObservers[i].observationId;
743 cJSON *json = cJSON_CreateObject();
745 cJSON_AddStringToObject(json,"href",gResourceUri);
746 cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
747 cJSON_AddBoolToObject(format, "state", Light.state);
748 cJSON_AddNumberToObject(format, "power", Light.power);
749 char * obsResp = cJSON_Print(json);
751 result = OCNotifyListOfObservers (Light.handle, obsNotify, j,
755 else if (gObserveNotifyType == 0)
757 // Notifying all observers
758 result = OCNotifyAllObservers (Light.handle, OC_NA_QOS);
759 if (OC_STACK_NO_OBSERVERS == result)
762 "=======> No more observers exist, stop sending observations");
763 gLightUnderObservation = 0;
768 OC_LOG (ERROR, TAG, "Incorrect notification type selected");
772 if(stopPresenceCount > 0)
774 OC_LOG_V(INFO, TAG, "================ Counting down to stop presence %d", stopPresenceCount);
776 if(!stopPresenceCount--)
778 OC_LOG(INFO, TAG, "================ stopping presence");
787 void *presenceNotificationGenerator(void *param)
791 OCDoHandle presenceNotificationHandles[numPresenceResources];
792 OCStackResult res = OC_STACK_OK;
794 std::array<std::string, numPresenceResources> presenceNotificationResources { {
795 std::string("core.fan"),
796 std::string("core.led") } };
797 std::array<std::string, numPresenceResources> presenceNotificationUris { {
798 std::string("/a/fan"),
799 std::string("/a/led") } };
801 for(int i=0; i<numPresenceResources; i++)
803 if(res == OC_STACK_OK)
806 res = OCCreateResource(&presenceNotificationHandles[i],
807 presenceNotificationResources.at(i).c_str(),
809 presenceNotificationUris.at(i).c_str(),
810 OCNOPEntityHandlerCb,
811 OC_DISCOVERABLE|OC_OBSERVABLE);
813 if(res != OC_STACK_OK)
815 OC_LOG_V(ERROR, TAG, "\"Presence Notification Generator\" failed to create resource "
816 "%s with result %s.", presenceNotificationResources.at(i).c_str(),
820 OC_LOG_V(INFO, TAG, PCF("Created %s for presence notification"),
821 presenceNotificationUris[i].c_str());
824 for(int i=0; i<numPresenceResources; i++)
826 if(res == OC_STACK_OK)
828 res = OCDeleteResource(presenceNotificationHandles[i]);
830 if(res != OC_STACK_OK)
832 OC_LOG_V(ERROR, TAG, "\"Presence Notification Generator\" failed to delete "\
833 "resource %s.", presenceNotificationResources.at(i).c_str());
836 OC_LOG_V(INFO, TAG, PCF("Deleted %s for presence notification"),
837 presenceNotificationUris[i].c_str());
843 static void PrintUsage()
845 OC_LOG(INFO, TAG, "Usage : ocserver -o <0|1>");
846 OC_LOG(INFO, TAG, "-o 0 : Notify all observers");
847 OC_LOG(INFO, TAG, "-o 1 : Notify list of observers");
850 int main(int argc, char* argv[])
853 pthread_t threadId_presence;
856 while ((opt = getopt(argc, argv, "o:")) != -1)
861 gObserveNotifyType = atoi(optarg);
869 if ((gObserveNotifyType != 0) && (gObserveNotifyType != 1))
875 OC_LOG(DEBUG, TAG, "OCServer is starting...");
877 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
879 OC_LOG(ERROR, TAG, "OCStack init error");
883 if (OCStartPresence(0) != OC_STACK_OK)
885 OC_LOG(ERROR, TAG, "OCStack presence/discovery error");
890 OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandlerCb);
892 OCStackResult deviceResult = SetDeviceInfo(contentType, dateOfManufacture, deviceName,
893 deviceUUID, firmwareVersion, hostName, manufacturerName,
894 manufacturerUrl, modelNumber, platformVersion, supportUrl, version);
896 if (deviceResult != OC_STACK_OK)
898 OC_LOG(INFO, TAG, "Device Registration failed!");
902 deviceResult = OCSetDeviceInfo(deviceInfo);
904 if (deviceResult != OC_STACK_OK)
906 OC_LOG(INFO, TAG, "Device Registration failed!");
911 * Declare and create the example resource: Light
913 createLightResource(gResourceUri, &Light);
915 // Initialize observations data structure for the resource
916 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
918 interestedObservers[i].valid = false;
922 * Create a thread for changing the representation of the Light
924 pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)NULL);
927 * Create a thread for generating changes that cause presence notifications
928 * to be sent to clients
932 pthread_create(&threadId_presence, NULL, presenceNotificationGenerator, (void *)NULL);
935 // Break from loop with Ctrl-C
936 OC_LOG(INFO, TAG, "Entering ocserver main loop...");
938 signal(SIGINT, handleSigInt);
941 if (OCProcess() != OC_STACK_OK)
943 OC_LOG(ERROR, TAG, "OCStack process error");
951 * Cancel the Light thread and wait for it to terminate
953 pthread_cancel(threadId);
954 pthread_join(threadId, NULL);
955 pthread_cancel(threadId_presence);
956 pthread_join(threadId_presence, NULL);
958 OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
960 if (OCStop() != OC_STACK_OK)
962 OC_LOG(ERROR, TAG, "OCStack process error");
968 int createLightResource (char *uri, LightResource *lightResource)
972 OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
976 lightResource->state = false;
977 lightResource->power= 0;
978 OCStackResult res = OCCreateResource(&(lightResource->handle),
983 OC_DISCOVERABLE|OC_OBSERVABLE);
984 OC_LOG_V(INFO, TAG, "Created Light resource with result: %s", getResult(res));
989 void DeleteDeviceInfo()
991 free(deviceInfo.contentType);
992 free(deviceInfo.dateOfManufacture);
993 free(deviceInfo.deviceName);
994 free(deviceInfo.deviceUUID);
995 free(deviceInfo.firmwareVersion);
996 free(deviceInfo.hostName);
997 free(deviceInfo.manufacturerName);
998 free(deviceInfo.manufacturerUrl);
999 free(deviceInfo.modelNumber);
1000 free(deviceInfo.platformVersion);
1001 free(deviceInfo.supportUrl);
1002 free(deviceInfo.version);
1005 bool DuplicateString(char** targetString, const char* sourceString)
1013 *targetString = (char *) malloc(strlen(sourceString) + 1);
1017 strncpy(*targetString, sourceString, (strlen(sourceString) + 1));
1024 OCStackResult SetDeviceInfo(const char *contentType, const char *dateOfManufacture,
1025 const char *deviceName, const char *deviceUUID, const char *firmwareVersion,
1026 const char *hostName, const char *manufacturerName, const char *manufacturerUrl,
1027 const char *modelNumber, const char *platformVersion, const char *supportUrl,
1028 const char *version)
1031 bool success = true;
1033 if(manufacturerName != NULL && (strlen(manufacturerName) > MAX_MANUFACTURER_NAME_LENGTH))
1035 return OC_STACK_INVALID_PARAM;
1038 if(manufacturerUrl != NULL && (strlen(manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH))
1040 return OC_STACK_INVALID_PARAM;
1043 if(!DuplicateString(&deviceInfo.contentType, contentType))
1048 if(!DuplicateString(&deviceInfo.dateOfManufacture, dateOfManufacture))
1053 if(!DuplicateString(&deviceInfo.deviceName, deviceName))
1058 if(!DuplicateString(&deviceInfo.deviceUUID, deviceUUID))
1063 if(!DuplicateString(&deviceInfo.firmwareVersion, firmwareVersion))
1068 if(!DuplicateString(&deviceInfo.hostName, hostName))
1073 if(!DuplicateString(&deviceInfo.manufacturerName, manufacturerName))
1078 if(!DuplicateString(&deviceInfo.manufacturerUrl, manufacturerUrl))
1083 if(!DuplicateString(&deviceInfo.modelNumber, modelNumber))
1088 if(!DuplicateString(&deviceInfo.platformVersion, platformVersion))
1093 if(!DuplicateString(&deviceInfo.supportUrl, supportUrl))
1098 if(!DuplicateString(&deviceInfo.version, version))
1109 return OC_STACK_ERROR;