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 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
34 #include "ocpayload.h"
38 //string length of "/a/light/" + std::numeric_limits<int>::digits10 + '\0'"
40 const int URI_MAXSIZE = 19;
42 static int gObserveNotifyType = 3;
45 int gLightUnderObservation = 0;
47 static GMainLoop *g_mainloop = NULL;
50 static LightResource Light;
51 // This variable determines instance number of the Light resource.
52 // Used by POST method to create a new instance of Light resource.
53 static int gCurrLightInstance = 0;
55 static LightResource gLightInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
57 Observers interestedObservers[SAMPLE_MAX_NUM_OBSERVATIONS];
60 static int stopPresenceCount = 10;
61 #define numPresenceResources (2)
64 char *gResourceUri= (char *)"/a/light";
65 const char *dateOfManufacture = "myDateOfManufacture";
66 const char *deviceName = "myDeviceName";
67 const char *deviceUUID = "myDeviceUUID";
68 const char *firmwareVersion = "myFirmwareVersion";
69 const char *manufacturerName = "myName";
70 const char *operatingSystemVersion = "myOS";
71 const char *hardwareVersion = "myHardwareVersion";
72 const char* platformID = "myPlatformID";
73 const char *manufacturerUrl = "myManufacturerUrl";
74 const char *modelNumber = "myModelNumber";
75 const char *platformVersion = "myPlatformVersion";
76 const char *supportUrl = "mySupportUrl";
77 const char *version = "myVersion";
78 const char *systemTime = "2015-05-15T11.04";
80 // Entity handler should check for resourceTypeName and ResourceInterface in order to GET
81 // the existence of a known resource
82 const char *resourceTypeName = "core.light";
83 const char *resourceInterface = OC_RSRVD_INTERFACE_DEFAULT;
85 OCPlatformInfo platformInfo;
86 OCDeviceInfo deviceInfo;
88 OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
90 OCRepPayload* payload = OCRepPayloadCreate();
93 cout << "Failed to allocate Payload";
97 OCRepPayloadSetUri(payload, uri);
98 OCRepPayloadSetPropBool(payload, "state", state);
99 OCRepPayloadSetPropInt(payload, "power", power);
104 //This function takes the request as an input and returns the response
105 OCRepPayload* constructResponse(OCEntityHandlerRequest *ehRequest)
107 if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
109 cout << "Incoming payload not a representation";
113 OCRepPayload* input = reinterpret_cast<OCRepPayload*>(ehRequest->payload);
115 LightResource *currLightResource = &Light;
117 if (ehRequest->resource == gLightInstance[0].handle)
119 currLightResource = &gLightInstance[0];
120 gResourceUri = (char *) "a/light/0";
122 else if (ehRequest->resource == gLightInstance[1].handle)
124 currLightResource = &gLightInstance[1];
125 gResourceUri = (char *) "a/light/1";
128 if(OC_REST_PUT == ehRequest->method)
130 // Get pointer to query
132 if(OCRepPayloadGetPropInt(input, "power", &pow))
134 currLightResource->power =pow;
138 if(OCRepPayloadGetPropBool(input, "state", &state))
140 currLightResource->state = state;
144 return getPayload(gResourceUri, currLightResource->power, currLightResource->state);
148 * Very simple example of query parsing.
149 * The query may have multiple filters separated by ';'.
150 * It is upto the entity handler to parse the query for the individual filters,
151 * VALIDATE them and respond as it sees fit.
153 * This function only returns false if the query is exactly "power<X" and
154 * current power is greater than X. If X cannot be parsed for an int,
157 bool checkIfQueryForPowerPassed(char * query)
159 if (query && strncmp(query, "power<", strlen("power<")) == 0)
161 char * pointerToOperator = strstr(query, "<");
163 if (pointerToOperator)
165 int powerRequested = atoi(pointerToOperator + 1);
166 if (Light.power > powerRequested)
168 cout << "\nCurrent power: "<< Light.power << "Requested: " << powerRequested;
177 * Application should validate and process these as desired.
179 OCEntityHandlerResult ValidateQueryParams (OCEntityHandlerRequest *entityHandlerRequest)
181 cout << "\nReceived query %s" << entityHandlerRequest->query;
182 cout << "\nNot processing query";
186 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
187 OCRepPayload **payload)
189 OCEntityHandlerResult ehResult;
190 bool queryPassed = checkIfQueryForPowerPassed(ehRequest->query);
192 // Empty payload if the query has no match.
195 OCRepPayload *getResp = constructResponse(ehRequest);
198 cout << "\nconstructResponse failed";
213 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
214 OCRepPayload** payload)
216 OCEntityHandlerResult ehResult;
217 OCRepPayload *putResp = constructResponse(ehRequest);
221 cout << "\nFailed to construct response";
231 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
232 OCEntityHandlerResponse *response, OCRepPayload** payload)
234 OCEntityHandlerResult ehResult = OC_EH_OK;
235 OCRepPayload *respPLPost_light = nullptr;
238 * The entity handler determines how to process a POST request.
239 * Per the REST paradigm, POST can also be used to update representation of existing
240 * resource or create a new resource.
241 * In the sample below, if the POST is for /a/light then a new instance of the Light
242 * resource is created with default representation (if representation is included in
243 * POST payload it can be used as initial values) as long as the instance is
244 * lesser than max new instance count. Once max instance count is reached, POST on
245 * /a/light updated the representation of /a/light (just like PUT).
248 if (ehRequest->resource == Light.handle)
250 if (gCurrLightInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
252 // Create new Light instance
253 char newLightUri[URI_MAXSIZE];
254 snprintf(newLightUri, URI_MAXSIZE, "/a/light/%d", gCurrLightInstance);
256 respPLPost_light = OCRepPayloadCreate();
257 OCRepPayloadSetUri(respPLPost_light, gResourceUri);
258 OCRepPayloadSetPropString(respPLPost_light, "createduri", newLightUri);
260 if (0 == createLightResource (newLightUri, &gLightInstance[gCurrLightInstance]))
262 cout << "\nCreated new Light instance";
263 gLightInstance[gCurrLightInstance].state = 0;
264 gLightInstance[gCurrLightInstance].power = 0;
265 gCurrLightInstance++;
266 strncpy ((char *)response->resourceUri, newLightUri, MAX_URI_LENGTH);
267 ehResult = OC_EH_RESOURCE_CREATED;
272 // Update repesentation of /a/light
275 respPLPost_light = constructResponse(ehRequest);
280 for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
282 if (ehRequest->resource == gLightInstance[i].handle)
284 gLightInstance[i].state = true;
285 gLightInstance[i].power = 22;
288 respPLPost_light = constructResponse(ehRequest);
293 respPLPost_light = constructResponse(ehRequest);
299 if ((respPLPost_light != NULL))
301 *payload = respPLPost_light;
305 cout << "\n Payload was NULL";
306 ehResult = OC_EH_ERROR;
312 OCEntityHandlerResult ProcessDeleteRequest (OCEntityHandlerRequest *ehRequest)
314 if(ehRequest == NULL)
316 cout << "\nThe ehRequest is NULL";
319 OCEntityHandlerResult ehResult = OC_EH_OK;
321 cout << "\nExecuting " << __func__ << " for resource " << ehRequest->resource;
324 * In the sample below, the application will:
325 * 1a. pass the delete request to the c stack
326 * 1b. internally, the c stack figures out what needs to be done and does it accordingly
327 * (e.g. send observers notification, remove observers...)
328 * 1c. the c stack returns with the result whether the request is fullfilled.
329 * 2. optionally, app removes observers out of its array 'interestedObservers'
332 if ((ehRequest != NULL) && (ehRequest->resource == Light.handle))
334 //Step 1: Ask stack to do the work.
335 OCStackResult result = OCDeleteResource(ehRequest->resource);
337 if (result == OC_STACK_OK)
339 cout << "\nDelete Resource operation succeeded.";
342 //Step 2: clear observers who wanted to observe this resource at the app level.
343 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
345 if (interestedObservers[i].resourceHandle == ehRequest->resource)
347 interestedObservers[i].valid = false;
348 interestedObservers[i].observationId = 0;
349 interestedObservers[i].resourceHandle = NULL;
353 else if (result == OC_STACK_NO_RESOURCE)
355 cout << "\nThe resource doesn't exist or it might have been deleted.";
356 ehResult = OC_EH_RESOURCE_DELETED;
360 cout << "\nEncountered error from OCDeleteResource().";
361 ehResult = OC_EH_ERROR;
364 else if (ehRequest->resource != Light.handle)
366 //Let's this app not supporting DELETE on some resources so
367 //consider the DELETE request is received for a non-support resource.
368 cout << "\nThe request is received for a non-support resource.";
369 ehResult = OC_EH_FORBIDDEN;
375 OCEntityHandlerResult ProcessNonExistingResourceRequest(OCEntityHandlerRequest *ehRequest)
377 cout << "\nExecuting " << __func__;
379 return OC_EH_RESOURCE_NOT_FOUND;
382 void ProcessObserveRegister (OCEntityHandlerRequest *ehRequest)
384 cout << "\nReceived observation registration request with observation Id "
385 << ehRequest->obsInfo.obsId;
386 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
388 if (interestedObservers[i].valid == false)
390 interestedObservers[i].observationId = ehRequest->obsInfo.obsId;
391 interestedObservers[i].valid = true;
392 gLightUnderObservation = 1;
398 void ProcessObserveDeregister (OCEntityHandlerRequest *ehRequest)
400 bool clientStillObserving = false;
402 cout << "\nReceived observation deregistration request for observation Id "
403 << ehRequest->obsInfo.obsId;
404 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
406 if (interestedObservers[i].observationId == ehRequest->obsInfo.obsId)
408 interestedObservers[i].valid = false;
410 if (interestedObservers[i].valid == true)
412 // Even if there is one single client observing we continue notifying entity handler
413 clientStillObserving = true;
416 if (clientStillObserving == false)
417 gLightUnderObservation = 0;
420 OCEntityHandlerResult
421 OCDeviceEntityHandlerCb (OCEntityHandlerFlag flag,
422 OCEntityHandlerRequest *entityHandlerRequest, char* uri, void* callbackParam)
424 cout << "\nInside device default entity handler - flags: " << flag << ", uri: %s" << uri;
426 OCEntityHandlerResult ehResult = OC_EH_OK;
427 OCEntityHandlerResponse response;
430 if (!entityHandlerRequest)
432 cout << "\nInvalid request pointer";
435 // Initialize certain response fields
436 response.numSendVendorSpecificHeaderOptions = 0;
437 memset(response.sendVendorSpecificHeaderOptions, 0,
438 sizeof response.sendVendorSpecificHeaderOptions);
439 memset(response.resourceUri, 0, sizeof response.resourceUri);
440 OCRepPayload* payload = nullptr;
443 if (flag & OC_REQUEST_FLAG)
445 cout << "\nFlag includes OC_REQUEST_FLAG";
447 if (entityHandlerRequest->resource == NULL)
449 cout << "\nReceived request from client to a non-existing resource";
450 ehResult = ProcessNonExistingResourceRequest(entityHandlerRequest);
452 else if (OC_REST_GET == entityHandlerRequest->method)
454 cout << "\nReceived OC_REST_GET from client";
455 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
457 else if (OC_REST_PUT == entityHandlerRequest->method)
459 cout << "\nReceived OC_REST_PUT from client";
460 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
462 else if (OC_REST_DELETE == entityHandlerRequest->method)
464 cout << "\nReceived OC_REST_DELETE from client";
465 ehResult = ProcessDeleteRequest (entityHandlerRequest);
469 cout << "\nReceived unsupported method " << entityHandlerRequest->method
471 ehResult = OC_EH_ERROR;
473 // If the result isn't an error or forbidden, send response
474 if (!((ehResult == OC_EH_ERROR) || (ehResult == OC_EH_FORBIDDEN)))
476 // Format the response. Note this requires some info about the request
477 response.requestHandle = entityHandlerRequest->requestHandle;
478 response.resourceHandle = entityHandlerRequest->resource;
479 response.ehResult = ehResult;
480 response.payload = reinterpret_cast<OCPayload*>(payload);
481 // Indicate that response is NOT in a persistent buffer
482 response.persistentBufferFlag = 0;
485 if (OCDoResponse(&response) != OC_STACK_OK)
487 cout << "\nError sending response";
488 ehResult = OC_EH_ERROR;
492 if (flag & OC_OBSERVE_FLAG)
494 cout << "\nFlag includes OC_OBSERVE_FLAG";
495 if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
497 cout << "\nReceived OC_OBSERVE_REGISTER from client";
499 else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
501 cout << "\nReceived OC_OBSERVE_DEREGISTER from client";
508 OCEntityHandlerResult
509 OCNOPEntityHandlerCb (OCEntityHandlerFlag flag,
510 OCEntityHandlerRequest *entityHandlerRequest, void* callbackParam)
512 // This is callback is associated with the 2 presence notification
513 // resources. They are non-operational.
517 OCEntityHandlerResult
518 OCEntityHandlerCb (OCEntityHandlerFlag flag,
519 OCEntityHandlerRequest *entityHandlerRequest, void* callback)
521 cout << "\nInside entity handler - flags: " << flag;
523 OCEntityHandlerResult ehResult = OC_EH_OK;
524 OCEntityHandlerResponse response;
527 if (!entityHandlerRequest)
529 cout << "\nInvalid request pointer";
533 // Initialize certain response fields
534 response.numSendVendorSpecificHeaderOptions = 0;
535 memset(response.sendVendorSpecificHeaderOptions,
536 0, sizeof response.sendVendorSpecificHeaderOptions);
537 memset(response.resourceUri, 0, sizeof response.resourceUri);
538 OCRepPayload* payload = nullptr;
540 if (flag & OC_REQUEST_FLAG)
542 cout << "\n=================================\n";
543 cout << "\nFlag includes OC_REQUEST_FLAG\n";
545 if (OC_REST_GET == entityHandlerRequest->method)
547 cout << "\nReceived OC_REST_GET from client";
548 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
549 cout << "\n=================================\n";
551 else if (OC_REST_PUT == entityHandlerRequest->method)
553 cout << "\nReceived OC_REST_PUT from client";
554 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
555 cout << "\n=================================\n";
557 else if (OC_REST_POST == entityHandlerRequest->method)
559 cout << "\nReceived OC_REST_POST from client";
560 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
561 cout << "\n=================================\n";
563 else if (OC_REST_DELETE == entityHandlerRequest->method)
565 cout << "\nReceived OC_REST_DELETE from client";
566 ehResult = ProcessDeleteRequest (entityHandlerRequest);
567 cout << "\n=================================\n";
571 cout << "\nReceived unsupported method " << entityHandlerRequest->method << " from client";
572 ehResult = OC_EH_ERROR;
574 // If the result isn't an error or forbidden, send response
575 if (!((ehResult == OC_EH_ERROR) || (ehResult == OC_EH_FORBIDDEN)))
577 // Format the response. Note this requires some info about the request
578 response.requestHandle = entityHandlerRequest->requestHandle;
579 response.resourceHandle = entityHandlerRequest->resource;
580 response.ehResult = ehResult;
581 response.payload = reinterpret_cast<OCPayload*>(payload);
582 // Indicate that response is NOT in a persistent buffer
583 response.persistentBufferFlag = 0;
585 // Handle vendor specific options
586 if(entityHandlerRequest->rcvdVendorSpecificHeaderOptions &&
587 entityHandlerRequest->numRcvdVendorSpecificHeaderOptions)
589 cout << "\nReceived vendor specific options";
591 OCHeaderOption * rcvdOptions =
592 entityHandlerRequest->rcvdVendorSpecificHeaderOptions;
593 for( i = 0; i < entityHandlerRequest->numRcvdVendorSpecificHeaderOptions; i++)
595 if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
597 cout << "\nReceived option with ID " << ((OCHeaderOption)rcvdOptions[i]).optionID;
600 OCHeaderOption * sendOptions = response.sendVendorSpecificHeaderOptions;
601 uint8_t option2[] = {21,22,23,24,25,26,27,28,29,30};
602 uint8_t option3[] = {31,32,33,34,35,36,37,38,39,40};
603 sendOptions[0].protocolID = OC_COAP_ID;
604 sendOptions[0].optionID = 2248;
605 memcpy(sendOptions[0].optionData, option2, sizeof(option2));
606 sendOptions[0].optionLength = 10;
607 sendOptions[1].protocolID = OC_COAP_ID;
608 sendOptions[1].optionID = 2600;
609 memcpy(sendOptions[1].optionData, option3, sizeof(option3));
610 sendOptions[1].optionLength = 10;
611 response.numSendVendorSpecificHeaderOptions = 2;
615 if (OCDoResponse(&response) != OC_STACK_OK)
617 cout << "\nError sending response";
618 ehResult = OC_EH_ERROR;
622 if (flag & OC_OBSERVE_FLAG)
624 cout << "\nFlag includes OC_OBSERVE_FLAG";
626 if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
628 cout << "\nReceived OC_OBSERVE_REGISTER from client";
629 ProcessObserveRegister (entityHandlerRequest);
631 else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
633 cout << "\nReceived OC_OBSERVE_DEREGISTER from client";
634 ProcessObserveDeregister (entityHandlerRequest);
638 OCPayloadDestroy(response.payload);
642 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
643 void handleSigInt(int signum)
645 if (signum == SIGINT)
651 void *ChangeLightRepresentation (void *param)
654 OCStackResult result = OC_STACK_ERROR;
657 uint8_t numNotifies = (SAMPLE_MAX_NUM_OBSERVATIONS)/2;
658 OCObservationId obsNotify[numNotifies];
664 if (gLightUnderObservation)
666 cout << "\n=====> Notifying stack of new power level" << Light.power;
667 if (gObserveNotifyType == 1)
669 // Notify list of observers. Alternate observers on the list will be notified.
671 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; (i=i+2))
673 if (interestedObservers[i].valid == true)
675 obsNotify[j] = interestedObservers[i].observationId;
680 OCRepPayload* payload = getPayload(gResourceUri, Light.power, Light.state);
681 result = OCNotifyListOfObservers (Light.handle, obsNotify, j,
683 OCRepPayloadDestroy(payload);
685 else if (gObserveNotifyType == 0)
687 // Notifying all observers
688 result = OCNotifyAllObservers (Light.handle, OC_NA_QOS);
689 if (OC_STACK_NO_OBSERVERS == result)
691 cout << "\n=====> No more observers exist, stop sending observations";
692 gLightUnderObservation = 0;
697 cout << "\nIncorrect notification type selected";
701 if(stopPresenceCount > 0)
703 cout << "\n=====> Counting down to stop presence " << stopPresenceCount;
705 if(!stopPresenceCount--)
707 cout << "\n=====> stopping presence";
716 void *presenceNotificationGenerator(void *param)
720 OCDoHandle presenceNotificationHandles[numPresenceResources];
721 OCStackResult res = OC_STACK_OK;
723 std::array<std::string, numPresenceResources> presenceNotificationResources { {
724 std::string("core.fan"),
725 std::string("core.led") } };
726 std::array<std::string, numPresenceResources> presenceNotificationUris { {
727 std::string("/a/fan"),
728 std::string("/a/led") } };
730 for(int i=0; i<numPresenceResources; i++)
732 if(res == OC_STACK_OK)
735 res = OCCreateResource(&presenceNotificationHandles[i],
736 presenceNotificationResources.at(i).c_str(),
737 OC_RSRVD_INTERFACE_DEFAULT,
738 presenceNotificationUris.at(i).c_str(),
739 OCNOPEntityHandlerCb,
741 OC_DISCOVERABLE|OC_OBSERVABLE);
743 if(res != OC_STACK_OK)
745 cout << "\nPresence Notification Generator failed[" << getResult(res)
746 << "] to create resource " << presenceNotificationResources.at(i).c_str();
749 cout << "\nCreated " << presenceNotificationUris[i].c_str() << " for presence notification";
752 for(int i=0; i<numPresenceResources; i++)
754 if(res == OC_STACK_OK)
756 res = OCDeleteResource(presenceNotificationHandles[i]);
758 if(res != OC_STACK_OK)
760 cout << "\nPresence Notification Generator failed to delete resource"
761 << presenceNotificationResources.at(i).c_str();
764 cout << "\nDeleted " << presenceNotificationUris[i].c_str() << " for presence notification";
770 int createLightResource (char *uri, LightResource *lightResource)
774 cout << "\nResource URI cannot be NULL";
778 lightResource->state = false;
779 lightResource->power= 0;
780 OCStackResult res = OCCreateResource(&(lightResource->handle),
786 OC_DISCOVERABLE|OC_OBSERVABLE);
787 cout << "\nCreated Light resource with result " << getResult(res);
792 void DeletePlatformInfo()
794 free (platformInfo.platformID);
795 free (platformInfo.manufacturerName);
796 free (platformInfo.manufacturerUrl);
797 free (platformInfo.modelNumber);
798 free (platformInfo.dateOfManufacture);
799 free (platformInfo.platformVersion);
800 free (platformInfo.operatingSystemVersion);
801 free (platformInfo.hardwareVersion);
802 free (platformInfo.firmwareVersion);
803 free (platformInfo.supportUrl);
804 free (platformInfo.systemTime);
807 void DeleteDeviceInfo()
809 free (deviceInfo.deviceName);
812 bool DuplicateString(char** targetString, const char* sourceString)
820 *targetString = (char *) malloc(strlen(sourceString) + 1);
824 strncpy(*targetString, sourceString, (strlen(sourceString) + 1));
831 OCStackResult SetPlatformInfo(const char* platformID, const char *manufacturerName,
832 const char *manufacturerUrl, const char *modelNumber, const char *dateOfManufacture,
833 const char *platformVersion, const char* operatingSystemVersion, const char* hardwareVersion,
834 const char *firmwareVersion, const char* supportUrl, const char* systemTime)
839 if(manufacturerName != NULL && (strlen(manufacturerName) > MAX_MANUFACTURER_NAME_LENGTH))
841 return OC_STACK_INVALID_PARAM;
844 if(manufacturerUrl != NULL && (strlen(manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH))
846 return OC_STACK_INVALID_PARAM;
849 if(!DuplicateString(&platformInfo.platformID, platformID))
854 if(!DuplicateString(&platformInfo.manufacturerName, manufacturerName))
859 if(!DuplicateString(&platformInfo.manufacturerUrl, manufacturerUrl))
864 if(!DuplicateString(&platformInfo.modelNumber, modelNumber))
869 if(!DuplicateString(&platformInfo.dateOfManufacture, dateOfManufacture))
874 if(!DuplicateString(&platformInfo.platformVersion, platformVersion))
879 if(!DuplicateString(&platformInfo.operatingSystemVersion, operatingSystemVersion))
884 if(!DuplicateString(&platformInfo.hardwareVersion, hardwareVersion))
889 if(!DuplicateString(&platformInfo.firmwareVersion, firmwareVersion))
894 if(!DuplicateString(&platformInfo.supportUrl, supportUrl))
899 if(!DuplicateString(&platformInfo.systemTime, systemTime))
909 DeletePlatformInfo();
910 return OC_STACK_ERROR;
913 OCStackResult SetDeviceInfo(const char* deviceName)
915 if(!DuplicateString(&deviceInfo.deviceName, deviceName))
917 return OC_STACK_ERROR;
922 static void PrintUsage()
924 cout << "\nUsage : ocserver -o <0|1>";
925 cout << "\n-o 0 : Notify all observers";
926 cout << "\n-o 1 : Notify list of observers";
929 void *GMainLoopThread(void *param)
934 if (OCProcess() != OC_STACK_OK)
936 cout << "\nOCStack process error";
939 #ifndef ROUTING_GATEWAY
946 g_main_loop_quit(g_mainloop);
951 int main(int argc, char* argv[])
954 pthread_t threadId_presence;
957 g_mainloop = g_main_loop_new(NULL, FALSE);
960 printf("g_main_loop_new failed\n");
964 while ((opt = getopt(argc, argv, "o:")) != -1)
969 gObserveNotifyType = atoi(optarg);
977 if ((gObserveNotifyType != 0) && (gObserveNotifyType != 1))
983 cout << "\nOCServer is starting...";
985 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
987 cout << "\nOCStack init error";
992 if (OCStartPresence(0) != OC_STACK_OK)
994 cout << "\nOCStack presence/discovery error";
999 OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandlerCb, NULL);
1001 OCStackResult registrationResult =
1002 SetPlatformInfo(platformID, manufacturerName, manufacturerUrl, modelNumber,
1003 dateOfManufacture, platformVersion, operatingSystemVersion, hardwareVersion,
1004 firmwareVersion, supportUrl, systemTime);
1006 if (registrationResult != OC_STACK_OK)
1008 cout << "\nPlatform info setting failed locally!";
1009 exit (EXIT_FAILURE);
1012 registrationResult = OCSetPlatformInfo(platformInfo);
1014 if (registrationResult != OC_STACK_OK)
1016 cout << "\nPlatform Registration failed!";
1017 exit (EXIT_FAILURE);
1020 registrationResult = SetDeviceInfo(deviceName);
1022 if (registrationResult != OC_STACK_OK)
1024 cout << "\nDevice info setting failed locally!";
1025 exit (EXIT_FAILURE);
1028 OCResourcePayloadAddStringLL(&deviceInfo.types, "oic.d.tv");
1030 registrationResult = OCSetDeviceInfo(deviceInfo);
1032 if (registrationResult != OC_STACK_OK)
1034 cout << "\nDevice Registration failed!";
1035 exit (EXIT_FAILURE);
1039 * Declare and create the example resource: Light
1041 createLightResource(gResourceUri, &Light);
1043 // Initialize observations data structure for the resource
1044 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
1046 interestedObservers[i].valid = false;
1050 * Create a thread for changing the representation of the Light
1052 pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)NULL);
1055 * Create a thread for generating changes that cause presence notifications
1056 * to be sent to clients
1059 #ifdef WITH_PRESENCE
1060 pthread_create(&threadId_presence, NULL, presenceNotificationGenerator, (void *)NULL);
1063 // Break from loop with Ctrl-C
1064 cout << "\nEntering ocserver main loop...";
1066 DeletePlatformInfo();
1069 signal(SIGINT, handleSigInt);
1071 int result = pthread_create(&g_thread, NULL, GMainLoopThread, (void *)NULL);
1074 printf("pthread_create failed in initialize\n");
1078 g_main_loop_run(g_mainloop);
1081 * Cancel the Light thread and wait for it to terminate
1083 pthread_cancel(threadId);
1084 pthread_join(threadId, NULL);
1085 pthread_cancel(threadId_presence);
1086 pthread_join(threadId_presence, NULL);
1088 cout << "\nExiting ocserver main loop...\n";
1090 if (OCStop() != OC_STACK_OK)
1092 cout << "\nOCStack process error";