Exemple #1
0
/**
 * @brief Called when a REST GET is request
 *
 * @param OCBaseResource base resource attributes
 *
 * @return result of the entityHandler
 */
 OCEntityHandlerResult getRequest(OCBaseResourceT *resource, OCRepPayload *payload)
 {
    // Get the attributes and set them.
    OCAttributeT *current = resource->attribute;
    while(current != NULL)
    {
        // Check type
        switch(current->value.dataType)
        {
        case INT:
            OCRepPayloadSetPropInt(payload, current->name, current->value.data.i);// *((int*)current->value.data));
            break;
        case DOUBLE:
            OCRepPayloadSetPropDouble(payload, current->name, current->value.data.d);// *((double*)current->value.data));
            break;
        case STRING:
            OCRepPayloadSetPropString(payload, current->name, current->value.data.str);// *((char**)current->value.data));
            break;
        case BOOL:
            OCRepPayloadSetPropBool(payload, current->name, current->value.data.b);// *((bool*)current->value.data));
            break;
        }

        current = current->next;
    }
    return OC_EH_OK;
 }
Exemple #2
0
OCStackResult OCCloudSession(const char *host, const char *query, const char *uId,
        const char *deviceId,
        const char *accesstoken,
        bool isLogin, 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 *loginoutPayload = OCRepPayloadCreate();

        if (uId != NULL)
        {
                OCRepPayloadSetPropString(loginoutPayload, "uid", uId);
        }

        if (deviceId != NULL)
        {
                OCRepPayloadSetPropString(loginoutPayload, "di", deviceId);
        }

        if (accesstoken != NULL)
        {
                OCRepPayloadSetPropString(loginoutPayload, "accesstoken", accesstoken);
        }
        OCRepPayloadSetPropBool(loginoutPayload, "login", isLogin);

        return OCDoResource(NULL, OC_REST_POST, targetUri, NULL, (OCPayload *)loginoutPayload,
                CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, NULL, 0);
}
Exemple #3
0
//This function takes the request as an input and returns the response
//in JSON format.
OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
{
    LEDResource *currLEDResource = &LED;

    OC_LOG(INFO, TAG, "Entering constructResponse");

    if (ehRequest->resource == gLedInstance[0].handle)
    {
        OC_LOG(INFO, TAG, "handle 0");
        currLEDResource = &gLedInstance[0];
        gResourceUri = const_cast<char *>("a/led/0");
    }
    else if (ehRequest->resource == gLedInstance[1].handle)
    {
        OC_LOG(INFO, TAG, "handle 1");
        currLEDResource = &gLedInstance[1];
        gResourceUri = const_cast<char *>("a/led/1");
    }

    if(OC_REST_PUT == ehRequest->method)
    {
        if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
        {
            OC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
            return nullptr;
        }

        OCRepPayload *putPayload = reinterpret_cast<OCRepPayload*> (ehRequest->payload);

        int64_t power;
        bool state;

        if (OCRepPayloadGetPropBool(putPayload, "state", &state))
        {
            currLEDResource->state = state;
        }
        if (OCRepPayloadGetPropInt (putPayload, "power", &power))
        {
            currLEDResource->power = power;
        }
    }

    OCRepPayload *response = OCRepPayloadCreate();

    if (!response)
    {
        OC_LOG_V(ERROR, TAG, "Memory allocation for response payload failed.");
    }

    OCRepPayloadSetUri (response, gResourceUri);
    OCRepPayloadSetPropBool(response, "state", currLEDResource->state);
    OCRepPayloadSetPropInt(response, "power", currLEDResource->power);

    return response;
}
OCPayload* putPayload()
{
    OCRepPayload* payload = OCRepPayloadCreate();

    if(!payload)
    {
        std::cout << "Failed to create put payload object"<<std::endl;
        std::exit(1);
    }
    OCRepPayloadSetPropInt(payload, "power", 42);
    OCRepPayloadSetPropBool(payload, "state", true);
    return (OCPayload*) payload;
}
OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
{
    OCRepPayload* payload = OCRepPayloadCreate();
    if(!payload)
    {
        OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
        return NULL;
    }

    OCRepPayloadSetUri(payload, uri);
    OCRepPayloadSetPropBool(payload, "state", state);
    OCRepPayloadSetPropInt(payload, "power", power);

    return payload;
}
OCEntityHandlerResult UpnpRenderingControl::processGetRequest(string uri, OCRepPayload *payload, string resourceType)
{
    if (payload == NULL)
    {
        throw "payload is null";
    }
    (void) resourceType;

    //TODO use async version with callback
    bool muteValue = false;
    int upnpVolumeValue = 0;
    GError *error = NULL;

    // get mute
    if (! gupnp_service_proxy_send_action(m_proxy, getMuteAction, &error,
        // IN args
        instanceIdParamName, G_TYPE_UINT, defaultInstanceID,
        channelParamName, G_TYPE_STRING, defaultChannel,
        NULL,
        // OUT args
        currentMuteParamName, G_TYPE_BOOLEAN, &muteValue,
        NULL))
    {
        ERROR_PRINT(getMuteAction << " action failed");
        if (error)
        {
            DEBUG_PRINT("Error message: " << error->message);
            g_error_free(error);
        }
        return OC_EH_ERROR;
    }

    if (!OCRepPayloadSetPropBool(payload, mutePropertyName, muteValue))
    {
        throw "Failed to set mute value in payload";
    }
    DEBUG_PRINT(mutePropertyName << ": " << (muteValue ? "true" : "false"));

    // get volume
    if (! gupnp_service_proxy_send_action(m_proxy, getVolumeAction, &error,
        // IN args
        instanceIdParamName, G_TYPE_UINT, defaultInstanceID,
        channelParamName, G_TYPE_STRING, defaultChannel,
        NULL,
        // OUT args
        currentVolumeParamName, G_TYPE_UINT, &upnpVolumeValue,
        NULL))
    {
        ERROR_PRINT(getVolumeAction << " action failed");
        if (error)
        {
            DEBUG_PRINT("Error message: " << error->message);
            g_error_free(error);
        }
        return OC_EH_ERROR;
    }

    int64_t volumeValue = upnpVolumeValue;
    if (!OCRepPayloadSetPropInt(payload, volumePropertyName, volumeValue))
    {
        throw "Failed to set volume value in payload";
    }
    DEBUG_PRINT(volumePropertyName << ": " << volumeValue);

    return UpnpService::processGetRequest(uri, payload, resourceType);
}
OCEntityHandlerResult UpnpRenderingControl::processPutRequest(OCEntityHandlerRequest *ehRequest,
        string uri, string resourceType, OCRepPayload *payload)
{
    (void) uri;
    if (!ehRequest || !ehRequest->payload ||
            ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
    {
        throw "Incoming payload is NULL or not a representation";
    }

    OCRepPayload *input = reinterpret_cast<OCRepPayload *>(ehRequest->payload);
    if (!input)
    {
        throw "PUT payload is null";
    }

    if (UPNP_OIC_TYPE_AUDIO == resourceType)
    {
        //TODO use async version with callback
        GError *error = NULL;

        // set mute
        bool muteValue = false;
        if (OCRepPayloadGetPropBool(input, mutePropertyName, &muteValue))
        {
            DEBUG_PRINT("New " << mutePropertyName << ": " << (muteValue ? "true" : "false"));
            if (! gupnp_service_proxy_send_action(m_proxy, setMuteAction, &error,
                // IN args
                instanceIdParamName, G_TYPE_UINT, defaultInstanceID,
                channelParamName, G_TYPE_STRING, defaultChannel,
                desiredMuteParamName, G_TYPE_BOOLEAN, muteValue,
                NULL,
                // OUT args (none)
                NULL))
            {
                ERROR_PRINT(setMuteAction << " action failed");
                if (error)
                {
                    DEBUG_PRINT("Error message: " << error->message);
                    g_error_free(error);
                }
                return OC_EH_ERROR;
            }

            if (!OCRepPayloadSetPropBool(payload, mutePropertyName, muteValue))
            {
                throw "Failed to set mute value in payload";
            }
            DEBUG_PRINT(mutePropertyName << ": " << (muteValue ? "true" : "false"));
        }

        // set volume
        int64_t volumeValue = 0;
        if (OCRepPayloadGetPropInt(input, volumePropertyName, &volumeValue))
        {
            DEBUG_PRINT("New " << volumePropertyName << ": " << volumeValue);
            int upnpVolumeValue = volumeValue;
            if (! gupnp_service_proxy_send_action(m_proxy, setVolumeAction, &error,
                // IN args
                instanceIdParamName, G_TYPE_UINT, defaultInstanceID,
                channelParamName, G_TYPE_STRING, defaultChannel,
                desiredVolumeParamName, G_TYPE_UINT, upnpVolumeValue,
                NULL,
                // OUT args (none)
                NULL))
            {
                ERROR_PRINT(setVolumeAction << " action failed");
                if (error)
                {
                    DEBUG_PRINT("Error message: " << error->message);
                    g_error_free(error);
                }
                return OC_EH_ERROR;
            }

            if (!OCRepPayloadSetPropInt(payload, volumePropertyName, volumeValue))
            {
                throw "Failed to set volume value in payload";
            }
            DEBUG_PRINT(volumePropertyName << ": " << volumeValue);
        }
    }
    else
    {
        throw "Failed due to unknown resource type";
    }

    return OC_EH_OK;
}
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;
        }
    }
Exemple #9
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;
}
Exemple #10
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;
}
Exemple #11
0
 /**
 * @brief Called when a REST PUT is request
 *
 * @param OCBaseResource base resource attributes
 *
 * @return result of the entityHandler
 */
 OCEntityHandlerResult putRequest(OCEntityHandlerRequest *ehRequest, OCRepPayload* payload, OCBaseResourceT *resource)
 {
    // Set the new states
    OCRepPayload* inputPayload = (OCRepPayload*)(ehRequest->payload);

    OCAttributeT *current = resource->attribute;
    while(current != NULL)
    {
        switch(current->value.dataType)
        {
        case INT:
        {
            int64_t value(0);
            if(OCRepPayloadGetPropInt(inputPayload, current->name, &value))
            {
                //OIC_LOG_V(DEBUG, TAG, "PUT: Type is int: %i", (int) value);
                //*((int*)current->value.data) = (int) value;
                current->value.data.i = value;
            }
            OCRepPayloadSetPropInt(payload, current->name, value);
            break;
        }
        case DOUBLE:
        {
            double value(0);
            if(OCRepPayloadGetPropDouble(inputPayload, current->name, &value))
            {
                //OIC_LOG_V(DEBUG, TAG, "PUT: type is double: &d", value);
                //*((double*)current->value.data) = value;
                current->value.data.d = value;
            }
            OCRepPayloadSetPropDouble(payload, current->name, value);
            break;
        }
        case STRING:
        {
            char* value("");
            if(OCRepPayloadGetPropString(inputPayload, current->name, &value))
            {
                //OIC_LOG_V(DEBUG, TAG, "PUT: type is string: %s", value);
                //*((char**)current->value.data) = value;
                current->value.data.str = value;
            }
            OCRepPayloadSetPropString(payload, current->name, value);
        }
        case BOOL:
        {
            bool value(false);
            if(OCRepPayloadGetPropBool(inputPayload, current->name, &value))
            {
                //OIC_LOG_V(DEBUG, TAG, "PUT: Type is bool: %s", value ? "true" : "false");
                //*((bool*)current->value.data) = value;
                current->value.data.b = value;
            }
            OCRepPayloadSetPropBool(payload, current->name, value);
            break;
        }

        }

        current = current->next;
    }

    // Set the output pins
    if(resource->OCIOhandler)
    {
        OIC_LOG_V(DEBUG, TAG, "Value of underObservation is: %s", resource->underObservation ? "true" : "false");
        resource->OCIOhandler(resource->attribute, OUTPUT, resource->handle, &resource->underObservation);
    }
    else
    {
        OIC_LOG(ERROR, TAG, "Resource OutputHandler has not been set");
    }

    OIC_LOG(DEBUG, TAG, "Leaving putRequest");

    return OC_EH_OK;
 }
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 bool add_property_in_post_req_msg(st_things_set_request_message_s *req_msg, OCRepPayload *req_payload, things_attribute_info_s *prop)
{
	RET_FALSE_IF_PARAM_IS_NULL(TAG, req_msg);
	RET_FALSE_IF_PARAM_IS_NULL(TAG, req_msg->rep);
	RET_FALSE_IF_PARAM_IS_NULL(TAG, req_msg->rep->payload);
	RET_FALSE_IF_PARAM_IS_NULL(TAG, req_payload);
	RET_FALSE_IF_PARAM_IS_NULL(TAG, prop);

	OCRepPayload *resp_payload = req_msg->rep->payload;

	THINGS_LOG_D(TAG, "Property Key is %s", prop->key);
	THINGS_LOG_D(TAG, "Property type is %d", prop->type);

	// Based on the property type, call appropriate methods to copy
	// the property from request payload to request representation.
	bool result = false;
	switch (prop->type) {
	case BOOL_ID: {
		bool value = false;
		if (OCRepPayloadGetPropBool(req_payload, prop->key, &value)) {
			result = OCRepPayloadSetPropBool(resp_payload, prop->key, value);
			if (!result) {
				THINGS_LOG_E(TAG, "Failed to set the boolean value of '%s' in request message.", prop->key);
			}
		} else {
			THINGS_LOG_E(TAG, "Failed to get the boolean value of '%s' for request message.", prop->key);
		}
	}
	break;
	case INT_ID: {
		int64_t value = 0;
		if (OCRepPayloadGetPropInt(req_payload, prop->key, &value)) {
			result = OCRepPayloadSetPropInt(resp_payload, prop->key, value);
			if (!result) {
				THINGS_LOG_E(TAG, "Failed to set the integer value of '%s' in request message", prop->key);
			}
		} else {
			THINGS_LOG_E(TAG, "Failed to get the integer value of '%s' for request message", prop->key);
		}
	}
	break;
	case DOUBLE_ID: {
		double value = 0.0;
		if (OCRepPayloadGetPropDouble(req_payload, prop->key, &value)) {
			result = OCRepPayloadSetPropDouble(resp_payload, prop->key, value);
			if (!result) {
				THINGS_LOG_E(TAG, "Failed to set the double value of '%s' in request message", prop->key);
			}
		} else {
			THINGS_LOG_E(TAG, "Failed to get the double value of '%s' for request message", prop->key);
		}
	}
	break;
	case STRING_ID: {
		char *value = NULL;
		if (OCRepPayloadGetPropString(req_payload, prop->key, &value)) {
			result = OCRepPayloadSetPropString(resp_payload, prop->key, value);
			if (!result) {
				THINGS_LOG_E(TAG, "Failed to set the string value of '%s' in request message", prop->key);
			}

			things_free(value);
		} else {
			THINGS_LOG_E(TAG, "Failed to get the string value of '%s' for request message", prop->key);
		}
	}
	break;
	case OBJECT_ID: {
		OCRepPayload *value = NULL;
		if (OCRepPayloadGetPropObject(req_payload, prop->key, &value)) {
			result = OCRepPayloadSetPropObject(resp_payload, prop->key, value);
			if (!result) {
				THINGS_LOG_E(TAG, "Failed to set the object value of '%s' in request message", prop->key);
			}

			OCRepPayloadDestroy(value);
		} else {
			THINGS_LOG_E(TAG, "Failed to get the object value of '%s' for request message", prop->key);
		}
	}
	break;
	case BYTE_ID: {
		OCByteString byte_value;
		if (OCRepPayloadGetPropByteString(req_payload, prop->key, &byte_value)) {
			result = OCRepPayloadSetPropByteString(resp_payload, prop->key, byte_value);
			if (!result) {
				THINGS_LOG_E(TAG, "Failed to set the byte string value of '%s' in request message", prop->key);
			}

			things_free(byte_value.bytes);
		} else {
			THINGS_LOG_E(TAG, "Failed to get the byte string value of '%s' for request message", prop->key);
		}
	}
	break;
	case INT_ARRAY_ID: {
		int64_t *value = NULL;
		size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
		if (OCRepPayloadGetIntArray(req_payload, prop->key, &value, dimensions)) {
			result = OCRepPayloadSetIntArray(resp_payload, prop->key, value, dimensions);
			if (!result) {
				THINGS_LOG_E(TAG, "Failed to set the integer array value of '%s' in request message", prop->key);
			}

			things_free(value);
		} else {
			THINGS_LOG_E(TAG, "Failed to get the integer array value of '%s' for request message", prop->key);
		}
	}
	break;
	case DOUBLE_ARRAY_ID: {
		double *value = NULL;
		size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
		if (OCRepPayloadGetDoubleArray(req_payload, prop->key, &value, dimensions)) {
			result = OCRepPayloadSetDoubleArray(resp_payload, prop->key, value, dimensions);
			if (!result) {
				THINGS_LOG_E(TAG, "Failed to set the double array value of '%s' in request message", prop->key);
			}

			things_free(value);
		} else {
			THINGS_LOG_E(TAG, "Failed to get the double array value of '%s' for request message", prop->key);
		}
	}
	break;
	case STRING_ARRAY_ID: {
		char **value = NULL;
		size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
		if (OCRepPayloadGetStringArray(req_payload, prop->key, &value, dimensions)) {
			result = OCRepPayloadSetStringArray(resp_payload, prop->key, value, dimensions);
			if (!result) {
				THINGS_LOG_E(TAG, "Failed to set the string array value of '%s' in request message", prop->key);
			}

			size_t len = calcDimTotal(dimensions);
			things_free_str_array(value, len);
		} else {
			THINGS_LOG_E(TAG, "Failed to get the string array value of '%s' for request message", prop->key);
		}
	}
	break;
	case OBJECT_ARRAY_ID: {
		OCRepPayload **value = NULL;
		size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
		if (OCRepPayloadGetPropObjectArray(req_payload, prop->key, &value, dimensions)) {
			result = OCRepPayloadSetPropObjectArray(resp_payload, prop->key, value, dimensions);
			if (!result) {
				THINGS_LOG_E(TAG, "Failed to set the object array value of '%s' in request message", prop->key);
			}

			size_t len = calcDimTotal(dimensions);
			for (size_t index = 0; index < len; index++) {
				OCRepPayloadDestroy(value[index]);
			}
			things_free(value);
		} else {
			THINGS_LOG_E(TAG, "Failed to get the object array value of '%s' for request message", prop->key);
		}
	}
	break;
	default:
		THINGS_LOG_E(TAG, "Invalid property type (%d).", prop->type);
		break;
	}

	return result;
}
Exemple #14
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;
    }
}
Exemple #15
0
void things_set_bool_value(struct things_representation_s *rep, char *key, bool value)
{
	OCRepPayloadSetPropBool(rep->payload, key, value);
}
Exemple #16
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;
}