1 //******************************************************************
3 // Copyright 2014 Samsung Electronics All Rights Reserved.
4 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
6 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
8 // Licensed under the Apache License, Version 2.0 (the "License");
9 // you may not use this file except in compliance with the License.
10 // You may obtain a copy of the License at
12 // http://www.apache.org/licenses/LICENSE-2.0
14 // Unless required by applicable law or agreed to in writing, software
15 // distributed under the License is distributed on an "AS IS" BASIS,
16 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 // See the License for the specific language governing permissions and
18 // limitations under the License.
20 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
32 #include "oic_malloc.h"
35 #include "ocpayload.h"
39 #define VERIFY_SUCCESS(op) \
41 if (op != OC_STACK_OK) \
43 cout << #op << " failed!!" << endl; \
48 //string length of "/a/light/" + std::numeric_limits<int>::digits10 + '\0'"
50 const int URI_MAXSIZE = 19;
52 static int gObserveNotifyType = 3;
55 int gLightUnderObservation = 0;
57 static GMainLoop *g_mainloop = NULL;
60 static LightResource Light;
61 // This variable determines instance number of the Light resource.
62 // Used by POST method to create a new instance of Light resource.
63 static int gCurrLightInstance = 0;
65 static LightResource gLightInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
67 Observers interestedObservers[SAMPLE_MAX_NUM_OBSERVATIONS];
70 static int stopPresenceCount = 10;
71 #define numPresenceResources (2)
74 char *gResourceUri= (char *)"/a/light";
75 const char *dateOfManufacture = "2016-01-15";
76 const char *deviceName = "myDeviceName";
77 const char *deviceUUID = "51b55ddc-ccbb-4cb3-a57f-494eeca13a21";
78 const char *firmwareVersion = "myFirmwareVersion";
79 const char *manufacturerName = "myName";
80 const char *operatingSystemVersion = "myOS";
81 const char *hardwareVersion = "myHardwareVersion";
82 const char *platformID = "0A3E0D6F-DBF5-404E-8719-D6880042463A";
83 const char *manufacturerLink = "https://www.iotivity.org";
84 const char *modelNumber = "myModelNumber";
85 const char *platformVersion = "myPlatformVersion";
86 const char *supportLink = "https://www.iotivity.org";
87 const char *version = "myVersion";
88 const char *systemTime = "2015-05-15T11.04";
89 const char *specVersion = "core.1.1.0";
90 const char *dataModelVersions = "res.1.1.0,sh.1.1.0";
91 const char *deviceType = "oic.d.tv";
93 // Entity handler should check for resourceTypeName and ResourceInterface in order to GET
94 // the existence of a known resource
95 const char *resourceTypeName = "core.light";
96 const char *resourceInterface = OC_RSRVD_INTERFACE_DEFAULT;
98 OCPlatformInfo platformInfo;
100 OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
102 OCRepPayload* payload = OCRepPayloadCreate();
105 cout << "Failed to allocate Payload";
109 OCRepPayloadSetUri(payload, uri);
110 OCRepPayloadSetPropBool(payload, "state", state);
111 OCRepPayloadSetPropInt(payload, "power", power);
116 //This function takes the request as an input and returns the response
117 OCRepPayload* constructResponse(OCEntityHandlerRequest *ehRequest)
119 if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
121 cout << "Incoming payload not a representation";
125 OCRepPayload* input = reinterpret_cast<OCRepPayload*>(ehRequest->payload);
127 LightResource *currLightResource = &Light;
129 if (ehRequest->resource == gLightInstance[0].handle)
131 currLightResource = &gLightInstance[0];
132 gResourceUri = (char *) "a/light/0";
134 else if (ehRequest->resource == gLightInstance[1].handle)
136 currLightResource = &gLightInstance[1];
137 gResourceUri = (char *) "a/light/1";
140 if(OC_REST_PUT == ehRequest->method)
142 // Get pointer to query
144 if(OCRepPayloadGetPropInt(input, "power", &pow))
146 currLightResource->power =pow;
150 if(OCRepPayloadGetPropBool(input, "state", &state))
152 currLightResource->state = state;
156 return getPayload(gResourceUri, currLightResource->power, currLightResource->state);
160 * Very simple example of query parsing.
161 * The query may have multiple filters separated by ';'.
162 * It is upto the entity handler to parse the query for the individual filters,
163 * VALIDATE them and respond as it sees fit.
165 * This function only returns false if the query is exactly "power<X" and
166 * current power is greater than X. If X cannot be parsed for an int,
169 bool checkIfQueryForPowerPassed(char * query)
171 if (query && strncmp(query, "power<", strlen("power<")) == 0)
173 char * pointerToOperator = strstr(query, "<");
175 if (pointerToOperator)
177 int powerRequested = atoi(pointerToOperator + 1);
178 if (Light.power > powerRequested)
180 cout << "\nCurrent power: "<< Light.power << "Requested: " << powerRequested;
189 * Application should validate and process these as desired.
191 OCEntityHandlerResult ValidateQueryParams (OCEntityHandlerRequest *entityHandlerRequest)
193 cout << "\nReceived query %s" << entityHandlerRequest->query;
194 cout << "\nNot processing query";
198 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
199 OCRepPayload **payload)
201 OCEntityHandlerResult ehResult;
202 bool queryPassed = checkIfQueryForPowerPassed(ehRequest->query);
204 // Empty payload if the query has no match.
207 OCRepPayload *getResp = constructResponse(ehRequest);
210 cout << "\nconstructResponse failed";
225 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
226 OCRepPayload** payload)
228 OCEntityHandlerResult ehResult;
229 OCRepPayload *putResp = constructResponse(ehRequest);
233 cout << "\nFailed to construct response";
243 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
244 OCEntityHandlerResponse *response, OCRepPayload** payload)
246 OCEntityHandlerResult ehResult = OC_EH_OK;
247 OCRepPayload *respPLPost_light = nullptr;
250 * The entity handler determines how to process a POST request.
251 * Per the REST paradigm, POST can also be used to update representation of existing
252 * resource or create a new resource.
253 * In the sample below, if the POST is for /a/light then a new instance of the Light
254 * resource is created with default representation (if representation is included in
255 * POST payload it can be used as initial values) as long as the instance is
256 * lesser than max new instance count. Once max instance count is reached, POST on
257 * /a/light updated the representation of /a/light (just like PUT).
260 if (ehRequest->resource == Light.handle)
262 if (gCurrLightInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
264 // Create new Light instance
265 char newLightUri[URI_MAXSIZE];
266 snprintf(newLightUri, URI_MAXSIZE, "/a/light/%d", gCurrLightInstance);
268 respPLPost_light = OCRepPayloadCreate();
269 OCRepPayloadSetUri(respPLPost_light, gResourceUri);
270 OCRepPayloadSetPropString(respPLPost_light, "createduri", newLightUri);
272 if (0 == createLightResource (newLightUri, &gLightInstance[gCurrLightInstance]))
274 cout << "\nCreated new Light instance";
275 gLightInstance[gCurrLightInstance].state = 0;
276 gLightInstance[gCurrLightInstance].power = 0;
277 gCurrLightInstance++;
278 strncpy ((char *)response->resourceUri, newLightUri, MAX_URI_LENGTH);
279 ehResult = OC_EH_RESOURCE_CREATED;
284 // Update repesentation of /a/light
287 respPLPost_light = constructResponse(ehRequest);
292 for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
294 if (ehRequest->resource == gLightInstance[i].handle)
296 gLightInstance[i].state = true;
297 gLightInstance[i].power = 22;
300 respPLPost_light = constructResponse(ehRequest);
305 respPLPost_light = constructResponse(ehRequest);
311 if ((respPLPost_light != NULL))
313 *payload = respPLPost_light;
317 cout << "\n Payload was NULL";
318 ehResult = OC_EH_ERROR;
324 OCEntityHandlerResult ProcessDeleteRequest (OCEntityHandlerRequest *ehRequest)
326 if(ehRequest == NULL)
328 cout << "\nThe ehRequest is NULL";
331 OCEntityHandlerResult ehResult = OC_EH_OK;
333 cout << "\nExecuting " << __func__ << " for resource " << ehRequest->resource;
336 * In the sample below, the application will:
337 * 1a. pass the delete request to the c stack
338 * 1b. internally, the c stack figures out what needs to be done and does it accordingly
339 * (e.g. send observers notification, remove observers...)
340 * 1c. the c stack returns with the result whether the request is fullfilled.
341 * 2. optionally, app removes observers out of its array 'interestedObservers'
344 if ((ehRequest != NULL) && (ehRequest->resource == Light.handle))
346 //Step 1: Ask stack to do the work.
347 OCStackResult result = OCDeleteResource(ehRequest->resource);
349 if (result == OC_STACK_OK)
351 cout << "\nDelete Resource operation succeeded.";
354 //Step 2: clear observers who wanted to observe this resource at the app level.
355 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
357 if (interestedObservers[i].resourceHandle == ehRequest->resource)
359 interestedObservers[i].valid = false;
360 interestedObservers[i].observationId = 0;
361 interestedObservers[i].resourceHandle = NULL;
365 else if (result == OC_STACK_NO_RESOURCE)
367 cout << "\nThe resource doesn't exist or it might have been deleted.";
368 ehResult = OC_EH_RESOURCE_DELETED;
372 cout << "\nEncountered error from OCDeleteResource().";
373 ehResult = OC_EH_ERROR;
376 else if (ehRequest->resource != Light.handle)
378 //Let's this app not supporting DELETE on some resources so
379 //consider the DELETE request is received for a non-support resource.
380 cout << "\nThe request is received for a non-support resource.";
381 ehResult = OC_EH_FORBIDDEN;
387 OCEntityHandlerResult ProcessNonExistingResourceRequest(OCEntityHandlerRequest *ehRequest)
389 cout << "\nExecuting " << __func__;
391 return OC_EH_RESOURCE_NOT_FOUND;
394 void ProcessObserveRegister (OCEntityHandlerRequest *ehRequest)
396 cout << "\nReceived observation registration request with observation Id "
397 << ehRequest->obsInfo.obsId;
398 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
400 if (interestedObservers[i].valid == false)
402 interestedObservers[i].observationId = ehRequest->obsInfo.obsId;
403 interestedObservers[i].valid = true;
404 gLightUnderObservation = 1;
410 void ProcessObserveDeregister (OCEntityHandlerRequest *ehRequest)
412 bool clientStillObserving = false;
414 cout << "\nReceived observation deregistration request for observation Id "
415 << ehRequest->obsInfo.obsId;
416 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
418 if (interestedObservers[i].observationId == ehRequest->obsInfo.obsId)
420 interestedObservers[i].valid = false;
422 if (interestedObservers[i].valid == true)
424 // Even if there is one single client observing we continue notifying entity handler
425 clientStillObserving = true;
428 if (clientStillObserving == false)
429 gLightUnderObservation = 0;
432 OCEntityHandlerResult
433 OCDeviceEntityHandlerCb (OCEntityHandlerFlag flag,
434 OCEntityHandlerRequest *entityHandlerRequest, char* uri, void* callbackParam)
436 cout << "\nInside device default entity handler - flags: " << flag << ", uri: %s" << uri;
438 OCEntityHandlerResult ehResult = OC_EH_OK;
439 OCEntityHandlerResponse response;
442 if (!entityHandlerRequest)
444 cout << "\nInvalid request pointer";
447 // Initialize certain response fields
448 response.numSendVendorSpecificHeaderOptions = 0;
449 memset(response.sendVendorSpecificHeaderOptions, 0,
450 sizeof response.sendVendorSpecificHeaderOptions);
451 memset(response.resourceUri, 0, sizeof response.resourceUri);
452 OCRepPayload* payload = nullptr;
455 if (flag & OC_REQUEST_FLAG)
457 cout << "\nFlag includes OC_REQUEST_FLAG";
459 if (entityHandlerRequest->resource == NULL)
461 cout << "\nReceived request from client to a non-existing resource";
462 ehResult = ProcessNonExistingResourceRequest(entityHandlerRequest);
464 else if (OC_REST_GET == entityHandlerRequest->method)
466 cout << "\nReceived OC_REST_GET from client";
467 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
469 else if (OC_REST_PUT == entityHandlerRequest->method)
471 cout << "\nReceived OC_REST_PUT from client";
472 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
474 else if (OC_REST_DELETE == entityHandlerRequest->method)
476 cout << "\nReceived OC_REST_DELETE from client";
477 ehResult = ProcessDeleteRequest (entityHandlerRequest);
481 cout << "\nReceived unsupported method " << entityHandlerRequest->method
483 ehResult = OC_EH_ERROR;
485 // If the result isn't an error or forbidden, send response
486 if (!((ehResult == OC_EH_ERROR) || (ehResult == OC_EH_FORBIDDEN)))
488 // Format the response. Note this requires some info about the request
489 response.requestHandle = entityHandlerRequest->requestHandle;
490 response.resourceHandle = entityHandlerRequest->resource;
491 response.ehResult = ehResult;
492 response.payload = reinterpret_cast<OCPayload*>(payload);
493 // Indicate that response is NOT in a persistent buffer
494 response.persistentBufferFlag = 0;
497 if (OCDoResponse(&response) != OC_STACK_OK)
499 cout << "\nError sending response";
500 ehResult = OC_EH_ERROR;
504 if (flag & OC_OBSERVE_FLAG)
506 cout << "\nFlag includes OC_OBSERVE_FLAG";
507 if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
509 cout << "\nReceived OC_OBSERVE_REGISTER from client";
511 else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
513 cout << "\nReceived OC_OBSERVE_DEREGISTER from client";
517 OCPayloadDestroy(response.payload);
521 OCEntityHandlerResult
522 OCNOPEntityHandlerCb (OCEntityHandlerFlag flag,
523 OCEntityHandlerRequest *entityHandlerRequest, void* callbackParam)
525 // This is callback is associated with the 2 presence notification
526 // resources. They are non-operational.
530 OCEntityHandlerResult
531 OCEntityHandlerCb (OCEntityHandlerFlag flag,
532 OCEntityHandlerRequest *entityHandlerRequest, void* callback)
534 cout << "\nInside entity handler - flags: " << flag;
536 OCEntityHandlerResult ehResult = OC_EH_OK;
537 OCEntityHandlerResponse response = { 0, 0, OC_EH_ERROR, 0, 0, { },{ 0 }, false };
540 if (!entityHandlerRequest)
542 cout << "\nInvalid request pointer";
546 // Initialize certain response fields
547 response.numSendVendorSpecificHeaderOptions = 0;
548 memset(response.sendVendorSpecificHeaderOptions,
549 0, sizeof response.sendVendorSpecificHeaderOptions);
550 memset(response.resourceUri, 0, sizeof response.resourceUri);
551 OCRepPayload* payload = nullptr;
553 if (flag & OC_REQUEST_FLAG)
555 cout << "\n=================================\n";
556 cout << "\nFlag includes OC_REQUEST_FLAG\n";
558 if (OC_REST_GET == entityHandlerRequest->method)
560 cout << "\nReceived OC_REST_GET from client";
561 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
562 cout << "\n=================================\n";
564 else if (OC_REST_PUT == entityHandlerRequest->method)
566 cout << "\nReceived OC_REST_PUT from client";
567 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
568 cout << "\n=================================\n";
570 else if (OC_REST_POST == entityHandlerRequest->method)
572 cout << "\nReceived OC_REST_POST from client";
573 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
574 cout << "\n=================================\n";
576 else if (OC_REST_DELETE == entityHandlerRequest->method)
578 cout << "\nReceived OC_REST_DELETE from client";
579 ehResult = ProcessDeleteRequest (entityHandlerRequest);
580 cout << "\n=================================\n";
584 cout << "\nReceived unsupported method " << entityHandlerRequest->method << " from client";
585 ehResult = OC_EH_ERROR;
587 // If the result isn't an error or forbidden, send response
588 if (!((ehResult == OC_EH_ERROR) || (ehResult == OC_EH_FORBIDDEN)))
590 // Format the response. Note this requires some info about the request
591 response.requestHandle = entityHandlerRequest->requestHandle;
592 response.resourceHandle = entityHandlerRequest->resource;
593 response.ehResult = ehResult;
594 response.payload = reinterpret_cast<OCPayload*>(payload);
595 // Indicate that response is NOT in a persistent buffer
596 response.persistentBufferFlag = 0;
598 // Handle vendor specific options
599 if(entityHandlerRequest->rcvdVendorSpecificHeaderOptions &&
600 entityHandlerRequest->numRcvdVendorSpecificHeaderOptions)
602 cout << "\nReceived vendor specific options";
604 OCHeaderOption * rcvdOptions =
605 entityHandlerRequest->rcvdVendorSpecificHeaderOptions;
606 for( i = 0; i < entityHandlerRequest->numRcvdVendorSpecificHeaderOptions; i++)
608 if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
610 cout << "\nReceived option with ID " << ((OCHeaderOption)rcvdOptions[i]).optionID;
613 OCHeaderOption * sendOptions = response.sendVendorSpecificHeaderOptions;
614 uint8_t option2[] = {21,22,23,24,25,26,27,28,29,30};
615 uint8_t option3[] = {31,32,33,34,35,36,37,38,39,40};
616 sendOptions[0].protocolID = OC_COAP_ID;
617 sendOptions[0].optionID = 2248;
618 memcpy(sendOptions[0].optionData, option2, sizeof(option2));
619 sendOptions[0].optionLength = 10;
620 sendOptions[1].protocolID = OC_COAP_ID;
621 sendOptions[1].optionID = 2600;
622 memcpy(sendOptions[1].optionData, option3, sizeof(option3));
623 sendOptions[1].optionLength = 10;
624 response.numSendVendorSpecificHeaderOptions = 2;
628 if (OCDoResponse(&response) != OC_STACK_OK)
630 cout << "\nError sending response";
631 ehResult = OC_EH_ERROR;
635 if (flag & OC_OBSERVE_FLAG)
637 cout << "\nFlag includes OC_OBSERVE_FLAG";
639 if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
641 cout << "\nReceived OC_OBSERVE_REGISTER from client";
642 ProcessObserveRegister (entityHandlerRequest);
644 else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
646 cout << "\nReceived OC_OBSERVE_DEREGISTER from client";
647 ProcessObserveDeregister (entityHandlerRequest);
651 OCPayloadDestroy(response.payload);
655 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
656 void handleSigInt(int signum)
658 if (signum == SIGINT)
664 void *ChangeLightRepresentation (void *param)
667 OCStackResult result = OC_STACK_ERROR;
670 uint8_t numNotifies = (SAMPLE_MAX_NUM_OBSERVATIONS)/2;
671 OCObservationId obsNotify[numNotifies];
677 if (gLightUnderObservation)
679 cout << "\n=====> Notifying stack of new power level" << Light.power;
680 if (gObserveNotifyType == 1)
682 // Notify list of observers. Alternate observers on the list will be notified.
684 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; (i=i+2))
686 if (interestedObservers[i].valid == true)
688 obsNotify[j] = interestedObservers[i].observationId;
693 OCRepPayload* payload = getPayload(gResourceUri, Light.power, Light.state);
694 result = OCNotifyListOfObservers (Light.handle, obsNotify, j,
696 OCRepPayloadDestroy(payload);
698 else if (gObserveNotifyType == 0)
700 // Notifying all observers
701 result = OCNotifyAllObservers (Light.handle, OC_NA_QOS);
702 if (OC_STACK_NO_OBSERVERS == result)
704 cout << "\n=====> No more observers exist, stop sending observations";
705 gLightUnderObservation = 0;
710 cout << "\nIncorrect notification type selected";
714 if(stopPresenceCount > 0)
716 cout << "\n=====> Counting down to stop presence " << stopPresenceCount;
718 if(!stopPresenceCount--)
720 cout << "\n=====> stopping presence";
729 void *presenceNotificationGenerator(void *param)
733 OCDoHandle presenceNotificationHandles[numPresenceResources];
734 OCStackResult res = OC_STACK_OK;
736 std::array<std::string, numPresenceResources> presenceNotificationResources { {
737 std::string("core.fan"),
738 std::string("core.led") } };
739 std::array<std::string, numPresenceResources> presenceNotificationUris { {
740 std::string("/a/fan"),
741 std::string("/a/led") } };
743 for(int i=0; i<numPresenceResources; i++)
745 if(res == OC_STACK_OK)
748 res = OCCreateResource(&presenceNotificationHandles[i],
749 presenceNotificationResources.at(i).c_str(),
750 OC_RSRVD_INTERFACE_DEFAULT,
751 presenceNotificationUris.at(i).c_str(),
752 OCNOPEntityHandlerCb,
754 OC_DISCOVERABLE|OC_OBSERVABLE);
756 if(res != OC_STACK_OK)
758 cout << "\nPresence Notification Generator failed[" << getResult(res)
759 << "] to create resource " << presenceNotificationResources.at(i).c_str();
762 cout << "\nCreated " << presenceNotificationUris[i].c_str() << " for presence notification";
765 for(int i=0; i<numPresenceResources; i++)
767 if(res == OC_STACK_OK)
769 res = OCDeleteResource(presenceNotificationHandles[i]);
771 if(res != OC_STACK_OK)
773 cout << "\nPresence Notification Generator failed to delete resource"
774 << presenceNotificationResources.at(i).c_str();
777 cout << "\nDeleted " << presenceNotificationUris[i].c_str() << " for presence notification";
783 int createLightResource (char *uri, LightResource *lightResource)
787 cout << "\nResource URI cannot be NULL";
791 lightResource->state = false;
792 lightResource->power= 0;
793 OCStackResult res = OCCreateResource(&(lightResource->handle),
799 OC_DISCOVERABLE|OC_OBSERVABLE);
800 cout << "\nCreated Light resource with result " << getResult(res);
805 void DeletePlatformInfo()
807 free (platformInfo.platformID);
808 free (platformInfo.manufacturerName);
809 free (platformInfo.manufacturerUrl);
810 free (platformInfo.modelNumber);
811 free (platformInfo.dateOfManufacture);
812 free (platformInfo.platformVersion);
813 free (platformInfo.operatingSystemVersion);
814 free (platformInfo.hardwareVersion);
815 free (platformInfo.firmwareVersion);
816 free (platformInfo.supportUrl);
817 free (platformInfo.systemTime);
820 bool DuplicateString(char** targetString, const char* sourceString)
828 *targetString = (char *) malloc(strlen(sourceString) + 1);
832 strncpy(*targetString, sourceString, (strlen(sourceString) + 1));
839 OCStackResult SetPlatformInfo(const char* platformID, const char *manufacturerName,
840 const char *manufacturerUrl, const char *modelNumber, const char *dateOfManufacture,
841 const char *platformVersion, const char* operatingSystemVersion, const char* hardwareVersion,
842 const char *firmwareVersion, const char* supportUrl, const char* systemTime)
847 if(manufacturerName != NULL && (strlen(manufacturerName) > MAX_PLATFORM_NAME_LENGTH))
849 return OC_STACK_INVALID_PARAM;
852 if(manufacturerUrl != NULL && (strlen(manufacturerUrl) > MAX_PLATFORM_URL_LENGTH))
854 return OC_STACK_INVALID_PARAM;
857 if(!DuplicateString(&platformInfo.platformID, platformID))
862 if(!DuplicateString(&platformInfo.manufacturerName, manufacturerName))
867 if(!DuplicateString(&platformInfo.manufacturerUrl, manufacturerUrl))
872 if(!DuplicateString(&platformInfo.modelNumber, modelNumber))
877 if(!DuplicateString(&platformInfo.dateOfManufacture, dateOfManufacture))
882 if(!DuplicateString(&platformInfo.platformVersion, platformVersion))
887 if(!DuplicateString(&platformInfo.operatingSystemVersion, operatingSystemVersion))
892 if(!DuplicateString(&platformInfo.hardwareVersion, hardwareVersion))
897 if(!DuplicateString(&platformInfo.firmwareVersion, firmwareVersion))
902 if(!DuplicateString(&platformInfo.supportUrl, supportUrl))
907 if(!DuplicateString(&platformInfo.systemTime, systemTime))
917 DeletePlatformInfo();
918 return OC_STACK_ERROR;
921 OCStackResult SetDeviceInfo()
923 OCResourceHandle resourceHandle = OCGetResourceHandleAtUri(OC_RSRVD_DEVICE_URI);
924 if (resourceHandle == NULL)
926 OIC_LOG(ERROR, TAG, "Device Resource does not exist.");
930 VERIFY_SUCCESS(OCBindResourceTypeToResource(resourceHandle, deviceType));
931 VERIFY_SUCCESS(OCSetPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DEVICE_NAME, deviceName));
932 VERIFY_SUCCESS(OCSetPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_SPEC_VERSION, specVersion));
933 VERIFY_SUCCESS(OCSetPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DATA_MODEL_VERSION,
936 OIC_LOG(INFO, TAG, "Device information initialized successfully.");
940 return OC_STACK_ERROR;
943 static void PrintUsage()
945 cout << "\nUsage : ocserver -o <0|1>";
946 cout << "\n-o 0 : Notify all observers";
947 cout << "\n-o 1 : Notify list of observers";
950 void *GMainLoopThread(void *param)
955 if (OCProcess() != OC_STACK_OK)
957 cout << "\nOCStack process error";
960 #ifndef ROUTING_GATEWAY
967 g_main_loop_quit(g_mainloop);
972 int main(int argc, char* argv[])
975 pthread_t threadId_presence;
978 g_mainloop = g_main_loop_new(NULL, FALSE);
981 printf("g_main_loop_new failed\n");
985 while ((opt = getopt(argc, argv, "o:")) != -1)
990 gObserveNotifyType = atoi(optarg);
998 if ((gObserveNotifyType != 0) && (gObserveNotifyType != 1))
1004 cout << "\nOCServer is starting...";
1006 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
1008 cout << "\nOCStack init error";
1012 #ifdef WITH_PRESENCE
1013 if (OCStartPresence(0) != OC_STACK_OK)
1015 cout << "\nOCStack presence/discovery error";
1020 OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandlerCb, NULL);
1022 OCStackResult registrationResult =
1023 SetPlatformInfo(platformID, manufacturerName, manufacturerLink, modelNumber,
1024 dateOfManufacture, platformVersion, operatingSystemVersion, hardwareVersion,
1025 firmwareVersion, supportLink, systemTime);
1027 if (registrationResult != OC_STACK_OK)
1029 cout << "\nPlatform info setting failed locally!";
1030 exit (EXIT_FAILURE);
1033 registrationResult = OCSetPlatformInfo(platformInfo);
1035 if (registrationResult != OC_STACK_OK)
1037 cout << "\nPlatform Registration failed!";
1038 exit (EXIT_FAILURE);
1041 registrationResult = SetDeviceInfo();
1043 if (registrationResult != OC_STACK_OK)
1045 cout << "\nDevice Registration failed!";
1046 exit (EXIT_FAILURE);
1050 * Declare and create the example resource: Light
1052 createLightResource(gResourceUri, &Light);
1054 // Initialize observations data structure for the resource
1055 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
1057 interestedObservers[i].valid = false;
1061 * Create a thread for changing the representation of the Light
1063 pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)NULL);
1066 * Create a thread for generating changes that cause presence notifications
1067 * to be sent to clients
1070 #ifdef WITH_PRESENCE
1071 pthread_create(&threadId_presence, NULL, presenceNotificationGenerator, (void *)NULL);
1074 // Break from loop with Ctrl-C
1075 cout << "\nEntering ocserver main loop...";
1077 DeletePlatformInfo();
1079 signal(SIGINT, handleSigInt);
1081 int result = pthread_create(&g_thread, NULL, GMainLoopThread, (void *)NULL);
1084 printf("pthread_create failed in initialize\n");
1088 g_main_loop_run(g_mainloop);
1091 * Cancel the Light thread and wait for it to terminate
1093 pthread_cancel(threadId);
1094 pthread_join(threadId, NULL);
1095 pthread_cancel(threadId_presence);
1096 pthread_join(threadId_presence, NULL);
1098 cout << "\nExiting ocserver main loop...\n";
1100 if (OCStop() != OC_STACK_OK)
1102 cout << "\nOCStack process error";