Exemple #1
0
// send notifications based on the qos of the request
// The qos passed as a parameter overrides what the client requested
// If we want the client preference taking high priority make:
// qos = resourceObserver->qos;
OCQualityOfService DetermineObserverQoS(OCMethod method, ResourceObserver * resourceObserver,
        OCQualityOfService appQoS)
{
    OCQualityOfService decidedQoS = appQoS;
    if(appQoS == OC_NA_QOS)
    {
        decidedQoS = resourceObserver->qos;
    }

    if(appQoS != OC_HIGH_QOS)
    {
        OC_LOG_V(INFO, TAG, "Current NON count for this observer is %d",
                resourceObserver->lowQosCount);
        #ifdef WITH_PRESENCE
        if((resourceObserver->forceHighQos \
                || resourceObserver->lowQosCount >= MAX_OBSERVER_NON_COUNT) \
                && method != OC_REST_PRESENCE)
        #else
        if(resourceObserver->forceHighQos \
                || resourceObserver->lowQosCount >= MAX_OBSERVER_NON_COUNT)
        #endif
            {
            resourceObserver->lowQosCount = 0;
            // at some point we have to to send CON to check on the
            // availability of observer
            OC_LOG(INFO, TAG, PCF("This time we are sending the  notification as High qos"));
            decidedQoS = OC_HIGH_QOS;
            }
        else
        {
            (resourceObserver->lowQosCount)++;
        }
    }
    return decidedQoS;
}
Exemple #2
0
// The loop function is called in an endless loop
void loop()
{
    // This artificial delay is kept here to avoid endless spinning
    // of Arduino microcontroller. Modify it as per specfic application needs.

    if (OCProcess() != OC_STACK_OK)
    {
        OC_LOG(ERROR, TAG, PCF("OCStack process error"));
        return;
    }

    char *user_cmd = NULL;

//  ble.pollingDisconnect();

    user_cmd = ble.Debug2BLE(true);
    ble.BLE2Debug( true );

    if ( user_cmd )
    {
        free( user_cmd );
        user_cmd = NULL;
    }

}
        void RCSRemoteResourceObject::startCaching(CacheUpdatedCallback cb)
        {
            SCOPE_LOG_F(DEBUG, TAG);

            if (isCaching())
            {
                OC_LOG(DEBUG, TAG, "startCaching : already Started");
                throw RCSBadRequestException{ "Caching already started." };
            }

            if (cb)
            {
                m_cacheId = ResourceCacheManager::getInstance()->requestResourceCache(
                        m_primitiveResource,
                        std::bind(cachingCallback, std::placeholders::_1, std::placeholders::_2,
                                std::move(cb)), REPORT_FREQUENCY::UPTODATE, 0);
            }
            else
            {
                m_cacheId = ResourceCacheManager::getInstance()->requestResourceCache(
                        m_primitiveResource, { }, REPORT_FREQUENCY::NONE, 0);
            }

            OC_LOG_V(DEBUG, TAG, "startCaching CACHE ID %d", m_cacheId);
        }
Exemple #4
0
// This is a function called back when a device is discovered
OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle /*handle*/,
                                        OCClientResponse * clientResponse)
{
    OC_LOG(INFO, TAG,
            "Entering discoveryReqCB (Application Layer CB)");
    OC_LOG_V(INFO, TAG, "StackResult: %s",
            getResult(clientResponse->result));

    if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
    {
        OC_LOG_V(INFO, TAG, "Callback Context recvd successfully");
    }

    OC_LOG_V(INFO, TAG,
            "Device =============> Discovered @ %s:%d",
            clientResponse->devAddr.addr,
            clientResponse->devAddr.port);
    OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);

    ConnType = clientResponse->connType;

    if(TestType == TEST_UNKNOWN_RESOURCE_GET_DEFAULT || TestType == TEST_UNKNOWN_RESOURCE_GET_BATCH ||\
            TestType == TEST_UNKNOWN_RESOURCE_GET_LINK_LIST)
    {
        InitGetRequestToUnavailableResource(clientResponse);
    }
    else
    {
        InitGetRequest(clientResponse);
    }
    return OC_STACK_KEEP_TRANSACTION;
}
Exemple #5
0
/**
 * This internal method is the entity handler for pstat resources.
 */
OCEntityHandlerResult PstatEntityHandler(OCEntityHandlerFlag flag,
        OCEntityHandlerRequest * ehRequest,
        void *callbackParam)
{
    OCEntityHandlerResult ehRet = OC_EH_ERROR;
    // This method will handle REST request (GET/POST) for /oic/sec/pstat
    if (flag & OC_REQUEST_FLAG)
    {
        OC_LOG (INFO, TAG, PCF("Flag includes OC_REQUEST_FLAG"));
        switch (ehRequest->method)
        {
            case OC_REST_GET:
                ehRet = HandlePstatGetRequest(ehRequest);
                break;
            case OC_REST_PUT:
                ehRet = HandlePstatPutRequest(ehRequest);
                break;
            default:
                ehRet = OC_EH_ERROR;
                SendSRMResponse(ehRequest, ehRet, NULL);
                break;
        }
    }
    return ehRet;
}
Exemple #6
0
int InitObserveRequest(OCClientResponse * clientResponse)
{
    OCStackResult ret;
    OCCallbackData cbData;
    OCDoHandle handle;
    std::ostringstream obsReg;
    obsReg << getQueryStrForGetPut();
    cbData.cb = getReqCB;
    cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
    cbData.cd = NULL;
    OC_LOG_V(INFO, TAG, "OBSERVE payload from client =");
    OCPayload* payload = putPayload();
    OC_LOG_PAYLOAD(INFO, TAG, payload);
    OCPayloadDestroy(payload);

    ret = OCDoResource(&handle, OC_REST_OBSERVE, obsReg.str().c_str(),
                       &clientResponse->devAddr, 0, ConnType,
                       OC_LOW_QOS, &cbData, NULL, 0);
    if (ret != OC_STACK_OK)
    {
        OC_LOG(ERROR, TAG, "OCStack resource error");
    }
    else
    {
        gObserveDoHandle = handle;
    }
    return ret;
}
Exemple #7
0
/**
 * Initialize DOXM resource by loading data from persistent storage.
 *
 * @retval  OC_STACK_OK for Success, otherwise some error value
 */
OCStackResult InitDoxmResource()
{
    OCStackResult ret = OC_STACK_ERROR;

    //Read DOXM resource from PS
    char* jsonSVRDatabase = GetSVRDatabase();
    if(jsonSVRDatabase)
    {
        //Convert JSON DOXM into binary format
        gDoxm = JSONToDoxmBin(jsonSVRDatabase, true);
    }
    /*
     * If SVR database in persistent storage got corrupted or
     * is not available for some reason, a default doxm is created
     * which allows user to initiate doxm provisioning again.
     */
    if(!jsonSVRDatabase || !gDoxm)
    {
        gDoxm = GetDoxmDefault();
    }
    ret = CheckDeviceID();
    if (ret == OC_STACK_OK)
    {
        //Instantiate 'oic.sec.doxm'
        ret = CreateDoxmResource();
    }
    else
    {
        OC_LOG (ERROR, TAG, "CheckDeviceID failed");
    }
    OICFree(jsonSVRDatabase);
    return ret;
}
Exemple #8
0
/*
 * This internal method is the entity handler for DOXM resources.
 */
OCEntityHandlerResult DoxmEntityHandler (OCEntityHandlerFlag flag,
                                        OCEntityHandlerRequest * ehRequest,
                                        void* callbackParam)
{
    (void)callbackParam;
    OCEntityHandlerResult ehRet = OC_EH_ERROR;

    if(NULL == ehRequest)
    {
        return ehRet;
    }


    if (flag & OC_REQUEST_FLAG)
    {
        OC_LOG (DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
        switch (ehRequest->method)
        {
            case OC_REST_GET:
                ehRet = HandleDoxmGetRequest(ehRequest);
                break;

            case OC_REST_PUT:
                ehRet = HandleDoxmPutRequest(ehRequest);
                break;

            default:
                ehRet = OC_EH_ERROR;
                SendSRMResponse(ehRequest, ehRet, NULL);
                break;
        }
    }

    return ehRet;
}
OCRepPayload* constructResponse(OCEntityHandlerRequest *ehRequest)
{
    OCRepPayload* payload = OCRepPayloadCreate();
    if (!payload)
    {
        OC_LOG(ERROR, ES_RH_TAG, "Failed to allocate Payload");
        return NULL;
    }

    if (ehRequest->resource == g_prov.handle)
    {
        OCRepPayloadSetUri(payload, OC_RSRVD_ES_URI_PROV);
        OCRepPayloadSetPropInt(payload, OC_RSRVD_ES_PS, g_prov.ps);
        OCRepPayloadSetPropInt(payload, OC_RSRVD_ES_TNT, g_prov.tnt);
        OCRepPayloadSetPropString(payload, OC_RSRVD_ES_TNN, g_prov.tnn);
        OCRepPayloadSetPropString(payload, OC_RSRVD_ES_CD, g_prov.cd);
    }
    else if (ehRequest->requestHandle == g_net.handle)
    {

        OCRepPayloadSetUri(payload, OC_RSRVD_ES_URI_NET);
        OCRepPayloadSetPropInt(payload, "ant", g_net.ant[0]);
    }
    return payload;
}
Exemple #10
0
OCStackApplicationResult getReqCB(void* ctx, OCDoHandle /*handle*/,
                                  OCClientResponse * clientResponse)
{
    OC_LOG_V(INFO, TAG, "StackResult: %s",
            getResult(clientResponse->result));
    if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
    {
        OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
        if(clientResponse->sequenceNumber == 0)
        {
            OC_LOG_V(INFO, TAG, "Callback Context for GET query recvd successfully");
            OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
        }
        else
        {
            OC_LOG_V(INFO, TAG, "Callback Context for Get recvd successfully %d",
                    gNumObserveNotifies);
            OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);;
            gNumObserveNotifies++;
            if (gNumObserveNotifies == 3)
            {
                if (OCCancel (gObserveDoHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK)
                {
                    OC_LOG(ERROR, TAG, "Observe cancel error");
                }
            }
        }
    }
    if(TestType == TEST_PUT_DEFAULT || TestType == TEST_PUT_BATCH || TestType == TEST_PUT_LINK_LIST)
    {
        InitPutRequest(clientResponse);
    }
    return OC_STACK_KEEP_TRANSACTION;
}
Exemple #11
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 )
{
    OCEntityHandlerResult ehRet = OC_EH_OK;

    if (entityHandlerRequest )
    {
        if (flag & OC_REQUEST_FLAG)
        {
            OC_LOG (INFO, TAG, PCF("Flag includes OC_REQUEST_FLAG"));
            if (OC_REST_GET == entityHandlerRequest->method)
            {
                if ( JsonGenerator( (char *)entityHandlerRequest->resJSONPayload,
                                    entityHandlerRequest->resJSONPayloadLen ) == false )
                {
                    ehRet  = OC_EH_ERROR;
                }
            }
            if (OC_REST_PUT == entityHandlerRequest->method)
            {
                if (JsonGenerator( (char *)entityHandlerRequest->resJSONPayload,
                                   entityHandlerRequest->resJSONPayloadLen ) == false )
                {
                    ehRet  = OC_EH_ERROR;
                }
            }

        }
        else if (flag & OC_OBSERVE_FLAG)
        {
            OC_LOG (INFO, TAG, PCF("Flag includes OC_OBSERVE_FLAG"));
            if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo->action)
            {
                OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_REGISTER from client"));
                g_PROXIUnderObservation = 1;
            }
            else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo->action)
            {
                OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_DEREGISTER from client"));
            }
        }

        Serial.println((char *)entityHandlerRequest->resJSONPayload);
    }

    return ehRet;
}
Exemple #12
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 )
{
    OCEntityHandlerResult ehRet = OC_EH_OK;

    if (entityHandlerRequest && (flag & OC_REQUEST_FLAG))
    {
        OC_LOG (INFO, TAG, PCF("Flag includes OC_REQUEST_FLAG"));
        if (OC_REST_GET == entityHandlerRequest->method)
        {
            if (JsonGenerator((char *)entityHandlerRequest->resJSONPayload, \
                              entityHandlerRequest->resJSONPayloadLen))
            {
            }
            else
            {
                ehRet = OC_EH_ERROR;
            }
        }
        if (OC_REST_PUT == entityHandlerRequest->method)
        {
            //Do something with the 'put' payload
            if (JsonGenerator((char *)entityHandlerRequest->resJSONPayload, \
                              entityHandlerRequest->resJSONPayloadLen))
            {
            }
            else
            {
                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"));
            g_PROXIUnderObservation = 1;
        }
        else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo->action)
        {
            OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_DEREGISTER from client"));
        }
    }

    return ehRet;
}
/**
 * Function to save the result of provisioning.
 *
 * @param[in,out] otmCtx   Context value of ownership transfer.
 * @param[in] res   result of provisioning
 */
static void SetResult(OTMContext_t* otmCtx, const OCStackResult res)
{
    OC_LOG_V(DEBUG, TAG, "IN SetResult : %d ", res);

    if(!otmCtx)
    {
        OC_LOG(WARNING, TAG, "OTMContext is NULL");
        return;
    }

    if(otmCtx->selectedDeviceInfo)
    {
        for(size_t i = 0; i < otmCtx->ctxResultArraySize; i++)
        {
            if(memcmp(otmCtx->selectedDeviceInfo->doxm->deviceID.id,
                      otmCtx->ctxResultArray[i].deviceId.id, UUID_LENGTH) == 0)
            {
                otmCtx->ctxResultArray[i].res = res;
                if(OC_STACK_OK != res)
                {
                    otmCtx->ctxHasError = true;
                }
            }
        }

        g_otmCtx = NULL;

        //If all request is completed, invoke the user callback.
        if(IsComplete(otmCtx))
        {
            otmCtx->ctxResultCallback(otmCtx->userCtx, otmCtx->ctxResultArraySize,
                                       otmCtx->ctxResultArray, otmCtx->ctxHasError);
            OICFree(otmCtx->ctxResultArray);
            OICFree(otmCtx);
        }
        else
        {
            if(OC_STACK_OK != StartOwnershipTransfer(otmCtx,
                                                     otmCtx->selectedDeviceInfo->next))
            {
                OC_LOG(ERROR, TAG, "Failed to StartOwnershipTransfer");
            }
        }
    }

    OC_LOG(DEBUG, TAG, "OUT SetResult");
}
int InitDiscovery()
{
    OCStackResult ret;
    OCCallbackData cbData;
    /* Start a discovery query*/
    char szQueryUri[64] = {};
    if (UNICAST_DISCOVERY)
    {
        char ipv4addr[IPV4_ADDR_SIZE];
        printf("Enter IPv4 address of the Server hosting "
               "resource (Ex: 192.168.0.15)\n");
        if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
        {
            //Strip newline char from ipv4addr
            StripNewLineChar(ipv4addr);
            snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_DISCOVERY_QUERY, ipv4addr);
        }
        else
        {
            OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
            return OC_STACK_INVALID_PARAM;
        }
    }
    else
    {
        strcpy(szQueryUri, MULTICAST_RESOURCE_DISCOVERY_QUERY);
    }
    cbData.cb = discoveryReqCB;
    cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
    cbData.cd = NULL;
    if (UNICAST_DISCOVERY)
    {
        ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_CONNTYPE,
                OC_LOW_QOS, &cbData, NULL, 0);
    }
    else
    {
        ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, (OC_ALL),
                OC_LOW_QOS, &cbData, NULL, 0);
    }

    if (ret != OC_STACK_OK)
    {
        OC_LOG(ERROR, TAG, "OCStack resource error");
    }
    return ret;
}
Exemple #15
0
static OCStackApplicationResult AmsMgrDiscoveryCallback(void *ctx, OCDoHandle handle,
                         OCClientResponse * clientResponse)
{
    OC_LOG_V(INFO, TAG, "%s Begin", __func__ );

    if (!ctx ||
        !clientResponse ||
        !clientResponse->payload||
        (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)||
        (OC_STACK_OK != clientResponse->result))
    {
        OC_LOG_V(ERROR, TAG, "%s Invalid Response ", __func__);
        return OC_STACK_KEEP_TRANSACTION;
    }

    (void)handle;
    PEContext_t *context = (PEContext_t *) ctx;
    if (context->state != AWAITING_AMS_RESPONSE)
    {
        OC_LOG_V(ERROR, TAG, "%s Invalid PE State ", __func__);
        return OC_STACK_DELETE_TRANSACTION;
    }

    OicSecDoxm_t *doxm = NULL;
    OC_LOG_V(INFO, TAG, "Doxm DeviceId Discovery response = %s\n",
          ((OCSecurityPayload*)clientResponse->payload)->securityData);
    doxm = JSONToDoxmBin(((OCSecurityPayload*)clientResponse->payload)->securityData);

    //As doxm is NULL amsmgr can't test if response from trusted AMS service
    //so keep the transaction.
    if(NULL == doxm)
    {
        OC_LOG_V(ERROR, TAG, "%s : Unable to convert JSON to Binary",__func__);
        return OC_STACK_KEEP_TRANSACTION;
    }

    OicUuid_t deviceId = {.id={}};
    memcpy(&deviceId, &doxm->deviceID, sizeof(deviceId));
    OICFree(doxm);

    /* TODO : By assuming that the first response received is the actual
     * AMS service, a 'bad device' can cause DoS attack.
     */
    if (memcmp(&context->amsMgrContext->amsDeviceId, &deviceId,
            sizeof(context->amsMgrContext->amsDeviceId)) == 0)
    {
        OC_LOG(INFO, TAG, "AMS Manager Sending unicast discovery to get secured port info");
        //Sending Unicast discovery to get secure port information
        if(OC_STACK_OK == SendUnicastSecurePortDiscovery(context, &clientResponse->devAddr,
                clientResponse->connType))
        {
            context->retVal = ACCESS_WAITING_FOR_AMS;
            return OC_STACK_DELETE_TRANSACTION;
        }
    }
    context->retVal = ACCESS_DENIED_AMS_SERVICE_ERROR;
    SRMSendResponse(context->retVal);
    return OC_STACK_DELETE_TRANSACTION;
}
Exemple #16
0
OCTagsPayload* OCCopyTagsResources(const char *deviceName, const unsigned char *id, const char *baseURI,
        uint8_t bitmap, uint16_t port, uint8_t ins, const char *rts,const  char *drel, uint32_t ttl)
{
    OCTagsPayload *tags = (OCTagsPayload *)OICCalloc(1, sizeof(OCTagsPayload));
    if (!tags)
    {
        return NULL;
    }
	if (deviceName)
    {
        tags->n.deviceName = OICStrdup(deviceName);
        if (!tags->n.deviceName)
        {
            goto memory_allocation_failed;
        }
    }
    if (id)
    {
        OICStrcpy((char*)tags->di.id, MAX_IDENTITY_SIZE, (char *)id);
        if (!tags->di.id)
        {
            goto memory_allocation_failed;
        }
    }
    if (baseURI)
    {
        tags->baseURI = OICStrdup(baseURI);
        if (!tags->baseURI)
        {
            goto memory_allocation_failed;
        }
    }
    tags->bitmap = bitmap;
    tags->port = port;
    tags->ins = ins;
    if (rts)
    {
        tags->rts = OICStrdup(rts);
        if (!tags->rts)
        {
            goto memory_allocation_failed;
        }
    }
    if (drel)
    {
        tags->drel = OICStrdup(drel);
        if (!tags->drel)
        {
            goto memory_allocation_failed;
        }
    }
    tags->ttl = ttl;
    return tags;

memory_allocation_failed:
    OC_LOG(ERROR, TAG, "Memory allocation failed.");
    OCFreeTagsResource(tags);
    return NULL;
}
void SimulatorRemoteResourceImpl::observe(ObserveType type,
        ObserveNotificationCallback callback)
{
    if (!callback)
    {
        OC_LOG(ERROR, TAG, "Invalid callback!");
        throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
    }

    std::lock_guard<std::mutex> lock(m_observeMutex);
    if (m_observeState)
    {
        OC_LOG(WARNING, TAG, "Resource already in observe state !");
        throw SimulatorException(SIMULATOR_ERROR, "Resource is already being observed!");
    }

    OC::ObserveCallback observeCallback = [this, callback](const OC::HeaderOptions & headerOptions,
                                          const OC::OCRepresentation & rep, const int errorCode,
                                          const int sequenceNum)
    {
        // Convert OCRepresentation to SimulatorResourceModel
        SimulatorResourceModelSP repModel = SimulatorResourceModel::create(rep);
        callback(m_id, static_cast<SimulatorResult>(errorCode), repModel, sequenceNum);
    };

    OC::ObserveType observeType = OC::ObserveType::Observe;
    if (type == ObserveType::OBSERVE_ALL)
    {
        observeType = OC::ObserveType::ObserveAll;
    }

    try
    {
        OCStackResult ocResult = m_ocResource->observe(observeType, OC::QueryParamsMap(), observeCallback);
        if (OC_STACK_OK != ocResult)
        {
            throw SimulatorException(static_cast<SimulatorResult>(ocResult), OC::OCException::reason(ocResult));
        }
    }
    catch (OC::OCException &e)
    {
        throw SimulatorException(static_cast<SimulatorResult>(e.code()), e.reason());
    }

    m_observeState = true;
}
Exemple #18
0
void ocInitialize () {
    char ipAddr[16] = "";
    OCGetInterfaceAddress (NULL, 0, AF_INET, (uint8_t *)ipAddr, 16);
    OC_LOG(DEBUG, TAG, PCF("IP addr is:"));
    OC_LOG_BUFFER(INFO, TAG, (uint8_t*)ipAddr, sizeof(ipAddr));
    delay(2000);
    OCInit (ipAddr, 8001, OC_SERVER);
}
Exemple #19
0
OCEntityHandlerResult OCEntityHandlerCb (OCEntityHandlerFlag flag,
        OCEntityHandlerRequest *entityHandlerRequest, void* callbackParam)
{
    OCEntityHandlerResult result = OC_EH_ERROR;
    OCEntityHandlerRequest *request = NULL;

    OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);

    if (flag & OC_REQUEST_FLAG)
    {
        OC_LOG(INFO, TAG, "Flag includes OC_REQUEST_FLAG");
        if (entityHandlerRequest)
        {
            OC_LOG_V (INFO, TAG, "request query %s from client",
                                        entityHandlerRequest->query);
            OC_LOG_PAYLOAD (INFO, TAG, entityHandlerRequest->payload);

            // Make deep copy of received request and queue it for slow processing
            request = CopyRequest(entityHandlerRequest);

            if (request)
            {

                OC_LOG(INFO, TAG, "Scheduling slow response for received request");
                gRequestList.push_back(request);
                // Indicate to the stack that this is a slow response
                result = OC_EH_SLOW;
                // Start the slow response alarm
                alarm(SLOW_RESPONSE_DELAY_SEC);
            }
            else
            {
                OC_LOG(ERROR, TAG, "Error queuing request for slow response");
                // Indicate to the stack that this is a slow response
                result = OC_EH_ERROR;
            }
        }
        else
        {
            OC_LOG(ERROR, TAG, "Invalid request");
            result = OC_EH_ERROR;
        }
    }
    return result;
}
Exemple #20
0
OCEntityHandlerRequest *CopyRequest(OCEntityHandlerRequest *entityHandlerRequest)
{
    OC_LOG(INFO, TAG, "Copying received request for slow response");

    OCEntityHandlerRequest *copyOfRequest =
            (OCEntityHandlerRequest *)OICMalloc(sizeof(OCEntityHandlerRequest));

    if (copyOfRequest)
    {
        // Do shallow copy
        memcpy(copyOfRequest, entityHandlerRequest, sizeof(OCEntityHandlerRequest));


        if (copyOfRequest->query)
        {
            copyOfRequest->query = OICStrdup(entityHandlerRequest->query);
            if(!copyOfRequest->query)
            {
                OC_LOG(ERROR, TAG, "Copy failed due to allocation failure");
                OICFree(copyOfRequest);
                return NULL;
            }
        }

        if (entityHandlerRequest->payload)
        {
            copyOfRequest->payload = reinterpret_cast<OCPayload*>
                    (OCRepPayloadClone ((OCRepPayload*) entityHandlerRequest->payload));
        }

        // Ignore vendor specific header options for example
        copyOfRequest->numRcvdVendorSpecificHeaderOptions = 0;
        copyOfRequest->rcvdVendorSpecificHeaderOptions = NULL;
    }

    if (copyOfRequest)
    {
        OC_LOG(INFO, TAG, "Copied client request");
    }
    else
    {
        OC_LOG(ERROR, TAG, "Error copying client request");
    }
    return copyOfRequest;
}
void printResourceList()
{
    ResourceNode * iter;
    iter = resourceList;
    OC_LOG(INFO, TAG, "Resource List: ");
    while(iter)
    {
        OC_LOG(INFO, TAG, "*****************************************************");
        OC_LOG_V(INFO, TAG, "sid = %s",iter->sid);
        OC_LOG_V(INFO, TAG, "uri = %s", iter->uri);
        OC_LOG_V(INFO, TAG, "ip = %s", iter->endpoint.addr);
        OC_LOG_V(INFO, TAG, "port = %d", iter->endpoint.port);
        switch (iter->endpoint.adapter)
        {
            case OC_ADAPTER_IP:
                OC_LOG(INFO, TAG, "connType = Default (IPv4)");
                break;
            case OC_ADAPTER_GATT_BTLE:
                OC_LOG(INFO, TAG, "connType = BLE");
                break;
            case OC_ADAPTER_RFCOMM_BTEDR:
                OC_LOG(INFO, TAG, "connType = BT");
                break;
            default:
                OC_LOG(INFO, TAG, "connType = Invalid connType");
                break;
        }
        OC_LOG(INFO, TAG, "*****************************************************");
        iter = iter->next;
    }
}
/**
 * function to create DB in case DB doesn't exists
 */
static OCStackResult createDB(const char* path)
{

    int result = 0;
    result = sqlite3_open_v2(path, &g_db, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, NULL);
    PDM_VERIFY_SQLITE_OK(TAG, result, ERROR, OC_STACK_ERROR);

    result = sqlite3_exec(g_db, PDM_CREATE_T_DEVICE_LIST, NULL, NULL, NULL);
    PDM_VERIFY_SQLITE_OK(TAG, result, ERROR, OC_STACK_ERROR);

    OC_LOG(INFO, TAG, "Created T_DEVICE_LIST");
    result = sqlite3_exec(g_db, PDM_CREATE_T_DEVICE_LINK, NULL, NULL, NULL);
    PDM_VERIFY_SQLITE_OK(TAG, result, ERROR, OC_STACK_ERROR);

    OC_LOG(INFO, TAG, "Created T_DEVICE_LINK_STATE");
    gInit = true;
    return OC_STACK_OK;
}
ResourceObserver* GetObserverUsingToken (const CAToken_t token, uint8_t tokenLength)
{
    ResourceObserver *out = NULL;

    if(token && *token)
    {
        OC_LOG(INFO, TAG, "Looking for token");
        OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)token, tokenLength);
        OC_LOG(INFO, TAG, "\tFound token:");

        LL_FOREACH (serverObsList, out)
        {
            OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)out->token, tokenLength);
            if((memcmp(out->token, token, tokenLength) == 0))
            {
                return out;
            }
        }
OCStackResult PDMGetToBeUnlinkedDevices(OCPairList_t **staleDevList, size_t *numOfDevices)
{
    CHECK_PDM_INIT(TAG);
    if (NULL != *staleDevList)
    {
        OC_LOG(ERROR, TAG, "Not null list will cause memory leak");
        return OC_STACK_INVALID_PARAM;
    }

    sqlite3_stmt *stmt = 0;
    int res = 0;
    res = sqlite3_prepare_v2(g_db, PDM_SQLITE_GET_STALE_INFO,
                              strlen(PDM_SQLITE_GET_STALE_INFO) + 1, &stmt, NULL);
    PDM_VERIFY_SQLITE_OK(TAG, res, ERROR, OC_STACK_ERROR);

    res = sqlite3_bind_int(stmt, PDM_BIND_INDEX_FIRST, PDM_STALE_STATE);
    PDM_VERIFY_SQLITE_OK(TAG, res, ERROR, OC_STACK_ERROR);

    int counter  = 0;
    while (SQLITE_ROW == sqlite3_step(stmt))
    {
        int i1 = sqlite3_column_int(stmt, PDM_FIRST_INDEX);
        int i2 = sqlite3_column_int(stmt, PDM_SECOND_INDEX);
        OicUuid_t temp1 = {{0,}};
        OicUuid_t temp2 = {{0,}};;
        getUUIDforId(i1, &temp1);
        getUUIDforId(i2, &temp2);

        OCPairList_t *tempNode = (OCPairList_t *) OICCalloc(1, sizeof(OCPairList_t));
        if (NULL == tempNode)
        {
            OC_LOG(ERROR, TAG, "No Memory");
            sqlite3_finalize(stmt);
            return OC_STACK_NO_MEMORY;
        }
        memcpy(&tempNode->dev.id, &temp1.id, UUID_LENGTH);
        memcpy(&tempNode->dev2.id, &temp2.id, UUID_LENGTH);
        LL_PREPEND(*staleDevList, tempNode);
        ++counter;
    }
    *numOfDevices = counter;
    sqlite3_finalize(stmt);
    return OC_STACK_OK;
}
OCEntityHandlerResult ProcessPutRequest(OCEntityHandlerRequest *ehRequest,
                                               OCRepPayload** payload)
{

    OCEntityHandlerResult ehResult = OC_EH_ERROR;
    if (ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
    {
        OC_LOG(ERROR, ES_RH_TAG, "Incoming payload not a representation");
        return ehResult;
    }

    OCRepPayload* input = (OCRepPayload*) (ehRequest->payload);
    if (!input)
    {
        OC_LOG(ERROR, ES_RH_TAG, "Failed to parse");
        return ehResult;
    }

    char* tnn;
    if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_TNN, &tnn))
    {
        sprintf(g_prov.tnn, "%s", tnn);
    }

    char* cd;
    if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_CD, &cd))
    {
        sprintf(g_prov.cd, "%s", cd);
    }

    g_flag = 1;

    OCRepPayload *getResp = constructResponse(ehRequest);
    if (!getResp)
    {
        OC_LOG(ERROR, ES_RH_TAG, "constructResponse failed");
        return OC_EH_ERROR;
    }

    *payload = getResp;
    ehResult = OC_EH_OK;

    return ehResult;
}
OCEntityHandlerResult OCEntityHandlerFanCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest * ehRequest)
{
    OCEntityHandlerResult ret = OC_EH_OK;
    OCEntityHandlerResponse response;
    char payload[MAX_RESPONSE_LENGTH] = {0};

    OC_LOG_V(INFO, TAG, "Callback for Fan");
    PrintReceivedMsgInfo(flag, ehRequest );

    if(ehRequest && flag == OC_REQUEST_FLAG)
    {
        if(OC_REST_GET == ehRequest->method)
        {
            ret = HandleCallback(ehRequest, rspGetFanDefault, rspFailureFan, payload, sizeof(payload));
        }
        else if(OC_REST_PUT == ehRequest->method)
        {
            ret = HandleCallback(ehRequest, rspPutFanDefault, rspFailureFan, payload, sizeof(payload));
        }
        else
        {
            OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
                    ehRequest->method);
            ret = OC_EH_ERROR;
        }

        if (ret == OC_EH_OK)
        {
            // Format the response.  Note this requires some info about the request
            response.requestHandle = ehRequest->requestHandle;
            response.resourceHandle = ehRequest->resource;
            response.ehResult = ret;
            response.payload = (unsigned char *)payload;
            response.payloadSize = strlen(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");
                ret = OC_EH_ERROR;
            }
        }

    }
    else if (ehRequest && flag == OC_OBSERVE_FLAG)
    {
        gLightUnderObservation = 1;
    }

    return ret;
}
OCStackApplicationResult getReqCB(void* ctx, OCDoHandle /*handle*/,
                                  OCClientResponse * clientResponse)
{
    if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
    {
        OC_LOG(INFO, TAG, "<====Callback Context for GET received successfully====>");
    }
    else
    {
        OC_LOG(ERROR, TAG, "<====Callback Context for GET fail====>");
    }

    if (clientResponse)
    {
        OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
        OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
        OC_LOG_PAYLOAD(INFO, clientResponse->payload);
        OC_LOG(INFO, TAG, ("=============> Get Response"));

        if (clientResponse->numRcvdVendorSpecificHeaderOptions > 0 )
        {
            OC_LOG (INFO, TAG, "Received vendor specific options");
            uint8_t i = 0;
            OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
            for (i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
            {
                if (((OCHeaderOption) rcvdOptions[i]).protocolID == OC_COAP_ID)
                {
                    OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
                            ((OCHeaderOption)rcvdOptions[i]).optionID );

                    OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
                        MAX_HEADER_OPTION_DATA_LENGTH);
                }
            }
        }
    }
    else
    {
        OC_LOG(ERROR, TAG, "<====GET Callback fail to receive clientResponse====>\n");
    }
    return OC_STACK_DELETE_TRANSACTION;
}
void loop() {
    Serial.println("entering loop...");
    SendReceiveTest();
    delay(5000);

    do {
        OC_LOG(DEBUG, MOD_NAME, PCF("All tests Completed"));
        delay(10000);
    } while (1);
}
/**
 * Find ACLs containing context->subject.
 * Search each ACL for requested resource.
 * If resource found, check for context->permission.
 * Set context->retVal to result from first ACL found which contains
 * correct subject AND resource.
 *
 * @retval void
 */
void ProcessAccessRequest(PEContext_t *context)
{
    OC_LOG(INFO, TAG, "Entering ProcessAccessRequest()");
    if(NULL != context)
    {
        const OicSecAcl_t *currentAcl = NULL;
        OicSecAcl_t *savePtr = NULL;

        // Start out assuming subject not found.
        context->retVal = ACCESS_DENIED_SUBJECT_NOT_FOUND;
        do
        {
            OC_LOG(INFO, TAG, "ProcessAccessRequest(): getting ACL...");
            currentAcl = GetACLResourceData(context->subject, &savePtr);
            if(NULL != currentAcl)
            {
                // Found the subject, so how about resource?
                OC_LOG(INFO, TAG, "ProcessAccessRequest(): \
                    found ACL matching subject.");
                context->retVal = ACCESS_DENIED_RESOURCE_NOT_FOUND;
                OC_LOG(INFO, TAG, "ProcessAccessRequest(): \
                    Searching for resource...");
                if(IsResourceInAcl(context->resource, currentAcl))
                {
                    OC_LOG(INFO, TAG, "ProcessAccessRequest(): \
                        found matching resource in ACL.");
                    context->matchingAclFound = true;

                    // Found the resource, so it's down to valid period & permission.
                    context->retVal = ACCESS_DENIED_INVALID_PERIOD;
                    if(IsAccessWithinValidTime(currentAcl))
                    {
                        context->retVal = ACCESS_DENIED_INSUFFICIENT_PERMISSION;
                        if(IsPermissionAllowingRequest(currentAcl->permission, \
                        context->permission))
                        {
                            context->retVal = ACCESS_GRANTED;
                        }
                    }
                }
            }
            else
            {
/**
 * Callback handler for handling callback of provisioning device 1.
 *
 * @param[in] ctx             ctx value passed to callback from calling function.
 * @param[in] UNUSED          handle to an invocation
 * @param[in] clientResponse  Response from queries to remote servers.
 * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
 *          and  OC_STACK_KEEP_TRANSACTION to keep it.
 */
static OCStackApplicationResult provisionCredentialCB1(void *ctx, OCDoHandle UNUSED,
                                                       OCClientResponse *clientResponse)
{
    VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
    (void)UNUSED;
    CredentialData_t* credData = (CredentialData_t*) ctx;
    OICFree(credData->credInfoFirst);
    const OCProvisionDev_t *deviceInfo = credData->deviceInfo2;
    OicSecCred_t *credInfo = credData->credInfo;
    const OCProvisionResultCB resultCallback = credData->resultCallback;
    if (clientResponse)
    {
        if (OC_STACK_RESOURCE_CREATED == clientResponse->result)
        {
            // send credentials to second device
            registerResultForCredProvisioning(credData, OC_STACK_RESOURCE_CREATED,1);
            OCStackResult res = provisionCredentials(credInfo, deviceInfo, credData,
                    provisionCredentialCB2);
            DeleteCredList(credInfo);
            if (OC_STACK_OK != res)
            {
                registerResultForCredProvisioning(credData, res,2);
                ((OCProvisionResultCB)(resultCallback))(credData->ctx, credData->numOfResults,
                                                        credData->resArr,
                                                        true);
                OICFree(credData->resArr);
                OICFree(credData);
                credData = NULL;
            }
        }
        else
        {
            registerResultForCredProvisioning(credData, OC_STACK_ERROR,1);
            ((OCProvisionResultCB)(resultCallback))(credData->ctx, credData->numOfResults,
                                                    credData->resArr,
                                                    true);
            OICFree(credData->resArr);
            OICFree(credData);
            credData = NULL;
        }
    }
    else
    {
        OC_LOG(INFO, TAG, "provisionCredentialCB received Null clientResponse for first device");
        registerResultForCredProvisioning(credData, OC_STACK_ERROR,1);
       ((OCProvisionResultCB)(resultCallback))(credData->ctx, credData->numOfResults,
                                                     credData->resArr,
                                                     true);
        DeleteCredList(credInfo);
        OICFree(credData->resArr);
        OICFree(credData);
        credData = NULL;
    }
    return OC_STACK_DELETE_TRANSACTION;
}