User Tools

Site Tools


control_manager_for_linux

Control Manager

This guide provides interaction details of the ControlManager (CM), which runs on top of the IoTivity base framework. The following sections provide details for developers to understand how to use SDK APIs and how the CM works to support the APIs.

CM architecture and components describes how the main operations of the SDK API are operated in the CM. The CM architectureis presented and the components in the architecture are described in detail.

SDK API and code snippets describes how an application can use the CM. We provide an Ubuntu linux based sample application which includes the functionality of discovering other controllee devices in the network, controling them and monitoring them.

Control Manager architecture and components

ControlManager runs both as IoTivity Client and IoTivity Server. ControlManager provides SDK APIs for discovery of controlee devices, and controlling them with RESTful resource operations. ControlManager also provides subscription/notification functionality for monitoring the device operations or state changes. Figure 1. ControlManager Architecture

Smart Home Data Model is based on Samsung Smart Home Profile. Smart Home Profile defines a resource model for all the available home devices and appliances, defines a hierarchical resource model and their attributes. There are a common set of resources and there are function specific resources. The common set of resources provides information related to device capabilities, device configuration and supported resources. Function specific resources provide resources specific toa device function such as Thermostat, Light, Door, etc. With the help of a data model, application developers can easilycompile device information, state and control the device.

RESTful Resource Request/Response handler provides the functionality of sending the requests to the controlee device by serializing it from the data model to a message format. It desterilizes the received response to smart home data model. It uses the Client module for sending requests and receiving responses.

Iotivity Client implements the client using the IoTivity base framework for performing messaging with other IoTivity devices per IoTivity protocol. It supports sending requests to other IoTivity devices (for example, thecontrolee device) and receiving responses from them.

Iotivity Server implements the server using theIoTivity base framework for responding to requests from other IoTivity devices. ControlManager acts like a server for responding to the discovery requests from other IoTivity devices and for receiving notifications sent from other ITtivity devices.

Device Discovery uses the IoTivity Discovery mechanism of the base framework for discovering other IoTivity devices. Apart from initial device discovery, the ControlManager discovery mechanism retrieves device specific information and capability and maintains the discovered device's information in the devices list.

Subscription/Notification Manager provides functionality of subscribing to other devices and receiving notifications from other devices as defined in the Samsung Smart Home Profile. This is RESTful subscription/notification mechanism which ControlManager subscribes to resources of other IoTivity Devices. The notifying device notifies the ControlManager server with the REST URI specified by the ControlManager during subscription request. ControlManager also maintains the subscription information for the devices and resources it has already subscribed.

All functionality of ControlManager is accessible to developers through SDK APIs.

SDK API


ControlManager

This class is a starting point for developers. With this class developers can start and stop ControlManager. By invoking the start function of ControlManager, it initializes the internal state and starts the device discovery procedure.

Initializing and starting ControlManager

bool
TestApp::initializeAndStartControlManager ()
{
	/* Initializing ControlManager */
	sp_shp = OC::Cm::ControlManager::getInstance();
	sp_shp->setLogLevel(OC::Cm::CMLogType::CM_LOG_TYPE_DEBUG);
 
	sp_ControlManagerListener = new ControlManagerListener();
	sp_shp->setListener(*sp_ControlManagerListener);
 
	/* Configuring subscription DB path */
	OC::Cm::Configuration* p_config = sp_shp->getConfiguration();
	p_config->setSubscriptionDbPath("CMSubscriptionDB"); // Developer needs to give actual DB Path
	sp_shp->setConfiguration(p_config);
 
	/* Intialize and configure self device */
	sp_myDevice = ::MyDevice::getInstance();
	/* Configure Device Details */
	sp_myDevice->setAddress(ipAddress);
	sp_myDevice->setDeviceType(OC::Cm::DeviceType_Unknown);
	sp_myDevice->setUUID(uuid.c_str()); //UUID: "E8113233-9A97-0000-0000-000000000000"
	sp_myDevice->setDescription("Description");
	sp_myDevice->setManufacturer("Manufacturer");
	sp_myDevice->setModelID("Model ID");
	sp_myDevice->setSerialNumber("Serial Number");
 
	/* Configure Supported Resources */
	sp_myDevice->setSupportedResourceType("Capability");
	sp_myDevice->setSupportedResourceType("Device");
	sp_myDevice->setSupportedResourceType("Devices");
	sp_myDevice->setSupportedResourceType("Information");
 
	/* Set Device Discovery Listener */
	DeviceFinderLister* pDeviceFinderLister new DeviceFinderLister();
	OC::Cm::DeviceType type(OC::Cm::DeviceType::DeviceType_All);
	OC::Cm::DeviceDomain domain(OC::Cm::DeviceDomain::DeviceDomain_All);
	sp_shp->getDeviceFinder()->setDeviceFinderListener(domain,type,pDeviceFinderLister);
 
	/* Set Notification Listener */
	NotificationResponseListener* pNotificationListener = new NotificationResponseListener();
	sp_shp->addNotificationListener(pNotificationListener);
 
	if (false == sp_shp->start(*sp_myDevice))
	{
		return false;
	}
 
	return true;
}

DeviceFinderListener

This class should be implemented for receiving the notifications of the devices that are newly joining the network or leaving the network.

class DeviceFinderListener : public OC::Cm::DeviceFinder::IDeviceFinderListener
{
	virtual void OnDeviceAdded( OC::Cm::Device& device )
	{
		/* This method will be invoked when a new device is discovered */
	}
 
	virtual void OnDeviceRemoved( OC::Cm::Device& device)
	{
		/*This method will be invoked when a device leaves the network */
	}
 
	virtual void OnDeviceUpdated( OC::Cm::Device& device)
	{
		/*This method will be invoked when a device details are updated */
	}
 
	virtual void OnDeviceError( OC::Cm::Device& device )
	{
		/*This method will be invoked when some error in device discovery */
	}
};

Notification Listener

This class should be implemented for receiving the notifications from the devices for which you are already subscribed.

class NotificationResponseListener : public OC::Cm::Notification::INotificationListener
{
 
	virtual void onNotificationReceived( std::string& uuid,								std::string& resource,
					std::string& eventType,
		 	 	 OC::Cm::Serialization::ISerializable* notification,
				 	 std::string& subscriptionURI,
				OC::Cm::Serialization::Xsd::DateTimeType* eventTime )
	{
	/* This method will be invoked on receiving a notification message from other device */
	}
 
	virtual void onMulticastedNotifcationReceived( const OC::Cm::Device& device,
					const std::string& elementType,
			const OC::Cm::Serialization::ISerializable* notification)
	{
	/* This method will be invoked on receiving a broadcastred message from other device */
	}
};

Device Control

After the device is discovered by the Control Manager, the device can be controlled easily by knowing the device type and its supported resources. For controlling the device, the application should set proper and acceptable attribute values according to resource data model classes.

Example code for controlling a Light device with LightResource:

LightResource* pLightResource = NULL;
 
/* PowerOff the Light device */
void powerOffLight()
{
	pLightResource = device‐>createResource(RT_LIGHT);
	if ( NULL != pLightResource )
	{
		int requestId;
		pLightResource‐>addResponseListener(*(new LightResourceResponseListener()));
		pLightResource‐>getLight(requestId);
	}
}
 
 
 
/* Handle response of actions performed on Light device*/
class LightResourceResponseListener : public ILightResourceResponseListener
{
	public:
	bool onGetLight(int& requestId, int status, ::Light* pRespData)
	{
		std::string power = pRespData‐>mpLightPower‐>value;
		// Check if light is powered on
		if (power.compare("on") == 0)
		{
			int requestId;
			Light *pLight = new Light();
			pLight‐>mpLightPower = new OnType();
			pLight‐>mpLightPower‐>value = "Off";
			// Power off the light
			pLightResource‐>putLight( requestId , *pLight);
		}
 
		return true;
	}
 
	bool onPutLight(int& requestId, int status)
	{
		if (status == 204)
		{
			// Light powered off successfully
		}
	}
};

Stop Control Manager

Developers should stop the framework when they want to exit the application. Stopping the framework stops the internal server and cleans up the internal components and allocations.

bool
TestApp::stopFramework()
{
/* Stop Control Manager */
    pControlManager->stop();
 
    /** Confirm SHP-Stop */
 
    OC::Cm::CMStates cmState = pControlManager->getState() ;
 
    if (OC::Cm::CM_STOPPED == cmState) 
{
        /* Control Manager Stopped Completely" */
    }
 
    /* Un-subscribe SHP Listener */
    pControlManager->removeListener(pControlManagerListener);
    if (pControlManagerListener) { delete pControlManagerListener; }
 
    /** Reset SHP Configuration */
    OC::Cm::Configuration *config = pControlManager->getConfiguration();
 
    if (NULL != config) {
        config->reset();
    }
 
    if (pControlManager) { delete pControlManager; }
 
    return true;
}

Controlled Device/Controllee (CD)


This guide provides details of the APIs offered by the Controlled Device/Controllee (CD) which runs on top of the IoTivity base framework.

CD architecture and components describes how the main operations of the API are realized in the CD. The architecture of the CD is presented and the components of the architecture are described in detail.

Controlled Device AP, and code snippets describes how an application can use the CD. Example code segments are included. The CD code also provides an Ubuntu Linux based sample application that starts up an instance of a Controlled Device, registers resources, advertises presence and responds to RESTful network stimulus.

Controlled Device architecture and components


A Controlled Device runs as an IoTivity Server. It provides APIs that allow control of device state, registration of resources with the base, and provides an application the ability to respond to received network stimulus (Create, Read, Update and Delete) as appropriate. It also provides the ability to manage received subscription requests and generate notifications in response based on local device events and state changes. Figure 1. ControlleeManager Architecture

Smart Home Data Model is based on the Samsung Smart Home Profile. The Smart Home Profile defines aresource model for all the available home devices and appliances, defines a hierarchical resource model and their attributes. There are a common set of resources and there are function specific resources. The Common set of resources provides information related to device capabilities, device configuration and supported resources. The Function specific resources provide resources specific to device function such as Thermostat, Light, Door, etc.

RESTful Resource Request/Response handler gives the application the ability to provide custom functionality in handling received resource targeted requests and the creation of responses to those requests. All resources are as identified in the Data Model.

Serialization provides the functionality of sending the responses to the Controlling device by serializing the data from the data model to message format. The element also de-serializes received requests to smart home data model format.

Iotivity Server implements the server using theIoTivity base framework for responding to requests from other IoTivity devices. The Controllee acts as a server for responding to the resource requests from other IoTivity devices and for receiving subscriptions sent from other IoTivity devices. The Server also provides Presence indications to the network.

Subscription/Notification Manager provides the functionality of handling subscriptions from other devices and generating notifications to other devices for resources of interest. This is a RESTful subscription/notification mechanism in which the ControlleeManager handles subscribe requests to its owned resources from other IoTivity Devices.

All of the functionality of the ControlleeManager is accessible to developers through APIs.

Controlled Device API


Key Classes:

ControlleeManager This class is starting point for developers. With this class developers can start and stop the Controlled Device (which also starts and stops Presence) and register resources that are known by the application. By invoking the start() method of the ControlleeManager, the stack initializes internal state and starts advertising presence to external IoTivity devices.

Configuration The ControlleeManager makes use of a default instance of the Configuration class to instantiate the internal data structures and dependencies. Developers can tailor these values depending on their own environment as part of the initialization of the stack.

MyDevice MyDevice is a singleton that encapsulates the properties of the Controlled Device. Developers should obtain an instance of MyDevice and use the provided accessor and mutator methods to customize the fundamental device information.

SubscriptionManager & SubscriptionDatabase If the application supports the ability for a client to subscribe to exposed resources and receive notifications that may be generated then the application shall create an instance of the SubscriptionManager and its associated Database and register these with the ControlleeManager. The database wrapper class shall be a concrete instantiation of the ISubscriptionDB virtual class. The framework provides an instance of such as class (SqliteSubscriptionDatabase) should the developer not want nor need to provide their own.

Use of The API:

Configuring the ControlleeManager & Associated Subscription Database

The application invokes the constructor for the ControlleeManager, providing to the framework the IP address associated with the stack instance. The application can then obtain an instance of the Configuration and set or change details as appropriate. Should the application support subscriptions it shall also provide an instance of the SubscriptionManager.

Example:

	/* Initializing ControlleeManager */
	OC::ControlleeManager *cmgr = new OC::ControlleeManager(MY_IP_ADDRESS):
 
	/* Set configuration information */
	OC::Cm::Configuration *config = cmgr->getConfiguration();
    	config->setAppType(OC::Cm::ApplicationType_Controllable);
 
	/* Configuring subscription DB path */
    	config->setSubscriptionDbPath("MY_DB_PATH"); 
    	OC::Cm::Notification::ISubscriptionDB subDBStore = 
new OC::Cm::Notification::SqliteSubscriptionDatabase();
    	OC::Cm::Notification::SubscriptionManager pSub = 
new OC::Cm::Notification::SubscriptionManager(subDBStore);
cmgr->setSubscriptionManager(*pSub);

Populating MyDevice

The application should obtain an instance of MyDevice and populate the attributes as appropriate for the device under its control.

Example:
	/* Intialize and configure device */
	sp_myDevice = ::MyDevice::getInstance();
 
	/* Configure Device Details */
	sp_myDevice->setAddress(MY_IP_ADDRESS);
	sp_myDevice->setDeviceType(OC::Cm::DeviceType_Unknown); 
	sp_myDevice->setUUID(MY_UUID); 
	sp_myDevice->setDescription("Description");
	sp_myDevice->setManufacturer("Manufacturer");
	sp_myDevice->setModelID("Model ID");
	sp_myDevice->setSerialNumber("Serial Number");

Registering Resources

The application shall register with the ControlleeManager the resources that it is exposing/supporting. All of the known resource types can be found in ResourceTypeEnum. The ControlleeManager will register the resource details with the IoTivity framework along with appropriate callback mechanisms. The application will realize code to handle reception of requests to the registered resources via realizations of the resource handlers.

By default the stack registers Capability, Device and Devices resources with the IoTivity framework; there is no need for the application to do so. If subscriptions are supported the stack will additionally register Subscription(s) and Notification(s) resources with the IoTivity framework.

Example:

    	int error;
std::list<resourcetypeenum> resourceType;
 
    	resourceType.push_back(RT_Light);   
   	resourceType.push_back(RT_Humidity);    
 
    	OC::ControlleeStatus status = cmgr->addResources(resourceType, error);
   	if (status != OC::ControlleeError)
    	{
       		 std::cout << "Registered all resources ok" << std::endl;
    	}
   	else
    	{
       		 std::cout << "Error in registering resources" << std::endl;
   	}

State Changes (start, stop)

The ControlleeManager provides methods that allow the application to start or stop the device as required.

Note: starting the device also starts Presence indications on the network and stopping the device stops these indications from being sent.

Example:

if (false == cmgr->start())
    	{
       		cout << "ProgramUtils::startFramework() => " 
<< "ERROR: Failed to Start framework" << std::endl);
}
 
	/* Application Logic */
 
    	cmgr->stop();

Device Control

For every known resource that can be registered by an application the API provides a default version of a resource handler class that is itself a concrete instance of a SyncResourceHandler; methods on this class are invoked depending on the nature of the request received by the stack that is targeted at the resource. These methods are onDELETE, onGET, onPOST and onPUT. The signatures for these methods provide status code, request data and the ability for the application to provide response data where needed. The request and response data classes are instances of a Resource class subclassed with attributes applicable to the resource being handled. This data is then serialized by the framework. The Application shall provide realizations of these methods as appropriate for the device on which the application is resident.

Example of the method signatures for a Humidity Resource:

        /**
         * This method will be invoked to handle a GET request.
         *
         * @param[out] statusCode   Http status code to be returned to the client
         * @param[out] respData Humidity object to be returned to the server through the serializer. This object should not be re-initialized by a user.
         *
         * @return  @c True If the request is properly handled @n
         *          @c False In case of any error occurred
        */
        bool onGET(  int &statusCode, ::Humidity *respData);
 
        /**
         * This method will be invoked to handle a PUT request.
         *
         * @param[out] statusCode   Http status code to be returned to the client
         * @param[in] reqData   Received Humidity object through the deserializer. This object should not be re-initialized by a user.
         *
         * @return  @c True If the request is properly handled @n
         *          @c False In case of any error occurred
        */
        bool onPUT(  int &statusCode, ::Humidity *reqData);

REST Framework for Control Manager


The following sections provide details for developers to understand how to use REST framework to process REST requests using theControl Manager. The Control Manager, on receiving the requests, passes it on to the IoTivity Base, which forwards the requests to the controllee device.

REST Framework for Control Manager's Architecture and Components


REST Framework for Control Manager enables the application to access and manage the RESTFul resources in a controllee device. REST framework instantiates the Control Manager module. Control Manager provides APIs for controlling devices with RESTful resources. Information available in the REST request, like the request URI, the HTTP method (GET/PUT/POST/DELETE), DeviceID, etc., allows the REST Framework to use the appropriate APIs in Control Manager to control the controllee device.

REST Request handler: Receives the REST request from Application, parses it, validates the request body(only schema validation) and forwards the request to the CM module via its interface. REST request handler will throw an error in case of invalid content (invalid URI/invalid request body, etc).

Web Cache: A basic caching sub-module, which caches the REST requests received from application. It responds with '304 Not Modified' when there is no change in the system after the same request was processed previously.

Web Filter: The main job of this sub-module is to parse the filter params from the request URI.

CM Module Interface: This sub-modules acts as an interface between REST Framework and the Control Manager. It is mainly responsible for forwarding the processed REST requests to the Control Manager. It creates and registers response listeners with the Control Manager, which uses them to respond back asynchronously. Also, a 'timeout' of 30 seconds is maintained here, after which if no response is received from Control Manager, an error is sent back to the application.

Application: The application is the entity that instantiates the REST Framework and uses it for processing REST requests. It receives the requests from the RESTClient, parses the HTTP request to extract information (method, URI, request body, etc,.) and forward them to the REST Framework for handling.

Note: the application can be developed in at least two ways.

  1. As a separate unit: Web Server, which is a different entity, receives requests from the REST Client and forwards the request to application via some form of IPC.
  2. As an integral part of the Web Server: Web Server receives the requests from the REST Client, passes it on the application directly.

REST Framework for Control Manager API's


Enumeration Data Types

HttpStatusCode

typedef enum {
    kHttpStatusCodeProcessing = 100,
    kHttpStatusCodeSuccessOk = 200,
    kHttpStatusCodeSuccessCreated = 201,
    kHttpStatusCodeAccepted = 202,
    kHttpStatusCodeSuccessNoContent = 204,
    kHttpStatusCodeSuccessPartialContent = 206,
    kHttpStatusCodeRedirectSpecialResponse = 300,
    kHttpStatusCodeRedirectMovedPermanently = 301,
    kHttpStatusCodeRedirectMovedTemporarily = 302,
    kHttpStatusCodeRedirectSeeOther = 303,
    kHttpStatusCodeRedirectNotModified = 304,
    kHttpStatusCodeRedirectTemporaryRedirect = 307,
    kHttpStatusCodeErrClientBadRequest = 400,
    kHttpStatusCodeErrClientUnauthorised = 401,
    kHttpStatusCodeErrClientForbidden = 403,
    kHttpStatusCodeErrClientNotFound = 404,
    kHttpStatusCodeErrClientNotAllowed = 405,
    kHttpStatusCodeErrClientNotAcceptable = 406,
    kHttpStatusCodeErrClientRequestTimeOut = 408,
    kHttpStatusCodeErrClientConflict = 409,
    kHttpStatusCodeErrClientLengthRequired = 411,
    kHttpStatusCodeErrClientPreconditionFailed = 412,
    kHttpStatusCodeErrClientRequestEntityTooLarge = 413,
    kHttpStatusCodeErrClientRequestUriTooLarge = 414,
    kHttpStatusCodeErrClientUnsupportedMediaType = 415,
    kHttpStatusCodeErrClientRangeNotSatisfiable = 416,
    kHttpStatusCodeErrServerInternalServerError = 500,
    kHttpStatusCodeErrServerNotImplemented = 501,
    kHttpStatusCodeErrServerBadGateway = 502,
    kHttpStatusCodeErrServerServiceUnavailable = 503,
    kHttpStatusCodeErrServerGatewayTimeOut = 504,
    kHttpStatusCodeErrServerInsufficientStorage = 507,
} HttpStatusCode;

HttpMethod

typedef enum {
    HTTP_METHOD_UNSET = -1,
    HTTP_METHOD_GET,
    HTTP_METHOD_POST,
    HTTP_METHOD_HEAD,
    HTTP_METHOD_OPTIONS,
    HTTP_METHOD_PROPFIND,
    HTTP_METHOD_MKCOL,
    HTTP_METHOD_PUT,
    HTTP_METHOD_DELETE,
    HTTP_METHOD_COPY,
    HTTP_METHOD_MOVE,
    HTTP_METHOD_PROPPATCH,
    HTTP_METHOD_REPORT,
    HTTP_METHOD_CHECKOUT,
    HTTP_METHOD_CHECKIN,
    HTTP_METHOD_VERSION_CONTROL,
    HTTP_METHOD_UNCHECKOUT,
    HTTP_METHOD_MKACTIVITY,
    HTTP_METHOD_MERGE,
    HTTP_METHOD_LOCK,
    HTTP_METHOD_UNLOCK,
    HTTP_METHOD_LABEL,
    HTTP_METHOD_CONNECT
} HttpMethod;

RestResponse

typedef enum {
    kRestFwUnknownError = -1,
    kRestFwProcessRequstFailed = 0,
    kRestFwUnInitialized,
    kRestFwProcessRequstSuccess,
} RestResponse;

Structures

HttpHeaderData

typedef struct {
    enum {NUM_HEADER_PARAMS = 20};
    std::string param_name[NUM_HEADER_PARAMS];
    std::string param_value[NUM_HEADER_PARAMS];
    int flag_outheader_overwrite[NUM_HEADER_PARAMS];
    int is_this_set[NUM_HEADER_PARAMS];
    HttpHeaderData();
    ~HttpHeaderData();
} HttpHeaderData;

HTTPReq

typedef struct {
    int req_type;
    std::string req_uri;
    std::string req_body;
    std::string query_parameters;
    HttpHeaderData* http_request_info;
} HTTPReq;

HTTPResponse

typedef struct {
    HttpStatusCode status;
    std::string response_body;
    HttpHeaderData headers;
} HTTPResponse;

HttpAPIVersion

typedef struct {
    unsigned int majorVersion;
    unsigned int minorVersion;
    unsigned int releaseVersion;
} HttpAPIVersion;

Classes

RestRequestHandler

RestRequestHandler is the main interface class. The application should use this to send REST requests to the REST framework.

class RestRequestHandler
{
public:
    static webservice::RestRequestHandler* GetInstance(void);
    bool Init(void);
    bool DeInit(void);
    void DestroyInstance(void);
    std::string ProcessRequest(int req_type, std::string req_uri, 
    std::string query_parameters, std::string req_body,
    const web_util::HttpHeaderData& http_request_info,
    int* response_code, web_util::HttpHeaderData* http_response_info);
};

RestRequestHandler's exposes the following methods:

  • GetInstance: Returns the singleton instance of RestRequestHandler.
  • Init: Initialize the RestRequestHandler object.
  • ProcessRequest: Process the given REST request. This method takes 'request method, resource URI, query parameters, request body and request headers' as input parameters. Application should take care of parsing all these values from REST request.
  • DeInit: Un-initialize the RestRequestHandler object.
  • DestroyInstance: Destroys the singleton instance of RestRequestHandler.

Sample Usage

The following diagram shows a sample request flow from REST client.

Initialize Rest Framework

bool InitRestFw() {
    webservice::RestRequestHandler* rest_engine = webservice::RestRequestHandler::GetInstance();
    if (rest_engine) {
        // initialize the Rest framework
        if (!rest_engine->Init()) {
            std::cout << "Rest framework Initialize failed" << std::endl;
            return false;
        }
        return true;
    }
    return false;
}

ReceiveAndProcess REST Request

void ReceiveAndrocessHttpRequest() {
    bool stop = false;
    while(!stop) {
 
	// Add code to receive ReST request (TODO)
 
       // below are the input_params (these values should be received from ReST request)
       // Static values are given for sample usage
       // request method
       web_util::HttpMethod req_method = web_util::HTTP_METHOD_GET;
       // request URI
       std::string resource = "devices";
       // request query params
       std::string query_parameters = "";
       // request headers to be sent (This request doesn't require any request headers)
       web_util::HttpHeaderData req_hdr;
 
       // output_params
       // response code received
       int response_code = 500;
       // response headers
       web_util::HttpHeaderData resp_hdr;
       // response body
       std::string response = "";
       web_util::RestResponse rest_resp;
 
       webservice::RestRequestHandler* rest_engine = webservice::RestRequestHandler::GetInstance();
       if (rest_engine) {
           // send request to Rest framework
           rest_resp = rest_engine->ProcessRequest(req_method, resource, query_parameters, req_body, req_hdr, &response_code, &resp_hdr, &response);
           if (rest_resp == web_util::kRestFwProcessRequstSuccess) {
             std::cout << "Successfully processed the request" << std::endl;
           } else if (rest_resp == web_util::kRestFwUnInitializedError) {
             std::cout << "Rest framework is not initialized" << std::endl;
           } else if (rest_resp == web_util::kRestFwProcessRequstFailed) {
             std::cout << "Failed to process the request" << std::endl;
           } else {
             std::cout << "Unknown error occurred" << std::endl;
           }
       }
	if (/*any_error*/)
	   stop = true;
     }
    return;
}

DeInit REST framework

bool DeInitRestFw() {
    webservice::RestRequestHandler* rest_engine = webservice::RestRequestHandler::GetInstance();
    if (rest_engine) {
        // Un-initialize the Rest framework
        if (!rest_engine->DeInit()) {
            std::cout << "Rest framework Initialize failed";
            return false;
        }
    }
    return true;
}

Destroy REST framework

bool DestroyRestFw() {
    webservice::RestRequestHandler* rest_engine = webservice::RestRequestHandler::GetInstance();
    if (rest_engine) {
        // destroy the Rest framework
        rest_engine->DestroyInstance();
        return true;
    }
    return false;
}

Combined Usage

int main() {
    // initialize rest framework
    if (!InitRestFw()) {
      std::cout << "InitRestFw failed" << std::endl;
      return 0;
    }
 
    // Start processing ReST requests
    ReceiveAndrocessHttpRequest();
 
    // un-initialize rest framework
    if (!DeInitRestFw()) {
        std::cout << "DeInitRestFw failed" << std::endl;
        return 0;
    }
 
 
 
    // destroy rest framework
    if (!DestroyRestFw()) {
        std::cout << "DestroyRestFw failed" << std::endl;
        return 0;
    }
    return 0;
}
control_manager_for_linux.txt · Last modified: 2015/07/04 10:39 by Jaeyoung Hwang