X-Git-Url: http://review.tizen.org/git/?a=blobdiff_plain;f=resource%2Fcsdk%2Fstack%2Fsamples%2Flinux%2FSimpleClientServer%2Focserver.cpp;h=13cf61bee86eb44519a16bbc8810b43d17c6b642;hb=5b285e73548cac989ef00461e1a96bc60b613ae1;hp=f13392527ad5410f33b1cfbbc6c06922b384f57d;hpb=2c5b9d1fa9fe6af0877e29e64e018908d88133a2;p=platform%2Fupstream%2Fiotivity.git diff --git a/resource/csdk/stack/samples/linux/SimpleClientServer/ocserver.cpp b/resource/csdk/stack/samples/linux/SimpleClientServer/ocserver.cpp index f133925..13cf61b 100644 --- a/resource/csdk/stack/samples/linux/SimpleClientServer/ocserver.cpp +++ b/resource/csdk/stack/samples/linux/SimpleClientServer/ocserver.cpp @@ -23,14 +23,24 @@ #include #include #include +#ifdef HAVE_UNISTD_H #include +#endif +#ifdef HAVE_WINDOWS_H +#include +#endif #include +#ifdef HAVE_PTHREAD_H #include +#endif #include +#include #include "ocstack.h" #include "logger.h" -#include "cJSON.h" +#include "ocpayload.h" #include "ocserver.h" +#include "common.h" +#include "platform_features.h" //string length of "/a/light/" + std::numeric_limits::digits10 + '\0'" // 9 + 9 + 1 = 19 @@ -50,50 +60,68 @@ static LightResource gLightInstance[SAMPLE_MAX_NUM_POST_INSTANCE]; Observers interestedObservers[SAMPLE_MAX_NUM_OBSERVATIONS]; +pthread_t threadId_observe; +pthread_t threadId_presence; + +static bool observeThreadStarted = false; + #ifdef WITH_PRESENCE -static int stopPresenceCount = 10; #define numPresenceResources (2) #endif -//TODO: Follow the pattern used in constructJsonResponse() when the payload is decided. -const char responsePayloadDeleteOk[] = - "{App determines payload: Delete Resource operation succeeded.}"; -const char responsePayloadDeleteNotOK[] = - "{App determines payload: Delete Resource operation failed.}"; -const char responsePayloadResourceDoesNotExist[] = - "{App determines payload: The resource does not exist.}"; -const char responsePayloadDeleteResourceNotSupported[] = - "{App determines payload: The request is received for a non-support resource.}"; - - char *gResourceUri= (char *)"/a/light"; -const char *contentType = "myContentType"; const char *dateOfManufacture = "myDateOfManufacture"; const char *deviceName = "myDeviceName"; const char *deviceUUID = "myDeviceUUID"; const char *firmwareVersion = "myFirmwareVersion"; -const char *hostName = "myHostName"; -const char *manufacturerName = "myManufacturerNa"; +const char *manufacturerName = "myName"; +const char *operatingSystemVersion = "myOS"; +const char *hardwareVersion = "myHardwareVersion"; +const char* platformID = "myPlatformID"; const char *manufacturerUrl = "myManufacturerUrl"; const char *modelNumber = "myModelNumber"; const char *platformVersion = "myPlatformVersion"; const char *supportUrl = "mySupportUrl"; const char *version = "myVersion"; +const char *systemTime = "2015-05-15T11.04"; +const char *specVersion = "myDeviceSpecVersion"; +const char* dataModleVersion = "myDeviceModleVersion"; // Entity handler should check for resourceTypeName and ResourceInterface in order to GET // the existence of a known resource const char *resourceTypeName = "core.light"; -const char *resourceInterface = "oc.mi.def"; +const char *resourceInterface = OC_RSRVD_INTERFACE_DEFAULT; +OCPlatformInfo platformInfo; OCDeviceInfo deviceInfo; +OCRepPayload* getPayload(const char* uri, int64_t power, bool state) +{ + OCRepPayload* payload = OCRepPayloadCreate(); + if(!payload) + { + OIC_LOG(ERROR, TAG, PCF("Failed to allocate Payload")); + return nullptr; + } + + OCRepPayloadSetUri(payload, uri); + OCRepPayloadSetPropBool(payload, "state", state); + OCRepPayloadSetPropInt(payload, "power", power); + + return payload; +} + //This function takes the request as an input and returns the response -//in JSON format. -char* constructJsonResponse (OCEntityHandlerRequest *ehRequest) +OCRepPayload* constructResponse(OCEntityHandlerRequest *ehRequest) { - cJSON *json = cJSON_CreateObject(); - cJSON *format; - char *jsonResponse; + if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION) + { + OIC_LOG(ERROR, TAG, PCF("Incoming payload not a representation")); + return nullptr; + } + + OCRepPayload* input = reinterpret_cast(ehRequest->payload); + LightResource *currLightResource = &Light; if (ehRequest->resource == gLightInstance[0].handle) @@ -109,43 +137,26 @@ char* constructJsonResponse (OCEntityHandlerRequest *ehRequest) if(OC_REST_PUT == ehRequest->method) { - // Get cJSON pointer to query - cJSON *putJson = cJSON_Parse((char *)ehRequest->reqJSONPayload); - - // Get root of JSON payload, then the 1st resource. - cJSON* carrier = cJSON_GetObjectItem(putJson, "oc"); - carrier = cJSON_GetArrayItem(carrier, 0); - carrier = cJSON_GetObjectItem(carrier, "rep"); - - cJSON* prop = cJSON_GetObjectItem(carrier,"power"); - if (prop) + // Get pointer to query + int64_t pow; + if(OCRepPayloadGetPropInt(input, "power", &pow)) { - currLightResource->power =prop->valueint; + currLightResource->power =pow; } - prop = cJSON_GetObjectItem(carrier,"state"); - if (prop) + bool state; + if(OCRepPayloadGetPropBool(input, "state", &state)) { - currLightResource->state = prop->valueint; + currLightResource->state = state; } - - cJSON_Delete(putJson); } - cJSON_AddStringToObject(json,"href",gResourceUri); - cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject()); - cJSON_AddBoolToObject(format, "state", currLightResource->state); - cJSON_AddNumberToObject(format, "power", currLightResource->power); - - jsonResponse = cJSON_Print(json); - cJSON_Delete(json); - - return jsonResponse; + return getPayload(gResourceUri, currLightResource->power, currLightResource->state); } /* * Very simple example of query parsing. - * The query may have multiple filters separated by '&'. + * The query may have multiple filters separated by ';'. * It is upto the entity handler to parse the query for the individual filters, * VALIDATE them and respond as it sees fit. @@ -155,17 +166,16 @@ char* constructJsonResponse (OCEntityHandlerRequest *ehRequest) */ bool checkIfQueryForPowerPassed(char * query) { - if (query && strcmp(query, "power<") == 0) + if (query && strncmp(query, "power<", strlen("power<")) == 0) { char * pointerToOperator = strstr(query, "<"); if (pointerToOperator) { int powerRequested = atoi(pointerToOperator + 1); - if (Light.power > powerRequested) { - OC_LOG_V(INFO, TAG, "Current power: %d. Requested: <%d", Light.power + OIC_LOG_V(INFO, TAG, "Current power: %d. Requested: <%d", Light.power , powerRequested); return false; } @@ -174,74 +184,34 @@ bool checkIfQueryForPowerPassed(char * query) return true; } -/* This method check the validity of resourceTypeName and resource interfaces - * Entity Handler has to parse the query string in order to process it +/* + * Application should validate and process these as desired. */ - OCEntityHandlerResult ValidateQueryParams (OCEntityHandlerRequest *entityHandlerRequest) { - bool resourceList = true; - uint8_t resourceIndex = 0; - OCEntityHandlerResult ehResult = OC_EH_ERROR; - - // Validate pointer - if (!entityHandlerRequest) - { - OC_LOG (ERROR, TAG, "Invalid request pointer"); - return ehResult; - } - //Added check for resource type & interface in server entity handle - - while(resourceList) - { - const char* typeName = OCGetResourceTypeName(entityHandlerRequest->resource, - resourceIndex); - const char* interfaceName = OCGetResourceInterfaceName(entityHandlerRequest->resource, - resourceIndex); - if(typeName && interfaceName) - { - if(strcmp(typeName,resourceTypeName) == 0 && - strcmp(interfaceName,resourceInterface) == 0) - { - ehResult = OC_EH_OK; - break; - } - resourceIndex++; - } - else - { - resourceList = false; - } - } - return ehResult; + OIC_LOG_V(INFO, TAG, PCF("Received query %s"), entityHandlerRequest->query); + OIC_LOG(INFO, TAG, PCF("Not processing query")); + return OC_EH_OK; } OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest, - char *payload, uint16_t maxPayloadSize) + OCRepPayload **payload) { OCEntityHandlerResult ehResult; - char *getResp = constructJsonResponse(ehRequest); - bool queryPassed = checkIfQueryForPowerPassed(ehRequest->query); // Empty payload if the query has no match. if (queryPassed) { - char *getResp = constructJsonResponse(ehRequest); - - if (maxPayloadSize > strlen ((char *)getResp)) - { - strncpy(payload, getResp, strlen((char *)getResp)); - ehResult = OC_EH_OK; - } - else + OCRepPayload *getResp = constructResponse(ehRequest); + if(!getResp) { - OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small", - maxPayloadSize); - ehResult = OC_EH_ERROR; + OIC_LOG(ERROR, TAG, "constructResponse failed"); + return OC_EH_ERROR; } - free(getResp); + *payload = getResp; + ehResult = OC_EH_OK; } else { @@ -252,35 +222,28 @@ OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest, } OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest, - char *payload, uint16_t maxPayloadSize) + OCRepPayload** payload) { OCEntityHandlerResult ehResult; - char *putResp = constructJsonResponse(ehRequest); + OCRepPayload *putResp = constructResponse(ehRequest); - if (maxPayloadSize > strlen ((char *)putResp)) - { - strncpy(payload, putResp, strlen((char *)putResp)); - ehResult = OC_EH_OK; - } - else + if(!putResp) { - OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small", - maxPayloadSize); - ehResult = OC_EH_ERROR; + OIC_LOG(ERROR, TAG, "Failed to construct Json response"); + return OC_EH_ERROR; } - free(putResp); + *payload = putResp; + ehResult = OC_EH_OK; return ehResult; } OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest, - OCEntityHandlerResponse *response, char *payload, uint16_t maxPayloadSize) + OCEntityHandlerResponse *response, OCRepPayload** payload) { OCEntityHandlerResult ehResult = OC_EH_OK; - char *respPLPost_light = NULL; - cJSON *json; - cJSON *format; + OCRepPayload *respPLPost_light = nullptr; /* * The entity handler determines how to process a POST request. @@ -301,30 +264,26 @@ OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest, char newLightUri[URI_MAXSIZE]; snprintf(newLightUri, URI_MAXSIZE, "/a/light/%d", gCurrLightInstance); - json = cJSON_CreateObject(); - cJSON_AddStringToObject(json,"href",gResourceUri); - cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject()); - cJSON_AddStringToObject(format, "createduri", (char *) newLightUri); + respPLPost_light = OCRepPayloadCreate(); + OCRepPayloadSetUri(respPLPost_light, gResourceUri); + OCRepPayloadSetPropString(respPLPost_light, "createduri", newLightUri); if (0 == createLightResource (newLightUri, &gLightInstance[gCurrLightInstance])) { - OC_LOG (INFO, TAG, "Created new Light instance\n"); + OIC_LOG (INFO, TAG, "Created new Light instance\n"); gLightInstance[gCurrLightInstance].state = 0; gLightInstance[gCurrLightInstance].power = 0; gCurrLightInstance++; - respPLPost_light = cJSON_Print(json); strncpy ((char *)response->resourceUri, newLightUri, MAX_URI_LENGTH); ehResult = OC_EH_RESOURCE_CREATED; } - - cJSON_Delete(json); } else { // Update repesentation of /a/light Light.state = true; Light.power = 11; - respPLPost_light = constructJsonResponse(ehRequest); + respPLPost_light = constructResponse(ehRequest); } } else @@ -337,43 +296,40 @@ OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest, gLightInstance[i].power = 22; if (i == 0) { - respPLPost_light = constructJsonResponse(ehRequest); + respPLPost_light = constructResponse(ehRequest); break; } else if (i == 1) { - respPLPost_light = constructJsonResponse(ehRequest); + respPLPost_light = constructResponse(ehRequest); } } } } - if ((respPLPost_light != NULL) && (maxPayloadSize > strlen ((char *)respPLPost_light))) + if ((respPLPost_light != NULL)) { - strncpy(payload, respPLPost_light, strlen((char *)respPLPost_light)); + *payload = respPLPost_light; } else { - OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small", - maxPayloadSize); + OIC_LOG(INFO, TAG, "Payload was NULL"); ehResult = OC_EH_ERROR; } - free(respPLPost_light); return ehResult; } -OCEntityHandlerResult ProcessDeleteRequest (OCEntityHandlerRequest *ehRequest, - char *payload, uint16_t maxPayloadSize) +OCEntityHandlerResult ProcessDeleteRequest (OCEntityHandlerRequest *ehRequest) { if(ehRequest == NULL) { - OC_LOG(INFO, TAG, "The ehRequest is NULL"); + OIC_LOG(INFO, TAG, "The ehRequest is NULL"); return OC_EH_ERROR; } OCEntityHandlerResult ehResult = OC_EH_OK; - OC_LOG_V(INFO, TAG, "\n\nExecuting %s for resource %d ", __func__, ehRequest->resource); + OIC_LOG_V(INFO, TAG, "\n\nExecuting %s for resource %p ", __func__, ehRequest->resource); /* * In the sample below, the application will: @@ -384,8 +340,6 @@ OCEntityHandlerResult ProcessDeleteRequest (OCEntityHandlerRequest *ehRequest, * 2. optionally, app removes observers out of its array 'interestedObservers' */ - const char* deleteResponse = NULL; - if ((ehRequest != NULL) && (ehRequest->resource == Light.handle)) { //Step 1: Ask stack to do the work. @@ -393,9 +347,8 @@ OCEntityHandlerResult ProcessDeleteRequest (OCEntityHandlerRequest *ehRequest, if (result == OC_STACK_OK) { - OC_LOG (INFO, TAG, "\n\nDelete Resource operation succeeded."); + OIC_LOG (INFO, TAG, "\n\nDelete Resource operation succeeded."); ehResult = OC_EH_OK; - deleteResponse = responsePayloadDeleteOk; //Step 2: clear observers who wanted to observe this resource at the app level. for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++) @@ -410,14 +363,12 @@ OCEntityHandlerResult ProcessDeleteRequest (OCEntityHandlerRequest *ehRequest, } else if (result == OC_STACK_NO_RESOURCE) { - OC_LOG(INFO, TAG, "\n\nThe resource doesn't exist or it might have been deleted."); - deleteResponse = responsePayloadResourceDoesNotExist; + OIC_LOG(INFO, TAG, "\n\nThe resource doesn't exist or it might have been deleted."); ehResult = OC_EH_RESOURCE_DELETED; } else { - OC_LOG(INFO, TAG, "\n\nEncountered error from OCDeleteResource()."); - deleteResponse = responsePayloadDeleteNotOK; + OIC_LOG(INFO, TAG, "\n\nEncountered error from OCDeleteResource()."); ehResult = OC_EH_ERROR; } } @@ -425,51 +376,30 @@ OCEntityHandlerResult ProcessDeleteRequest (OCEntityHandlerRequest *ehRequest, { //Let's this app not supporting DELETE on some resources so //consider the DELETE request is received for a non-support resource. - OC_LOG_V(INFO, TAG, "\n\nThe request is received for a non-support resource."); - deleteResponse = responsePayloadDeleteResourceNotSupported; + OIC_LOG_V(INFO, TAG, "\n\nThe request is received for a non-support resource."); ehResult = OC_EH_FORBIDDEN; } - if (maxPayloadSize > strlen ((char *)deleteResponse)) - { - strncpy(payload, deleteResponse, strlen((char *)deleteResponse)); - } - else - { - OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small", - maxPayloadSize); - ehResult = OC_EH_ERROR; - } - return ehResult; } -OCEntityHandlerResult ProcessNonExistingResourceRequest(OCEntityHandlerRequest *ehRequest, - char *payload, uint16_t maxPayloadSize) +OCEntityHandlerResult ProcessNonExistingResourceRequest(OCEntityHandlerRequest * /*ehRequest*/) { - OC_LOG_V(INFO, TAG, "\n\nExecuting %s ", __func__); - - const char* response = NULL; - response = responsePayloadResourceDoesNotExist; - - if ( (ehRequest != NULL) && - (maxPayloadSize > strlen ((char *)response)) ) - { - strncpy((char *)payload, response, strlen((char *)response)); - } - else - { - OC_LOG_V (ERROR, TAG, "Response buffer: %d bytes is too small", - maxPayloadSize); - } + OIC_LOG_V(INFO, TAG, "\n\nExecuting %s ", __func__); return OC_EH_RESOURCE_NOT_FOUND; } void ProcessObserveRegister (OCEntityHandlerRequest *ehRequest) { - OC_LOG_V (INFO, TAG, "Received observation registration request with observation Id %d", + OIC_LOG_V (INFO, TAG, "Received observation registration request with observation Id %d", ehRequest->obsInfo.obsId); + + if (!observeThreadStarted) + { + pthread_create (&threadId_observe, NULL, ChangeLightRepresentation, (void *)NULL); + observeThreadStarted = 1; + } for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++) { if (interestedObservers[i].valid == false) @@ -486,7 +416,7 @@ void ProcessObserveDeregister (OCEntityHandlerRequest *ehRequest) { bool clientStillObserving = false; - OC_LOG_V (INFO, TAG, "Received observation deregistration request for observation Id %d", + OIC_LOG_V (INFO, TAG, "Received observation deregistration request for observation Id %d", ehRequest->obsInfo.obsId); for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++) { @@ -506,18 +436,19 @@ void ProcessObserveDeregister (OCEntityHandlerRequest *ehRequest) OCEntityHandlerResult OCDeviceEntityHandlerCb (OCEntityHandlerFlag flag, - OCEntityHandlerRequest *entityHandlerRequest, char* uri) + OCEntityHandlerRequest *entityHandlerRequest, + char* uri, + void* /*callbackParam*/) { - OC_LOG_V (INFO, TAG, "Inside device default entity handler - flags: 0x%x, uri: %s", flag, uri); + OIC_LOG_V (INFO, TAG, "Inside device default entity handler - flags: 0x%x, uri: %s", flag, uri); - OCEntityHandlerResult ehResult = OC_EH_ERROR; + OCEntityHandlerResult ehResult = OC_EH_OK; OCEntityHandlerResponse response; - char payload[MAX_RESPONSE_LENGTH] = {0}; // Validate pointer if (!entityHandlerRequest) { - OC_LOG (ERROR, TAG, "Invalid request pointer"); + OIC_LOG (ERROR, TAG, "Invalid request pointer"); return OC_EH_ERROR; } // Initialize certain response fields @@ -525,86 +456,68 @@ OCDeviceEntityHandlerCb (OCEntityHandlerFlag flag, memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions); memset(response.resourceUri, 0, sizeof response.resourceUri); + OCRepPayload* payload = nullptr; - // Entity handler to check the validity of resourceTypeName and resource interfaces - // It is Entity handler's responsibility to keep track of the list of resources prior to call - // Requested method - ehResult = ValidateQueryParams(entityHandlerRequest); - if (flag & OC_INIT_FLAG) - { - OC_LOG (INFO, TAG, "Flag includes OC_INIT_FLAG"); - } if (flag & OC_REQUEST_FLAG) { - OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG"); - // Entity handler to check the validity of resourceType and resource interface - if( ehResult == OC_EH_OK ) + OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG"); + + if (entityHandlerRequest->resource == NULL) { - if (entityHandlerRequest->resource == NULL) - { - OC_LOG (INFO, TAG, "Received request from client to a non-existing resource"); - ehResult = ProcessNonExistingResourceRequest(entityHandlerRequest, - payload, sizeof(payload) - 1); - } - else if (OC_REST_GET == entityHandlerRequest->method) - { - OC_LOG (INFO, TAG, "Received OC_REST_GET from client"); - ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload) - 1); - } - else if (OC_REST_PUT == entityHandlerRequest->method) - { - OC_LOG (INFO, TAG, "Received OC_REST_PUT from client"); - ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload) - 1); - } - else if (OC_REST_DELETE == entityHandlerRequest->method) - { - OC_LOG (INFO, TAG, "Received OC_REST_DELETE from client"); - ehResult = ProcessDeleteRequest (entityHandlerRequest, payload, sizeof(payload) - 1); - } - else - { - OC_LOG_V (INFO, TAG, "Received unsupported method %d from client", - entityHandlerRequest->method); - ehResult = OC_EH_ERROR; - } + OIC_LOG (INFO, TAG, "Received request from client to a non-existing resource"); + ehResult = ProcessNonExistingResourceRequest(entityHandlerRequest); + } + else if (OC_REST_GET == entityHandlerRequest->method) + { + OIC_LOG (INFO, TAG, "Received OC_REST_GET from client"); + ehResult = ProcessGetRequest (entityHandlerRequest, &payload); + } + else if (OC_REST_PUT == entityHandlerRequest->method) + { + OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client"); + ehResult = ProcessPutRequest (entityHandlerRequest, &payload); + } + else if (OC_REST_DELETE == entityHandlerRequest->method) + { + OIC_LOG (INFO, TAG, "Received OC_REST_DELETE from client"); + ehResult = ProcessDeleteRequest (entityHandlerRequest); } else { - OC_LOG_V (INFO, TAG, - "Invalid ResourceInterface Type & Name received from client for method: %d ", + OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client", entityHandlerRequest->method); + ehResult = OC_EH_ERROR; } - // If the result isn't an error or forbidden, send response + // If the result isn't an error or forbidden, send response if (!((ehResult == OC_EH_ERROR) || (ehResult == OC_EH_FORBIDDEN))) { // Format the response. Note this requires some info about the request response.requestHandle = entityHandlerRequest->requestHandle; response.resourceHandle = entityHandlerRequest->resource; response.ehResult = ehResult; - response.payload = payload; - response.payloadSize = strlen(payload); + response.payload = reinterpret_cast(payload); // Indicate that response is NOT in a persistent buffer response.persistentBufferFlag = 0; // Send the response if (OCDoResponse(&response) != OC_STACK_OK) { - OC_LOG(ERROR, TAG, "Error sending response"); + OIC_LOG(ERROR, TAG, "Error sending response"); ehResult = OC_EH_ERROR; } } } if (flag & OC_OBSERVE_FLAG) { - OC_LOG(INFO, TAG, "Flag includes OC_OBSERVE_FLAG"); + OIC_LOG(INFO, TAG, "Flag includes OC_OBSERVE_FLAG"); if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action) { - OC_LOG (INFO, TAG, "Received OC_OBSERVE_REGISTER from client"); + OIC_LOG (INFO, TAG, "Received OC_OBSERVE_REGISTER from client"); } else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action) { - OC_LOG (INFO, TAG, "Received OC_OBSERVE_DEREGISTER from client"); + OIC_LOG (INFO, TAG, "Received OC_OBSERVE_DEREGISTER from client"); } } @@ -612,8 +525,9 @@ OCDeviceEntityHandlerCb (OCEntityHandlerFlag flag, } OCEntityHandlerResult -OCNOPEntityHandlerCb (OCEntityHandlerFlag flag, - OCEntityHandlerRequest *entityHandlerRequest) +OCNOPEntityHandlerCb (OCEntityHandlerFlag /*flag*/, + OCEntityHandlerRequest * /*entityHandlerRequest*/, + void* /*callbackParam*/) { // This is callback is associated with the 2 presence notification // resources. They are non-operational. @@ -622,18 +536,17 @@ OCNOPEntityHandlerCb (OCEntityHandlerFlag flag, OCEntityHandlerResult OCEntityHandlerCb (OCEntityHandlerFlag flag, - OCEntityHandlerRequest *entityHandlerRequest) + OCEntityHandlerRequest *entityHandlerRequest, void* /*callback*/) { - OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag); + OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag); OCEntityHandlerResult ehResult = OC_EH_OK; - OCEntityHandlerResponse response; - char payload[MAX_RESPONSE_LENGTH] = {0}; + OCEntityHandlerResponse response = { 0, 0, OC_EH_ERROR, 0, 0, { },{ 0 }, false }; // Validate pointer if (!entityHandlerRequest) { - OC_LOG (ERROR, TAG, "Invalid request pointer"); + OIC_LOG (ERROR, TAG, "Invalid request pointer"); return OC_EH_ERROR; } @@ -642,57 +555,37 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag, memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions); memset(response.resourceUri, 0, sizeof response.resourceUri); + OCRepPayload* payload = nullptr; - // Entity handler to check the validity of resourceTypeName and resource interfaces - // It is Entity handler's responsibility to keep track of the list of resources prior to call - // Requested method - - ehResult = ValidateQueryParams(entityHandlerRequest); - - if (flag & OC_INIT_FLAG) - { - OC_LOG (INFO, TAG, "Flag includes OC_INIT_FLAG"); - } if (flag & OC_REQUEST_FLAG) { - OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG"); + OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG"); - // Entity handler to check the validity of resourceType and resource interface - // Entity handler to check the validity of resourceType and resource interface - if(ehResult == OC_EH_OK) + if (OC_REST_GET == entityHandlerRequest->method) { - if (OC_REST_GET == entityHandlerRequest->method) - { - OC_LOG (INFO, TAG, "Received OC_REST_GET from client"); - ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload) - 1); - } - else if (OC_REST_PUT == entityHandlerRequest->method) - { - OC_LOG (INFO, TAG, "Received OC_REST_PUT from client"); - ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload) - 1); - } - else if (OC_REST_POST == entityHandlerRequest->method) - { - OC_LOG (INFO, TAG, "Received OC_REST_POST from client"); - ehResult = ProcessPostRequest (entityHandlerRequest, &response, payload, sizeof(payload) - 1); - } - else if (OC_REST_DELETE == entityHandlerRequest->method) - { - OC_LOG (INFO, TAG, "Received OC_REST_DELETE from client"); - ehResult = ProcessDeleteRequest (entityHandlerRequest, payload, sizeof(payload) - 1); - } - else - { - OC_LOG_V (INFO, TAG, "Received unsupported method %d from client", - entityHandlerRequest->method); - ehResult = OC_EH_ERROR; - } + OIC_LOG (INFO, TAG, "Received OC_REST_GET from client"); + ehResult = ProcessGetRequest (entityHandlerRequest, &payload); + } + else if (OC_REST_PUT == entityHandlerRequest->method) + { + OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client"); + ehResult = ProcessPutRequest (entityHandlerRequest, &payload); + } + else if (OC_REST_POST == entityHandlerRequest->method) + { + OIC_LOG (INFO, TAG, "Received OC_REST_POST from client"); + ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload); + } + else if (OC_REST_DELETE == entityHandlerRequest->method) + { + OIC_LOG (INFO, TAG, "Received OC_REST_DELETE from client"); + ehResult = ProcessDeleteRequest (entityHandlerRequest); } else { - OC_LOG_V (INFO, TAG, - "Invalid ResourceInterface Type & Name received from client for method: %d ", + OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client", entityHandlerRequest->method); + ehResult = OC_EH_ERROR; } // If the result isn't an error or forbidden, send response if (!((ehResult == OC_EH_ERROR) || (ehResult == OC_EH_FORBIDDEN))) @@ -701,8 +594,7 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag, response.requestHandle = entityHandlerRequest->requestHandle; response.resourceHandle = entityHandlerRequest->resource; response.ehResult = ehResult; - response.payload = payload; - response.payloadSize = strlen(payload); + response.payload = reinterpret_cast(payload); // Indicate that response is NOT in a persistent buffer response.persistentBufferFlag = 0; @@ -710,7 +602,7 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag, if(entityHandlerRequest->rcvdVendorSpecificHeaderOptions && entityHandlerRequest->numRcvdVendorSpecificHeaderOptions) { - OC_LOG (INFO, TAG, "Received vendor specific options"); + OIC_LOG (INFO, TAG, "Received vendor specific options"); uint8_t i = 0; OCHeaderOption * rcvdOptions = entityHandlerRequest->rcvdVendorSpecificHeaderOptions; @@ -718,10 +610,10 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag, { if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID) { - OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with", + OIC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with", ((OCHeaderOption)rcvdOptions[i]).optionID ); - OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData, + OIC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData, MAX_HEADER_OPTION_DATA_LENGTH); } } @@ -742,27 +634,28 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag, // Send the response if (OCDoResponse(&response) != OC_STACK_OK) { - OC_LOG(ERROR, TAG, "Error sending response"); + OIC_LOG(ERROR, TAG, "Error sending response"); ehResult = OC_EH_ERROR; } } } if (flag & OC_OBSERVE_FLAG) { - OC_LOG(INFO, TAG, "Flag includes OC_OBSERVE_FLAG"); + OIC_LOG(INFO, TAG, "Flag includes OC_OBSERVE_FLAG"); if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action) { - OC_LOG (INFO, TAG, "Received OC_OBSERVE_REGISTER from client"); + OIC_LOG (INFO, TAG, "Received OC_OBSERVE_REGISTER from client"); ProcessObserveRegister (entityHandlerRequest); } else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action) { - OC_LOG (INFO, TAG, "Received OC_OBSERVE_DEREGISTER from client"); + OIC_LOG (INFO, TAG, "Received OC_OBSERVE_DEREGISTER from client"); ProcessObserveDeregister (entityHandlerRequest); } } + OCPayloadDestroy(response.payload); return ehResult; } @@ -781,8 +674,7 @@ void *ChangeLightRepresentation (void *param) OCStackResult result = OC_STACK_ERROR; uint8_t j = 0; - uint8_t numNotifies = (SAMPLE_MAX_NUM_OBSERVATIONS)/2; - OCObservationId obsNotify[numNotifies]; + OCObservationId obsNotify[(SAMPLE_MAX_NUM_OBSERVATIONS)/2]; while (!gQuitFlag) { @@ -790,7 +682,7 @@ void *ChangeLightRepresentation (void *param) Light.power += 5; if (gLightUnderObservation) { - OC_LOG_V(INFO, TAG, " =====> Notifying stack of new power level %d\n", Light.power); + OIC_LOG_V(INFO, TAG, " =====> Notifying stack of new power level %d\n", Light.power); if (gObserveNotifyType == 1) { // Notify list of observers. Alternate observers on the list will be notified. @@ -804,17 +696,10 @@ void *ChangeLightRepresentation (void *param) } } - cJSON *json = cJSON_CreateObject(); - cJSON *format; - cJSON_AddStringToObject(json,"href",gResourceUri); - cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject()); - cJSON_AddBoolToObject(format, "state", Light.state); - cJSON_AddNumberToObject(format, "power", Light.power); - char * obsResp = cJSON_Print(json); - cJSON_Delete(json); + OCRepPayload* payload = getPayload(gResourceUri, Light.power, Light.state); result = OCNotifyListOfObservers (Light.handle, obsNotify, j, - obsResp, OC_NA_QOS); - free(obsResp); + payload, OC_NA_QOS); + OCRepPayloadDestroy(payload); } else if (gObserveNotifyType == 0) { @@ -822,27 +707,16 @@ void *ChangeLightRepresentation (void *param) result = OCNotifyAllObservers (Light.handle, OC_NA_QOS); if (OC_STACK_NO_OBSERVERS == result) { - OC_LOG (INFO, TAG, + OIC_LOG (INFO, TAG, "=======> No more observers exist, stop sending observations"); gLightUnderObservation = 0; } } else { - OC_LOG (ERROR, TAG, "Incorrect notification type selected"); + OIC_LOG (ERROR, TAG, "Incorrect notification type selected"); } } -#ifdef WITH_PRESENCE - if(stopPresenceCount > 0) - { - OC_LOG_V(INFO, TAG, "================ Counting down to stop presence %d", stopPresenceCount); - } - if(!stopPresenceCount--) - { - OC_LOG(INFO, TAG, "================ stopping presence"); - OCStopPresence(); - } -#endif } return NULL; } @@ -850,7 +724,9 @@ void *ChangeLightRepresentation (void *param) #ifdef WITH_PRESENCE void *presenceNotificationGenerator(void *param) { - sleep(5); + uint8_t secondsBeforePresence = 10; + OIC_LOG_V(INFO, TAG, "Will send out presence in %u seconds", secondsBeforePresence); + sleep(secondsBeforePresence); (void)param; OCDoHandle presenceNotificationHandles[numPresenceResources]; OCStackResult res = OC_STACK_OK; @@ -869,19 +745,20 @@ void *presenceNotificationGenerator(void *param) sleep(1); res = OCCreateResource(&presenceNotificationHandles[i], presenceNotificationResources.at(i).c_str(), - resourceInterface, + OC_RSRVD_INTERFACE_DEFAULT, presenceNotificationUris.at(i).c_str(), OCNOPEntityHandlerCb, + NULL, OC_DISCOVERABLE|OC_OBSERVABLE); } if(res != OC_STACK_OK) { - OC_LOG_V(ERROR, TAG, "\"Presence Notification Generator\" failed to create resource " + OIC_LOG_V(ERROR, TAG, "\"Presence Notification Generator\" failed to create resource " "%s with result %s.", presenceNotificationResources.at(i).c_str(), getResult(res)); break; } - OC_LOG_V(INFO, TAG, PCF("Created %s for presence notification"), + OIC_LOG_V(INFO, TAG, PCF("Created %s for presence notification"), presenceNotificationUris[i].c_str()); } sleep(5); @@ -893,177 +770,63 @@ void *presenceNotificationGenerator(void *param) } if(res != OC_STACK_OK) { - OC_LOG_V(ERROR, TAG, "\"Presence Notification Generator\" failed to delete "\ + OIC_LOG_V(ERROR, TAG, "\"Presence Notification Generator\" failed to delete "\ "resource %s.", presenceNotificationResources.at(i).c_str()); break; } - OC_LOG_V(INFO, TAG, PCF("Deleted %s for presence notification"), + OIC_LOG_V(INFO, TAG, PCF("Deleted %s for presence notification"), presenceNotificationUris[i].c_str()); } - return NULL; -} -#endif -static void PrintUsage() -{ - OC_LOG(INFO, TAG, "Usage : ocserver -o <0|1>"); - OC_LOG(INFO, TAG, "-o 0 : Notify all observers"); - OC_LOG(INFO, TAG, "-o 1 : Notify list of observers"); -} - -int main(int argc, char* argv[]) -{ - pthread_t threadId; - pthread_t threadId_presence; - int opt; - - while ((opt = getopt(argc, argv, "o:")) != -1) - { - switch(opt) - { - case 'o': - gObserveNotifyType = atoi(optarg); - break; - default: - PrintUsage(); - return -1; - } - } - - if ((gObserveNotifyType != 0) && (gObserveNotifyType != 1)) - { - PrintUsage(); - return -1; - } - - OC_LOG(DEBUG, TAG, "OCServer is starting..."); - - if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK) - { - OC_LOG(ERROR, TAG, "OCStack init error"); - return 0; - } -#ifdef WITH_PRESENCE - if (OCStartPresence(0) != OC_STACK_OK) - { - OC_LOG(ERROR, TAG, "OCStack presence/discovery error"); - return 0; - } -#endif - - OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandlerCb); - - OCStackResult deviceResult = SetDeviceInfo(contentType, dateOfManufacture, deviceName, - deviceUUID, firmwareVersion, hostName, manufacturerName, - manufacturerUrl, modelNumber, platformVersion, supportUrl, version); - - if (deviceResult != OC_STACK_OK) - { - OC_LOG(INFO, TAG, "Device Registration failed!"); - exit (EXIT_FAILURE); - } - - deviceResult = OCSetDeviceInfo(deviceInfo); - - if (deviceResult != OC_STACK_OK) - { - OC_LOG(INFO, TAG, "Device Registration failed!"); - exit (EXIT_FAILURE); - } - - /* - * Declare and create the example resource: Light - */ - createLightResource(gResourceUri, &Light); + OIC_LOG(INFO, TAG, "================ stopping presence"); + OCStopPresence(); - // Initialize observations data structure for the resource - for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++) - { - interestedObservers[i].valid = false; - } - - /* - * Create a thread for changing the representation of the Light - */ - pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)NULL); - - /* - * Create a thread for generating changes that cause presence notifications - * to be sent to clients - */ - - #ifdef WITH_PRESENCE - pthread_create(&threadId_presence, NULL, presenceNotificationGenerator, (void *)NULL); - #endif - - // Break from loop with Ctrl-C - OC_LOG(INFO, TAG, "Entering ocserver main loop..."); - DeleteDeviceInfo(); - signal(SIGINT, handleSigInt); - while (!gQuitFlag) - { - if (OCProcess() != OC_STACK_OK) - { - OC_LOG(ERROR, TAG, "OCStack process error"); - return 0; - } - - sleep(2); - } - - /* - * Cancel the Light thread and wait for it to terminate - */ - pthread_cancel(threadId); - pthread_join(threadId, NULL); - pthread_cancel(threadId_presence); - pthread_join(threadId_presence, NULL); - - OC_LOG(INFO, TAG, "Exiting ocserver main loop..."); - - if (OCStop() != OC_STACK_OK) - { - OC_LOG(ERROR, TAG, "OCStack process error"); - } - - return 0; + return NULL; } +#endif int createLightResource (char *uri, LightResource *lightResource) { if (!uri) { - OC_LOG(ERROR, TAG, "Resource URI cannot be NULL"); + OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL"); return -1; } lightResource->state = false; lightResource->power= 0; OCStackResult res = OCCreateResource(&(lightResource->handle), - resourceTypeName, - resourceInterface, + "core.light", + "oc.mi.def", uri, OCEntityHandlerCb, + NULL, OC_DISCOVERABLE|OC_OBSERVABLE); - OC_LOG_V(INFO, TAG, "Created Light resource with result: %s", getResult(res)); + OIC_LOG_V(INFO, TAG, "Created Light resource with result: %s", getResult(res)); return 0; } +void DeletePlatformInfo() +{ + free (platformInfo.platformID); + free (platformInfo.manufacturerName); + free (platformInfo.manufacturerUrl); + free (platformInfo.modelNumber); + free (platformInfo.dateOfManufacture); + free (platformInfo.platformVersion); + free (platformInfo.operatingSystemVersion); + free (platformInfo.hardwareVersion); + free (platformInfo.firmwareVersion); + free (platformInfo.supportUrl); + free (platformInfo.systemTime); +} + void DeleteDeviceInfo() { - free(deviceInfo.contentType); - free(deviceInfo.dateOfManufacture); - free(deviceInfo.deviceName); - free(deviceInfo.deviceUUID); - free(deviceInfo.firmwareVersion); - free(deviceInfo.hostName); - free(deviceInfo.manufacturerName); - free(deviceInfo.manufacturerUrl); - free(deviceInfo.modelNumber); - free(deviceInfo.platformVersion); - free(deviceInfo.supportUrl); - free(deviceInfo.version); + free (deviceInfo.deviceName); + free (deviceInfo.specVersion); + free (deviceInfo.dataModleVersion); } bool DuplicateString(char** targetString, const char* sourceString) @@ -1085,11 +848,10 @@ bool DuplicateString(char** targetString, const char* sourceString) return false; } -OCStackResult SetDeviceInfo(const char *contentType, const char *dateOfManufacture, - const char *deviceName, const char *deviceUUID, const char *firmwareVersion, - const char *hostName, const char *manufacturerName, const char *manufacturerUrl, - const char *modelNumber, const char *platformVersion, const char *supportUrl, - const char *version) +OCStackResult SetPlatformInfo(const char* platformID, const char *manufacturerName, + const char *manufacturerUrl, const char *modelNumber, const char *dateOfManufacture, + const char *platformVersion, const char* operatingSystemVersion, const char* hardwareVersion, + const char *firmwareVersion, const char* supportUrl, const char* systemTime) { bool success = true; @@ -1104,71 +866,279 @@ OCStackResult SetDeviceInfo(const char *contentType, const char *dateOfManufactu return OC_STACK_INVALID_PARAM; } - if(!DuplicateString(&deviceInfo.contentType, contentType)) + if(!DuplicateString(&platformInfo.platformID, platformID)) { success = false; } - if(!DuplicateString(&deviceInfo.dateOfManufacture, dateOfManufacture)) + if(!DuplicateString(&platformInfo.manufacturerName, manufacturerName)) { success = false; } - if(!DuplicateString(&deviceInfo.deviceName, deviceName)) + if(!DuplicateString(&platformInfo.manufacturerUrl, manufacturerUrl)) { success = false; } - if(!DuplicateString(&deviceInfo.deviceUUID, deviceUUID)) + if(!DuplicateString(&platformInfo.modelNumber, modelNumber)) { success = false; } - if(!DuplicateString(&deviceInfo.firmwareVersion, firmwareVersion)) + if(!DuplicateString(&platformInfo.dateOfManufacture, dateOfManufacture)) { success = false; } - if(!DuplicateString(&deviceInfo.hostName, hostName)) + if(!DuplicateString(&platformInfo.platformVersion, platformVersion)) { success = false; } - if(!DuplicateString(&deviceInfo.manufacturerName, manufacturerName)) + if(!DuplicateString(&platformInfo.operatingSystemVersion, operatingSystemVersion)) { success = false; } - if(!DuplicateString(&deviceInfo.manufacturerUrl, manufacturerUrl)) + if(!DuplicateString(&platformInfo.hardwareVersion, hardwareVersion)) { success = false; } - if(!DuplicateString(&deviceInfo.modelNumber, modelNumber)) + if(!DuplicateString(&platformInfo.firmwareVersion, firmwareVersion)) { success = false; } - if(!DuplicateString(&deviceInfo.platformVersion, platformVersion)) + if(!DuplicateString(&platformInfo.supportUrl, supportUrl)) { success = false; } - if(!DuplicateString(&deviceInfo.supportUrl, supportUrl)) + if(!DuplicateString(&platformInfo.systemTime, systemTime)) { success = false; } - if(!DuplicateString(&deviceInfo.version, version)) + if(success) { - success = false; + return OC_STACK_OK; } - if(success) + DeletePlatformInfo(); + return OC_STACK_ERROR; +} + +OCStackResult SetDeviceInfo(const char* deviceName, const char* specVersion, const char* dataModleVersion) +{ + if(!DuplicateString(&deviceInfo.deviceName, deviceName)) { - return OC_STACK_OK; + return OC_STACK_ERROR; + } + if(!DuplicateString(&deviceInfo.specVersion, specVersion)) + { + return OC_STACK_ERROR; + } + if(!DuplicateString(&deviceInfo.dataModleVersion, dataModleVersion)) + { + return OC_STACK_ERROR; + } + return OC_STACK_OK; +} + +static void PrintUsage() +{ + OIC_LOG(INFO, TAG, "Usage : ocserver -o <0|1>"); + OIC_LOG(INFO, TAG, "-o 0 : Notify all observers"); + OIC_LOG(INFO, TAG, "-o 1 : Notify list of observers"); +} + +#ifdef RA_ADAPTER +static void jidbound(char *jid) +{ + OIC_LOG_V(INFO, TAG, "\n\n Bound JID: %s\n\n", jid); +} +#endif + +int main(int argc, char* argv[]) +{ + +#ifdef RA_ADAPTER + char host[] = "localhost"; + char user[] = "test1"; + char pass[] = "intel123"; + char empstr[] = ""; + OCRAInfo_t rainfo = {}; + + rainfo.hostname = host; + rainfo.port = 5222; + rainfo.xmpp_domain = host; + rainfo.username = user; + rainfo.password = pass; + rainfo.resource = empstr; + rainfo.user_jid = empstr; + rainfo.jidbound = jidbound; +#endif + + int opt = 0; + while ((opt = getopt(argc, argv, "o:s:p:d:u:w:r:j:")) != -1) + { + switch(opt) + { + case 'o': + gObserveNotifyType = atoi(optarg); + break; +#ifdef RA_ADAPTER + case 's': + rainfo.hostname = optarg; + break; + case 'p': + rainfo.port = atoi(optarg); + break; + case 'd': + rainfo.xmpp_domain = optarg; + break; + case 'u': + rainfo.username = optarg; + break; + case 'w': + rainfo.password = optarg; + break; + case 'j': + rainfo.user_jid = optarg; + break; + case 'r': + rainfo.resource = optarg; + break; +#endif + default: + PrintUsage(); + return -1; + } + } + + if ((gObserveNotifyType != 0) && (gObserveNotifyType != 1)) + { + PrintUsage(); + return -1; + } + +#ifdef RA_ADAPTER + OCSetRAInfo(&rainfo); +#endif + + OIC_LOG(DEBUG, TAG, "OCServer is starting..."); + + if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK) + { + OIC_LOG(ERROR, TAG, "OCStack init error"); + return 0; + } +#ifdef WITH_PRESENCE + if (OCStartPresence(0) != OC_STACK_OK) + { + OIC_LOG(ERROR, TAG, "OCStack presence/discovery error"); + return 0; } +#endif + + OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandlerCb, NULL); + + OCStackResult registrationResult = + SetPlatformInfo(platformID, manufacturerName, manufacturerUrl, modelNumber, + dateOfManufacture, platformVersion, operatingSystemVersion, hardwareVersion, + firmwareVersion, supportUrl, systemTime); + if (registrationResult != OC_STACK_OK) + { + OIC_LOG(INFO, TAG, "Platform info setting failed locally!"); + exit (EXIT_FAILURE); + } + + registrationResult = OCSetPlatformInfo(platformInfo); + + if (registrationResult != OC_STACK_OK) + { + OIC_LOG(INFO, TAG, "Platform Registration failed!"); + exit (EXIT_FAILURE); + } + + registrationResult = SetDeviceInfo(deviceName, specVersion, dataModleVersion); + + if (registrationResult != OC_STACK_OK) + { + OIC_LOG(INFO, TAG, "Device info setting failed locally!"); + exit (EXIT_FAILURE); + } + + OCResourcePayloadAddStringLL(&deviceInfo.types, "oic.d.tv"); + + registrationResult = OCSetDeviceInfo(deviceInfo); + + if (registrationResult != OC_STACK_OK) + { + OIC_LOG(INFO, TAG, "Device Registration failed!"); + exit (EXIT_FAILURE); + } + + /* + * Declare and create the example resource: Light + */ + createLightResource(gResourceUri, &Light); + + // Initialize observations data structure for the resource + for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++) + { + interestedObservers[i].valid = false; + } + + + /* + * Create a thread for generating changes that cause presence notifications + * to be sent to clients + */ + + #ifdef WITH_PRESENCE + pthread_create(&threadId_presence, NULL, presenceNotificationGenerator, (void *)NULL); + #endif + + // Break from loop with Ctrl-C + OIC_LOG(INFO, TAG, "Entering ocserver main loop..."); + + DeletePlatformInfo(); DeleteDeviceInfo(); - return OC_STACK_ERROR; + + signal(SIGINT, handleSigInt); + + while (!gQuitFlag) + { + if (OCProcess() != OC_STACK_OK) + { + OIC_LOG(ERROR, TAG, "OCStack process error"); + return 0; + } + } + + if (observeThreadStarted) + { +#ifdef HAVE_PTHREAD_H + pthread_cancel(threadId_observe); + pthread_join(threadId_observe, NULL); +#endif + } + +#ifdef HAVE_PTHREAD_H + pthread_cancel(threadId_presence); + pthread_join(threadId_presence, NULL); +#endif + + OIC_LOG(INFO, TAG, "Exiting ocserver main loop..."); + + if (OCStop() != OC_STACK_OK) + { + OIC_LOG(ERROR, TAG, "OCStack process error"); + } + + return 0; }