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 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
39 #include "ocpayload.h"
42 //string length of "/a/light/" + std::numeric_limits<int>::digits10 + '\0'"
44 const int URI_MAXSIZE = 19;
46 static int gObserveNotifyType = 3;
49 int gLightUnderObservation = 0;
51 static LightResource Light;
52 // This variable determines instance number of the Light resource.
53 // Used by POST method to create a new instance of Light resource.
54 static int gCurrLightInstance = 0;
56 static LightResource gLightInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
58 Observers interestedObservers[SAMPLE_MAX_NUM_OBSERVATIONS];
60 pthread_t threadId_observe;
61 pthread_t threadId_presence;
63 static bool observeThreadStarted = false;
66 #define numPresenceResources (2)
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 OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
95 OCRepPayload* payload = OCRepPayloadCreate();
98 OIC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
102 OCRepPayloadSetUri(payload, uri);
103 OCRepPayloadSetPropBool(payload, "state", state);
104 OCRepPayloadSetPropInt(payload, "power", power);
109 //This function takes the request as an input and returns the response
110 OCRepPayload* constructResponse(OCEntityHandlerRequest *ehRequest)
112 if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
114 OIC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
118 OCRepPayload* input = reinterpret_cast<OCRepPayload*>(ehRequest->payload);
120 LightResource *currLightResource = &Light;
122 if (ehRequest->resource == gLightInstance[0].handle)
124 currLightResource = &gLightInstance[0];
125 gResourceUri = (char *) "a/light/0";
127 else if (ehRequest->resource == gLightInstance[1].handle)
129 currLightResource = &gLightInstance[1];
130 gResourceUri = (char *) "a/light/1";
133 if(OC_REST_PUT == ehRequest->method)
135 // Get pointer to query
137 if(OCRepPayloadGetPropInt(input, "power", &pow))
139 currLightResource->power =pow;
143 if(OCRepPayloadGetPropBool(input, "state", &state))
145 currLightResource->state = state;
149 return getPayload(gResourceUri, currLightResource->power, currLightResource->state);
153 * Very simple example of query parsing.
154 * The query may have multiple filters separated by ';'.
155 * It is upto the entity handler to parse the query for the individual filters,
156 * VALIDATE them and respond as it sees fit.
158 * This function only returns false if the query is exactly "power<X" and
159 * current power is greater than X. If X cannot be parsed for an int,
162 bool checkIfQueryForPowerPassed(char * query)
164 if (query && strncmp(query, "power<", strlen("power<")) == 0)
166 char * pointerToOperator = strstr(query, "<");
168 if (pointerToOperator)
170 int powerRequested = atoi(pointerToOperator + 1);
171 if (Light.power > powerRequested)
173 OIC_LOG_V(INFO, TAG, "Current power: %d. Requested: <%d", Light.power
183 * Application should validate and process these as desired.
185 OCEntityHandlerResult ValidateQueryParams (OCEntityHandlerRequest *entityHandlerRequest)
187 OIC_LOG_V(INFO, TAG, PCF("Received query %s"), entityHandlerRequest->query);
188 OIC_LOG(INFO, TAG, PCF("Not processing query"));
192 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
193 OCRepPayload **payload)
195 OCEntityHandlerResult ehResult;
196 bool queryPassed = checkIfQueryForPowerPassed(ehRequest->query);
198 // Empty payload if the query has no match.
201 OCRepPayload *getResp = constructResponse(ehRequest);
204 OIC_LOG(ERROR, TAG, "constructResponse failed");
219 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
220 OCRepPayload** payload)
222 OCEntityHandlerResult ehResult;
223 OCRepPayload *putResp = constructResponse(ehRequest);
227 OIC_LOG(ERROR, TAG, "Failed to construct Json response");
237 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
238 OCEntityHandlerResponse *response, OCRepPayload** payload)
240 OCEntityHandlerResult ehResult = OC_EH_OK;
241 OCRepPayload *respPLPost_light = nullptr;
244 * The entity handler determines how to process a POST request.
245 * Per the REST paradigm, POST can also be used to update representation of existing
246 * resource or create a new resource.
247 * In the sample below, if the POST is for /a/light then a new instance of the Light
248 * resource is created with default representation (if representation is included in
249 * POST payload it can be used as initial values) as long as the instance is
250 * lesser than max new instance count. Once max instance count is reached, POST on
251 * /a/light updated the representation of /a/light (just like PUT)
254 if (ehRequest->resource == Light.handle)
256 if (gCurrLightInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
258 // Create new Light instance
259 char newLightUri[URI_MAXSIZE];
260 snprintf(newLightUri, URI_MAXSIZE, "/a/light/%d", gCurrLightInstance);
262 respPLPost_light = OCRepPayloadCreate();
263 OCRepPayloadSetUri(respPLPost_light, gResourceUri);
264 OCRepPayloadSetPropString(respPLPost_light, "createduri", newLightUri);
266 if (0 == createLightResource (newLightUri, &gLightInstance[gCurrLightInstance]))
268 OIC_LOG (INFO, TAG, "Created new Light instance\n");
269 gLightInstance[gCurrLightInstance].state = 0;
270 gLightInstance[gCurrLightInstance].power = 0;
271 gCurrLightInstance++;
272 strncpy ((char *)response->resourceUri, newLightUri, MAX_URI_LENGTH);
273 ehResult = OC_EH_RESOURCE_CREATED;
278 // Update repesentation of /a/light
281 respPLPost_light = constructResponse(ehRequest);
286 for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
288 if (ehRequest->resource == gLightInstance[i].handle)
290 gLightInstance[i].state = true;
291 gLightInstance[i].power = 22;
294 respPLPost_light = constructResponse(ehRequest);
299 respPLPost_light = constructResponse(ehRequest);
305 if ((respPLPost_light != NULL))
307 *payload = respPLPost_light;
311 OIC_LOG(INFO, TAG, "Payload was NULL");
312 ehResult = OC_EH_ERROR;
318 OCEntityHandlerResult ProcessDeleteRequest (OCEntityHandlerRequest *ehRequest)
320 if(ehRequest == NULL)
322 OIC_LOG(INFO, TAG, "The ehRequest is NULL");
325 OCEntityHandlerResult ehResult = OC_EH_OK;
327 OIC_LOG_V(INFO, TAG, "\n\nExecuting %s for resource %p ", __func__, ehRequest->resource);
330 * In the sample below, the application will:
331 * 1a. pass the delete request to the c stack
332 * 1b. internally, the c stack figures out what needs to be done and does it accordingly
333 * (e.g. send observers notification, remove observers...)
334 * 1c. the c stack returns with the result whether the request is fullfilled.
335 * 2. optionally, app removes observers out of its array 'interestedObservers'
338 if ((ehRequest != NULL) && (ehRequest->resource == Light.handle))
340 //Step 1: Ask stack to do the work.
341 OCStackResult result = OCDeleteResource(ehRequest->resource);
343 if (result == OC_STACK_OK)
345 OIC_LOG (INFO, TAG, "\n\nDelete Resource operation succeeded.");
348 //Step 2: clear observers who wanted to observe this resource at the app level.
349 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
351 if (interestedObservers[i].resourceHandle == ehRequest->resource)
353 interestedObservers[i].valid = false;
354 interestedObservers[i].observationId = 0;
355 interestedObservers[i].resourceHandle = NULL;
359 else if (result == OC_STACK_NO_RESOURCE)
361 OIC_LOG(INFO, TAG, "\n\nThe resource doesn't exist or it might have been deleted.");
362 ehResult = OC_EH_RESOURCE_DELETED;
366 OIC_LOG(INFO, TAG, "\n\nEncountered error from OCDeleteResource().");
367 ehResult = OC_EH_ERROR;
370 else if (ehRequest->resource != Light.handle)
372 //Let's this app not supporting DELETE on some resources so
373 //consider the DELETE request is received for a non-support resource.
374 OIC_LOG_V(INFO, TAG, "\n\nThe request is received for a non-support resource.");
375 ehResult = OC_EH_FORBIDDEN;
381 OCEntityHandlerResult ProcessNonExistingResourceRequest(OCEntityHandlerRequest * /*ehRequest*/)
383 OIC_LOG_V(INFO, TAG, "\n\nExecuting %s ", __func__);
385 return OC_EH_RESOURCE_NOT_FOUND;
388 void ProcessObserveRegister (OCEntityHandlerRequest *ehRequest)
390 OIC_LOG_V (INFO, TAG, "Received observation registration request with observation Id %d",
391 ehRequest->obsInfo.obsId);
393 if (!observeThreadStarted)
395 pthread_create (&threadId_observe, NULL, ChangeLightRepresentation, (void *)NULL);
396 observeThreadStarted = 1;
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 OIC_LOG_V (INFO, TAG, "Received observation deregistration request for observation Id %d",
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,
436 void* /*callbackParam*/)
438 OIC_LOG_V (INFO, TAG, "Inside device default entity handler - flags: 0x%x, uri: %s", flag, uri);
440 OCEntityHandlerResult ehResult = OC_EH_OK;
441 OCEntityHandlerResponse response;
444 if (!entityHandlerRequest)
446 OIC_LOG (ERROR, TAG, "Invalid request pointer");
449 // Initialize certain response fields
450 response.numSendVendorSpecificHeaderOptions = 0;
451 memset(response.sendVendorSpecificHeaderOptions, 0,
452 sizeof response.sendVendorSpecificHeaderOptions);
453 memset(response.resourceUri, 0, sizeof response.resourceUri);
454 OCRepPayload* payload = nullptr;
457 if (flag & OC_REQUEST_FLAG)
459 OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
461 if (entityHandlerRequest->resource == NULL)
463 OIC_LOG (INFO, TAG, "Received request from client to a non-existing resource");
464 ehResult = ProcessNonExistingResourceRequest(entityHandlerRequest);
466 else if (OC_REST_GET == entityHandlerRequest->method)
468 OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
469 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
471 else if (OC_REST_PUT == entityHandlerRequest->method)
473 OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
474 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
476 else if (OC_REST_DELETE == entityHandlerRequest->method)
478 OIC_LOG (INFO, TAG, "Received OC_REST_DELETE from client");
479 ehResult = ProcessDeleteRequest (entityHandlerRequest);
483 OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
484 entityHandlerRequest->method);
485 ehResult = OC_EH_ERROR;
487 // If the result isn't an error or forbidden, send response
488 if (!((ehResult == OC_EH_ERROR) || (ehResult == OC_EH_FORBIDDEN)))
490 // Format the response. Note this requires some info about the request
491 response.requestHandle = entityHandlerRequest->requestHandle;
492 response.resourceHandle = entityHandlerRequest->resource;
493 response.ehResult = ehResult;
494 response.payload = reinterpret_cast<OCPayload*>(payload);
495 // Indicate that response is NOT in a persistent buffer
496 response.persistentBufferFlag = 0;
499 if (OCDoResponse(&response) != OC_STACK_OK)
501 OIC_LOG(ERROR, TAG, "Error sending response");
502 ehResult = OC_EH_ERROR;
506 if (flag & OC_OBSERVE_FLAG)
508 OIC_LOG(INFO, TAG, "Flag includes OC_OBSERVE_FLAG");
509 if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
511 OIC_LOG (INFO, TAG, "Received OC_OBSERVE_REGISTER from client");
513 else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
515 OIC_LOG (INFO, TAG, "Received OC_OBSERVE_DEREGISTER from client");
522 OCEntityHandlerResult
523 OCNOPEntityHandlerCb (OCEntityHandlerFlag /*flag*/,
524 OCEntityHandlerRequest * /*entityHandlerRequest*/,
525 void* /*callbackParam*/)
527 // This is callback is associated with the 2 presence notification
528 // resources. They are non-operational.
532 OCEntityHandlerResult
533 OCEntityHandlerCb (OCEntityHandlerFlag flag,
534 OCEntityHandlerRequest *entityHandlerRequest, void* /*callback*/)
536 OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
538 OCEntityHandlerResult ehResult = OC_EH_OK;
539 OCEntityHandlerResponse response = { 0, 0, OC_EH_ERROR, 0, 0, { },{ 0 }, false };
542 if (!entityHandlerRequest)
544 OIC_LOG (ERROR, TAG, "Invalid request pointer");
548 // Initialize certain response fields
549 response.numSendVendorSpecificHeaderOptions = 0;
550 memset(response.sendVendorSpecificHeaderOptions,
551 0, sizeof response.sendVendorSpecificHeaderOptions);
552 memset(response.resourceUri, 0, sizeof response.resourceUri);
553 OCRepPayload* payload = nullptr;
555 if (flag & OC_REQUEST_FLAG)
557 OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
559 if (OC_REST_GET == entityHandlerRequest->method)
561 OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
562 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
564 else if (OC_REST_PUT == entityHandlerRequest->method)
566 OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
567 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
569 else if (OC_REST_POST == entityHandlerRequest->method)
571 OIC_LOG (INFO, TAG, "Received OC_REST_POST from client");
572 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
574 else if (OC_REST_DELETE == entityHandlerRequest->method)
576 OIC_LOG (INFO, TAG, "Received OC_REST_DELETE from client");
577 ehResult = ProcessDeleteRequest (entityHandlerRequest);
581 OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
582 entityHandlerRequest->method);
583 ehResult = OC_EH_ERROR;
585 // If the result isn't an error or forbidden, send response
586 if (!((ehResult == OC_EH_ERROR) || (ehResult == OC_EH_FORBIDDEN)))
588 // Format the response. Note this requires some info about the request
589 response.requestHandle = entityHandlerRequest->requestHandle;
590 response.resourceHandle = entityHandlerRequest->resource;
591 response.ehResult = ehResult;
592 response.payload = reinterpret_cast<OCPayload*>(payload);
593 // Indicate that response is NOT in a persistent buffer
594 response.persistentBufferFlag = 0;
596 // Handle vendor specific options
597 if(entityHandlerRequest->rcvdVendorSpecificHeaderOptions &&
598 entityHandlerRequest->numRcvdVendorSpecificHeaderOptions)
600 OIC_LOG (INFO, TAG, "Received vendor specific options");
602 OCHeaderOption * rcvdOptions =
603 entityHandlerRequest->rcvdVendorSpecificHeaderOptions;
604 for( i = 0; i < entityHandlerRequest->numRcvdVendorSpecificHeaderOptions; i++)
606 if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
608 OIC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
609 ((OCHeaderOption)rcvdOptions[i]).optionID );
611 OIC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
612 MAX_HEADER_OPTION_DATA_LENGTH);
615 OCHeaderOption * sendOptions = response.sendVendorSpecificHeaderOptions;
616 uint8_t option2[] = {21,22,23,24,25,26,27,28,29,30};
617 uint8_t option3[] = {31,32,33,34,35,36,37,38,39,40};
618 sendOptions[0].protocolID = OC_COAP_ID;
619 sendOptions[0].optionID = 2248;
620 memcpy(sendOptions[0].optionData, option2, sizeof(option2));
621 sendOptions[0].optionLength = 10;
622 sendOptions[1].protocolID = OC_COAP_ID;
623 sendOptions[1].optionID = 2600;
624 memcpy(sendOptions[1].optionData, option3, sizeof(option3));
625 sendOptions[1].optionLength = 10;
626 response.numSendVendorSpecificHeaderOptions = 2;
630 if (OCDoResponse(&response) != OC_STACK_OK)
632 OIC_LOG(ERROR, TAG, "Error sending response");
633 ehResult = OC_EH_ERROR;
637 if (flag & OC_OBSERVE_FLAG)
639 OIC_LOG(INFO, TAG, "Flag includes OC_OBSERVE_FLAG");
641 if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
643 OIC_LOG (INFO, TAG, "Received OC_OBSERVE_REGISTER from client");
644 ProcessObserveRegister (entityHandlerRequest);
646 else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
648 OIC_LOG (INFO, TAG, "Received OC_OBSERVE_DEREGISTER from client");
649 ProcessObserveDeregister (entityHandlerRequest);
653 OCPayloadDestroy(response.payload);
657 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
658 void handleSigInt(int signum)
660 if (signum == SIGINT)
666 void *ChangeLightRepresentation (void *param)
669 OCStackResult result = OC_STACK_ERROR;
672 uint8_t numNotifies = (SAMPLE_MAX_NUM_OBSERVATIONS)/2;
673 OCObservationId obsNotify[numNotifies];
679 if (gLightUnderObservation)
681 OIC_LOG_V(INFO, TAG, " =====> Notifying stack of new power level %d\n", Light.power);
682 if (gObserveNotifyType == 1)
684 // Notify list of observers. Alternate observers on the list will be notified.
686 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; (i=i+2))
688 if (interestedObservers[i].valid == true)
690 obsNotify[j] = interestedObservers[i].observationId;
695 OCRepPayload* payload = getPayload(gResourceUri, Light.power, Light.state);
696 result = OCNotifyListOfObservers (Light.handle, obsNotify, j,
698 OCRepPayloadDestroy(payload);
700 else if (gObserveNotifyType == 0)
702 // Notifying all observers
703 result = OCNotifyAllObservers (Light.handle, OC_NA_QOS);
704 if (OC_STACK_NO_OBSERVERS == result)
707 "=======> No more observers exist, stop sending observations");
708 gLightUnderObservation = 0;
713 OIC_LOG (ERROR, TAG, "Incorrect notification type selected");
721 void *presenceNotificationGenerator(void *param)
723 uint8_t secondsBeforePresence = 10;
724 OIC_LOG_V(INFO, TAG, "Will send out presence in %u seconds", secondsBeforePresence);
725 sleep(secondsBeforePresence);
727 OCDoHandle presenceNotificationHandles[numPresenceResources];
728 OCStackResult res = OC_STACK_OK;
730 std::array<std::string, numPresenceResources> presenceNotificationResources { {
731 std::string("core.fan"),
732 std::string("core.led") } };
733 std::array<std::string, numPresenceResources> presenceNotificationUris { {
734 std::string("/a/fan"),
735 std::string("/a/led") } };
737 for(int i=0; i<numPresenceResources; i++)
739 if(res == OC_STACK_OK)
742 res = OCCreateResource(&presenceNotificationHandles[i],
743 presenceNotificationResources.at(i).c_str(),
744 OC_RSRVD_INTERFACE_DEFAULT,
745 presenceNotificationUris.at(i).c_str(),
746 OCNOPEntityHandlerCb,
748 OC_DISCOVERABLE|OC_OBSERVABLE);
750 if(res != OC_STACK_OK)
752 OIC_LOG_V(ERROR, TAG, "\"Presence Notification Generator\" failed to create resource "
753 "%s with result %s.", presenceNotificationResources.at(i).c_str(),
757 OIC_LOG_V(INFO, TAG, PCF("Created %s for presence notification"),
758 presenceNotificationUris[i].c_str());
761 for(int i=0; i<numPresenceResources; i++)
763 if(res == OC_STACK_OK)
765 res = OCDeleteResource(presenceNotificationHandles[i]);
767 if(res != OC_STACK_OK)
769 OIC_LOG_V(ERROR, TAG, "\"Presence Notification Generator\" failed to delete "\
770 "resource %s.", presenceNotificationResources.at(i).c_str());
773 OIC_LOG_V(INFO, TAG, PCF("Deleted %s for presence notification"),
774 presenceNotificationUris[i].c_str());
777 OIC_LOG(INFO, TAG, "================ stopping presence");
784 int createLightResource (char *uri, LightResource *lightResource)
788 OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
792 lightResource->state = false;
793 lightResource->power= 0;
794 OCStackResult res = OCCreateResource(&(lightResource->handle),
800 OC_DISCOVERABLE|OC_OBSERVABLE);
801 OIC_LOG_V(INFO, TAG, "Created Light resource with result: %s", getResult(res));
806 void DeletePlatformInfo()
808 free (platformInfo.platformID);
809 free (platformInfo.manufacturerName);
810 free (platformInfo.manufacturerUrl);
811 free (platformInfo.modelNumber);
812 free (platformInfo.dateOfManufacture);
813 free (platformInfo.platformVersion);
814 free (platformInfo.operatingSystemVersion);
815 free (platformInfo.hardwareVersion);
816 free (platformInfo.firmwareVersion);
817 free (platformInfo.supportUrl);
818 free (platformInfo.systemTime);
821 void DeleteDeviceInfo()
823 free (deviceInfo.deviceName);
826 bool DuplicateString(char** targetString, const char* sourceString)
834 *targetString = (char *) malloc(strlen(sourceString) + 1);
838 strncpy(*targetString, sourceString, (strlen(sourceString) + 1));
845 OCStackResult SetPlatformInfo(const char* platformID, const char *manufacturerName,
846 const char *manufacturerUrl, const char *modelNumber, const char *dateOfManufacture,
847 const char *platformVersion, const char* operatingSystemVersion, const char* hardwareVersion,
848 const char *firmwareVersion, const char* supportUrl, const char* systemTime)
853 if(manufacturerName != NULL && (strlen(manufacturerName) > MAX_MANUFACTURER_NAME_LENGTH))
855 return OC_STACK_INVALID_PARAM;
858 if(manufacturerUrl != NULL && (strlen(manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH))
860 return OC_STACK_INVALID_PARAM;
863 if(!DuplicateString(&platformInfo.platformID, platformID))
868 if(!DuplicateString(&platformInfo.manufacturerName, manufacturerName))
873 if(!DuplicateString(&platformInfo.manufacturerUrl, manufacturerUrl))
878 if(!DuplicateString(&platformInfo.modelNumber, modelNumber))
883 if(!DuplicateString(&platformInfo.dateOfManufacture, dateOfManufacture))
888 if(!DuplicateString(&platformInfo.platformVersion, platformVersion))
893 if(!DuplicateString(&platformInfo.operatingSystemVersion, operatingSystemVersion))
898 if(!DuplicateString(&platformInfo.hardwareVersion, hardwareVersion))
903 if(!DuplicateString(&platformInfo.firmwareVersion, firmwareVersion))
908 if(!DuplicateString(&platformInfo.supportUrl, supportUrl))
913 if(!DuplicateString(&platformInfo.systemTime, systemTime))
923 DeletePlatformInfo();
924 return OC_STACK_ERROR;
927 OCStackResult SetDeviceInfo(const char* deviceName)
929 if(!DuplicateString(&deviceInfo.deviceName, deviceName))
931 return OC_STACK_ERROR;
936 static void PrintUsage()
938 OIC_LOG(INFO, TAG, "Usage : ocserver -o <0|1>");
939 OIC_LOG(INFO, TAG, "-o 0 : Notify all observers");
940 OIC_LOG(INFO, TAG, "-o 1 : Notify list of observers");
944 static void jidbound(char *jid)
946 OIC_LOG_V(INFO, TAG, "\n\n Bound JID: %s\n\n", jid);
950 int main(int argc, char* argv[])
954 char host[] = "localhost";
955 char user[] = "test1";
956 char pass[] = "intel123";
958 OCRAInfo_t rainfo = {};
960 rainfo.hostname = host;
962 rainfo.xmpp_domain = host;
963 rainfo.username = user;
964 rainfo.password = pass;
965 rainfo.resource = empstr;
966 rainfo.user_jid = empstr;
967 rainfo.jidbound = jidbound;
971 while ((opt = getopt(argc, argv, "o:s:p:d:u:w:r:j:")) != -1)
976 gObserveNotifyType = atoi(optarg);
980 rainfo.hostname = optarg;
983 rainfo.port = atoi(optarg);
986 rainfo.xmpp_domain = optarg;
989 rainfo.username = optarg;
992 rainfo.password = optarg;
995 rainfo.user_jid = optarg;
998 rainfo.resource = optarg;
1007 if ((gObserveNotifyType != 0) && (gObserveNotifyType != 1))
1014 OCSetRAInfo(&rainfo);
1017 OIC_LOG(DEBUG, TAG, "OCServer is starting...");
1019 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
1021 OIC_LOG(ERROR, TAG, "OCStack init error");
1024 #ifdef WITH_PRESENCE
1025 if (OCStartPresence(0) != OC_STACK_OK)
1027 OIC_LOG(ERROR, TAG, "OCStack presence/discovery error");
1032 OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandlerCb, NULL);
1034 OCStackResult registrationResult =
1035 SetPlatformInfo(platformID, manufacturerName, manufacturerUrl, modelNumber,
1036 dateOfManufacture, platformVersion, operatingSystemVersion, hardwareVersion,
1037 firmwareVersion, supportUrl, systemTime);
1039 if (registrationResult != OC_STACK_OK)
1041 OIC_LOG(INFO, TAG, "Platform info setting failed locally!");
1042 exit (EXIT_FAILURE);
1045 registrationResult = OCSetPlatformInfo(platformInfo);
1047 if (registrationResult != OC_STACK_OK)
1049 OIC_LOG(INFO, TAG, "Platform Registration failed!");
1050 exit (EXIT_FAILURE);
1053 registrationResult = SetDeviceInfo(deviceName);
1055 if (registrationResult != OC_STACK_OK)
1057 OIC_LOG(INFO, TAG, "Device info setting failed locally!");
1058 exit (EXIT_FAILURE);
1061 OCResourcePayloadAddStringLL(&deviceInfo.types, "oic.d.tv");
1063 registrationResult = OCSetDeviceInfo(deviceInfo);
1065 if (registrationResult != OC_STACK_OK)
1067 OIC_LOG(INFO, TAG, "Device Registration failed!");
1068 exit (EXIT_FAILURE);
1072 * Declare and create the example resource: Light
1074 createLightResource(gResourceUri, &Light);
1076 // Initialize observations data structure for the resource
1077 for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
1079 interestedObservers[i].valid = false;
1084 * Create a thread for generating changes that cause presence notifications
1085 * to be sent to clients
1088 #ifdef WITH_PRESENCE
1089 pthread_create(&threadId_presence, NULL, presenceNotificationGenerator, (void *)NULL);
1092 // Break from loop with Ctrl-C
1093 OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
1095 DeletePlatformInfo();
1098 signal(SIGINT, handleSigInt);
1102 if (OCProcess() != OC_STACK_OK)
1104 OIC_LOG(ERROR, TAG, "OCStack process error");
1109 if (observeThreadStarted)
1111 pthread_cancel(threadId_observe);
1112 pthread_join(threadId_observe, NULL);
1115 pthread_cancel(threadId_presence);
1116 pthread_join(threadId_presence, NULL);
1118 OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
1120 if (OCStop() != OC_STACK_OK)
1122 OIC_LOG(ERROR, TAG, "OCStack process error");