con-server.cpp 9.53 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
//******************************************************************
//
// Copyright 2014 Samsung Electronics All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

///
/// This sample shows how one could create a resource (collection) with children.
///

#include <functional>
#include <thread>

#include "OCPlatform.h"
#include "OCApi.h"
#include "ThingsManager.h"
#include "ConfigurationCollection.h"
#include "DiagnosticsCollection.h"
#include "FactorySetCollection.h"

using namespace OC;
using namespace OIC;

const int SUCCESS_RESPONSE = 0;
int g_Steps = 0;
int isWaiting = 0;

// Default system configuration value's variables
// The variable's names should be same as the names of "extern" variables defined in
44 45 46 47 48
// "ConfigurationResource.h"
std::string defaultLocation;
std::string defaultRegion;
std::string defaultSystemTime;
std::string defaultCurrency;
49 50 51 52 53 54 55 56

static ThingsManager* g_thingsmanager;

// Forward declaring the entityHandler (Configuration)
bool prepareResponseForResource(std::shared_ptr< OCResourceRequest > request);
OCStackResult sendResponseForResource(std::shared_ptr< OCResourceRequest > pRequest);
OCEntityHandlerResult entityHandlerForResource(std::shared_ptr< OCResourceRequest > request);

57 58 59
ConfigurationResource *myConfigurationResource;
DiagnosticsResource *myDiagnosticsResource;
FactorySetResource *myFactorySetResource;
60 61 62 63 64 65 66 67

typedef std::function< void(OCRepresentation&) > putFunc;
typedef std::function< OCRepresentation(void) > getFunc;

getFunc getGetFunction(std::string uri)
{
    getFunc res = NULL;

68
    if (uri == myConfigurationResource->getUri())
69
    {
70 71
        res = std::bind(&ConfigurationResource::getConfigurationRepresentation,
                myConfigurationResource);
72
    }
73
    else if (uri == myDiagnosticsResource->getUri())
74
    {
75 76
        res = std::bind(&DiagnosticsResource::getDiagnosticsRepresentation,
                myDiagnosticsResource);
77 78 79 80 81 82 83 84 85
    }

    return res;
}

putFunc getPutFunction(std::string uri)
{
    putFunc res = NULL;

86
    if (uri == myConfigurationResource->getUri())
87
    {
88 89
        res = std::bind(&ConfigurationResource::setConfigurationRepresentation,
                myConfigurationResource, std::placeholders::_1);
90
    }
91
    else if (uri == myDiagnosticsResource->getUri())
92
    {
93 94
        res = std::bind(&DiagnosticsResource::setDiagnosticsRepresentation,
                myDiagnosticsResource, std::placeholders::_1);
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
    }

    return res;
}

// This function prepares a response for any incoming request to Light resource.
bool prepareResponseForResource(std::shared_ptr< OCResourceRequest > request)
{
    std::cout << "\tIn Server CPP prepareResponseForResource:\n";
    bool result = false;
    if (request)
    {
        // Get the request type and request flag
        std::string requestType = request->getRequestType();
        int requestFlag = request->getRequestHandlerFlag();

Charlie Lenahan's avatar
Charlie Lenahan committed
111
        if (requestFlag == RequestHandlerFlag::RequestFlag)
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
        {
            std::cout << "\t\trequestFlag : Request\n";

            // If the request type is GET
            if (requestType == "GET")
            {
                std::cout << "\t\t\trequestType : GET\n";
                // GET operations are directly handled while sending the response
                // in the sendLightResponse function
                result = true;
            }
            else if (requestType == "PUT")
            {
                std::cout << "\t\t\trequestType : PUT\n";
                putFunc putFunction;
                OCRepresentation rep = request->getResourceRepresentation();

                putFunction = getPutFunction(request->getResourceUri());

                // Do related operations related to PUT request
                putFunction(rep);
                result = true;
            }
            else if (requestType == "POST")
            {
                // POST request operations
            }
            else if (requestType == "DELETE")
            {
                // DELETE request operations
            }
        }
        else if (requestFlag == RequestHandlerFlag::ObserverFlag)
        {
            std::cout << "\t\trequestFlag : Observer\n";
        }
    }
    else
    {
        std::cout << "Request invalid" << std::endl;
    }

    return result;
}

OCStackResult sendResponseForResource(std::shared_ptr< OCResourceRequest > pRequest)
{
    auto pResponse = std::make_shared< OC::OCResourceResponse >();

    // Check for query params (if any)
    QueryParamsMap queryParamsMap = pRequest->getQueryParameters();

    pResponse->setRequestHandle(pRequest->getRequestHandle());
    pResponse->setResourceHandle(pRequest->getResourceHandle());

    getFunc getFunction;
    getFunction = getGetFunction(pRequest->getResourceUri());

    OCRepresentation rep;
    rep = getFunction();

    auto findRes = queryParamsMap.find("if");

    if (findRes != queryParamsMap.end())
    {
        pResponse->setResourceRepresentation(rep, findRes->second);
    }
    else
    {
        pResponse->setResourceRepresentation(rep, DEFAULT_INTERFACE);
    }

    pResponse->setErrorCode(200);
    pResponse->setResponseResult(OC_EH_OK);

    return OCPlatform::sendResponse(pResponse);
}

OCEntityHandlerResult entityHandlerForResource(std::shared_ptr< OCResourceRequest > request)
{
    std::cout << "\tIn Server CPP (entityHandlerForResource) entity handler:\n";
    OCEntityHandlerResult ehResult = OC_EH_ERROR;

195 196
    QueryParamsMap test = request->getQueryParameters();

197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
    if (prepareResponseForResource(request))
    {
        if (OC_STACK_OK == sendResponseForResource(request))
        {
            ehResult = OC_EH_OK;
        }
        else
        {
            std::cout << "sendResponse failed." << std::endl;
        }
    }
    else
    {
        std::cout << "PrepareResponse failed." << std::endl;
    }
    return ehResult;
}

// callback handler on GET request
void onBootstrap(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode)
{
218
    isWaiting = 0;
219

220
    if (eCode != SUCCESS_RESPONSE)
221 222
    {
        std::cout << "onGET Response error: " << eCode << std::endl;
223
        return ;
224
    }
225 226 227 228

    std::cout << "\n\nGET request was successful" << std::endl;
    std::cout << "\tResource URI: " << rep.getUri() << std::endl;

229 230 231 232 233 234 235 236 237 238
    defaultRegion = rep.getValue< std::string >("r");
    defaultSystemTime = rep.getValue< std::string >("st");
    defaultCurrency = rep.getValue< std::string >("c");
    defaultLocation = rep.getValue< std::string >("loc");

    std::cout << "\tLocation : " << defaultLocation << std::endl;
    std::cout << "\tSystemTime : " << defaultSystemTime << std::endl;
    std::cout << "\tCurrency : " << defaultCurrency << std::endl;
    std::cout << "\tRegion : " << defaultRegion << std::endl;

239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
}

int main()
{
    //**************************************************************
    // STEP 0
    // Create PlatformConfig object
    PlatformConfig cfg
    { OC::ServiceType::InProc, OC::ModeType::Both, "0.0.0.0", 0, OC::QualityOfService::LowQos };

    OCPlatform::Configure(cfg);
    g_thingsmanager = new ThingsManager();
    //**************************************************************

    if (getuid() != 0)
    {
        std::cout << "NOTE: You may gain the root privilege (e.g, reboot)\n";
        std::cout << "NOTE: Now, you don't have it.\n";
    }

    try
    {
        // Perform app tasks
        while (true)
        {

            if (isWaiting > 0)
                continue;

            isWaiting = 0;

            std::cout << endl << endl << "(0) Quit" << std::endl;
            std::cout << "(1) Bootstrap" << std::endl;
            std::cout << "(2) Create Configuration Resources" << std::endl;

            cin >> g_Steps;
            //
            if (g_Steps == 0)
                break;
            else if (g_Steps == 1)
            {
280 281 282 283
                if( g_thingsmanager->doBootstrap(&onBootstrap) == OC_STACK_OK)
                    isWaiting = 1;
                else
                    std::cout << "A callback pointer of the function is NULL." << std::endl;
284 285 286
            }
            else if (g_Steps == 2)
            {
287 288 289 290 291 292
                myConfigurationResource = new ConfigurationResource();
                myConfigurationResource->createResources(&entityHandlerForResource);

                myDiagnosticsResource = new DiagnosticsResource();
                myDiagnosticsResource->createResources(&entityHandlerForResource);

293

294 295 296 297 298
                myFactorySetResource = new FactorySetResource();
                myFactorySetResource->createResources(&entityHandlerForResource);
                myDiagnosticsResource->factoryReset = std::function < void()
                        > (std::bind(&ConfigurationResource::factoryReset,
                                myConfigurationResource));
299 300 301 302 303 304 305 306 307 308 309 310

                isWaiting = 1;
            }
        }
    }
    catch (OCException e)
    {
        std::cout << "Exception in main: " << e.what();
    }

    // No explicit call to stop the platform.
    // When OCPlatform destructor is invoked, internally we do platform cleanup
311
    return 0;
312 313
}