예제 #1
0
/**
 * @brief Create and loads the payload
 *
 * @return the created payload
 */
 OCRepPayload *getPayload(OCEntityHandlerRequest *ehRequest, OCBaseResourceT *resource)
 {
     OIC_LOG(DEBUG, TAG, "Getting Payload");
     if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
     {
         OIC_LOG(ERROR, TAG, "Incoming payload not a representation");
         return NULL;
     }

    OCRepPayload *payload = OCRepPayloadCreate();

    if(!payload)
    {
        OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
        return NULL;
    }

    OCRepPayloadSetUri(payload, resource->uri);
    //OCRepPayloadSetPropString(payload, "name", resource->name);

    return payload;
 }
예제 #2
0
OCStackResult ProvisionEnrollee(OCQualityOfService qos, const char *query, const char *resUri,
                                OCDevAddr *destination, int pauseBeforeStart) {


    // This sleep is required in case of BLE provisioning due to packet drop issue.
    OIC_LOG_V(INFO, ES_PROV_TAG, "Sleeping for %d seconds", pauseBeforeStart);
    sleep(pauseBeforeStart);
    OIC_LOG_V(INFO, ES_PROV_TAG, "\n\nExecuting ProvisionEnrollee%s", __func__);

    OCRepPayload *payload = OCRepPayloadCreate();

    OCRepPayloadSetUri(payload, resUri);
    OCRepPayloadSetPropString(payload, OC_RSRVD_ES_TNN, netProvInfo->netAddressInfo.WIFI.ssid);
    OCRepPayloadSetPropString(payload, OC_RSRVD_ES_CD, netProvInfo->netAddressInfo.WIFI.pwd);

    OIC_LOG_V(DEBUG, ES_PROV_TAG, "OCPayload ready for ProvisionEnrollee");

    OCStackResult ret = InvokeOCDoResource(query, OC_REST_PUT, destination, qos,
                                           ProvisionEnrolleeResponse, payload, NULL, 0);

    return ret;
}
예제 #3
0
//Client should call refresh before expiresin or when receive 4.01 during sign-in
OCStackResult OCCloudRefresh(const char *host, const char *query, const char *uId,
        const char *deviceId, const char *refreshtoken, OCClientResponseHandler response)
{
        char    targetUri[MAX_URI_LENGTH * 2] = { 0, };
        snprintf(targetUri, MAX_URI_LENGTH * 2, "%s%s", host, query);

        OCCallbackData cbData;
        memset(&cbData, 0, sizeof(OCCallbackData));
        cbData.cb = response;
        cbData.cd = NULL;
        cbData.context = (void *)DEFAULT_CONTEXT_VALUE;

        OCRepPayload *refreshPayload = OCRepPayloadCreate();

        OCRepPayloadSetPropString(refreshPayload, "uid", uId);
        OCRepPayloadSetPropString(refreshPayload, "di", deviceId);
        OCRepPayloadSetPropString(refreshPayload, "granttype", "refresh_token");
        OCRepPayloadSetPropString(refreshPayload, "refreshtoken", refreshtoken);

        return OCDoResource(NULL, OC_REST_POST, targetUri, NULL, (OCPayload *)refreshPayload,
                CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, NULL, 0);
}
예제 #4
0
OCRepPayload* constructResponse(OCEntityHandlerRequest *ehRequest)
{
    OCRepPayload* payload = OCRepPayloadCreate();
    if (!payload)
    {
        OIC_LOG(ERROR, ES_RH_TAG, "Failed to allocate Payload");
        return NULL;
    }

    if (ehRequest->resource == gProvResource.handle)
    {
        OIC_LOG(INFO, ES_RH_TAG, "constructResponse prov res");
        OCRepPayloadSetUri(payload, OC_RSRVD_ES_URI_PROV);
        OCRepPayloadSetPropInt(payload, OC_RSRVD_ES_PS, gProvResource.ps);
        OCRepPayloadSetPropInt(payload, OC_RSRVD_ES_TNT, gProvResource.tnt);
    }
    else if (ehRequest->requestHandle == gNetResource.handle)
    {

        OCRepPayloadSetUri(payload, OC_RSRVD_ES_URI_NET);
        OCRepPayloadSetPropInt(payload, "ant", gNetResource.ant[0]);
    }
    return payload;
}
예제 #5
0
static bool OCParseSingleRepPayload(OCRepPayload** outPayload, CborValue *objMap)
{
    if (!outPayload)
    {
        return false;
    }

    bool err = false;

    if (cbor_value_is_map(objMap))
    {
        if (!*outPayload)
        {
            *outPayload = OCRepPayloadCreate();
            if(!*outPayload)
            {
                return CborErrorOutOfMemory;
            }
        }

        OCRepPayload* curPayload = *outPayload;

        size_t len;
        CborValue repMap;
        err = err || cbor_value_enter_container(objMap, &repMap);

        while(!err && cbor_value_is_valid(&repMap))
        {
            char* name;
            err = err || cbor_value_dup_text_string(&repMap, &name, &len, NULL);
            err = err || cbor_value_advance(&repMap);

            CborType type = cbor_value_get_type(&repMap);
            switch(type)
            {
            case CborNullType:
                err = !OCRepPayloadSetNull(curPayload, name);
                break;
            case CborIntegerType:
            {
                int64_t intval = 0;
                err = err || cbor_value_get_int64(&repMap, &intval);
                if (!err)
                {
                    err = !OCRepPayloadSetPropInt(curPayload, name, intval);
                }
            }
            break;
            case CborDoubleType:
            {
                double doubleval = 0;
                err = err || cbor_value_get_double(&repMap, &doubleval);
                if (!err)
                {
                    err = !OCRepPayloadSetPropDouble(curPayload, name, doubleval);
                }
            }
            break;
            case CborBooleanType:
            {
                bool boolval = false;
                err = err || cbor_value_get_boolean(&repMap, &boolval);
                if (!err)
                {
                    err = !OCRepPayloadSetPropBool(curPayload, name, boolval);
                }
            }
            break;
            case CborTextStringType:
            {
                char* strval = NULL;
                err = err || cbor_value_dup_text_string(&repMap, &strval, &len, NULL);
                if (!err)
                {
                    err = !OCRepPayloadSetPropStringAsOwner(curPayload, name, strval);
                }
            }
            break;
            case CborByteStringType:
            {
                uint8_t* bytestrval = NULL;
                err = err || cbor_value_dup_byte_string(&repMap, &bytestrval, &len, NULL);
                if (!err)
                {
                    OCByteString tmp = {.bytes = bytestrval, .len = len};
                    err = !OCRepPayloadSetPropByteStringAsOwner(curPayload, name, &tmp);
                }
            }
            break;
            case CborMapType:
            {
                OCRepPayload *pl = NULL;
                err = err || OCParseSingleRepPayload(&pl, &repMap);
                if (!err)
                {
                    err = !OCRepPayloadSetPropObjectAsOwner(curPayload, name, pl);
                }
            }
            break;
            case CborArrayType:
                err = err || OCParseArray(curPayload, name, &repMap);
                break;
            default:
                OC_LOG_V(ERROR, TAG, "Parsing rep property, unknown type %d", repMap.type);
                err = true;
            }

            if (type != CborMapType && cbor_value_is_valid(&repMap))
            {
                err = err || cbor_value_advance(&repMap);
            }
            OICFree(name);
        }

        err = err || cbor_value_leave_container(objMap, &repMap);

        if(err)
        {
            OCRepPayloadDestroy(*outPayload);
            *outPayload = NULL;
        }
    }
예제 #6
0
static OCStackResult
HandleBatchInterface(OCEntityHandlerRequest *ehRequest)
{
    if (!ehRequest)
    {
        return OC_STACK_INVALID_PARAM;
    }

    OCResource * collResource = (OCResource *) ehRequest->resource;

    OCRepPayload* payload = OCRepPayloadCreate();
    if (!payload)
    {
        return OC_STACK_NO_MEMORY;
    }

    if (collResource)
    {
        OCRepPayloadSetUri(payload, collResource->uri);
    }

    OCEntityHandlerResponse response = {0};
    response.ehResult = OC_EH_OK;
    response.payload = (OCPayload*)payload;
    response.persistentBufferFlag = 0;
    response.requestHandle = (OCRequestHandle) ehRequest->requestHandle;
    response.resourceHandle = (OCResourceHandle) collResource;
    OCStackResult stackRet = OCDoResponse(&response);

    if (stackRet == OC_STACK_OK)
    {
        for (uint8_t i = 0; i < MAX_CONTAINED_RESOURCES; i++)
        {
            OCResource* temp = collResource->rsrcResources[i];
            if (temp)
            {
                // Note that all entity handlers called through a collection
                // will get the same pointer to ehRequest, the only difference
                // is ehRequest->resource
                ehRequest->resource = (OCResourceHandle) temp;

                OCEntityHandlerResult ehResult = temp->entityHandler(OC_REQUEST_FLAG, ehRequest,
                                                                     temp->entityHandlerCallbackParam);

                // The default collection handler is returning as OK
                if (stackRet != OC_STACK_SLOW_RESOURCE)
                {
                    stackRet = OC_STACK_OK;
                }
                // if a single resource is slow, then entire response will be treated
                // as slow response
                if (ehResult == OC_EH_SLOW)
                {
                    OC_LOG(INFO, TAG, "This is a slow resource");
                    ((OCServerRequest *)ehRequest->requestHandle)->slowFlag = 1;
                    stackRet = EntityHandlerCodeToOCStackCode(ehResult);
                }
            }
            else
            {
                break;
            }
        }
        ehRequest->resource = (OCResourceHandle) collResource;
    }
    return stackRet;
}
예제 #7
0
static bool OCParseSingleRepPayload(OCRepPayload** outPayload, CborValue* repParent)
{
    if (!outPayload)
    {
        return false;
    }

    *outPayload = OCRepPayloadCreate();
    OCRepPayload* curPayload = *outPayload;
    bool err = false;
    if(!*outPayload)
    {
        return CborErrorOutOfMemory;
    }

    size_t len;
    CborValue curVal;
    err = err || cbor_value_map_find_value(repParent, OC_RSRVD_HREF, &curVal);
    if(cbor_value_is_valid(&curVal))
    {
        err = err || cbor_value_dup_text_string(&curVal, &curPayload->uri, &len,
            NULL);
    }

    err = err || cbor_value_map_find_value(repParent, OC_RSRVD_PROPERTY, &curVal);
    if(cbor_value_is_valid(&curVal))
    {
        CborValue insidePropValue = {0};
        err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_RESOURCE_TYPE,
                &insidePropValue);

        if(cbor_value_is_text_string(&insidePropValue))
        {
            char* allRt = NULL;
            err = err || cbor_value_dup_text_string(&insidePropValue, &allRt, &len, NULL);

            char* savePtr;

            if (allRt)
            {
                char* curPtr = strtok_r(allRt, " ", &savePtr);

                while (curPtr)
                {
                    char* trimmed = InPlaceStringTrim(curPtr);
                    if (trimmed[0] != '\0')
                    {
                        OCRepPayloadAddResourceType(curPayload, curPtr);
                    }
                    curPtr = strtok_r(NULL, " ", &savePtr);
                }
            }
            OICFree(allRt);
        }

        err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_INTERFACE, &insidePropValue);

        if(cbor_value_is_text_string(&insidePropValue))
        {
            char* allIf = NULL;
            err = err || cbor_value_dup_text_string(&insidePropValue, &allIf, &len, NULL);

            char* savePtr;

            if (allIf)
            {
                char* curPtr = strtok_r(allIf, " ", &savePtr);

                while (curPtr)
                {
                    char* trimmed = InPlaceStringTrim(curPtr);
                    if (trimmed[0] != '\0')
                    {
                        OCRepPayloadAddInterface(curPayload, curPtr);
                    }
                    curPtr = strtok_r(NULL, " ", &savePtr);
                }
            }
            OICFree(allIf);
        }
    }

    err = err || cbor_value_map_find_value(repParent, OC_RSRVD_REPRESENTATION, &curVal);
    if(cbor_value_is_map(&curVal))
    {
        CborValue repMap;
        err = err || cbor_value_enter_container(&curVal, &repMap);

        while(!err && cbor_value_is_valid(&repMap))
        {
            char* name;
            err = err || cbor_value_dup_text_string(&repMap, &name, &len, NULL);

            err = err || cbor_value_advance(&repMap);

            int64_t intval = 0;
            bool boolval = false;
            char* strval = NULL;
            double doubleval = 0;
            OCRepPayload* pl;

            switch(cbor_value_get_type(&repMap))
            {
                case CborNullType:
                    err = !OCRepPayloadSetNull(curPayload, name);
                    break;
                case CborIntegerType:
                    err = err || cbor_value_get_int64(&repMap, &intval);
                    if (!err)
                    {
                        err = !OCRepPayloadSetPropInt(curPayload, name, intval);
                    }
                    break;
                case CborDoubleType:
                    err = err || cbor_value_get_double(&repMap, &doubleval);
                    if (!err)
                    {
                        err = !OCRepPayloadSetPropDouble(curPayload, name, doubleval);
                    }
                    break;
                case CborBooleanType:
                    err = err || cbor_value_get_boolean(&repMap, &boolval);
                    if (!err)
                    {
                        err = !OCRepPayloadSetPropBool(curPayload, name, boolval);
                    }
                    break;
                case CborTextStringType:
                    err = err || cbor_value_dup_text_string(&repMap, &strval, &len, NULL);
                    if (!err)
                    {
                        err = !OCRepPayloadSetPropStringAsOwner(curPayload, name, strval);
                    }
                    break;
                case CborMapType:
                    err = err || OCParseSingleRepPayload(&pl, &repMap);
                    if (!err)
                    {
                        err = !OCRepPayloadSetPropObjectAsOwner(curPayload, name, pl);
                    }
                    break;
                case CborArrayType:
                    err = err || OCParseArray(curPayload, name, &repMap);
                    break;
                default:
                    OC_LOG_V(ERROR, TAG, "Parsing rep property, unknown type %d", repMap.type);
                    err = true;
            }

             err = err || cbor_value_advance(&repMap);
            OICFree(name);
        }
        err = err || cbor_value_leave_container(&curVal, &repMap);
    }

    if(err)
    {
        OCRepPayloadDestroy(*outPayload);
        *outPayload = NULL;
    }

    return err;
}
예제 #8
0
// This is the entity handler for the registered resource.
// This is invoked by OCStack whenever it recevies a request for this resource.
OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest,
                                        void *callbackParam)
{
    OCEntityHandlerResult ehRet = OC_EH_OK;
    OCEntityHandlerResponse response = {0};
    OCRepPayload* payload = OCRepPayloadCreate();
    if(!payload)
    {
        OC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
        return OC_EH_ERROR;
    }

    if(entityHandlerRequest && (flag & OC_REQUEST_FLAG))
    {
        OC_LOG (INFO, TAG, PCF("Flag includes OC_REQUEST_FLAG"));

        if(OC_REST_GET == entityHandlerRequest->method)
        {
            OCRepPayloadSetUri(payload, "/a/light");
            OCRepPayloadSetPropBool(payload, "state", true);
            OCRepPayloadSetPropInt(payload, "power", 10);
        }
        else if(OC_REST_PUT == entityHandlerRequest->method)
        {
            //Do something with the 'put' payload
            OCRepPayloadSetUri(payload, "/a/light");
            OCRepPayloadSetPropBool(payload, "state", false);
            OCRepPayloadSetPropInt(payload, "power", 0);
        }

        if (ehRet == OC_EH_OK)
        {
            // Format the response.  Note this requires some info about the request
            response.requestHandle = entityHandlerRequest->requestHandle;
            response.resourceHandle = entityHandlerRequest->resource;
            response.ehResult = ehRet;
            response.payload = (OCPayload*) payload;
            response.numSendVendorSpecificHeaderOptions = 0;
            memset(response.sendVendorSpecificHeaderOptions, 0,
                    sizeof response.sendVendorSpecificHeaderOptions);
            memset(response.resourceUri, 0, sizeof response.resourceUri);
            // 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");
                ehRet = OC_EH_ERROR;
            }
        }
    }
    if (entityHandlerRequest && (flag & OC_OBSERVE_FLAG))
    {
        if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
        {
            OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_REGISTER from client"));
            gLightUnderObservation = 1;
        }
        else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
        {
            OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_DEREGISTER from client"));
        }
    }

    return ehRet;
}
예제 #9
0
OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest,
                                        void *callbackParam)
{
    OCEntityHandlerResult ehRet = OC_EH_OK;
    OCEntityHandlerResponse response = {0};
    OCRepPayload* payload = OCRepPayloadCreate();
    if(!payload)
    {
        //OC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
        return OC_EH_ERROR;
    }

    if(entityHandlerRequest && (flag & OC_REQUEST_FLAG))
    {
        //OC_LOG (INFO, TAG, PCF("Flag includes OC_REQUEST_FLAG"));

        if(OC_REST_GET == entityHandlerRequest->method)
        {
            OCRepPayloadSetUri(payload, "/iotar/speaker");
            OCRepPayloadSetPropInt(payload, "state", speaker.state);
            OCRepPayloadSetPropInt(payload, "volume",speaker.volume);
            OCRepPayloadSetPropInt(payload, "time", speaker.time);
            OCRepPayloadSetPropInt(payload, "present_song",speaker.present_song);
            OCRepPayloadSetPropInt(payload, "next_song", speaker.next_song);
            
            
        }
        else if(OC_REST_PUT == entityHandlerRequest->method)
        {
			
			
			//OC_LOG_V(DEBUG, TAG, "put \n");
			
			  //풋 올때 데이터 어떻게 받지?? 
			OCRepPayload* pay = (OCRepPayload*) entityHandlerRequest-> payload;
			
			int64_t order = 0;
			int64_t temp = 0;
			char in[10];
			OCRepPayloadGetPropInt(pay, "order", &order);
			
			if(order == 30){   //재생 
				OCRepPayloadGetPropInt(pay, "temp", &temp);
				
				makeString('a', temp, (char*)&in); 
				
				speaker.present_song = temp;
				Serial1.println(in);
				millis_prv = millis();
				save_time = 0;
				speaker.state = 1;
			}else if(order == 31){  //볼륨 설정 
				
				OCRepPayloadGetPropInt(pay, "temp", &temp);
				
				makeString('v', temp, (char*)&in); 
				
				speaker.volume = temp;
				Serial1.println(in);
				
			}else if(order == 32){  //다음 노래 설정 
				
				OCRepPayloadGetPropInt(pay, "temp", &temp);
				
				makeString('d', temp, (char*)&in); 
				
				speaker.next_song = temp;
				Serial1.println(in);
				
			}else if(order == 33){  // 현재 아무일 안하고 있으면 0, 재생중 1, 일시정지 2. 로 세팅.
				
				Serial1.println('x');
				
			}else if(order == 34) { //정지.
				
				Serial1.println('s');
				
			}else if(order == 35) { // +1 볼륨.
				speaker.volume++;
				if(speaker.volume >= 100){
					speaker.volume = 100;
				}
				makeString('v', speaker.volume, (char*)&in); 
				Serial1.println(in);
				
				
			}else if(order == 36) { // -1 볼륨.
				
				speaker.volume--;
				if(speaker.volume < 1){
					speaker.volume = 1;
				}
				makeString('v', speaker.volume, (char*)&in); 
				Serial1.println(in);
				
			}else if(order == 37){ // 일시정지, 일시정지 풀기.
				
				Serial1.println('p');
				if(speaker.state == 1){
					speaker.state = 2;
					save_time = speaker.time+2;
				}else{
					speaker.state = 1;
					millis_prv = millis();
				}
			}else if(order == 38){   //다음노래 재생 
				speaker.present_song++;
				if(speaker.present_song > MAX_SONG){
					speaker.present_song = 1;
				}
				
				makeString('a', speaker.present_song, (char*)&in); 
				
				Serial1.println(in);
				millis_prv = millis();
				save_time = 0;
				speaker.state = 1;
			}else if(order == 39){ // 이전 노래 재생 
				
				speaker.present_song--;
				if(speaker.present_song < 1){
						speaker.present_song = MAX_SONG;
				}
				
			
				
				makeString('a', speaker.present_song, (char*)&in); 
				Serial1.println(in);
				millis_prv = millis();
				save_time = 0;
				speaker.state = 1;
				
				
			}
			
			
			
			
        
			
			OCRepPayloadSetUri(payload, "/iotar/speaker");
			OCRepPayloadSetPropInt(payload, "time", speaker.time);
          
            
            
            
        }

        if (ehRet == OC_EH_OK)
        {
            // Format the response.  Note this requires some info about the request
            response.requestHandle = entityHandlerRequest->requestHandle;
            response.resourceHandle = entityHandlerRequest->resource;
            response.ehResult = ehRet;
            response.payload = (OCPayload*) payload;
            response.numSendVendorSpecificHeaderOptions = 0;
            memset(response.sendVendorSpecificHeaderOptions, 0,
                    sizeof response.sendVendorSpecificHeaderOptions);
            memset(response.resourceUri, 0, sizeof response.resourceUri);
            // 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");
                ehRet = OC_EH_ERROR;
            }
        }
    }
    if (entityHandlerRequest && (flag & OC_OBSERVE_FLAG))
    {
        if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
        {
           // OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_REGISTER from client"));
            gLightUnderObservation = 1;
        }
        else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
        {
           // OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_DEREGISTER from client"));
            gLightUnderObservation = 0;
        }
    }
    OCRepPayloadDestroy(payload);
    return ehRet;
}
예제 #10
0
OCStackResult SendListObserverNotification (OCResource * resource,
        OCObservationId  *obsIdList, uint8_t numberOfIds,
        const OCRepPayload *payload,
        uint32_t maxAge,
        OCQualityOfService qos)
{
    (void)maxAge;
    if(!resource || !obsIdList || !payload)
    {
        return OC_STACK_INVALID_PARAM;
    }

    uint8_t numIds = numberOfIds;
    ResourceObserver *observer = NULL;
    uint8_t numSentNotification = 0;
    OCServerRequest * request = NULL;
    OCStackResult result = OC_STACK_ERROR;
    bool observeErrorFlag = false;

    OC_LOG(INFO, TAG, "Entering SendListObserverNotification");
    while(numIds)
    {
        observer = GetObserverUsingId (*obsIdList);
        if(observer)
        {
            // Found observer - verify if it matches the resource handle
            if (observer->resource == resource)
            {
                qos = DetermineObserverQoS(OC_REST_GET, observer, qos);


                result = AddServerRequest(&request, 0, 0, 1, OC_REST_GET,
                        0, resource->sequenceNum, qos, observer->query,
                        NULL, NULL, observer->token, observer->tokenLength,
                        observer->resUri, 0, observer->acceptFormat,
                        &observer->devAddr);

                if(request)
                {
                    request->observeResult = OC_STACK_OK;
                    if(result == OC_STACK_OK)
                    {
                        OCEntityHandlerResponse ehResponse = {0};
                        ehResponse.ehResult = OC_EH_OK;
                        ehResponse.payload = (OCPayload*)OCRepPayloadCreate();
                        if(!ehResponse.payload)
                        {
                            FindAndDeleteServerRequest(request);
                            continue;
                        }
                        memcpy(ehResponse.payload, payload, sizeof(*payload));
                        ehResponse.persistentBufferFlag = 0;
                        ehResponse.requestHandle = (OCRequestHandle) request;
                        ehResponse.resourceHandle = (OCResourceHandle) resource;
                        result = OCDoResponse(&ehResponse);
                        if(result == OC_STACK_OK)
                        {
                            OC_LOG_V(INFO, TAG, "Observer id %d notified.", *obsIdList);

                            // Increment only if OCDoResponse is successful
                            numSentNotification++;

                            OICFree(ehResponse.payload);
                            FindAndDeleteServerRequest(request);
                        }
                        else
                        {
                            OC_LOG_V(INFO, TAG, "Error notifying observer id %d.", *obsIdList);
                        }
                    }
                    else
                    {
                        FindAndDeleteServerRequest(request);
                    }
                }
                // Since we are in a loop, set an error flag to indicate
                // at least one error occurred.
                if (result != OC_STACK_OK)
                {
                    observeErrorFlag = true;
                }
            }
        }
        obsIdList++;
        numIds--;
    }

    if(numSentNotification == numberOfIds && !observeErrorFlag)
    {
        return OC_STACK_OK;
    }
    else if(numSentNotification == 0)
    {
        return OC_STACK_NO_OBSERVERS;
    }
    else
    {
        OC_LOG(ERROR, TAG, "Observer notification error");
        return OC_STACK_ERROR;
    }
}
예제 #11
0
static CborError OCParseSingleRepPayload(OCRepPayload **outPayload, CborValue *objMap, bool isRoot)
{
    CborError err = CborUnknownError;
    char *name = NULL;
    bool res;
    VERIFY_PARAM_NON_NULL(TAG, outPayload, "Invalid Parameter outPayload");
    VERIFY_PARAM_NON_NULL(TAG, objMap, "Invalid Parameter objMap");

    if (cbor_value_is_map(objMap))
    {
        if (!*outPayload)
        {
            *outPayload = OCRepPayloadCreate();
            if (!*outPayload)
            {
                return CborErrorOutOfMemory;
            }
        }

        OCRepPayload *curPayload = *outPayload;

        size_t len = 0;
        CborValue repMap;
        err = cbor_value_enter_container(objMap, &repMap);
        VERIFY_CBOR_SUCCESS(TAG, err, "Failed entering repMap");

        while (!err && cbor_value_is_valid(&repMap))
        {
            if (cbor_value_is_text_string(&repMap))
            {
                err = cbor_value_dup_text_string(&repMap, &name, &len, NULL);
                VERIFY_CBOR_SUCCESS(TAG, err, "Failed finding tag name in the map");
                err = cbor_value_advance(&repMap);
                VERIFY_CBOR_SUCCESS(TAG, err, "Failed advancing rootMap");
                if (name &&
                    isRoot &&
                    ((0 == strcmp(OC_RSRVD_HREF, name)) ||
                     (0 == strcmp(OC_RSRVD_RESOURCE_TYPE, name)) ||
                    (0 == strcmp(OC_RSRVD_INTERFACE, name))))
                {
                    err = cbor_value_advance(&repMap);
                    OICFree(name);
                    continue;
                }
            }
            CborType type = cbor_value_get_type(&repMap);
            switch (type)
            {
                case CborNullType:
                    res = OCRepPayloadSetNull(curPayload, name);
                    break;
                case CborIntegerType:
                    {
                        int64_t intval = 0;
                        err = cbor_value_get_int64(&repMap, &intval);
                        VERIFY_CBOR_SUCCESS(TAG, err, "Failed getting int value");
                        res = OCRepPayloadSetPropInt(curPayload, name, intval);
                    }
                    break;
                case CborDoubleType:
                    {
                        double doubleval = 0;
                        err = cbor_value_get_double(&repMap, &doubleval);
                        VERIFY_CBOR_SUCCESS(TAG, err, "Failed getting double value");
                        res = OCRepPayloadSetPropDouble(curPayload, name, doubleval);
                    }
                    break;
                case CborBooleanType:
                    {
                        bool boolval = false;
                        err = cbor_value_get_boolean(&repMap, &boolval);
                        VERIFY_CBOR_SUCCESS(TAG, err, "Failed getting boolean value");
                        res = OCRepPayloadSetPropBool(curPayload, name, boolval);
                    }
                    break;
                case CborTextStringType:
                    {
                        char *strval = NULL;
                        err = cbor_value_dup_text_string(&repMap, &strval, &len, NULL);
                        VERIFY_CBOR_SUCCESS(TAG, err, "Failed getting string value");
                        res = OCRepPayloadSetPropStringAsOwner(curPayload, name, strval);
                    }
                    break;
                case CborByteStringType:
                    {
                        uint8_t* bytestrval = NULL;
                        err = cbor_value_dup_byte_string(&repMap, &bytestrval, &len, NULL);
                        VERIFY_CBOR_SUCCESS(TAG, err, "Failed getting byte string value");
                        OCByteString tmp = {.bytes = bytestrval, .len = len};
                        res = OCRepPayloadSetPropByteStringAsOwner(curPayload, name, &tmp);
                    }
                    break;
                case CborMapType:
                    {
                        OCRepPayload *pl = NULL;
                        err = OCParseSingleRepPayload(&pl, &repMap, false);
                        VERIFY_CBOR_SUCCESS(TAG, err, "Failed setting parse single rep");
                        res = OCRepPayloadSetPropObjectAsOwner(curPayload, name, pl);
                    }
                    break;
                case CborArrayType:
                    err = OCParseArray(curPayload, name, &repMap);
                    break;
                default:
                    OIC_LOG_V(ERROR, TAG, "Parsing rep property, unknown type %d", repMap.type);
                    res = false;
            }
            if (type != CborArrayType)
            {
                err = (CborError) !res;
            }
            VERIFY_CBOR_SUCCESS(TAG, err, "Failed setting value");

            if (type != CborMapType && cbor_value_is_valid(&repMap))
            {
                err = cbor_value_advance(&repMap);
                VERIFY_CBOR_SUCCESS(TAG, err, "Failed advance repMap");
            }
            OICFree(name);
            name = NULL;
        }
        if (cbor_value_is_container(objMap))
        {
            err = cbor_value_leave_container(objMap, &repMap);
            VERIFY_CBOR_SUCCESS(TAG, err, "Failed to leave container");
        }
        return err;
    }

exit:
    OICFree(name);
    OCRepPayloadDestroy(*outPayload);
    *outPayload = NULL;
    return err;
}
static int _icd_state_value_from_gvariant(OCRepPayload *repr, GVariantIter *iter)
{
	int ret;
	char *key;
	GVariant *var;
	const char *str_value;
	OCRepPayload *repr_value;
	struct icd_state_list_s value_list = {0};

	while (g_variant_iter_loop(iter, "{sv}", &key, &var)) {

		if (g_variant_is_of_type(var, G_VARIANT_TYPE_BOOLEAN)) {
			OCRepPayloadSetPropBool(repr, key, g_variant_get_boolean(var));

		} else if (g_variant_is_of_type(var, G_VARIANT_TYPE_INT32)) {
			OCRepPayloadSetPropInt(repr, key, g_variant_get_int32(var));

		} else if (g_variant_is_of_type(var, G_VARIANT_TYPE_DOUBLE)) {
			OCRepPayloadSetPropDouble(repr, key, g_variant_get_double(var));

		} else if (g_variant_is_of_type(var, G_VARIANT_TYPE_STRING)) {
			str_value = g_variant_get_string(var, NULL);
			if (NULL == str_value) {
				ERR("g_variant_get_string() Fail");
				_icd_payload_state_list_destroy(&value_list);
				return IOTCON_ERROR_OUT_OF_MEMORY;
			}
			if (IC_STR_EQUAL == strcmp(IC_STR_NULL, str_value))
				OCRepPayloadSetNull(repr, key);
			else
				OCRepPayloadSetPropString(repr, key, str_value);

		} else if (g_variant_is_of_type(var, G_VARIANT_TYPE("ay"))) {
			OCByteString byte_value;
			byte_value.bytes = (uint8_t*)g_variant_get_data(var);
			byte_value.len = g_variant_get_size(var);
			OCRepPayloadSetPropByteString(repr, key, byte_value);

		} else if (g_variant_is_of_type(var, G_VARIANT_TYPE("a{sv}"))) {
			GVariantIter state_iter;
			repr_value = OCRepPayloadCreate();
			g_variant_iter_init(&state_iter, var);

			ret = _icd_state_value_from_gvariant(repr_value, &state_iter);
			if (IOTCON_ERROR_NONE != ret) {
				ERR("_icd_state_value_from_gvariant() Fail(%d)", ret);
				_icd_payload_state_list_destroy(&value_list);
				OCRepPayloadDestroy(repr_value);
				return ret;
			}
			OCRepPayloadSetPropObjectAsOwner(repr, key, repr_value);

		} else if (g_variant_is_of_type(var, G_VARIANT_TYPE_ARRAY)) {
			memset(&value_list, 0, sizeof(struct icd_state_list_s));
			ret = _icd_state_list_from_gvariant(var, &value_list, 0);
			if (IOTCON_ERROR_NONE != ret) {
				ERR("_icd_state_list_from_gvariant() Fail(%d)", ret);
				_icd_payload_state_list_destroy(&value_list);
				return ret;
			}
			ret = _icd_state_array_from_list(repr, &value_list, key);
			if (IOTCON_ERROR_NONE != ret) {
				ERR("_icd_state_array_from_list() Fail(%d)", ret);
				_icd_payload_state_list_destroy(&value_list);
				return ret;
			}

		} else {
			ERR("Invalid type(%s)", g_variant_get_type_string(var));
			return IOTCON_ERROR_INVALID_TYPE;
		}
	}

	return IOTCON_ERROR_NONE;
}
static int _icd_state_list_from_gvariant(GVariant *var,
		struct icd_state_list_s *value_list, int depth)
{
	int ret;
	GVariantIter iter;
	const GVariantType *type;
	union icd_state_value_u *value;

	type = g_variant_get_type(var);

	g_variant_iter_init(&iter, var);

	value_list->dimensions[depth] = g_variant_iter_n_children(&iter);
	DBG("[%d]list dim : %d", depth, value_list->dimensions[depth]);

	if (g_variant_type_equal(G_VARIANT_TYPE("ab"), type)) {
		bool b;
		value_list->type = OCREP_PROP_BOOL;
		while (g_variant_iter_loop(&iter, "b", &b)) {
			value = calloc(1, sizeof(union icd_state_value_u));
			if (NULL == value) {
				ERR("calloc() Fail(%d)", errno);
				return IOTCON_ERROR_OUT_OF_MEMORY;
			}
			value->b = b;
			value_list->list = g_list_append(value_list->list, value);
		}
	} else if (g_variant_type_equal(G_VARIANT_TYPE("ai"), type)) {
		int i;
		value_list->type = OCREP_PROP_INT;
		while (g_variant_iter_loop(&iter, "i", &i)) {
			value = calloc(1, sizeof(union icd_state_value_u));
			if (NULL == value) {
				ERR("calloc() Fail(%d)", errno);
				return IOTCON_ERROR_OUT_OF_MEMORY;
			}
			value->i = i;
			value_list->list = g_list_append(value_list->list, value);
		}
	} else if (g_variant_type_equal(G_VARIANT_TYPE("ad"), type)) {
		double d;
		value_list->type = OCREP_PROP_DOUBLE;
		while (g_variant_iter_loop(&iter, "d", &d)) {
			value = calloc(1, sizeof(union icd_state_value_u));
			if (NULL == value) {
				ERR("calloc() Fail(%d)", errno);
				return IOTCON_ERROR_OUT_OF_MEMORY;
			}
			value->d = d;
			value_list->list = g_list_append(value_list->list, value);
		}
	} else if (g_variant_type_equal(G_VARIANT_TYPE("as"), type)) {
		char *s;
		value_list->type = OCREP_PROP_STRING;
		while (g_variant_iter_next(&iter, "s", &s))
			value_list->list = g_list_append(value_list->list, s);
	} else if (g_variant_type_equal(G_VARIANT_TYPE("av"), type)) {
		GVariant *value;
		if (g_variant_iter_loop(&iter, "v", &value)) {
			if (g_variant_is_of_type(value, G_VARIANT_TYPE("a{sv}"))) {
				OCRepPayload *repr;
				GVariantIter state_iter;
				value_list->type = OCREP_PROP_OBJECT;
				do {
					repr = OCRepPayloadCreate();
					g_variant_iter_init(&state_iter, value);
					ret = _icd_state_value_from_gvariant(repr, &state_iter);
					if (IOTCON_ERROR_NONE != ret) {
						ERR("_icd_state_value_from_gvariant() Fail(%d)", ret);
						OCRepPayloadDestroy(repr);
						return ret;
					}
					value_list->list = g_list_append(value_list->list, repr);
				} while (g_variant_iter_loop(&iter, "v", &value));

			} else if (g_variant_is_of_type(value, G_VARIANT_TYPE("ay"))) {
				OCByteString *byte_str;
				value_list->type = OCREP_PROP_BYTE_STRING;
				do {
					byte_str = calloc(1, sizeof(OCByteString));
					if (NULL == byte_str) {
						ERR("calloc() Fail(%d)", errno);
						return IOTCON_ERROR_OUT_OF_MEMORY;
					}

					byte_str->len = g_variant_get_size(value);
					byte_str->bytes = calloc(byte_str->len, sizeof(uint8_t));
					if (NULL == byte_str->bytes) {
						ERR("calloc() Fail(%d)", errno);
						free(byte_str);
						return IOTCON_ERROR_OUT_OF_MEMORY;
					}
					memcpy(byte_str->bytes, g_variant_get_data(value), byte_str->len);

					value_list->list = g_list_append(value_list->list, byte_str);
				} while (g_variant_iter_loop(&iter, "v", &value));

			} else if (g_variant_is_of_type(value, G_VARIANT_TYPE_ARRAY)) {
				do {
					ret = _icd_state_list_from_gvariant(value, value_list, depth + 1);
					if (IOTCON_ERROR_NONE != ret) {
						ERR("_icd_state_list_from_gvariant() Fail(%d)", ret);
						return ret;
					}
				} while (g_variant_iter_loop(&iter, "v", &value));
			}
		}
	}

	return IOTCON_ERROR_NONE;
}
OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
        OCEntityHandlerResponse *response, OCRepPayload** payload)
{
    OCEntityHandlerResult ehResult = OC_EH_OK;
    OCRepPayload *respPLPost_light = nullptr;

    /*
     * The entity handler determines how to process a POST request.
     * Per the REST paradigm, POST can also be used to update representation of existing
     * resource or create a new resource.
     * In the sample below, if the POST is for /a/light then a new instance of the Light
     * resource is created with default representation (if representation is included in
     * POST payload it can be used as initial values) as long as the instance is
     * lesser than max new instance count. Once max instance count is reached, POST on
     * /a/light updated the representation of /a/light (just like PUT)
     */

    if (ehRequest->resource == Light.handle)
    {
        if (gCurrLightInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
        {
            // Create new Light instance
            char newLightUri[URI_MAXSIZE];
            snprintf(newLightUri, URI_MAXSIZE, "/a/light/%d", gCurrLightInstance);

            respPLPost_light = OCRepPayloadCreate();
            OCRepPayloadSetUri(respPLPost_light, gResourceUri);
            OCRepPayloadSetPropString(respPLPost_light, "createduri", newLightUri);

            if (0 == createLightResource (newLightUri, &gLightInstance[gCurrLightInstance]))
            {
                OIC_LOG (INFO, TAG, "Created new Light instance\n");
                gLightInstance[gCurrLightInstance].state = 0;
                gLightInstance[gCurrLightInstance].power = 0;
                gCurrLightInstance++;
                strncpy ((char *)response->resourceUri, newLightUri, MAX_URI_LENGTH);
                ehResult = OC_EH_RESOURCE_CREATED;
            }
        }
        else
        {
            // Update repesentation of /a/light
            Light.state = true;
            Light.power = 11;
            respPLPost_light = constructResponse(ehRequest);
        }
    }
    else
    {
        for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
        {
            if (ehRequest->resource == gLightInstance[i].handle)
            {
                gLightInstance[i].state = true;
                gLightInstance[i].power = 22;
                if (i == 0)
                {
                    respPLPost_light = constructResponse(ehRequest);
                    break;
                }
                else if (i == 1)
                {
                    respPLPost_light = constructResponse(ehRequest);
                }
            }
        }
    }

    if ((respPLPost_light != NULL))
    {
        *payload = respPLPost_light;
    }
    else
    {
        OIC_LOG(INFO, TAG, "Payload was NULL");
        ehResult = OC_EH_ERROR;
    }

    return ehResult;
}
예제 #15
0
OCEntityHandlerResult BuzzerOCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest,
                                        void *callbackParam)
{
	OCEntityHandlerResult ehRet = OC_EH_OK;
	OCEntityHandlerResponse response = {0};
	OCRepPayload* payload = OCRepPayloadCreate();
	if(!payload) {
		OC_LOG(ERROR, TAG, ("Failed to allocate Payload"));
		return OC_EH_ERROR;
	}

	if(entityHandlerRequest && (flag & OC_REQUEST_FLAG)) {
		OC_LOG (INFO, TAG, ("Flag includes OC_REQUEST_FLAG"));

		if(OC_REST_GET == entityHandlerRequest->method) {
			OCRepPayloadSetUri(payload, "/grove/buzzer");
			OCRepPayloadSetPropInt(payload, "tone", buzzer.tone);
		} else if(OC_REST_PUT == entityHandlerRequest->method) {
			int64_t tone;
			OC_LOG(INFO, TAG, ("PUT request"));
			OCRepPayload *rep = (OCRepPayload *)entityHandlerRequest->payload;
			OCRepPayloadGetPropInt(rep, "tone", &tone);
			if(tone > 1915)
				tone = 1915;
			else if(tone < 956)
				tone = 956;
			buzzer.tone = (int)tone;
			OC_LOG_V(INFO, TAG, "Buzzer tone: %d", buzzer.tone);
			buzzer_put();
			OCRepPayloadSetPropInt(payload, "tone", buzzer.tone);
		}

		if (ehRet == OC_EH_OK) {
			// Format the response.  Note this requires some info about the request
			response.requestHandle = entityHandlerRequest->requestHandle;
			response.resourceHandle = entityHandlerRequest->resource;
			response.ehResult = ehRet;
			response.payload = (OCPayload*) payload;
			response.numSendVendorSpecificHeaderOptions = 0;
			memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
			memset(response.resourceUri, 0, sizeof response.resourceUri);
			// 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");
				ehRet = OC_EH_ERROR;
			}
		}
	}

	if (entityHandlerRequest && (flag & OC_OBSERVE_FLAG)) {
		if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action) {
			OC_LOG (INFO, TAG, ("Received OC_OBSERVE_REGISTER from client"));
			gLightUnderObservation = 1;
		} else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action) {
			OC_LOG (INFO, TAG, ("Received OC_OBSERVE_DEREGISTER from client"));
			gLightUnderObservation = 0;
		}
	}
	OCRepPayloadDestroy(payload);
	return ehRet;
}
예제 #16
0
void CHPJsonToRepPayload(cJSON* rootJSon, OCRepPayload* payload)
{
    cJSON* dataJson = rootJSon->child;
    while (dataJson)
    {
        switch (dataJson->type)
        {
            case cJSON_String:
                OCRepPayloadSetPropString(payload, dataJson->string, dataJson->valuestring);
                break;
            case cJSON_Number:
                if (dataJson->valueint == dataJson->valuedouble)
                {
                    OCRepPayloadSetPropInt(payload, dataJson->string, dataJson->valueint);
                }
                else
                {
                    OCRepPayloadSetPropDouble(payload, dataJson->string, dataJson->valuedouble);
                }
                break;
            case cJSON_False:
                OCRepPayloadSetPropBool(payload, dataJson->string, false);
                break;
            case cJSON_True:
                OCRepPayloadSetPropBool(payload, dataJson->string, true);
                break;
            case cJSON_Object:
            {
                OCRepPayload* childPayload = OCRepPayloadCreate();
                CHPJsonToRepPayload(dataJson,childPayload);
                OCRepPayloadSetPropObject(payload, dataJson->string,childPayload );
                break;
            }
            case cJSON_Array:
            {
                int size = cJSON_GetArraySize(dataJson);
                size_t dimensions[MAX_REP_ARRAY_DEPTH];
                dimensions[0] = size;
                dimensions[1] = dimensions[2] = 0;

                int i = 0;
                int type = cJSON_IsReference;
                int numType = 0;    // int:1, double:2
                const int intType = 1;
                const int doubleType = 2;

                int64_t intArray[size];
                double doubleArray[size];
                char* strArray[size];
                OCRepPayload* objPayloadArray[size];

                for (; i < size ; ++i)
                {
                    cJSON* subitem = cJSON_GetArrayItem(dataJson, i);
                    if (subitem == NULL)
                    {
                        continue;
                    }

                    if ((type != cJSON_IsReference) && (type != subitem->type))
                    {
                        continue;
                    }
                    else
                    {
                        type = subitem->type;
                        switch (type)
                        {
                            case cJSON_Number:
                                if (subitem->valueint == subitem->valuedouble)
                                {
                                    numType = intType;
                                    intArray[i] = (int64_t) subitem->valueint;
                                }
                                else
                                {
                                    numType = doubleType;
                                    doubleArray[i] = subitem->valuedouble;
                                }
                                break;
                            case cJSON_String:
                                strArray[i] = subitem->valuestring;
                                break;
                            case cJSON_Object:
                                objPayloadArray[i] = OCRepPayloadCreate();
                                CHPJsonToRepPayload(subitem,objPayloadArray[i]);
                                break;
                            default:
                                OIC_LOG(ERROR, TAG, "wrong ArrayType in JsonToRepPayload()");
                                break;
                        }
                    }
                }

                switch (type)
                {
                    case cJSON_Number:
                    if (numType == intType)
                    {
                        OCRepPayloadSetIntArray(payload, dataJson->string,(const int64_t*)intArray,
                                                dimensions);
                    }
                    else if (numType == doubleType)
                    {
                        OCRepPayloadSetDoubleArray(payload, dataJson->string,
                                                   (const double*)doubleArray,
                                                   dimensions);
                    }
                    break;
                    case cJSON_String:
                        OCRepPayloadSetStringArray(payload, dataJson->string,
                                                   (const char**)strArray,
                                                   dimensions);
                    break;
                    case cJSON_Object:
                        OCRepPayloadSetPropObjectArray(payload, dataJson->string,
                                                       (const OCRepPayload**)objPayloadArray,
                                                       dimensions);
                        break;
                  default:
                        OIC_LOG(ERROR, TAG, "wrong ArrayType in JsonToRepPayload()");
                        break;
                }
                break;
            }
        }
        dataJson = dataJson->next;
    }
}
예제 #17
0
 virtual void SetUp() {
     // Create Payload
     payload_in = OCRepPayloadCreate();
     ASSERT_TRUE(payload_in != NULL);
 }
OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
        OCEntityHandlerResponse *response, OCRepPayload **payload)
{
    OCRepPayload *respPLPost_led = NULL;
    OCEntityHandlerResult ehResult = OC_EH_OK;

    /*
     * The entity handler determines how to process a POST request.
     * Per the REST paradigm, POST can also be used to update representation of existing
     * resource or create a new resource.
     * In the sample below, if the POST is for /a/led then a new instance of the LED
     * resource is created with default representation (if representation is included in
     * POST payload it can be used as initial values) as long as the instance is
     * lesser than max new instance count. Once max instance count is reached, POST on
     * /a/led updated the representation of /a/led (just like PUT)
     */

    if (ehRequest->resource == LED.handle)
    {
        if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
        {
            // Create new LED instance
            char newLedUri[15] = "/a/led/";
            int newLedUriLength = strlen(newLedUri);
            snprintf (newLedUri + newLedUriLength, sizeof(newLedUri)-newLedUriLength, "%d", gCurrLedInstance);

            respPLPost_led = OCRepPayloadCreate();
            OCRepPayloadSetUri(respPLPost_led, gResourceUri);
            OCRepPayloadSetPropString(respPLPost_led, "createduri", newLedUri);

            if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
            {
                OIC_LOG (INFO, TAG, "Created new LED instance");
                gLedInstance[gCurrLedInstance].state = 0;
                gLedInstance[gCurrLedInstance].power = 0;
                gCurrLedInstance++;
                strncpy ((char *)response->resourceUri, newLedUri, MAX_URI_LENGTH);
                ehResult = OC_EH_RESOURCE_CREATED;
            }
        }
        else
        {
            respPLPost_led = constructResponse(ehRequest);
        }
    }
    else
    {
        for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
        {
            if (ehRequest->resource == gLedInstance[i].handle)
            {
                if (i == 0)
                {
                    respPLPost_led = constructResponse(ehRequest);
                    break;
                }
                else if (i == 1)
                {
                    respPLPost_led = constructResponse(ehRequest);
                }
            }
        }
    }

    if (respPLPost_led != NULL)
    {
        *payload = respPLPost_led;
        ehResult = OC_EH_OK;
    }
    else
    {
        OIC_LOG_V (INFO, TAG, "Payload was NULL");
        ehResult = OC_EH_ERROR;
    }

    return ehResult;
}
예제 #19
0
static OCStackResult OCParseRepPayload(OCPayload **outPayload, CborValue *root)
{
    OCStackResult ret = OC_STACK_INVALID_PARAM;
    CborError err;
    OCRepPayload *temp = NULL;
    OCRepPayload *rootPayload = NULL;
    OCRepPayload *curPayload = NULL;
    CborValue rootMap = *root;
    VERIFY_PARAM_NON_NULL(TAG, outPayload, "Invalid Parameter outPayload");
    VERIFY_PARAM_NON_NULL(TAG, root, "Invalid Parameter root");

    *outPayload = NULL;
    if (cbor_value_is_array(root))
    {
        err = cbor_value_enter_container(root, &rootMap);
    }
    while (cbor_value_is_valid(&rootMap))
    {
        temp = OCRepPayloadCreate();
        ret = OC_STACK_NO_MEMORY;
        VERIFY_PARAM_NON_NULL(TAG, temp, "Failed allocating memory");

        CborValue curVal;
        ret = OC_STACK_MALFORMED_RESPONSE;

        if (cbor_value_is_map(&rootMap))
        {
            err = cbor_value_map_find_value(&rootMap, OC_RSRVD_HREF, &curVal);
            if (cbor_value_is_valid(&curVal))
            {
                size_t len = 0;
                err = cbor_value_dup_text_string(&curVal, &temp->uri, &len, NULL);
                VERIFY_CBOR_SUCCESS(TAG, err, "Failed to find uri");
            }
        }
        // Resource types
        if (cbor_value_is_map(&rootMap))
        {
            if (CborNoError == cbor_value_map_find_value(&rootMap, OC_RSRVD_RESOURCE_TYPE, &curVal))
            {
                err =  OCParseStringLL(&rootMap, OC_RSRVD_RESOURCE_TYPE, &temp->types);
                VERIFY_CBOR_SUCCESS(TAG, err, "Failed to find rt type tag/value");
            }
        }

        // Interface Types
        if (cbor_value_is_map(&rootMap))
        {
            if (CborNoError == cbor_value_map_find_value(&rootMap, OC_RSRVD_INTERFACE, &curVal))
            {
                err =  OCParseStringLL(&rootMap, OC_RSRVD_INTERFACE, &temp->interfaces);
                VERIFY_CBOR_SUCCESS(TAG, err, "Failed to find interfaces tag/value");
            }
        }

        if (cbor_value_is_map(&rootMap))
        {
            err = OCParseSingleRepPayload(&temp, &rootMap, true);
            VERIFY_CBOR_SUCCESS(TAG, err, "Failed to parse single rep payload");
        }
        if(rootPayload == NULL)
        {
            rootPayload = temp;
            curPayload = temp;
        }
        else
        {
            curPayload->next = temp;
            curPayload = curPayload->next;
        }

        if (cbor_value_is_array(&rootMap))
        {
            err = cbor_value_advance(&rootMap);
            VERIFY_CBOR_SUCCESS(TAG, err, "Failed to advance single rep payload");
        }
    }
    *outPayload = (OCPayload *)rootPayload;
    return OC_STACK_OK;

exit:
    OCRepPayloadDestroy(temp);
    OCRepPayloadDestroy(rootPayload);
    OIC_LOG(ERROR, TAG, "CBOR error in ParseRepPayload");
    return ret;
}