From: Sangkoo Kim Date: Mon, 17 Apr 2017 05:29:08 +0000 (+0900) Subject: Initial version X-Git-Tag: submit/tizen/20170418.092249~6 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=HEAD;p=platform%2Fcore%2Fservice%2Fcloud%2Fua-client.git Initial version --- diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100755 index 0000000..15d1344 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,76 @@ +cmake_minimum_required (VERSION 2.8) + +project (ua-client) + +#set(CMAKE_SKIP_BUILD_RPATH TRUE) + +include(CheckCXXCompilerFlag) + +CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11) +CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X) +IF(COMPILER_SUPPORTS_CXX11) + SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") +ELSEIF(COMPILER_SUPPORTS_CXX0X) + SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x") +ELSE() + MESSAGE(STATUS "The compiler ${CMAKE_CXX_COMPILER} has no C++ support. Please use a different C++ compiler.") +ENDIF() + +install(FILES ${CMAKE_SOURCE_DIR}/res/device_info.ini DESTINATION /opt/usr/data/ua_client/) +install(FILES ${CMAKE_SOURCE_DIR}/res/.firmware_controlee.dat DESTINATION /opt/usr/data/ua_client/) + + +set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS} -O2 -g -Wall") + +add_definitions(-D__TIZEN__ -D_GNU_SOURCE -DTIZEN_DEBUG_ENABLE -DTB_LOG -DWITH_CLOUD -DRD_SERVER) + +include_directories( + ${CMAKE_SOURCE_DIR}/inc/ + ${CMAKE_SOURCE_DIR}/inc/iotivity/ + ) + +set(SOURCES + ${CMAKE_SOURCE_DIR}/src/ua_client.cpp + ${CMAKE_SOURCE_DIR}/src/ua_http.cpp + ${CMAKE_SOURCE_DIR}/src/ua_json_parser.cpp + ) + +#set(dependents "boost dlog glib-2.0 iotivity libcurl uuid json-glib-1.0 capi-network-connection") +set(dependents "boost dlog glib-2.0 libcurl uuid json-glib-1.0 capi-network-connection capi-network-wifi") +include(FindPkgConfig) +pkg_check_modules(${PROJECT_NAME} REQUIRED ${dependents}) + +foreach(flag ${${PROJECT_NAME}_CFLAGS}) + set(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag} -std=c++11") +endforeach(flag) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS}") + +#find_library(IOTIVITY_LIBRARY +# NAMES oc oc_logger octbstack ocsrm routingmanager connectivity_abstraction c_common coap logger +# PATHS ${CMAKE_SOURCE_DIR}/lib/ +#) + +set(LINK_STATIC_LIBS + oc + oc_logger + octbstack + ocsrm + routingmanager + connectivity_abstraction + c_common + coap + resource_directory + logger + pthread + rt + uuid + capi-network-wifi + ) + +set(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed") + +link_directories(${CMAKE_SOURCE_DIR}/lib/) +add_executable(${PROJECT_NAME} ${SOURCES}) +target_link_libraries(${PROJECT_NAME} ${${PROJECT_NAME}_LDFLAGS} ${LINK_STATIC_LIBS}) +install(TARGETS ${PROJECT_NAME} DESTINATION bin) diff --git a/content_server/content_server.js b/content_server/content_server.js new file mode 100644 index 0000000..8ee06e0 --- /dev/null +++ b/content_server/content_server.js @@ -0,0 +1,299 @@ +const PORT = 8000 +const IMAGE_DIR = "/var/www/images/" + +const HTTP_OK = 200; +const HTTP_BAD_REQUEST = 400; +const HTTP_INTERNAL_ERROR = 500; + +var express = require('express'); +var app = express(); +var fs = require("fs"); +var host_ip = require("ip"); + +var bodyParser = require('body-parser'); +var multer = require('multer'); +const cp = require('child_process'); +var sqlite3 = require('sqlite3').verbose(); +var db = new sqlite3.Database('firmware.db'); +var child = cp.fork(__dirname +'/sub.js'); +var qcount = 0; +var cmd_list = []; +var resp_msg = {}; +var update_msg = {}; +var g_res; + +app.use(express.static('public')); +app.use(bodyParser.urlencoded({ extended: false })); + +app.get('/file_upload.html', function (req, res) { + res.sendFile( __dirname + "/" + "file_upload.html" ); +// res.sendFile( __dirname + "/" + "file_upload3.html" ); +}) + +/* +app.get('/monitoring.html', function (req, res) { + res.sendFile( __dirname + "/" + "monitoring.html" ); +// res.sendFile( __dirname + "/" + "file_upload3.html" ); +}) +*/ + +var server = app.listen(PORT, function () { + var host = host_ip.address(); + var port = server.address().port; + + console.log("content-server listening at http://%s:%s", host, port) +}) + +db.serialize(function() { + db.run("CREATE TABLE IF NOT EXISTS full_tbl (manufacturer TEXT, model TEXT, version TEXT, file TEXT, patch_version TEXT, patch_url TEXT, priority INT)"); + db.each("SELECT model, version, file FROM full_tbl", function(err, row) { + console.log(row.model, ",", row.version, ":", row.file); + }); +}); + + +var upload = multer({ dest: '/tmp/'}); + +// curl -v -X GET http://localhost:3000/firmware?manufacturer=samsung&model=tm1&version=1.0 +app.get('/firmware', function(req, res){ + console.log("url: [", req.url, "]"); + console.log("query: [", req.query, "]"); + var manufacturer = req.query.manufacturer; + var model = req.query.model; + var cur_ver = req.query.version; + console.log("manufacturer: [", manufacturer, "]"); + console.log("model: [", model, "]"); + + if (!(manufacturer || model || version)) { + console.log("bad request - manufacturer[", manufacturer, "], model[", model, "]"); + res.status(HTTP_BAD_REQUEST).json({errmsg: "missing parameters"}); + return; + } + + var ret = {}; + db.get("SELECT * FROM full_tbl WHERE manufacturer=? AND model=? AND version=?", manufacturer, model, cur_ver, function(err, row) { + if (err){ + console.error("error", err); + res.status(HTTP_INTERNAL_ERROR).json(err); + } + else if (!row) { + console.log('firmware not found'); + res.status(HTTP_BAD_REQUEST).json({errmsg:'firmware not found'}); + } + else { + console.log(row); + ret.old_version = cur_ver; + ret.new_verion = row.patch_version; + ret.url = row.patch_url; + ret.priority = row.priority; + res.json(ret); + } + }); +}); + + +app.post('/file_upload', upload.single('file'), function(req, res) { + var file = IMAGE_DIR + req.file.originalname; + var mf = req.body.manufacturer; + var model = req.body.model; + var ver = req.body.version; + var priority = req.body.priority; + console.log("req.file: ", file); + console.log("manufacturer: ", mf); + console.log("model: ", model); + console.log("version: ", ver); + console.log("priority: ", priority); + + if(!(file && mf && model && ver)) { + console.log("file[", file,"], manufacturer[",mf ,"], model[", model,"], version[",ver ,"]"); + res.status(HTTP_BAD_REQUEST).json({errmsg: "missing parameters"}); + return; + } + + + console.log("req.body:", req.body); + cmd_list = []; + resp_msg = {}; + resp_msg.results = []; + update_msg = {}; + update_msg.urls = []; + + if(req.body.upload) { + fs.rename(req.file.path, file, function(err) { + if (err) { + console.log("error: ", err); + res.status(HTTP_INTERNAL_ERROR).json(err); + } else { + db.get("SELECT file FROM full_tbl WHERE manufacturer=? and model=? and version=?", mf, model, ver, function(err, row) { + if (err){ + console.error("error", err); + res.status(HTTP_INTERNAL_ERROR).json(err); + } + else if (row) { + console.log("the same version already exists"); + res.status(HTTP_BAD_REQUEST).json({errmsg:'version duplicated'}); + } + else { + db.run("INSERT INTO full_tbl (manufacturer, model, version, file, patch_version, patch_url, priority) VALUES (?,?,?,?,?,?,?)", mf, model, ver, file, ver, req.file.originalname, priority, function(err) { + if (err){ + console.error("error", err); + res.status(HTTP_INTERNAL_ERROR).json(err); + } + else + res.json({'manufacturer':mf, 'model': model, 'version':ver, 'file':req.file.originalname, 'priority':priority}); + }); + } + }); + } + }); + } + else if(req.body.bsdiff) { + db.each("SELECT * FROM full_tbl WHERE manufacturer=? and model=?", mf, model, + function(err, row){ /* result callback */ + console.log("old version [" + row.version + "]"); + if(ver > row.version) { + var cmd = {}; + cmd.old_ver = row.version; + cmd.old_file = row.file; + cmd.new_file = file; + cmd.new_ver = ver; +// var cmd = __dirname + '/ss_bsdiff' + " " + old_file + " " + file + " "+ patch_file; + console.log("cmd:", cmd); + cmd_list.push(cmd); + } + }, function(err,row) { /* completion callback */ + if (err){ + console.error("error", err); + res.status(HTTP_INTERNAL_ERROR).json(err); + } + else if(row==0 || cmd_list.length == 0){ + res.status(HTTP_BAD_REQUEST).json({'errmsg':'no firmware available'}); + } + else { + update_msg.manufacturer = mf; + update_msg.model = model; +// update_msg.cmd = "WRITE"; + update_msg.priority = priority; + console.log("cmd list:", cmd_list, ", length:", cmd_list.length); + // send the first cmd to child process + child.send(cmd_list[0]); + qcount = 1; + g_res = res; // after processing the last command, g_res is used for response + } + }); + } + else if(req.body.diff) { + var old_ver = req.body.old_version; + if(!old_ver) { + console.log("old_version", old_ver,"]"); + res.status(HTTP_BAD_REQUEST).json({errmsg: "missing parameters: old_version"}); + return; + } + + fs.rename(req.file.path, file, function(err) { + if (err) { + console.log("error: ", err); + res.status(HTTP_INTERNAL_ERROR).json(err); + } else { + db.get("SELECT * FROM full_tbl WHERE manufacturer=? and model=? and version=?", mf, model, old_ver, function(err, row) { + if (err){ + console.error("error", err); + res.status(HTTP_INTERNAL_ERROR).json(err); + } + else if (!row) { + console.log("version not found"); + res.status(HTTP_BAD_REQUEST).json({errmsg:'version not found'}); + } + else { + var patch_url = "http://" + host_ip.address() + "/images/" + req.file.originalname; + db.run("UPDATE full_tbl SET patch_version=?, patch_url=?, priority=? WHERE manufacturer=? AND model=? AND version=?", ver, patch_url, priority, mf, model, old_ver, function(err) { + if (err){ + console.error("error", err); + res.status(HTTP_INTERNAL_ERROR).json(err); + } + else + res.json({'manufacturer':mf, 'model': model, 'old_version':old_ver, 'new_version':ver, 'url':patch_url ,'priority':priority, }); + }); + } + }); + } + }); + } +}); + + +child.on('message', function(m) { + console.log('return:', m); + console.log('qcount:', qcount, "qlength:", cmd_list.length); + + var resp = {}; + resp.version = m.old_ver; + resp.errmsg = m.errmsg; + resp_msg.results.push(resp); + + var update = {}; + update.old_version = m.old_ver; + update.new_version = m.new_ver; + update.url = "http://" + host_ip.address() + "/images/" + m.patch_name; + console.log("added:", update); + update_msg.urls.push(update); + + db.run("UPDATE full_tbl SET patch_version=?,patch_url=?,priority=? WHERE manufacturer=? AND model=? AND version=?", update.new_version, update.url, update_msg.priority, update_msg.manufacturer, update_msg.model, update.old_version, function(err) { + if (err){ + console.error("error", err); + res.status(HTTP_INTERNAL_ERROR).json(err); + } + else { + if (qcount == cmd_list.length) { + // the last command + console.log("diff done"); + console.log("update_msg:", update_msg); + g_res.json(resp_msg); + } + else { + // request the next command + console.log("cmd:", cmd_list[qcount]); + child.send(cmd_list[qcount]); + qcount++; + } + } + }); +}); + +/* else if(req.body.nodiff) { + db.get("SELECT file FROM full_tbl WHERE manufacturer=? and model=? and version=?", mf, model, ver, function(err, row) { + if (err){ + console.error("error", err); + res.status(HTTP_INTERNAL_ERROR).json(err); + } + else if (!row) { + console.log("firmware not found"); + res.status(HTTP_BAD_REQUEST).json({errmsg:'firmware not found'}); + } + else { + var resp = {}; + resp.old_ver = m.old_ver; + resp.new_ver = m.new_ver; + resp.errmsg = "success"; + resp.patch_name = patch_name; + console.log(resp); + update_msg.manufacturer = mf; + update_msg.model = model; + update_msg.cmd = "WRITE"; + + var options = { + uri: REST_SERVER_ADDR+"/devices/update", + method: 'POST', + json: update_msg + }; + request.post(options, function(error, response, body) { + if(error) { + console.log(error); + } + else { + console.log(body); + } + }); + } + }); + } */ diff --git a/content_server/file_upload.html b/content_server/file_upload.html new file mode 100644 index 0000000..be2cf65 --- /dev/null +++ b/content_server/file_upload.html @@ -0,0 +1,108 @@ + + +Firmware Uploading Form + + +

Firmware Upload:

+Select a file to upload:
+ +
+
+Manufacturer:
+
+Model:
+
+New Firmware Version:
+
+Priority:
+

+ +

+Old Firmware Version:
+
+ +
+
RESULT
+
+ + + + + diff --git a/content_server/install.sh b/content_server/install.sh new file mode 100755 index 0000000..76b4997 --- /dev/null +++ b/content_server/install.sh @@ -0,0 +1,12 @@ +#/bin/bash +sudo apt-get install nginx +echo "Configuring /etc/nginx/sites-available/default" +sudo chmod 777 /etc/nginx/sites-available/default +echo 'server { + location /images/ { + root /var/www; + } +}' >> /etc/nginx/sites-available/default +echo "mkdir & chmod /var/www/images" +sudo mkdir /var/www/images/ +sudo chmod 777 /var/www/images/ diff --git a/content_server/package.json b/content_server/package.json new file mode 100644 index 0000000..c7d2d96 --- /dev/null +++ b/content_server/package.json @@ -0,0 +1,17 @@ +{ + "name": "tizen-firmware-rest-api-server", + "version": "0.0.1", + "main": "apiserver.js", + "dependencies": { + "express": "4.14.x", + "body-parser": "1.16.x", + "sqlite3": "3.1.x", + "ref": "1.3.x", + "ffi": "2.2.x", + "hashmap": "2.0.x", + "child_process": "1.0.x", + "request" : "2.81.x", + "multer" : "1.3.x", + "ip" : "1.1.x" + } +} diff --git a/content_server/ss_bsdiff b/content_server/ss_bsdiff new file mode 100755 index 0000000..107ae6d Binary files /dev/null and b/content_server/ss_bsdiff differ diff --git a/content_server/ss_bspatch b/content_server/ss_bspatch new file mode 100755 index 0000000..956d75d Binary files /dev/null and b/content_server/ss_bspatch differ diff --git a/content_server/sub.js b/content_server/sub.js new file mode 100644 index 0000000..fd8146a --- /dev/null +++ b/content_server/sub.js @@ -0,0 +1,33 @@ +const webpath = "/var/www/images" +const exec = require('child_process').exec; +var errmsg; + +process.on('message', function(m) { + console.log("message:",m); + console.log("old_ver:",m.old_ver); + console.log("old_file:",m.old_file); + console.log("new_file:",m.new_file); + var patch_name = "patch_" + m.old_ver + "-" + m.new_ver; + var patch_file = webpath + "/" + patch_name; + console.log("patch:", patch_file); + var cmd = __dirname + "/ss_bsdiff" + " " + m.old_file + " " + m.new_file + " "+ patch_file; + var cmd2 = ";chmod 755 " + patch_file; + console.log(cmd); + exec(cmd+cmd2, function(error) { + if (error) { + console.log(error); + errmsg = error; + // res.sendStatus(500); + } else { + var resp = {}; + resp.old_ver = m.old_ver; + resp.new_ver = m.new_ver; + resp.errmsg = "success"; + resp.patch_name = patch_name; + console.log(resp); + process.send(resp); + // process.disconnect(); + } + }); +}); + diff --git a/inc/iotivity/AttributeValue.h b/inc/iotivity/AttributeValue.h new file mode 100644 index 0000000..3315356 --- /dev/null +++ b/inc/iotivity/AttributeValue.h @@ -0,0 +1,156 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH 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. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +/** + * @file + * + * This file contains the definition of the internally used type + * AttributeValue. + */ + +#ifndef OC_ATTRIBUTEVALUE_H_ +#define OC_ATTRIBUTEVALUE_H_ + +// These defines are required to get the boost::variant to hold more than 20 items. +// documentation requires that you use a power of 10 +#define BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS +#define BOOST_MPL_LIMIT_LIST_SIZE 30 +#define BOOST_MPL_LIMIT_VECTOR_SIZE 30 +#include +#include +#include +namespace OC +{ + class OCRepresentation; + + struct NullType{}; + + // Since null needs to be encoded in a special fashion in JSON, the encoder + // needs to know the index of the NullType Sentinel Any time the code does a special + // case for the NullType, we use the AttributeValueNullIndex. This MUST be kept up to date + // with the variant's which() for NullType. + static const int AttributeValueNullIndex = 0; + typedef boost::variant< + NullType, // Note: this handles the null-type and must match the above static const + int, + double, + bool, + std::string, + OC::OCRepresentation, + OCByteString, + + // Sequences: + std::vector, + std::vector, + std::vector, + std::vector, + std::vector, + std::vector, + + // Nested sequences: + std::vector>, + std::vector>>, + + std::vector>, + std::vector>>, + + std::vector>, + std::vector>>, + + std::vector>, + std::vector>>, + + std::vector>, + std::vector>>, + + std::vector>, + std::vector>>, + + // used for binary data type + std::vector + > AttributeValue; + + enum class AttributeType + { + Null, + Integer, + Double, + Boolean, + String, + OCRepresentation, + Vector, + Binary, + OCByteString + }; + + template + struct AttributeTypeConvert{}; + + template<> + struct AttributeTypeConvert + { + BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::Null; + }; + + template<> + struct AttributeTypeConvert + { + BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::Integer; + }; + + template<> + struct AttributeTypeConvert + { + BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::Double; + }; + + template<> + struct AttributeTypeConvert + { + BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::Boolean; + }; + + template<> + struct AttributeTypeConvert + { + BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::String; + }; + + template<> + struct AttributeTypeConvert + { + BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::OCRepresentation; + }; + + template<> + struct AttributeTypeConvert + { + BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::OCByteString; + }; + + template<> + struct AttributeTypeConvert> + { + BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::Binary; + }; + + std::ostream& operator << (std::ostream& os, const AttributeType at); +} +#endif // OC_ATTRIBUTEVALUE_H_ diff --git a/inc/iotivity/CAManager.h b/inc/iotivity/CAManager.h new file mode 100644 index 0000000..3a19a07 --- /dev/null +++ b/inc/iotivity/CAManager.h @@ -0,0 +1,90 @@ +/* **************************************************************** + * + * Copyright 2016 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. + * + ******************************************************************/ + +#ifndef CA_MANAGER_H_ +#define CA_MANAGER_H_ + +#include + +namespace OC +{ + /** + * This namespace contains the main entrance/functionality to monitoring network changes. + * It may be used with OC::CAManager::functionName. To set a custom callback function, + * the implementer must make a call to CAManager::setNetworkMonitorHandler. + */ + namespace CAManager + { + // typedef to get adapter status changes from CA. + typedef std::function ConnectionChangedCallback; + + // typedef to get connection status changes from CA. + typedef std::function AdapterChangedCallback; + + /** + * Set network monitoring handler. + * @param adapterHandler adapter state change handler to handle changes for + * any transport types. + * @param connectionHandler connection state change handler to handle changes for + * connection with remote devices. + * @return Returns ::OC_STACK_OK if success. + */ + OCStackResult setNetworkMonitorHandler(AdapterChangedCallback adapterHandler, + ConnectionChangedCallback connectionHandler); + + /** + * Set port number to use. + * @param adapter transport adapter type to assign the specified port number. + * @param flag transport flag information. + * @param port the specified port number to use. + * @return Returns ::OC_STACK_OK if success. + */ + OCStackResult setPortNumberToAssign(OCTransportAdapter adapter, + OCTransportFlags flag, uint16_t port); + + /** + * Get the assigned port number. + * @param adapter transport adapter type to get the opened port number. + * @param flag transport flag information. + * @return Returns currently assigned port number. + */ + uint16_t getAssignedPortNumber(OCTransportAdapter adapter, OCTransportFlags flag); + +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) + /** + * Select the cipher suite for TLS/DTLS handshake. + * @param cipher cipher suite (Note : Make sure endianness). + * 0x35 : TLS_RSA_WITH_AES_256_CBC_SHA + * 0xC018 : TLS_ECDH_anon_WITH_AES_128_CBC_SHA + * 0xC037 : TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 + * 0xC0AE : TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 + * @param adapter transport adapter type. + * @return Returns ::OC_STACK_OK if success. + */ + OCStackResult setCipherSuite(const uint16_t cipher, OCTransportAdapter adapter); +#endif // defined(__WITH_DTLS__) || defined(__WITH_TLS__) + } +} + +#endif // CA_MANAGER_H_ + + + diff --git a/inc/iotivity/IClientWrapper.h b/inc/iotivity/IClientWrapper.h new file mode 100644 index 0000000..b453068 --- /dev/null +++ b/inc/iotivity/IClientWrapper.h @@ -0,0 +1,158 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH 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. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef OC_I_CLIENT_WRAPPER_H_ +#define OC_I_CLIENT_WRAPPER_H_ + +#include +#include +#include + +namespace OC +{ + class OCPlatform_impl; + + class IClientWrapper : public std::enable_shared_from_this + { + protected: + + public: + typedef std::shared_ptr Ptr; + + IClientWrapper() + {} + + virtual OCStackResult ListenForResource(const std::string& serviceUrl, + const std::string& resourceType, + OCConnectivityType connectivityType, + FindCallback& callback, + QualityOfService QoS) = 0; + + virtual OCStackResult ListenForResource2(const std::string& serviceUrl, + const std::string& resourceType, + OCConnectivityType connectivityType, + FindResListCallback& callback, + QualityOfService QoS) = 0; + + virtual OCStackResult ListenErrorForResource(const std::string& serviceUrl, + const std::string& resourceType, + OCConnectivityType connectivityType, + FindCallback& callback, + FindErrorCallback& errorCallback, + QualityOfService QoS) = 0; + + virtual OCStackResult ListenForDevice(const std::string& serviceUrl, + const std::string& deviceURI, + OCConnectivityType connectivityType, + FindDeviceCallback& callback, + QualityOfService QoS) = 0; + + virtual OCStackResult GetResourceRepresentation( + const OCDevAddr& devAddr, + const std::string& uri, + const QueryParamsMap& queryParams, + const HeaderOptions& headerOptions, + OCConnectivityType connectivityType, + GetCallback& callback, QualityOfService QoS)=0; + + virtual OCStackResult PutResourceRepresentation( + const OCDevAddr& devAddr, + const std::string& uri, + const OCRepresentation& rep, const QueryParamsMap& queryParams, + const HeaderOptions& headerOptions, + PutCallback& callback, QualityOfService QoS) = 0; + + virtual OCStackResult PostResourceRepresentation( + const OCDevAddr& devAddr, + const std::string& uri, + const OCRepresentation& rep, const QueryParamsMap& queryParams, + const HeaderOptions& headerOptions, + OCConnectivityType connectivityType, + PostCallback& callback, QualityOfService QoS) = 0; + + virtual OCStackResult DeleteResource( + const OCDevAddr& devAddr, + const std::string& uri, + const HeaderOptions& headerOptions, + OCConnectivityType connectivityType, + DeleteCallback& callback, QualityOfService QoS) = 0; + + virtual OCStackResult ObserveResource( + ObserveType observeType, OCDoHandle* handle, + const OCDevAddr& devAddr, + const std::string& uri, + const QueryParamsMap& queryParams, + const HeaderOptions& headerOptions, ObserveCallback& callback, + QualityOfService QoS)=0; + + virtual OCStackResult CancelObserveResource( + OCDoHandle handle, + const std::string& host, + const std::string& uri, + const HeaderOptions& headerOptions, + QualityOfService QoS)=0; + + virtual OCStackResult SubscribePresence(OCDoHandle* handle, + const std::string& host, + const std::string& resourceType, + OCConnectivityType connectivityType, + SubscribeCallback& presenceHandler)=0; + + virtual OCStackResult UnsubscribePresence(OCDoHandle handle) =0; + +#ifdef WITH_CLOUD + virtual OCStackResult SubscribeDevicePresence(OCDoHandle* handle, + const std::string& host, + const std::vector& di, + OCConnectivityType connectivityType, + ObserveCallback& callback) = 0; +#endif + + virtual OCStackResult GetDefaultQos(QualityOfService& qos) = 0; + + virtual OCStackResult FindDirectPairingDevices(unsigned short waittime, + GetDirectPairedCallback& callback) = 0; + + virtual OCStackResult GetDirectPairedDevices(GetDirectPairedCallback& callback) = 0; + + virtual OCStackResult DoDirectPairing(std::shared_ptr< OCDirectPairing > peer, + const OCPrm_t& pmSel, const std::string& pinNumber, + DirectPairingCallback& resultCallback) = 0; + +#ifdef WITH_MQ + virtual OCStackResult ListenForMQTopic( + const OCDevAddr& devAddr, + const std::string& resourceUri, + const QueryParamsMap& queryParams, const HeaderOptions& headerOptions, + MQTopicCallback& callback, QualityOfService QoS) = 0; + + virtual OCStackResult PutMQTopicRepresentation( + const OCDevAddr& devAddr, + const std::string& uri, + const OCRepresentation& rep, + const QueryParamsMap& queryParams, const HeaderOptions& headerOptions, + MQTopicCallback& callback, QualityOfService QoS) = 0; +#endif + virtual ~IClientWrapper(){} + }; +} + +#endif + diff --git a/inc/iotivity/IServerWrapper.h b/inc/iotivity/IServerWrapper.h new file mode 100644 index 0000000..d49dc1b --- /dev/null +++ b/inc/iotivity/IServerWrapper.h @@ -0,0 +1,83 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH 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. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef OC_I_SERVER_WRAPPER_H_ +#define OC_I_SERVER_WRAPPER_H_ + +#include +#include + +#include +#include +#include +#include + +namespace OC +{ + class IServerWrapper + { + protected: + + public: + typedef std::shared_ptr Ptr; + + IServerWrapper() + {} + + virtual ~IServerWrapper(){}; + + virtual OCStackResult registerResource( + OCResourceHandle& resourceHandle, + std::string& resourceURI, + const std::string& resourceTypeName, + const std::string& resourceInterface, + EntityHandler& entityHandler, + uint8_t resourceProperty) = 0; + + virtual OCStackResult registerDeviceInfo( + const OCDeviceInfo deviceInfo) = 0; + + virtual OCStackResult registerPlatformInfo( + const OCPlatformInfo PlatformInfo) = 0; + + virtual OCStackResult unregisterResource( + const OCResourceHandle& resourceHandle) = 0; + virtual OCStackResult bindTypeToResource( + const OCResourceHandle& resourceHandle, + const std::string& resourceTypeName) = 0; + + virtual OCStackResult bindInterfaceToResource( + const OCResourceHandle& resourceHandle, + const std::string& resourceInterfaceName) = 0; + + virtual OCStackResult startPresence(const unsigned int seconds) = 0; + + virtual OCStackResult stopPresence() = 0; + + virtual OCStackResult setDefaultDeviceEntityHandler(EntityHandler entityHandler) = 0; + + virtual OCStackResult sendResponse(const std::shared_ptr pResponse) = 0; + + virtual OCStackResult setPropertyValue(OCPayloadType type, const std::string& tag, const std::string& value) = 0; + virtual OCStackResult getPropertyValue(OCPayloadType type, const std::string& tag, std::string& value) = 0; + }; +} + +#endif diff --git a/inc/iotivity/InProcClientWrapper.h b/inc/iotivity/InProcClientWrapper.h new file mode 100644 index 0000000..bbf6a38 --- /dev/null +++ b/inc/iotivity/InProcClientWrapper.h @@ -0,0 +1,248 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH 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. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef OC_IN_PROC_CLIENT_WRAPPER_H_ +#define OC_IN_PROC_CLIENT_WRAPPER_H_ + +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace OC +{ + namespace ClientCallbackContext + { + struct GetContext + { + GetCallback callback; + GetContext(GetCallback cb) : callback(cb){} + }; + + struct SetContext + { + PutCallback callback; + SetContext(PutCallback cb) : callback(cb){} + }; + + struct ListenContext + { + FindCallback callback; + std::weak_ptr clientWrapper; + + ListenContext(FindCallback cb, std::weak_ptr cw) + : callback(cb), clientWrapper(cw){} + }; + + struct ListenContext2 + { + FindResListCallback callback; + std::weak_ptr clientWrapper; + + ListenContext2(FindResListCallback cb, std::weak_ptr cw) + : callback(cb), clientWrapper(cw){} + }; + + struct ListenErrorContext + { + FindCallback callback; + FindErrorCallback errorCallback; + std::weak_ptr clientWrapper; + + ListenErrorContext(FindCallback cb1, FindErrorCallback cb2, + std::weak_ptr cw) + : callback(cb1), errorCallback(cb2), clientWrapper(cw){} + }; + + struct DeviceListenContext + { + FindDeviceCallback callback; + IClientWrapper::Ptr clientWrapper; + DeviceListenContext(FindDeviceCallback cb, IClientWrapper::Ptr cw) + : callback(cb), clientWrapper(cw){} + }; + + struct SubscribePresenceContext + { + SubscribeCallback callback; + SubscribePresenceContext(SubscribeCallback cb) : callback(cb){} + }; + + struct DeleteContext + { + DeleteCallback callback; + DeleteContext(DeleteCallback cb) : callback(cb){} + }; + + struct ObserveContext + { + ObserveCallback callback; + ObserveContext(ObserveCallback cb) : callback(cb){} + }; + + struct DirectPairingContext + { + DirectPairingCallback callback; + DirectPairingContext(DirectPairingCallback cb) : callback(cb){} + + }; + +#ifdef WITH_MQ + struct MQTopicContext + { + MQTopicCallback callback; + std::weak_ptr clientWrapper; + MQTopicContext(MQTopicCallback cb, std::weak_ptr cw) + : callback(cb), clientWrapper(cw){} + }; +#endif + } + + class InProcClientWrapper : public IClientWrapper + { + + public: + + InProcClientWrapper(std::weak_ptr csdkLock, + PlatformConfig cfg); + virtual ~InProcClientWrapper(); + + virtual OCStackResult ListenForResource(const std::string& serviceUrl, + const std::string& resourceType, OCConnectivityType transportFlags, + FindCallback& callback, QualityOfService QoS); + + virtual OCStackResult ListenForResource2(const std::string& serviceUrl, + const std::string& resourceType, OCConnectivityType transportFlags, + FindResListCallback& callback, QualityOfService QoS); + + virtual OCStackResult ListenErrorForResource(const std::string& serviceUrl, + const std::string& resourceType, OCConnectivityType transportFlags, + FindCallback& callback, FindErrorCallback& errorCallback, QualityOfService QoS); + + virtual OCStackResult ListenForDevice(const std::string& serviceUrl, + const std::string& deviceURI, OCConnectivityType transportFlags, + FindDeviceCallback& callback, QualityOfService QoS); + + virtual OCStackResult GetResourceRepresentation( + const OCDevAddr& devAddr, + const std::string& uri, + const QueryParamsMap& queryParams, const HeaderOptions& headerOptions, + OCConnectivityType connectivityType, + GetCallback& callback, QualityOfService QoS); + + virtual OCStackResult PutResourceRepresentation( + const OCDevAddr& devAddr, + const std::string& uri, + const OCRepresentation& attributes, const QueryParamsMap& queryParams, + const HeaderOptions& headerOptions, PutCallback& callback, QualityOfService QoS); + + virtual OCStackResult PostResourceRepresentation( + const OCDevAddr& devAddr, + const std::string& uri, + const OCRepresentation& attributes, const QueryParamsMap& queryParams, + const HeaderOptions& headerOptions, OCConnectivityType connectivityType, + PostCallback& callback, QualityOfService QoS); + + virtual OCStackResult DeleteResource( + const OCDevAddr& devAddr, + const std::string& uri, + const HeaderOptions& headerOptions, + OCConnectivityType connectivityType, + DeleteCallback& callback, QualityOfService QoS); + + virtual OCStackResult ObserveResource( + ObserveType observeType, OCDoHandle* handle, + const OCDevAddr& devAddr, + const std::string& uri, + const QueryParamsMap& queryParams, const HeaderOptions& headerOptions, + ObserveCallback& callback, QualityOfService QoS); + + virtual OCStackResult CancelObserveResource( + OCDoHandle handle, + const std::string& host, + const std::string& uri, + const HeaderOptions& headerOptions, QualityOfService QoS); + + virtual OCStackResult SubscribePresence( + OCDoHandle *handle, + const std::string& host, + const std::string& resourceType, + OCConnectivityType transportFlags, + SubscribeCallback& presenceHandler); + + virtual OCStackResult UnsubscribePresence(OCDoHandle handle); + +#ifdef WITH_CLOUD + virtual OCStackResult SubscribeDevicePresence(OCDoHandle* handle, + const std::string& host, + const std::vector& di, + OCConnectivityType connectivityType, + ObserveCallback& callback); +#endif + + OCStackResult GetDefaultQos(QualityOfService& QoS); + + virtual OCStackResult FindDirectPairingDevices(unsigned short waittime, + GetDirectPairedCallback& callback); + + virtual OCStackResult GetDirectPairedDevices(GetDirectPairedCallback& callback); + + virtual OCStackResult DoDirectPairing(std::shared_ptr peer, const OCPrm_t& pmSel, + const std::string& pinNumber, DirectPairingCallback& resultCallback); + +#ifdef WITH_MQ + virtual OCStackResult ListenForMQTopic( + const OCDevAddr& devAddr, + const std::string& resourceUri, + const QueryParamsMap& queryParams, const HeaderOptions& headerOptions, + MQTopicCallback& callback, QualityOfService QoS); + + virtual OCStackResult PutMQTopicRepresentation( + const OCDevAddr& devAddr, + const std::string& uri, + const OCRepresentation& rep, + const QueryParamsMap& queryParams, const HeaderOptions& headerOptions, + MQTopicCallback& callback, QualityOfService QoS); +#endif + + private: + void listeningFunc(); + std::string assembleSetResourceUri(std::string uri, const QueryParamsMap& queryParams); + std::string assembleSetResourceUri(std::string uri, const QueryParamsList& queryParams); + OCPayload* assembleSetResourcePayload(const OCRepresentation& attributes); + OCHeaderOption* assembleHeaderOptions(OCHeaderOption options[], + const HeaderOptions& headerOptions); + void convert(const OCDPDev_t *list, PairedDevices& dpList); + std::thread m_listeningThread; + bool m_threadRun; + std::weak_ptr m_csdkLock; + + private: + PlatformConfig m_cfg; + }; +} + +#endif + diff --git a/inc/iotivity/InProcServerWrapper.h b/inc/iotivity/InProcServerWrapper.h new file mode 100644 index 0000000..0ea25e8 --- /dev/null +++ b/inc/iotivity/InProcServerWrapper.h @@ -0,0 +1,83 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH 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. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef OC_IN_PROC_SERVER_WRAPPER_H_ +#define OC_IN_PROC_SERVER_WRAPPER_H_ + +#include +#include + +#include + +namespace OC +{ + class InProcServerWrapper : public IServerWrapper + { + public: + InProcServerWrapper( + std::weak_ptr csdkLock, + PlatformConfig cfg); + virtual ~InProcServerWrapper(); + + virtual OCStackResult registerResource( + OCResourceHandle& resourceHandle, + std::string& resourceURI, + const std::string& resourceTypeName, + const std::string& resourceInterface, + EntityHandler& entityHandler, + uint8_t resourceProperty); + + virtual OCStackResult registerDeviceInfo( + const OCDeviceInfo deviceInfo); + + virtual OCStackResult registerPlatformInfo( + const OCPlatformInfo PlatformInfo); + + virtual OCStackResult unregisterResource( + const OCResourceHandle& resourceHandle); + + virtual OCStackResult bindTypeToResource( + const OCResourceHandle& resourceHandle, + const std::string& resourceTypeName); + + virtual OCStackResult bindInterfaceToResource( + const OCResourceHandle& resourceHandle, + const std::string& resourceInterface); + + virtual OCStackResult startPresence(const unsigned int seconds); + + virtual OCStackResult stopPresence(); + + virtual OCStackResult setDefaultDeviceEntityHandler(EntityHandler entityHandler); + + virtual OCStackResult sendResponse(const std::shared_ptr pResponse); + + virtual OCStackResult setPropertyValue(OCPayloadType type, const std::string& tag, const std::string& value); + virtual OCStackResult getPropertyValue(OCPayloadType type, const std::string& tag, std::string& value); + + private: + void processFunc(); + std::thread m_processThread; + bool m_threadRun; + std::weak_ptr m_csdkLock; + }; +} + +#endif diff --git a/inc/iotivity/InitializeException.h b/inc/iotivity/InitializeException.h new file mode 100644 index 0000000..ab5282f --- /dev/null +++ b/inc/iotivity/InitializeException.h @@ -0,0 +1,39 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH 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. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef OC_INITIALIZE_EXCEPTION_H_ +#define OC_INITIALIZE_EXCEPTION_H_ + +#include +#include "StringConstants.h" + +namespace OC +{ + class InitializeException : public OC::OCException + { + public: + InitializeException(const std::string& msg, OCStackResult reasonCode): + OC::OCException(msg, reasonCode) + { + } + }; +} + +#endif diff --git a/inc/iotivity/OCAccountManager.h b/inc/iotivity/OCAccountManager.h new file mode 100644 index 0000000..11fa50b --- /dev/null +++ b/inc/iotivity/OCAccountManager.h @@ -0,0 +1,356 @@ +/* **************************************************************** + * + * Copyright 2016 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. + * + ******************************************************************/ + +#ifndef OC_ACCOUNT_MANAGER_H_ +#define OC_ACCOUNT_MANAGER_H_ + +#include + +#include +#include +#include + +namespace OC +{ + class OCAccountManager + { + friend class OCPlatform_impl; + + public: + typedef std::shared_ptr Ptr; + + OCAccountManager(OCAccountManager&&) = default; + OCAccountManager(const OCAccountManager&) = delete; + OCAccountManager& operator=(OCAccountManager&&) = delete; + OCAccountManager& operator=(const OCAccountManager&) = delete; + + virtual ~OCAccountManager(void); + + /** + * Function to get the host address of account server. + * + * @return std::string host address + */ + std::string host() const; + + /** + * Function to get the connectivity type for account server. + * + * @return enum connectivity type (flags and adapter) + */ + OCConnectivityType connectivityType() const; + + /** + * Function for account registration to account server. + * + * @param authProvider Provider name used for authentication. + * @param authCode The authorization code obtained by using an authorization server + * as an intermediary between the client and resource owner. + * @param cloudConnectHandler Callback function that will get the result of the operation. + * + * @return Returns ::OC_STACK_OK if success + */ + OCStackResult signUp(const std::string& authProvider, + const std::string& authCode, + PostCallback cloudConnectHandler); + + /** + * Overload + * + * @param authProvider Provider name used for authentication. + * @param authCode The authorization code obtained by using an authorization server + * as an intermediary between the client and resource owner. + * @param options The option values depends on auth provider. + * @param cloudConnectHandler Callback function that will get the result of the operation. + * + * @return Returns ::OC_STACK_OK if success + */ + OCStackResult signUp(const std::string& authProvider, + const std::string& authCode, + const QueryParamsMap& options, + PostCallback cloudConnectHandler); + + /** + * Function for sign-in to account server. + * + * @param userUuid Identifier of the user obtained by account registration. + * @param accessToken Identifier of the resource obtained by account registration. + * @param cloudConnectHandler Callback function that will get the result of the operation. + * + * @return Returns ::OC_STACK_OK if success + */ + OCStackResult signIn(const std::string& userUuid, + const std::string& accessToken, + PostCallback cloudConnectHandler); + + /** + * Function for sign-out to account server. + * + * @param accessToken Identifier of the resource obtained by account registration. + * @param cloudConnectHandler Callback function that will get the result of the operation. + * + * @return Returns ::OC_STACK_OK if success + */ + OCStackResult signOut(const std::string& accessToken, + PostCallback cloudConnectHandler); + + /** + * Function for refresh access token to account server. + * + * @param userUuid Identifier of the user obtained by account registration. + * @param refreshToken Refresh token used for access token refresh. + * @param cloudConnectHandler Callback function that will get the result of the operation. + * + * @return Returns ::OC_STACK_OK if success + */ + OCStackResult refreshAccessToken(const std::string& userUuid, + const std::string& refreshToken, + PostCallback cloudConnectHandler); + + /** + * Function to get information of the user to account server. + * + * @param queryParams Map that has a query key and value for specific users. + * Account server can response information of more than one user. + * @param cloudConnectHandler Callback function that will get the result of the operation. + * + * @return Returns ::OC_STACK_OK if success + */ + OCStackResult searchUser(const QueryParamsMap& queryParams, + GetCallback cloudConnectHandler); + + /** + * Function to delete the device registered on the account signed-in. + * + * @param accessToken Identifier of the resource obtained by account registration. + * @param deviceId Device ID to delete. + * @param cloudConnectHandler Callback function that will get the result of the operation. + * + * @return Returns ::OC_STACK_OK if success + */ + OCStackResult deleteDevice(const std::string& accessToken, + const std::string& deviceId, + DeleteCallback cloudConnectHandler); + + /** + * Function to create a group on account server. + * + * @param cloudConnectHandler Callback function that will get the result of the operation. + * + * @return Returns ::OC_STACK_OK if success + */ + OCStackResult createGroup(PostCallback cloudConnectHandler); + + /** + * Overload + * + * @param queryParams Map that has optional properties and values to create a group. + * Defined properties on the OCF spec are [gname, parent] so far. + * (2016/10/19) + * @param cloudConnectHandler Callback function that will get the result of the operation. + * + * @return Returns ::OC_STACK_OK if success + */ + OCStackResult createGroup(const QueryParamsMap& queryParams, + PostCallback cloudConnectHandler); + + /** + * Function to delete the group from account server. + * + * @param groupId Group ID to delete. + * @param cloudConnectHandler Callback function that will get the result of the operation. + * + * @return Returns ::OC_STACK_OK if success + */ + OCStackResult deleteGroup(const std::string& groupId, + DeleteCallback cloudConnectHandler); + + /** + * Function to get infomation of all your group from account server. + * + * @param cloudConnectHandler Callback function that will get the result of the operation. + * + * @return Returns ::OC_STACK_OK if success + */ + + OCStackResult getGroupInfoAll(GetCallback cloudConnectHandler); + + /** + * Function to get information of the specific group from account server. + * + * @param groupId Group ID to get information. + * @param cloudConnectHandler Callback function that will get the result of the operation. + * + * @return Returns ::OC_STACK_OK if success + */ + OCStackResult getGroupInfo(const std::string& groupId, + GetCallback cloudConnectHandler); + + /** + * Function to add values for properties to the group on account server. + * + * @param groupId Group ID to add property values. + * @param propertyValue OCRepresentation info that has pairs of property and value. + * Defined properties on the OCF spec are [members, masters, devices, + * resources, links] so far. (2016/10/19) + * @param cloudConnectHandler Callback function that will get the result of the operation. + * + * @return Returns ::OC_STACK_OK if success + */ + OCStackResult addPropertyValueToGroup(const std::string& groupId, + const OCRepresentation propertyValue, + PostCallback cloudConnectHandler); + + /** + * Function to delete values for properties from the group on account server. + * + * @param groupId Group ID to delete information. + * @param propertyValue OCRepresentation info that has pairs of property and value. + * Defined properties on the OCF spec are [members, masters, devices, + * resources, links] so far. (2016/10/19) + * @param cloudConnectHandler Callback function that will get the result of the operation. + * + * @return Returns ::OC_STACK_OK if success + */ + OCStackResult deletePropertyValueFromGroup(const std::string& groupId, + const OCRepresentation propertyValue, + PostCallback cloudConnectHandler); + + /** + * Function to update values for properties on the group on account server. + * It completely replaces existing values for specific properties. + * + * @param groupId Group ID to add devices. + * @param propertyValue OCRepresentation info that has pairs of property and value. + * Defined properties on the OCF spec are [members, gname, owner, + * masters, devices, resources, latitude, longitude, radius, + * backgroundImage] so far. (2016/10/19) + * @param cloudConnectHandler Callback function that will get the result of the operation. + * + * @return Returns ::OC_STACK_OK if success + */ + OCStackResult updatePropertyValueOnGroup(const std::string& groupId, + const OCRepresentation propertyValue, + PostCallback cloudConnectHandler); + + /** + * Function to register observe to group resource on account server. + * You can receive a notify when any value of property get changed in the group you joined. + * + * @param cloudConnectHandler Callback function that will get the result of the operation. + * + * @return Returns ::OC_STACK_OK if success + */ + OCStackResult observeGroup(ObserveCallback cloudConnectHandler); + + /** + * Function to cancel observe to group resource on account server. + * + * @return Returns ::OC_STACK_OK if success + */ + OCStackResult cancelObserveGroup(); + + /** + * Function to register observe to invitation resource on account server. + * You can receive a notify when you send or receive a invitation. + * Sending a invitation will be notified as 'invite' and Receiving will be as 'invited'. + * If you receive a invitation from other user, you should call 'replyToInvitation' to + * delete the invitation on account server, otherwise it will remain on the server. + * + * @param cloudConnectHandler Callback function that will get the result of the operation. + * + * @return Returns ::OC_STACK_OK if success + */ + OCStackResult observeInvitation(ObserveCallback cloudConnectHandler); + + /** + * Function to cancel observe to invitation resource on account server. + * + * @return Returns ::OC_STACK_OK if success + */ + OCStackResult cancelObserveInvitation(); + + /** + * Function to send a invitation to invite a user into a group. + * + * @param groupId Group ID for inviting. + * @param userUuid Identifier of the user to invite. + * @param cloudConnectHandler Callback function that will get the result of the operation. + * + * @return Returns ::OC_STACK_OK if success + */ + OCStackResult sendInvitation(const std::string& groupId, + const std::string& userUuid, + PostCallback cloudConnectHandler); + + /** + * Function to cancel a invitation you has sent on account server before the invited user + * replies. + * + * @param groupId Group ID to cancel a invitation. + * @param userUuid Identifier of the user to cancel a invitation. + * @param cloudConnectHandler Callback function that will get the result of the operation. + * + * @return Returns ::OC_STACK_OK if success + */ + OCStackResult cancelInvitation(const std::string& groupId, + const std::string& userUuid, + DeleteCallback cloudConnectHandler); + + /** + * Function to reply to the invitation that you has received. + * If you set accept as true, you will join the group as a member and the invitation + * will be deleted on account server. + * If false, only the invitation will be deleted. + * + * @param groupId Group ID to delete a invitation. + * @param accept boolean whether to join the group or not. + * @param cloudConnectHandler Callback function that will get the result of the operation. + * + * @return Returns ::OC_STACK_OK if success + */ + OCStackResult replyToInvitation(const std::string& groupId, + const bool accept, + DeleteCallback cloudConnectHandler); + + private: + std::weak_ptr m_clientWrapper; + std::string m_deviceID; + std::string m_host; + std::string m_userUuid; + OCDoHandle m_invitationObserveHandle; + OCDoHandle m_groupObserveHandle; + OCConnectivityType m_connType; + QualityOfService m_defaultQos; + + private: + OCAccountManager(std::weak_ptr clientWrapper, + const std::string& host, + OCConnectivityType connectivityType); + + OCStackResult signInOut(const std::string& userUuid, + const std::string& accessToken, + bool isSignIn, + PostCallback cloudConnectHandler); + }; +} // namespace OC + +#endif // OC_ACCOUNT_MANAGER_H_ + diff --git a/inc/iotivity/OCApi.h b/inc/iotivity/OCApi.h new file mode 100644 index 0000000..ff2d212 --- /dev/null +++ b/inc/iotivity/OCApi.h @@ -0,0 +1,306 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH 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. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef OC_OCAPI_H_ +#define OC_OCAPI_H_ + +#include +#include +#include +#include +#include +#include +#if defined(_MSC_VER) +#include +#endif + +#include "octypes.h" +#include "OCHeaderOption.h" +#include +#include "StringConstants.h" +#include "oc_logger.hpp" + +#include + +namespace OC +{ + class OCResource; + class OCResourceRequest; + class OCResourceResponse; + class OCDirectPairing; +} // namespace OC + +namespace OC +{ +#if defined(_MSC_VER) + extern std::ostream& oclog(); +#else + typedef boost::iostreams::stream log_target_t; + + namespace detail + { + /* We'll want to provide some sort of explicit hook for custom logging at some + point; until then, this should do nicely (note that since these are lambdas, + later a special target could be captured, allowing much flexibility): */ + auto oclog_target = []() -> log_target_t& + { + static OC::oc_log_stream ols(oc_make_ostream_logger); + static log_target_t os(ols); + + return os; + }; + } // namespace OC::detail + + auto oclog = []() -> boost::iostreams::stream& + { + return detail::oclog_target(); + }; +#endif +} // namespace OC + +namespace OC +{ + + enum class OCPlatformStatus + { + PlatformUp, + PlatformDown + }; + + enum class OCAdvertisementStatus + { + None + }; + + typedef std::string URI; + + enum class ServiceType + { + InProc, + OutOfProc + }; + + /** + * Host Mode of Operation. + */ + enum class ModeType + { + Server, + Client, + Both, + Gateway /**< Client server mode along with routing capabilities.*/ + }; + + /** + * Quality of Service attempts to abstract the guarantees provided by the underlying transport + * protocol. The precise definitions of each quality of service level depend on the + * implementation. In descriptions below are for the current implementation and may changed + * over time. + */ + enum class QualityOfService : uint8_t + { + /** Packet delivery is best effort. */ + LowQos = OC_LOW_QOS, + + /** Packet delivery is best effort. */ + MidQos = OC_MEDIUM_QOS, + + /** Acknowledgments are used to confirm delivery. */ + HighQos = OC_HIGH_QOS, + + /** No Quality is defined, let the stack decide. */ + NaQos = OC_NA_QOS + }; + + /** + * Data structure to provide the configuration. + */ + struct PlatformConfig + { + /** indicate InProc or OutOfProc. */ + ServiceType serviceType; + + /** indicate whether we want to do server, client or both. */ + ModeType mode; + + /** default flags for server. */ + OCConnectivityType serverConnectivity; + + /** default flags for client. */ + OCConnectivityType clientConnectivity; + + /** not used. */ + std::string ipAddress; + + /** not used. */ + uint16_t port; + + /** indicate Quality of Service : LowQos, MidQos,HighQos and NaQos(No quality Defined). */ + QualityOfService QoS; + + /** persistant storage Handler structure (open/read/write/close/unlink). */ + OCPersistentStorage *ps; + + public: + PlatformConfig() + : serviceType(ServiceType::InProc), + mode(ModeType::Both), + serverConnectivity(CT_DEFAULT), + clientConnectivity(CT_DEFAULT), + ipAddress("0.0.0.0"), + port(0), + QoS(QualityOfService::NaQos), + ps(nullptr) + {} + PlatformConfig(const ServiceType serviceType_, + const ModeType mode_, + OCConnectivityType serverConnectivity_, + OCConnectivityType clientConnectivity_, + const QualityOfService QoS_, + OCPersistentStorage *ps_ = nullptr) + : serviceType(serviceType_), + mode(mode_), + serverConnectivity(serverConnectivity_), + clientConnectivity(clientConnectivity_), + ipAddress(""), + port(0), + QoS(QoS_), + ps(ps_) + {} + // for backward compatibility + PlatformConfig(const ServiceType serviceType_, + const ModeType mode_, + const std::string& ipAddress_, + const uint16_t port_, + const QualityOfService QoS_, + OCPersistentStorage *ps_ = nullptr) + : serviceType(serviceType_), + mode(mode_), + serverConnectivity(CT_DEFAULT), + clientConnectivity(CT_DEFAULT), + ipAddress(ipAddress_), + port(port_), + QoS(QoS_), + ps(ps_) + {} + }; + + enum RequestHandlerFlag + { + RequestFlag = 1 << 1, + ObserverFlag = 1 << 2 + }; + + enum class ObserveType + { + Observe, + ObserveAll + }; + + // Typedef for list of resource handles. + typedef std::vector ResourceHandles; + + // Typedef for header option vector. + // OCHeaderOption class is in HeaderOption namespace. + typedef std::vector HeaderOptions; + + // Typedef for query parameter map. + typedef std::map QueryParamsMap; + + // Typedef for query parameter map with Vector + typedef std::map< std::string, std::vector > QueryParamsList; + + // Typedef for list of observation IDs. + typedef std::vector ObservationIds; + + enum class ObserveAction + { + ObserveRegister, + ObserveUnregister + }; + + typedef struct + { + // Action associated with observation request + ObserveAction action; + // Identifier for observation being registered/unregistered + OCObservationId obsId; + + OCConnectivityType connectivityType; + std::string address; + uint16_t port; + } ObservationInfo; + + // const strings for different interfaces + + // Default interface + const std::string DEFAULT_INTERFACE = "oic.if.baseline"; + + // Used in discovering (GET) links to other resources of a collection. + const std::string LINK_INTERFACE = "oic.if.ll"; + + // Used in GET, PUT, POST, DELETE methods on links to other resources of a collection. + const std::string BATCH_INTERFACE = "oic.if.b"; + + // Used in GET, PUT, POST methods on links to other remote resources of a group. + const std::string GROUP_INTERFACE = "oic.mi.grp"; + + //Typedef for list direct paired devices + typedef std::vector> PairedDevices; + + typedef std::function)> FindCallback; + + typedef std::function FindErrorCallback; + + typedef std::function>)> FindResListCallback; + + typedef std::function FindDeviceCallback; + + typedef std::function FindPlatformCallback; + + typedef std::function)> EntityHandler; + + typedef std::function SubscribeCallback; + + typedef std::function GetCallback; + + typedef std::function PostCallback; + + typedef std::function PutCallback; + + typedef std::function DeleteCallback; + + typedef std::function ObserveCallback; + + typedef std::function, OCStackResult)> DirectPairingCallback; + + typedef std::function GetDirectPairedCallback; + + typedef std::function)> MQTopicCallback; +} // namespace OC + +#endif diff --git a/inc/iotivity/OCCloudProvisioning.hpp b/inc/iotivity/OCCloudProvisioning.hpp new file mode 100755 index 0000000..491f68a --- /dev/null +++ b/inc/iotivity/OCCloudProvisioning.hpp @@ -0,0 +1,139 @@ +//**************************************************************** +// +// Copyright 2016 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. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef OC_CLOUD_PROVISIONING_CXX_H_ +#define OC_CLOUD_PROVISIONING_CXX_H_ + +#include + +#include "occloudprovisioning.h" +#include "OCApi.h" +#include "OCPlatform_impl.h" +#include "CAManager.h" + +namespace OC +{ + typedef std::function ResponseCallBack; + typedef std::function AclIdResponseCallBack; + + /** + * Context to be passed to the underlying stack. This is passed back as argument + * to the callback function + */ + struct CloudProvisionContext + { + ResponseCallBack callback; + CloudProvisionContext(ResponseCallBack cb) : callback(cb){} + }; + + struct AclIdContext + { + AclIdResponseCallBack callback; + AclIdContext(AclIdResponseCallBack cb) : callback(cb){} + }; + + class OCCloudProvisioning + { + + private: + OCDevAddr m_devAddr; + public: + + /** + * API to construct the CloudProvisioning + * @param ipAddr address of the cloud server + * @param port port of the cloud server + */ + OCCloudProvisioning(std::string& ipAddr, uint16_t port); + ~OCCloudProvisioning(); + + void setIpAddr(std::string& ipAddr) + { + memcpy(m_devAddr.addr, ipAddr.c_str(), MAX_ADDR_STR_SIZE); + } + + void setPort(uint16_t port) + { + m_devAddr.port = port; + } + + /** + * API to Request a certificate from the cloud + * @param callback function called by the stack on completion of request + * @return ::OC_STACK_OK on Success and other values otherwise + */ + OCStackResult requestCertificate(ResponseCallBack callback); + + /** + * API to get ACL ID for the device + * @param deviceId device ID for which the Acl ID is requested + * @param callback function called by the stack on completion of request + * @return ::OC_STACK_OK on Success and other values otherwise + */ + OCStackResult getAclIdByDevice(const std::string& deviceId, AclIdResponseCallBack callback); + + /** + * API to get ACL information about the given Acl ID + * @param aclId ACL ID for which the Acl information is requested + * @param callback function called by the stack on completion of request + * @return ::OC_STACK_OK on Success and other values otherwise + */ + OCStackResult getIndividualAclInfo(const std::string& aclId, ResponseCallBack callback); + + /** + * API to get certificate revocation list + * @param callback function called by the stack on completion of request + * @return ::OC_STACK_OK on Success and other values otherwise + */ + OCStackResult getCRL(ResponseCallBack callback); + + /** + * API to post the certificate revocation list to cloud + * @param thisUpdate thisUpdate [mandatory param] + * @param nextUpdate nextUpdate [mandatory param] + * @param crl revocation list [optional] + * @param serialNumbers [optional] + * @param callback function called by the stack on completion of request + * @return ::OC_STACK_OK on Success and other values otherwise + */ + OCStackResult postCRL(const std::string& thisUpdate, + const std::string& nextUpdate, + const OCByteString *crl, + const stringArray_t *serialNumbers, + ResponseCallBack callback); + + /** + * Common callback wrapper for all the callback functions. + * @param ctx user context passed to the request API + * @param result result of the request performed + * @param data response data + */ + static void callbackWrapper(void* ctx, OCStackResult result, void* data); + + /** + * Callback wrapper for Acl ID get request + * @param ctx user context passed to the request API + * @param result result of the request performed + * @param data AclID for the device + */ + static void aclIdResponseWrapper(void* ctx, OCStackResult result, void* data); + }; +} +#endif //OC_CLOUD_PROVISIONING_CXX_H_ diff --git a/inc/iotivity/OCDirectPairing.h b/inc/iotivity/OCDirectPairing.h new file mode 100644 index 0000000..3f27b83 --- /dev/null +++ b/inc/iotivity/OCDirectPairing.h @@ -0,0 +1,69 @@ +//****************************************************************** +// +// Copyright 2016 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. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef OC_DIRECT_PAIRING_H_ +#define OC_DIRECT_PAIRING_H_ +#include + +namespace OC +{ + class OCDirectPairing + { + public: + OCDirectPairing(OCDPDev_t *ptr); + /** + * Function to get the host address of direct pairing device. + * + * @return Returns host address in the format + * :IP:securePort + */ + std::string getHost(); + + /** + * Function to get the device ID of the direct pairing device. + * + * @return Returns device ID (UUID) + */ + std::string getDeviceID(); + + /** + * Function to get the pairing methods supported by direct pairing device. + * + * @return Returns vector of pairing methods supported. + * DP_NOT_ALLOWED + * DP_PRE_CONFIGURED + * DP_RANDOM_PIN + */ + std::vector getPairingMethods(); + + /** + * Function to get the connectivity Type. + * + * @return Returns connectivity Type + */ + OCConnectivityType getConnType(); + + OCDPDev_t* getDev(); + + private: + OCDPDev_t *m_devPtr; + }; +} +#endif //OC_DIRECT_PAIRING_H_ diff --git a/inc/iotivity/OCException.h b/inc/iotivity/OCException.h new file mode 100644 index 0000000..1d70e7d --- /dev/null +++ b/inc/iotivity/OCException.h @@ -0,0 +1,56 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH 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. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef OC_EXCEPTION_H_ +#define OC_EXCEPTION_H_ + +#include +#include +#include + +namespace OC { + +class OCException : public std::runtime_error +{ + public: + OCException(const std::string& msg, OCStackResult reason = OC_STACK_ERROR) + : std::runtime_error(msg), + m_reason(reason) + {} + + static std::string reason(const OCStackResult sr); + + std::string reason() const + { + return reason(m_reason); + } + + OCStackResult code() const + { + return m_reason; + } + + private: + OCStackResult m_reason; +}; + +} // namespace OC + +#endif diff --git a/inc/iotivity/OCHeaderOption.h b/inc/iotivity/OCHeaderOption.h new file mode 100644 index 0000000..78f9029 --- /dev/null +++ b/inc/iotivity/OCHeaderOption.h @@ -0,0 +1,124 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH 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. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +/** + * @file + * + * This file contains the declaration of classes and its members related to + * OCHeaderOption. + */ + +#ifndef OC_HEADEROPTION_H_ +#define OC_HEADEROPTION_H_ + +#include +#include +namespace OC +{ + namespace HeaderOption + { + /** + * @brief OCHeaderOption class allows to create instances which comprises optionID + * and optionData as members. These are used in setting Header options. + * After creating instances of OCHeaderOptions, use setHeaderOptions API + * (in OCResource.h) to set header Options. + * NOTE: HeaderOptionID is an unsigned integer value which MUST be within + * range of 2048 to 3000 inclusive of lower and upper bound + * except for If-Match with empty(num : 1), If-None-Match(num : 5), + * Location-Path(num : 8), Location-Query(num : 20) option. + * HeaderOptions instance creation fails if above condition is not satisfied. + */ + const uint16_t MIN_HEADER_OPTIONID = 2048; + const uint16_t MAX_HEADER_OPTIONID = 3000; + const uint16_t IF_MATCH_OPTION_ID = 1; + const uint16_t IF_NONE_MATCH_OPTION_ID = 5; + const uint16_t LOCATION_PATH_OPTION_ID = 8; + const uint16_t LOCATION_QUERY_OPTION_ID = 20; + + class OCHeaderOption + { + private: + uint16_t m_optionID; + std::string m_optionData; + + public: + /** + * OCHeaderOption constructor + */ + OCHeaderOption(uint16_t optionID, std::string optionData): + m_optionID(optionID), + m_optionData(optionData) + { + if (!(optionID >= MIN_HEADER_OPTIONID && optionID <= MAX_HEADER_OPTIONID) + && optionID != IF_MATCH_OPTION_ID + && optionID != IF_NONE_MATCH_OPTION_ID + && optionID != LOCATION_PATH_OPTION_ID + && optionID != LOCATION_QUERY_OPTION_ID) + { + throw OCException(OC::Exception::OPTION_ID_RANGE_INVALID); + } + } + + virtual ~OCHeaderOption(){} + + OCHeaderOption(const OCHeaderOption&) = default; + +#if defined(_MSC_VER) && (_MSC_VER < 1900) + OCHeaderOption(OCHeaderOption&& o) + { + std::memmove(this, &o, sizeof(o)); + } +#else + OCHeaderOption(OCHeaderOption&&) = default; +#endif + + OCHeaderOption& operator=(const OCHeaderOption&) = default; + +#if defined(_MSC_VER) && (_MSC_VER < 1900) + OCHeaderOption& operator=(OCHeaderOption&& o) + { + std::memmove(this, &o, sizeof(o)); + } +#else + OCHeaderOption& operator=(OCHeaderOption&&) = default; +#endif + + /** + * API to get Option ID + * @return unsigned integer option ID + */ + uint16_t getOptionID() const + { + return m_optionID; + } + + /* + * API to get Option data + * @return std::string of option data + */ + std::string getOptionData() const + { + return m_optionData; + } + }; + } // namespace HeaderOption +} // namespace OC + +#endif // OC_HEADEROPTION_H_ diff --git a/inc/iotivity/OCPlatform.h b/inc/iotivity/OCPlatform.h new file mode 100644 index 0000000..9903611 --- /dev/null +++ b/inc/iotivity/OCPlatform.h @@ -0,0 +1,707 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH 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. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +/** + * @file + * + * This file contains the declaration of classes and its members related to + * OCPlatform. + */ + +#ifndef OC_PLATFORM_H_ +#define OC_PLATFORM_H_ +#include +#include +namespace OC +{ + /** + * This namespace contains the main entrance/functionality of the product. + * It may be used with OC::OCPlatform::functionName. To set a custom configuration, + * the implementer must make a call to OCPlatform::Configure before the first usage + * of a function in this namespace. + */ + namespace OCPlatform + { + /** + * API for overwriting the default configuration of the OCPlatform object. + * @note Any calls made to this AFTER the first call to OCPlatform::Instance + * will have no affect + */ + void Configure(const PlatformConfig& config); + + // typedef for handle to cancel presence info with + typedef OCDoHandle OCPresenceHandle; + + /** + * API for notifying base that resource's attributes have changed. + * + * @param resourceHandle resource handle of the resource + * + * @return Returns ::OC_STACK_OK if success. + * @note This API is for server side only. + * @note OCResourceHandle is defined in ocstack.h + * @note OCStackResult is defined in ocstack.h. + * @see notifyAllObservers(OCResourceHandle, QualityOfService) + */ + OCStackResult notifyAllObservers(OCResourceHandle resourceHandle); + + /** + * @overload + * + * @param resourceHandle resource handle of the resource + * @param QoS the quality of communication + * @see notifyAllObservers(OCResourceHandle) + */ + OCStackResult notifyAllObservers(OCResourceHandle resourceHandle, QualityOfService QoS); + + /** + * API for notifying only specific clients that resource's attributes have changed. + * + * @param resourceHandle resource handle of the resource + * @param observationIds std vector of observationIds. These set of ids are ones which + * which will be notified upon resource change. + * @param responsePtr OCResourceResponse pointer used by app to fill the response for this + * resource change. + * + * @return Returns ::OC_STACK_OK if success. + * @note This API is for server side only. + * @note OCResourceHandle is defined in ocstack.h. + * @note OCStackResult is defined in ocstack.h. + * @see notifyListOfObservers(OCResourceHandle, ObservationIds&, const std::shared_ptr, QualityOfService) + */ + OCStackResult notifyListOfObservers( + OCResourceHandle resourceHandle, + ObservationIds& observationIds, + const std::shared_ptr responsePtr); + /** + * @overload + * + * @param resourceHandle resource handle of the resource + * @param observationIds std vector of observationIds. These set of ids are ones which + * which will be notified upon resource change. + * @param responsePtr OCResourceResponse pointer used by app to fill the response for this + * resource change. + * @param QoS the quality of communication + * @see notifyListOfObservers(OCResourceHandle, ObservationIds&, const std::shared_ptr) + */ + OCStackResult notifyListOfObservers( + OCResourceHandle resourceHandle, + ObservationIds& observationIds, + const std::shared_ptr responsePtr, + QualityOfService QoS); + + /** + * API for Service and Resource Discovery. + * @note This API applies to client side only. + * + * @param host Host IP Address of a service to direct resource discovery query. If null or + * empty, performs multicast resource discovery query + * @param resourceURI name of the resource. If null or empty, performs search for all + * resource names + * @param connectivityType ::OCConnectivityType type of connectivity indicating the + * interface. Example: CT_DEFAULT, CT_ADAPTER_IP, CT_ADAPTER_TCP. + * @param resourceHandler Handles callbacks, success states and failure states. + * + * Four modes of discovery defined as follows: + * (NULL/Empty, NULL/Empty) - Performs ALL service discovery AND ALL resource + * discovery. + * (NULL/Empty, Not Empty) - Performs query for a filtered/scoped/particular + * resource(s) from ALL services. + * (Not Empty, NULL/Empty) - Performs ALL resource discovery on a particular service. + * (Not Empty, Not Empty) - Performs query for a filtered/scoped/particular + * resource(s) + * from a particular service. + * + * @return Returns ::OC_STACK_OK if success. + * @note First parameter 'host' currently represents an IP address. This will change in + * future and will refer to endpoint interface so that we can refer to other transports such + * as BTH etc. + * @note OCStackResult is defined in ocstack.h. + * @see findResource(const std::string&, const std::string&, OCConnectivityType, FindCallback, QualityOfService) + */ + OCStackResult findResource(const std::string& host, const std::string& resourceURI, + OCConnectivityType connectivityType, FindCallback resourceHandler); + /** + * @overload + * + * @param host Host IP Address of a service to direct resource discovery query. If null or + * empty, performs multicast resource discovery query + * @param resourceURI name of the resource. If null or empty, performs search for all + * resource names + * @param connectivityType ::OCConnectivityType type of connectivity indicating the + * interface. Example: CT_DEFAULT, CT_ADAPTER_IP, CT_ADAPTER_TCP. + * @param resourceHandler Handles callbacks, success states and failure states. + * + * Four modes of discovery defined as follows: + * (NULL/Empty, NULL/Empty) - Performs ALL service discovery AND ALL resource + * discovery. + * (NULL/Empty, Not Empty) - Performs query for a filtered/scoped/particular + * resource(s) from ALL services. + * (Not Empty, NULL/Empty) - Performs ALL resource discovery on a particular service. + * (Not Empty, Not Empty) - Performs query for a filtered/scoped/particular + * resource(s) + * from a particular service. + * @param QoS QualityOfService the quality of communication + * @see findResource(const std::string&, const std::string&, OCConnectivityType, FindCallback) + */ + OCStackResult findResource(const std::string& host, const std::string& resourceURI, + OCConnectivityType connectivityType, FindCallback resourceHandler, + QualityOfService QoS); + + OCStackResult findResource(const std::string& host, const std::string& resourceURI, + OCConnectivityType connectivityType, FindCallback resourceHandler, + FindErrorCallback errorHandler); + + OCStackResult findResource(const std::string& host, const std::string& resourceURI, + OCConnectivityType connectivityType, FindCallback resourceHandler, + FindErrorCallback errorHandler, QualityOfService QoS); + + OCStackResult findResourceList(const std::string& host, const std::string& resourceURI, + OCConnectivityType connectivityType, FindResListCallback resourceHandler, + QualityOfService QoS = QualityOfService::LowQos); + + OCStackResult setPropertyValue(OCPayloadType type, const std::string& tag, const std::string& value); + OCStackResult setPropertyValue(OCPayloadType type, const std::string& tag, const std::vector& value); + OCStackResult getPropertyValue(OCPayloadType type, const std::string& tag, std::string& value); + OCStackResult getPropertyValue(OCPayloadType type, const std::string& tag, std::vector& value); + /** + * API for Device Discovery + * + * + * @param host Host IP Address. If null or empty, Multicast is performed. + * @param deviceURI Uri containing address to the virtual device in C Stack + ("/oic/d") + * @param connectivityType ::OCConnectivityType type of connectivity indicating the + * interface. Example: CT_DEFAULT, CT_ADAPTER_IP, CT_ADAPTER_TCP. + * @param deviceInfoHandler device discovery callback + * + * @return Returns ::OC_STACK_OK if success. + * @note OCStackResult is defined in ocstack.h. + * @see getDeviceInfo(const std::string&, const std::string&, OCConnectivityType, FindDeviceCallback, QualityOfService) + */ + OCStackResult getDeviceInfo(const std::string& host, const std::string& deviceURI, + OCConnectivityType connectivityType, FindDeviceCallback deviceInfoHandler); + /** + * @overload + * + * @param host Host IP Address. If null or empty, Multicast is performed. + * @param deviceURI Uri containing address to the virtual device in C Stack + ("/oic/d") + * @param connectivityType ::OCConnectivityType type of connectivity indicating the + * interface. Example: CT_DEFAULT, CT_ADAPTER_IP, CT_ADAPTER_TCP. + * @param deviceInfoHandler device discovery callback + * @param QoS the quality of communication + * @see getDeviceInfo(const std::string&, const std::string&, OCConnectivityType, FindDeviceCallback) + */ + OCStackResult getDeviceInfo(const std::string& host, const std::string& deviceURI, + OCConnectivityType connectivityType, FindDeviceCallback deviceInfoHandler, + QualityOfService QoS); + + /** + * API for Platform Discovery + * + * + * @param host Host IP Address. If null or empty, Multicast is performed. + * @param platformURI Uri containing address to the virtual platform in C Stack + ("/oic/p") + * @param connectivityType ::OCConnectivityType type of connectivity indicating the + * interface. Example: CT_DEFAULT, CT_ADAPTER_IP, CT_ADAPTER_TCP. + * @param platformInfoHandler platform discovery callback + * + * @return Returns ::OC_STACK_OK if success. + * + * @note OCStackResult is defined in ocstack.h. + * @see getPlatformInfo(const std::string&, const std::string&, OCConnectivityType, FindPlatformCallback, QualityOfService) + */ + OCStackResult getPlatformInfo(const std::string& host, const std::string& platformURI, + OCConnectivityType connectivityType, FindPlatformCallback platformInfoHandler); + /** + * @overload + * + * @param host Host IP Address. If null or empty, Multicast is performed. + * @param platformURI Uri containing address to the virtual platform in C Stack + ("/oic/p") + * @param connectivityType ::OCConnectivityType type of connectivity indicating the + * interface. Example: CT_DEFAULT, CT_ADAPTER_IP, CT_ADAPTER_TCP. + * @param platformInfoHandler platform discovery callback + * @param QoS the quality of communication + * @see getPlatformInfo(const std::string&, const std::string&, OCConnectivityType, FindPlatformCallback) + */ + OCStackResult getPlatformInfo(const std::string& host, const std::string& platformURI, + OCConnectivityType connectivityType, FindPlatformCallback platformInfoHandler, + QualityOfService QoS); + + /** + * This API registers a resource with the server + * @note This API applies to server side only. + * + * @param resourceHandle Upon successful registration, resourceHandle will be filled + * @param resourceURI The URI of the resource. Example: "a/light". See NOTE below + * @param resourceTypeName The resource type. Example: "light" + * @param resourceInterface The resource interface (whether it is collection etc). + * @param entityHandler entity handler callback. + * @param resourceProperty indicates the property of the resource. Defined in ocstack.h. + * setting resourceProperty as OC_DISCOVERABLE will allow Discovery of this resource + * setting resourceProperty as OC_OBSERVABLE will allow observation + * settings resourceProperty as OC_DISCOVERABLE | OC_OBSERVABLE will allow both discovery and + * observation + * + * @return Returns ::OC_STACK_OK if success. + * @note "a/light" is a relative URI. + * Above relative URI will be prepended (by core) with a host IP + namespace "oic" + * Therefore, fully qualified URI format would be //HostIP-Address/namespace/relativeURI" + * Example, a relative URI: 'a/light' will result in a fully qualified URI: + * //192.168.1.1/oic/a/light" + * First parameter can take a relative URI and core will take care of preparing the fully + * qualified URI OR + * first parameter can take fully qualified URI and core will take that as is for further + * operations + * @note OCStackResult is defined in ocstack.h. + * @note entity handler callback : + * When you set specific return value like OC_EH_CHANGED, OC_EH_CONTENT, + * OC_EH_SLOW and etc in entity handler callback, + * ocstack will be not send response automatically to client + * except for error return value like OC_EH_ERROR + * If you want to send response to client with specific result, + * OCDoResponse API should be called with the result value. + */ + OCStackResult registerResource(OCResourceHandle& resourceHandle, + std::string& resourceURI, + const std::string& resourceTypeName, + const std::string& resourceInterface, + EntityHandler entityHandler, + uint8_t resourceProperty); + + /** + * This API registers a resource with the server + * @note This API applies to server & client side. + * + * @param resourceHandle Upon successful registration, resourceHandle will be filled + * @param resource The instance of OCResource that all data filled. + * + * @return Returns ::OC_STACK_OK if success. + * @note OCStackResult is defined in ocstack.h. + */ + OCStackResult registerResource(OCResourceHandle& resourceHandle, + const std::shared_ptr< OCResource > resource); + + /** + * Register Device Info + * + * @param deviceInfo structure containing all the device specific information + * @return Returns ::OC_STACK_OK if no errors and ::OC_STACK_ERROR in case of stack process error + */ + OCStackResult registerDeviceInfo(const OCDeviceInfo deviceInfo); + + /** + * Register Platform Info + * + * @param platformInfo structure containing all the platform specific information + * @return Returns ::OC_STACK_OK if no errors and ::OC_STACK_ERROR in case of stack process error + */ + OCStackResult registerPlatformInfo(const OCPlatformInfo platformInfo); + + /** + * Set default device entity handler + * + * @param entityHandler entity handler to handle requests for + * any undefined resources or default actions. + * if NULL is passed it removes the device default entity handler. + * @return Returns ::OC_STACK_OK if no errors and ::OC_STACK_ERROR in case of stack process error + * @note entity handler callback : + * When you set specific return value like OC_EH_CHANGED, OC_EH_CONTENT, + * OC_EH_SLOW and etc in entity handler callback, + * ocstack will be not send response automatically to client + * except for error return value like OC_EH_ERROR + * If you want to send response to client with specific result, + * sendResponse API should be called with the result value. + */ + OCStackResult setDefaultDeviceEntityHandler(EntityHandler entityHandler); + + /** + * This API unregisters a resource with the server + * @note This API applies to server side only. + * + * @param resourceHandle This is the resource handle which we need to unregister from the + * server + * + * @return Returns ::OC_STACK_OK if success. + * @note OCStackResult is defined in ocstack.h. + */ + OCStackResult unregisterResource(const OCResourceHandle& resourceHandle); + + /** + * Add a resource to a collection resource. + * + * @param collectionHandle handle to the collection resource + * @param resourceHandle handle to resource to be added to the collection resource + * + * @return Returns ::OC_STACK_OK if success. + * @note OCStackResult is defined in ocstack.h. + * @note bindResource must be used only after the both collection resource and + * resource to add under a collections are created and respective handles obtained + * + * @par Example: + * -# registerResource(homeResourceHandle, "a/home", "home", Link_Interface, + * entityHandler, OC_DISCOVERABLE | OC_OBSERVABLE); + * -# registerResource(kitchenResourceHandle, "a/kitchen", "kitchen", Link_Interface, + * entityHandler, OC_DISCOVERABLE | OC_OBSERVABLE); + * -# bindResource(homeResourceHandle, kitchenResourceHandle); + * @par + * At the end of Step 3, resource "a/home" will contain a reference to "a/kitchen". + */ + OCStackResult bindResource(const OCResourceHandle collectionHandle, + const OCResourceHandle resourceHandle); + + /** + * Add multiple resources to a collection resource. + * + * @param collectionHandle handle to the collection resource + * @param addedResourceHandleList reference to list of resource handles to be added to the + * collection resource + * + * @return Returns ::OC_STACK_OK if success. + * @note OCStackResult is defined in ocstack.h. + * @note bindResources must be used only after the both collection resource and + * list of resources to add under a collection are created and respective handles + * obtained. + * + * @par Example: + * -# registerResource(homeResourceHandle, "a/home", "home", Link_Interface, + * homeEntityHandler, OC_DISCOVERABLE | OC_OBSERVABLE); + * -# registerResource(kitchenResourceHandle, "a/kitchen", "kitchen", Link_Interface, + * kitchenEntityHandler, OC_DISCOVERABLE | OC_OBSERVABLE); + * -# registerResource(roomResourceHandle, "a/room", "room", Link_Interface, + * roomEntityHandler, OC_DISCOVERABLE | OC_OBSERVABLE); + * -# std::vector rList; rList.push_back(kitchenResourceHandle); + * rList.push_back(roomResourceHandle); + * -# bindResource(homeResourceHandle, rList); + * @par + * At the end of Step 5, resource "a/home" will contain a references to "a/kitchen" and + * "a/room" + */ + OCStackResult bindResources(const OCResourceHandle collectionHandle, + const std::vector& addedResourceHandleList); + + /** + * Unbind a resource from a collection resource. + * + * @param collectionHandle handle to the collection resource + * @param resourceHandle resource handle to be unbound from the collection resource + * + * @return Returns ::OC_STACK_OK if success. + * @note OCStackResult is defined in ocstack.h. + * @note unbindResource must be used only after the both collection resource and + * resource to unbind from a collection are created and respective handles obtained + * + * @par Example: + * -# registerResource(homeResourceHandle, "a/home", "home", Link_Interface, + * entityHandler, OC_DISCOVERABLE | OC_OBSERVABLE); + * -# registerResource(kitchenResourceHandle, "a/kitchen", "kitchen", Link_Interface, + * entityHandler, OC_DISCOVERABLE | OC_OBSERVABLE); + * -# bindResource(homeResourceHandle, kitchenResourceHandle); + * -# unbindResource(homeResourceHandle, kitchenResourceHandle); + * @par + * At the end of Step 4, resource "a/home" will no longer reference "a/kitchen". + */ + OCStackResult unbindResource(const OCResourceHandle collectionHandle, + const OCResourceHandle resourceHandle); + + /** + * Unbind resources from a collection resource. + * + * @param collectionHandle handle to the collection resource + * @param resourceHandleList List of resource handles to be unbound from the collection + * resource + * + * @return Returns ::OC_STACK_OK if success. + * @note OCStackResult is defined in ocstack.h. + * @note unbindResources must be used only after the both collection resource and + * list of resources resource to unbind from a collection are created and respective handles + * obtained. + * + * @par Example: + * -# registerResource(homeResourceHandle, "a/home", "home", Link_Interface, + * homeEntityHandler, OC_DISCOVERABLE | OC_OBSERVABLE); + * -# registerResource(kitchenResourceHandle, "a/kitchen", "kitchen", Link_Interface, + * kitchenEntityHandler, OC_DISCOVERABLE | OC_OBSERVABLE); + * -# registerResource(roomResourceHandle, "a/room", "room", Link_Interface, + * roomEntityHandler, OC_DISCOVERABLE | OC_OBSERVABLE); + * -# std::vector rList; rList.push_back(kitchenResourceHandle); + * rList.push_back(roomResourceHandle); + * -# bindResource(homeResourceHandle, rList); + * -# unbindResources(homeResourceHandle, rList); + * @par + * At the end of Step 6, resource "a/home" will no longer reference to "a/kitchen" and + * "a/room" + */ + OCStackResult unbindResources(const OCResourceHandle collectionHandle, + const std::vector& resourceHandleList); + + /** + * Binds a type to a particular resource + * @param resourceHandle handle to the resource + * @param resourceTypeName new typename to bind to the resource + * + * @return Returns ::OC_STACK_OK if success. + */ + OCStackResult bindTypeToResource(const OCResourceHandle& resourceHandle, + const std::string& resourceTypeName); + + /** + * Binds an interface to a particular resource + * @param resourceHandle handle to the resource + * @param resourceInterfaceName new interface to bind to the resource + * + * @return Returns ::OC_STACK_OK if success. + */ + OCStackResult bindInterfaceToResource(const OCResourceHandle& resourceHandle, + const std::string& resourceInterfaceName); + + + /** + * Start Presence announcements. + * + * @param ttl time to live + * @par + * If ttl is '0', then the default stack value will be used (60 Seconds). + * If ttl is greater than OC_MAX_PRESENCE_TTL_SECONDS, then the ttl will be set to + * OC_MAX_PRESENCE_TTL_SECONDS. + * @par + * @return Returns ::OC_STACK_OK if success. + * + * Server can call this function when it comes online for the + * first time, or when it comes back online from offline mode, + * or when it re enters network. + * + */ + OCStackResult startPresence(const unsigned int ttl); + + /** + * Stop Presence announcements. + * + * @return Returns ::OC_STACK_OK if success. + * + * Server can call this function when it is terminating, + * going offline, or when going away from network. + * + */ + OCStackResult stopPresence(); + + /** + * subscribes to a server's presence change events. By making this subscription, + * every time a server adds/removes/alters a resource, starts or is intentionally + * stopped (potentially more to be added later). + * + * @param presenceHandle a handle object that can be used to identify this subscription + * request. It can be used to unsubscribe from these events in the future. + * It will be set upon successful return of this method. + * @param host The IP address/addressable name of the server to subscribe to. + * This should be in the format coap://address:port + * @param connectivityType ::OCConnectivityType type of connectivity indicating the + * interface. Example: CT_DEFAULT, CT_ADAPTER_IP, CT_ADAPTER_TCP. + * @param presenceHandler callback function that will receive notifications/subscription + * events + * + * @return Returns ::OC_STACK_OK if success. + * @copydoc subscribePresence(OCPresenceHandle&, const std::string&, resourceType, OCConnectivityType, SubscribeCallback) + */ + OCStackResult subscribePresence(OCPresenceHandle& presenceHandle, const std::string& host, + OCConnectivityType connectivityType, SubscribeCallback presenceHandler); + /** + * @overload + * + * @param presenceHandle a handle object that can be used to identify this subscription + * request. It can be used to unsubscribe from these events in the future. + * It will be set upon successful return of this method. + * @param host The IP address/addressable name of the server to subscribe to. + * This should be in the format coap://address:port + * @param resourceType a resource type specified as a filter for subscription callbacks. + * @param connectivityType ::OCConnectivityType type of connectivity indicating the + * interface. Example: CT_DEFAULT, CT_ADAPTER_IP, CT_ADAPTER_TCP. + * @param presenceHandler callback function that will receive notifications/subscription + * events + * @see subscribePresence(OCPresenceHandle&, const std::string&, OCConnectivityType, SubscribeCallback) + */ + OCStackResult subscribePresence(OCPresenceHandle& presenceHandle, const std::string& host, + const std::string& resourceType, OCConnectivityType connectivityType, + SubscribeCallback presenceHandler); + + /** + * unsubscribes from a previously subscribed server's presence events. Note that + * you may for a short time still receive events from the server since it may take time + * for the unsubscribe to take effect. + * + * @param presenceHandle the handle object provided by the subscribePresence call that + * identifies this subscription. + * + * @return Returns ::OC_STACK_OK if success. + */ + OCStackResult unsubscribePresence(OCPresenceHandle presenceHandle); + +#ifdef WITH_CLOUD + /** + * Subscribes to a server's device presence change events. + * + * @param presenceHandle a handle object that can be used to identify this subscription + * request. It can be used to unsubscribe from these events in the future. + * It will be set upon successful return of this method. + * @param host The IP address/addressable name of the server to subscribe to. + * This should be in the format coap://address:port + * @param di Vector which can have the devices id. + * @param connectivityType ::OCConnectivityType type of connectivity indicating the + * interface. Example: CT_DEFAULT, CT_ADAPTER_IP, CT_ADAPTER_TCP. + * @param observeHandler handles callback + * The callback function will be invoked with a map of attribute name and values. + * The callback function will also have the result from this observe operation + * This will have error codes + * + * @return Returns ::OC_STACK_OK if success. + */ + OCStackResult subscribeDevicePresence(OCPresenceHandle& presenceHandle, + const std::string& host, + const std::vector& di, + OCConnectivityType connectivityType, + ObserveCallback callback); +#endif + + /** + * Creates a resource proxy object so that get/put/observe functionality + * can be used without discovering the object in advance. Note that the + * consumer of this method needs to provide all of the details required to + * correctly contact and observe the object. If the consumer lacks any of + * this information, they should discover the resource object normally. + * Additionally, you can only create this object if OCPlatform was initialized + * to be a Client or Client/Server. Otherwise, this will return an empty + * shared ptr. + * + * @param host a string containing a resolvable host address of the server + * holding the resource. Currently this should be in the format + * coap://address:port, though in the future, we expect this to + * change to //address:port + * + * @param uri the rest of the resource's URI that will permit messages to be + * properly routed. Example: /a/light + * + * @param connectivityType ::OCConnectivityType type of connectivity indicating the + * interface. Example: CT_DEFAULT, CT_ADAPTER_IP, CT_ADAPTER_TCP. + * if you want to use a specific Flag like IPv4, + * you should apply OR operation for the flag in here. + * Example: static_cast(CT_ADAPTER_TCP + * | OC_IP_USE_V4) + * + * @param isObservable a boolean containing whether the resource supports observation + * + * @param resourceTypes a collection of resource types implemented by the resource + * + * @param interfaces a collection of interfaces that the resource supports/implements + * @return OCResource::Ptr a shared pointer to the new resource object + */ + OCResource::Ptr constructResourceObject(const std::string& host, + const std::string& uri, + OCConnectivityType connectivityType, bool isObservable, + const std::vector& resourceTypes, + const std::vector& interfaces); + + /** + * Allows application entity handler to send response to an incoming request. + * + * @param pResponse OCResourceResponse pointer that will permit to set values related + * to resource response. + * + * @return Returns ::OC_STACK_OK if success. + */ + OCStackResult sendResponse(const std::shared_ptr pResponse); + + /** + * Find all the Direct Pairing capable devices. + * + * @param waittime timeoutbefore the callback is called + * @param callback function to callback with discovered devices after timeout + * + * @return Returns ::OC_STACK_OK if success + */ + OCStackResult findDirectPairingDevices(unsigned short waittime, + GetDirectPairedCallback callback); + + /** + * Get all the Direct paired devices. + * + * @param callback function to callback with the list of paired devices + * + * @return Returns ::OC_STACK_OK if success + */ + OCStackResult getDirectPairedDevices(GetDirectPairedCallback callback); + + /** + * Perform the Direct Pairing with the selected peer device + * + * @param peer device to direct pair with + * @param pmSel Selected pairing method + * @param pinNumber pin to validate peer & perform the direct pairing + * @param resultCallback callback function that will get the result of the operation + * + * @return Returns ::OC_STACK_OK if success + */ + OCStackResult doDirectPairing(std::shared_ptr peer, OCPrm_t pmSel, + const std::string& pinNumber, + DirectPairingCallback resultCallback); +#ifdef WITH_CLOUD + /** + * Create an account manager object that can be used for doing request to account server. + * You can only create this object if OCPlatform was initialized to be a Client or + * Client/Server. Otherwise, this will return an empty shared ptr. + * + * @note For now, OCPlatform SHOULD be initialized to be a Client/Server(Both) for the + * methods of this object to work since device id is not generated on Client mode. + * + * @param host Host IP Address of a account server. + * @param connectivityType ::OCConnectivityType type of connectivity indicating the + * interface. Example: CT_DEFAULT, CT_ADAPTER_IP, CT_ADAPTER_TCP. + * if you want to use a specific Flag like IPv4, + * you should apply OR operation for the flag in here. + * Example: static_cast(CT_ADAPTER_TCP + * | OC_IP_USE_V4) + * + * @return OCAccountManager::Ptr a shared pointer to the new account manager object + */ + OCAccountManager::Ptr constructAccountManagerObject(const std::string& host, + OCConnectivityType connectivityType); +#endif // WITH_CLOUD + + /** + * gets the deviceId of the client + * + * @param deviceId pointer. + * @return Returns ::OC_STACK_OK if success. + */ + OCStackResult getDeviceId(OCUUIdentity *deviceId); + + /** + * sets the deviceId of the client + * + * @param deviceId pointer. + * @return Returns ::OC_STACK_OK if success. + */ + OCStackResult setDeviceId(const OCUUIdentity *deviceId); + } +} + +#endif // OC_PLATFORM_H_ diff --git a/inc/iotivity/OCPlatform_impl.h b/inc/iotivity/OCPlatform_impl.h new file mode 100644 index 0000000..6adefc7 --- /dev/null +++ b/inc/iotivity/OCPlatform_impl.h @@ -0,0 +1,305 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH 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. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +/** + * @file + * + * Implementation of the OCPlatform functionality. It contains a singleton + * interface that is used only by the OCPlatform namespace and is the + * central entrance to the stack. + */ + +#ifndef OC_PLATFORM_IMPL_H_ +#define OC_PLATFORM_IMPL_H_ + +#include + +#include "OCApi.h" +#include "OCResource.h" +#include "WrapperFactory.h" +#include "OCResourceRequest.h" +#include "OCResourceResponse.h" +#include "OCRepresentation.h" +#include "OCDirectPairing.h" + +#ifdef WITH_CLOUD +#include "OCAccountManager.h" +#endif + +#include "oc_logger.hpp" + +namespace OC +{ + class OCPlatform_impl + { + private: + static PlatformConfig& globalConfig(); + public: + static void Configure(const PlatformConfig& config); + + static OCPlatform_impl& Instance(); + + public: + // typedef for handle to cancel presence info with + typedef OCDoHandle OCPresenceHandle; + + virtual ~OCPlatform_impl(void); + + OCStackResult notifyAllObservers(OCResourceHandle resourceHandle); + + OCStackResult notifyAllObservers(OCResourceHandle resourceHandle, QualityOfService QoS); + + OCStackResult notifyListOfObservers( + OCResourceHandle resourceHandle, + ObservationIds& observationIds, + const std::shared_ptr responsePtr); + + OCStackResult notifyListOfObservers( + OCResourceHandle resourceHandle, + ObservationIds& observationIds, + const std::shared_ptr responsePtr, + QualityOfService QoS); + + OCStackResult findResource(const std::string& host, const std::string& resourceURI, + OCConnectivityType connectivityType, FindCallback resourceHandler); + + OCStackResult findResource(const std::string& host, const std::string& resourceURI, + OCConnectivityType connectivityType, FindCallback resourceHandler, + QualityOfService QoS); + + OCStackResult findResource(const std::string& host, const std::string& resourceURI, + OCConnectivityType connectivityType, FindCallback resourceHandler, + FindErrorCallback errorHandler); + + OCStackResult findResource(const std::string& host, const std::string& resourceURI, + OCConnectivityType connectivityType, FindCallback resourceHandler, + FindErrorCallback errorHandler, QualityOfService QoS); + + OCStackResult findResourceList(const std::string& host, const std::string& resourceURI, + OCConnectivityType connectivityType, FindResListCallback resourceHandler, + QualityOfService QoS); + + OCStackResult getDeviceInfo(const std::string& host, const std::string& deviceURI, + OCConnectivityType connectivityType, FindDeviceCallback deviceInfoHandler); + + OCStackResult getDeviceInfo(const std::string& host, const std::string& deviceURI, + OCConnectivityType connectivityType, FindDeviceCallback deviceInfoHandler, + QualityOfService QoS); + + OCStackResult getPlatformInfo(const std::string& host, const std::string& platformURI, + OCConnectivityType connectivityType, FindPlatformCallback platformInfoHandler); + + OCStackResult getPlatformInfo(const std::string& host, const std::string& platformURI, + OCConnectivityType connectivityType, FindPlatformCallback platformInfoHandler, + QualityOfService QoS); + + /** + * API for Device Discovery + * + * @param host Host IP Address. If null or empty, Multicast is performed. + * @param deviceURI Uri containing address to the virtual device in C Stack + * ("/oic/d") + * @param deviceInfoHandler device discovery callback + * @param QualityOfService the quality of communication + * @return Returns ::OC_STACK_OK if success. + * @note OCStackResult is defined in ocstack.h. + */ + OCStackResult getDeviceInfo(const std::string& host, const std::string& deviceURI, + FindDeviceCallback deviceInfoHandler); + OCStackResult getDeviceInfo(const std::string& host, const std::string& deviceURI, + FindDeviceCallback deviceInfoHandler, QualityOfService QoS); + + /** + * API for Platform Discovery + * + * @param host Host IP Address. If null or empty, Multicast is performed. + * @param platformURI Uri containing address to the virtual platform in C Stack + * ("/oic/p") + * @param platformInfoHandler platform discovery callback + * @param QualityOfService the quality of communication + * @return Returns ::OC_STACK_OK if success. + * @note OCStackResult is defined in ocstack.h. + */ + OCStackResult getPlatformInfo(const std::string& host, const std::string& platformURI, + FindPlatformCallback platformInfoHandler); + OCStackResult getPlatformInfo(const std::string& host, const std::string& platformURI, + FindPlatformCallback platformInfoHandler, QualityOfService QoS); + + OCStackResult setPropertyValue(OCPayloadType type, const std::string& tag, const std::string& value); + OCStackResult setPropertyValue(OCPayloadType type, const std::string& tag, const std::vector& value); + OCStackResult getPropertyValue(OCPayloadType type, const std::string& tag, std::string& value); + + /** + * This API registers a resource with the server + * @note This API applies to server side only. + * + * @param resourceHandle Upon successful registration, resourceHandle will be filled + * @param resourceURI The URI of the resource. Example: "a/light". See NOTE below + * @param resourceTypeName The resource type. Example: "light" + * @param resourceInterface The resource interface (whether it is collection etc). + * @param entityHandler entity handler callback. + * @param resourceProperty indicates the property of the resource. Defined in ocstack.h. + * setting resourceProperty as OC_DISCOVERABLE will allow Discovery of this resource + * setting resourceProperty as OC_OBSERVABLE will allow observation + * settings resourceProperty as OC_DISCOVERABLE | OC_OBSERVABLE will allow both discovery + * and observation + * + * @return Returns ::OC_STACK_OK if success. + * @note "a/light" is a relative URI. + * Above relative URI will be prepended (by core) with a host IP + namespace "oc" + * Therefore, fully qualified URI format would be //HostIP-Address/namespace/relativeURI" + * Example, a relative URI: 'a/light' will result in a fully qualified URI: + * //192.168.1.1/oic/a/light" + * First parameter can take a relative URI and core will take care of preparing the fully + * qualified URI OR + * first parameter can take fully qualified URI and core will take that as is for further + * operations + * @note OCStackResult is defined in ocstack.h. + */ + OCStackResult registerResource(OCResourceHandle& resourceHandle, + std::string& resourceURI, + const std::string& resourceTypeName, + const std::string& resourceInterface, + EntityHandler entityHandler, + uint8_t resourceProperty); + + OCStackResult registerResource(OCResourceHandle& resourceHandle, + const std::shared_ptr resource); + + /** + * This API registers all the device specific information + * + * @param deviceInfo Structure containing all the device related information + * + * @return Returns ::OC_STACK_OK if success + * @note OCDeviceInfo is defined in OCStack.h + */ + OCStackResult registerDeviceInfo(const OCDeviceInfo deviceInfo); + + /** + * This API registers all the platform specific information + * + * @param platformInfo Structure containing all the platform related information + * + * @return Returns ::OC_STACK_OK if success + * @note OCPlatformInfo is defined in OCStack.h + */ + OCStackResult registerPlatformInfo(const OCPlatformInfo platformInfo); + + OCStackResult setDefaultDeviceEntityHandler(EntityHandler entityHandler); + + OCStackResult unregisterResource(const OCResourceHandle& resourceHandle) const; + + OCStackResult bindResource(const OCResourceHandle collectionHandle, + const OCResourceHandle resourceHandle); + + OCStackResult bindResources(const OCResourceHandle collectionHandle, + const std::vector& addedResourceHandleList); + + OCStackResult unbindResource(const OCResourceHandle collectionHandle, + const OCResourceHandle resourceHandle); + + OCStackResult unbindResources(const OCResourceHandle collectionHandle, + const std::vector& resourceHandleList); + + OCStackResult bindTypeToResource(const OCResourceHandle& resourceHandle, + const std::string& resourceTypeName) const; + + OCStackResult bindInterfaceToResource(const OCResourceHandle& resourceHandle, + const std::string& resourceInterfaceName) const; + + OCStackResult startPresence(const unsigned int ttl); + + OCStackResult stopPresence(); + + OCStackResult subscribePresence(OCPresenceHandle& presenceHandle, const std::string& host, + OCConnectivityType connectivityType, SubscribeCallback presenceHandler); + + OCStackResult subscribePresence(OCPresenceHandle& presenceHandle, const std::string& host, + const std::string& resourceType, OCConnectivityType connectivityType, + SubscribeCallback presenceHandler); + OCStackResult unsubscribePresence(OCPresenceHandle presenceHandle); + +#ifdef WITH_CLOUD + OCStackResult subscribeDevicePresence(OCPresenceHandle& presenceHandle, + const std::string& host, + const std::vector& di, + OCConnectivityType connectivityType, + ObserveCallback callback); +#endif + + OCResource::Ptr constructResourceObject(const std::string& host, const std::string& uri, + OCConnectivityType connectivityType, bool isObservable, + const std::vector& resourceTypes, + const std::vector& interfaces); + OCStackResult sendResponse(const std::shared_ptr pResponse); + std::weak_ptr csdkLock(); + + OCStackResult findDirectPairingDevices(unsigned short waittime, + GetDirectPairedCallback callback); + + OCStackResult getDirectPairedDevices(GetDirectPairedCallback callback); + + OCStackResult doDirectPairing(std::shared_ptr peer, OCPrm_t pmSel, + const std::string& pinNumber, + DirectPairingCallback resultCallback); +#ifdef WITH_CLOUD + OCAccountManager::Ptr constructAccountManagerObject(const std::string& host, + OCConnectivityType connectivityType); +#endif // WITH_CLOUD + + OCStackResult getDeviceId(OCUUIdentity *myUuid); + + OCStackResult setDeviceId(const OCUUIdentity *myUuid); + + private: + PlatformConfig m_cfg; + + private: + std::unique_ptr m_WrapperInstance; + IServerWrapper::Ptr m_server; + IClientWrapper::Ptr m_client; + std::shared_ptr m_csdkLock; + + private: + /** + * Constructor for OCPlatform_impl. Constructs a new OCPlatform_impl from a given + * PlatformConfig with appropriate fields + * @param config PlatformConfig struct which has details such as modeType + * (server/client/both), in-proc/out-of-proc etc. + */ + OCPlatform_impl(const PlatformConfig& config); + + /** + * Private function to initialize the platform + */ + void init(const PlatformConfig& config); + + /** + * Private constructor/operators to prevent copying + * of this object + */ + OCPlatform_impl(const OCPlatform_impl& other)= delete; + OCPlatform_impl& operator=(const OCPlatform_impl&) = delete; + OCPlatform_impl& operator=(const OCPlatform_impl&&) = delete; + }; +} + +#endif //__OCPLATFORM_IMPL_H diff --git a/inc/iotivity/OCProvisioningManager.hpp b/inc/iotivity/OCProvisioningManager.hpp new file mode 100644 index 0000000..dd60ced --- /dev/null +++ b/inc/iotivity/OCProvisioningManager.hpp @@ -0,0 +1,445 @@ +//**************************************************************** +// +// Copyright 2015 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. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef OC_PROVISIONINGMANAGER_CXX_H_ +#define OC_PROVISIONINGMANAGER_CXX_H_ + +#include + +#include "pinoxmcommon.h" +#include "ocprovisioningmanager.h" +#include "OCApi.h" +#include "OCPlatform_impl.h" + +namespace OC +{ + class OCSecureResource; + + typedef std::vector> DeviceList_t; + typedef std::vector UuidList_t; + typedef std::vector PMResultList_t; + typedef std::function ResultCallBack; + typedef std::functionCertChainCallBack; + + struct ProvisionContext + { + ResultCallBack callback; + ProvisionContext(ResultCallBack cb) : callback(cb){} + }; + + struct TrustCertChainContext + { + CertChainCallBack callback; + TrustCertChainContext(CertChainCallBack cb) : callback(cb){} + }; + /** + * This class is for credential's to be set to devices. + * The types supported are + * 0: no security mode + * 1: symmetric pair-wise key + * 2: symmetric group key + * 4: asymmetric key + * 8: signed asymmetric key (aka certificate) + * 16: PIN /password + */ + class Credential + { + OicSecCredType_t type; + size_t keySize; + public: + Credential() = default; + Credential(OicSecCredType_t type, size_t size) : type(type), keySize(size) + {} + + /** + * API to get credential type of device. + * @return credential type of device. + */ + OicSecCredType_t getCredentialType() const + { + return type; + } + + /** + * API to get size of credential key type. + * @return size of credential key type. + */ + size_t getCredentialKeySize() const + { + return keySize; + } + + /** + * API to set credential type of device. + * Device can have following credential types + * - symmetric pair-wise key + * - symmetric group key + * - asymmetric key + * - signed asymmetric key (aka certificate) + * - PIN /password + * @param type credential type. + */ + void setCredentialType(OicSecCredType_t type) + { + this->type = type; + } + + /** + * API to set size of credential key type. + * @param keySize credential key size. + * @note can be either 128 or 256 for symmetric pair-wise key + */ + void setCredentialKeySize(size_t keySize) + { + this->keySize = keySize; + } + }; + + class OCSecure + { + public: + /** + * The API is responsible for initialization of the provisioning manager. It will load + * provisioning database which have owned device's list and their linked status. + * + * @param dbPath file path of the sqlite3 database. + * + * @return ::OC_STACK_OK in case of success and other value otherwise. + */ + static OCStackResult provisionInit(const std::string& dbPath); + + /** + * API is responsible for discovery of devices in it's subnet. It will list + * all the device in subnet which are not yet owned. + * + * @param timeout Timeout in seconds, time until which function will listen to + * responses from server before returning the list of devices. + * @param list List of candidate devices to be provisioned. + * @return ::OC_STACK_OK in case of success and other value otherwise. + */ + static OCStackResult discoverUnownedDevices(unsigned short timeout, + DeviceList_t &list); + + /** + * API is responsible for discovery of devices in it's subnet. It will list + * all the device in subnet which are already owned by calling provisioning client. + * + * @param timeout Timeout in seconds, time until which function will listen to + * responses from server before returning the list of devices. + * @param list List of owned devices. + * @return ::OC_STACK_OK in case of success and other value otherwise. + */ + static OCStackResult discoverOwnedDevices(unsigned short timeout, + DeviceList_t &list); + + /** + * API is responsible for discovery of devices in specified endpoint/deviceID. + * And this function will only return the specified device's response. + * + * @param timeout Timeout in seconds, time until which function will listen to + * responses from server before returning the specified device. + * @param deviceID deviceID of target device + * @param foundDevice OCSecureResource object of found device. + * @return ::OC_STACK_OK in case of success and other value otherwise.\n + * ::OC_STACK_INVALID_PARAM when deviceID is NULL or ppFoundDevice is not + * initailized. + */ + static OCStackResult discoverSingleDevice(unsigned short timeout, + const OicUuid_t* deviceID, + std::shared_ptr &foundDevice); + + /** + * API for registering Ownership transfer methods for a particular transfer Type. + * + * @param oxm Ownership transfer method. + * @param callbackData CallbackData Methods for ownership transfer. + * @param inputPin Callback method to input pin for verification. + * @return ::OC_STACK_OK in case of success and other value otherwise. + */ + static OCStackResult setOwnerTransferCallbackData(OicSecOxm_t oxm, + OTMCallbackData_t* callbackData, InputPinCallback inputPin); + + /** + * API to get status of all the devices in current subnet. The status include endpoint + * information and doxm information which can be extracted during owned and unowned + * discovery. Along with this information, API will provide information about + * devices' status. + * Device can have following states + * - ON/OFF: Device is switched on or off. + * + * @param timeout Wait time for the API. + * @param ownedDevList List of owned devices. + * @param unownedDevList List of unowned devices. + * @return ::OC_STACK_OK in case of success and other value otherwise. + */ + static OCStackResult getDevInfoFromNetwork(unsigned short timeout, + DeviceList_t &ownedDevList, + DeviceList_t &unownedDevList); + /** + * Server API to register callback to display stack generated PIN. + * + * @param displayPin Callback Method to Display generated PIN. + * @return ::OC_STACK_OK in case of success and other value otherwise. + */ + static OCStackResult setDisplayPinCB(GeneratePinCallback displayPin); + + /** + * API to remove device credential and ACL from all devices in subnet. + * + * @param resultCallback Callback provided by API user, callback will be called when + * credential revocation is finished. + * @param uuid Device uuid to be revoked. + * @param waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device + * discovery in seconds. + * @return ::OC_STACK_OK in case of success and other value otherwise. + */ + static OCStackResult removeDeviceWithUuid(unsigned short waitTimeForOwnedDeviceDiscovery, + std::string uuid, + ResultCallBack resultCallback); + + /** + * API to save ACL which has several ACE into Acl of SVR. + * + * @param acl ACL to be saved in Acl of SVR. + * @return OC_STACK_OK in case of success and other value otherwise. + */ + static OCStackResult saveACL(const OicSecAcl_t* acl); + +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) + /** + * API to save Trust certificate chain into Cred of SVR. + * + * @param[in] trustCertChain Trust certificate chain to be saved in Cred of SVR. + * @param[in] chainSize Size of trust certificate chain to be saved in Cred of SVR + * @param[in] encodingType Encoding type of trust certificate chain to be saved in Cred of SVR + * @param[out] credId CredId of saved trust certificate chain in Cred of SVR. + * @return OC_STACK_OK in case of success and other value otherwise. + */ + static OCStackResult saveTrustCertChain(uint8_t *trustCertChain, size_t chainSize, + OicEncodingType_t encodingType, uint16_t *credId); + + /* + * API to read Trust certificate chain from SVR. + * Caller must free when done using the returned trust certificate + * @param[in] credId CredId of trust certificate chain in SVR. + * @param[out] trustCertChain Trust certificate chain. + * @param[out] chainSize Size of trust certificate chain + * @return OC_STACK_OK in case of success and other value otherwise. + */ + static OCStackResult readTrustCertChain(uint16_t credId, uint8_t **trustCertChain, + size_t *chainSize); + + /** + * API to register Notifier for trustCertChain change. + * + * @param[in] TrustCertChainChangeCB trustCertChain Change will be + * notified asynchronously. User need to "delete[]" trustCertChain + * in the callback function. + * @return OC_STACK_OK in case of success and other value otherwise. + */ + static OCStackResult registerTrustCertChangeNotifier(CertChainCallBack); + + /** + * API to remove Already registered Notifier. + * + *@return OC_STACK_OK always, kept it for symmetry. + */ + static OCStackResult removeTrustCertChangeNotifier(); + + /** + * Notifier wrapper for trustCertChain change. + * + * @param[in] ctx User context returned in callback + * @param[in] credId trustCertChain changed for this ID + * @param[in] trustCertChain trustcertchain binary blob + * @param[in] chainSize size of trustCertChain + */ + static void certCallbackWrapper(void* ctx, uint16_t credId, uint8_t *trustCertChain, + size_t chainSize); +#endif // __WITH_DTLS__ || __WITH_TLS__ + + }; + + /** + * This class represents a secure virtual device, which can be provisioned by the + * provisioning client. + */ + class OCSecureResource + { + private: + std::weak_ptr m_csdkLock; + OCProvisionDev_t *devPtr; // pointer to device. + + public: + OCSecureResource(); + OCSecureResource(std::weak_ptr csdkLock, OCProvisionDev_t *dPtr); + + ~OCSecureResource(); + + /** + * API to provision credentials between two devices and ACLs for the devices who + * act as a server. + * + * @param cred Type of credentials & key size to be provisioned to the device. + * @param acl1 ACL for device 1. If this is not required set NULL. + * @param device2 Second device to be provisioned. + * @param acl2 ACL for device 2. If this is not required set NULL. + * @param resultCallback Callback will be called when provisioning request receives + * a response from first resource server. + * @return ::OC_STACK_OK in case of success and other value otherwise. + */ + OCStackResult provisionPairwiseDevices(const Credential &cred, const OicSecAcl_t* acl1, + const OCSecureResource &device2, const OicSecAcl_t* acl2, + ResultCallBack resultCallback); + + /** + * API to do ownership transfer for un-owned device. + * + * @param resultCallback Result callback function to be invoked when + * ownership transfer finished. + * @return ::OC_STACK_OK in case of success and other value otherwise. + */ + OCStackResult doOwnershipTransfer(ResultCallBack resultCallback); + + /** + * API to send ACL information to resource. + * + * @param acl ACL to provision. + * @param resultCallback Callback will be called when provisioning request + * receives a response from resource server. + * @return ::OC_STACK_OK in case of success and other value otherwise. + */ + OCStackResult provisionACL(const OicSecAcl_t* acl, + ResultCallBack resultCallback); + + /** + * API to provision credential to devices. + * + * @param cred Type of credentials to be provisioned to the device. + * @param device2 Second device' instance, representing resource to be provisioned. + * @param resultCallback Callback will be called when provisioning request receives + * a response from first resource server. + * @return ::OC_STACK_OK in case of success and other value otherwise. + */ + OCStackResult provisionCredentials(const Credential &cred, + const OCSecureResource &device2, + ResultCallBack resultCallback); + + /** + * API to remove the credential & relationship between the two devices. + * + * @param device2 Second device information to be unlinked. + * @param resultCallback Callback provided by API user, callback will be called when + * device unlink is finished. + * @return ::OC_STACK_OK in case of success and other value otherwise. + */ + OCStackResult unlinkDevices(const OCSecureResource &device2, + ResultCallBack resultCallback); + + /** + * API to remove device credential from all devices in subnet. + * + * @param resultCallback Callback provided by API user, callback will be called when + * credential revocation is finished. + * @param waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device + * discovery in seconds. + * @return ::OC_STACK_OK in case of success and other value otherwise. + */ + OCStackResult removeDevice(unsigned short waitTimeForOwnedDeviceDiscovery, + ResultCallBack resultCallback); + + /** + * API to provision DirectPairing to devices. + * + * @param pconf pointer to PCONF (Pairing Configuration). + * @param resultCallback Callback will be called when provisioning request receives + * a response from first resource server. + * @return ::OC_STACK_OK in case of success and other value otherwise. + */ + OCStackResult provisionDirectPairing(const OicSecPconf_t *pconf, + ResultCallBack resultCallback); + +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) + /** + * API to provision cert. + * + * @param type type of cred. + * @param credId id of cert. + * @param resultCallback Callback will be called when provisioning request + * receives a response from resource server. + * @return ::OC_STACK_OK in case of success and other value otherwise. + */ + OCStackResult provisionTrustCertChain(OicSecCredType_t type, uint16_t credId, + ResultCallBack resultCallback); + +#endif // __WITH_DTLS__ or __WITH_TLS__ + + /** + * This method is used to get linked devices' IDs. + * + * @param uuidList Information about the list of linked devices uuids. + * @return ::OC_STACK_OK in case of success and other value otherwise. + */ + OCStackResult getLinkedDevices(UuidList_t &uuidList); + + /** + * API to get the device ID of this resource. + * @return device ID. + */ + std::string getDeviceID(); + + /** + * API to get the information of device for provisioning. + * @return @ref OCProvisionDev_t Reference provides information of device for provisioning. + */ + OCProvisionDev_t* getDevPtr()const; + + /** + * This function returns the device's IP address. + * @return device address. + */ + std::string getDevAddr(); + + /** + * This function returns the device's Status. + * @return Device status (1 = ON and 2 = OFF). + */ + int getDeviceStatus(); + + /** + * This function provides the owned status of the device. + * @return Device owned status. + */ + bool getOwnedStatus(); + + + /** + * Common callback wrapper, which will be called from OC-APIs. + */ + static void callbackWrapper(void* ctx, int nOfRes, + OCProvisionResult_t *arr, bool hasError); + + private: + void validateSecureResource(); + }; + +} +#endif // OC_PROVISIONINGMANAGER_CXX_H_ diff --git a/inc/iotivity/OCRepresentation.h b/inc/iotivity/OCRepresentation.h new file mode 100644 index 0000000..309b3e5 --- /dev/null +++ b/inc/iotivity/OCRepresentation.h @@ -0,0 +1,512 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH 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. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +/** + * @file + * + * This file contains the declaration of classes and its members related + * to OCRepresentation. + */ + +#ifndef OC_REPRESENTATION_H_ +#define OC_REPRESENTATION_H_ + +#include +#include +#include +#include + +#include +#include + +#ifdef __ANDROID__ +#include "OCAndroid.h" +#endif + +#include + +namespace OC +{ + + enum class InterfaceType + { + None, + LinkParent, + BatchParent, + DefaultParent, + LinkChild, + BatchChild, + DefaultChild + }; + + class MessageContainer + { + public: + void setPayload(const OCPayload* rep); + + void setPayload(const OCRepPayload* rep); + + OCRepPayload* getPayload() const; + + const std::vector& representations() const; + + void addRepresentation(const OCRepresentation& rep); + + const OCRepresentation& operator[](int index) const + { + return m_reps[index]; + } + + const OCRepresentation& back() const + { + return m_reps.back(); + } + private: + std::vector m_reps; + }; + class OCRepresentation + { + public: + friend bool operator==(const OC::OCRepresentation&, const OC::OCRepresentation&); + // Note: Implementation of all constructors and destructors + // are all placed in the same location due to a crash that + // was observed in Android, where merely constructing/destructing + // an OCRepresentation object was enough to cause an invalid 'free'. + // It is believed that this is a result of incompatible compiler + // options between the gradle JNI and armeabi scons build, however + // this fix will work in the meantime. + OCRepresentation(): m_interfaceType(InterfaceType::None){} + +#if defined(_MSC_VER) && (_MSC_VER < 1900) + OCRepresentation(OCRepresentation&& o) + { + std::memmove(this, &o, sizeof(o)); + } +#else + OCRepresentation(OCRepresentation&&) = default; +#endif + + OCRepresentation(const OCRepresentation&) = default; + + OCRepresentation& operator=(const OCRepresentation&) = default; + +#if defined(_MSC_VER) && (_MSC_VER < 1900) + OCRepresentation& operator=(OCRepresentation&& o) + { + std::memmove(this, &o, sizeof(o)); + return *this; + } +#else + OCRepresentation& operator=(OCRepresentation&&) = default; +#endif + + virtual ~OCRepresentation(){} + + void setDevAddr(const OCDevAddr addr); + + const std::string getHost() const; + + OCRepPayload* getPayload() const; + + void addChild(const OCRepresentation&); + + void clearChildren(); + + const std::vector& getChildren() const; + + void setChildren(const std::vector& children); + + void setUri(const char* uri); + + void setUri(const std::string& uri); + + std::string getUri() const; + + const std::vector& getResourceTypes() const; + + const std::vector& getDataModelVersions() const; + + void setResourceTypes(const std::vector& resourceTypes); + + void addResourceType(const std::string& str); + + const std::vector& getResourceInterfaces() const; + + void setResourceInterfaces(const std::vector& resourceInterfaces); + + void addResourceInterface(const std::string& str); + + void addDataModelVersion(const std::string& str); + + bool emptyData() const; + + int numberOfAttributes() const; + + bool erase(const std::string& str); + + template + void setValue(const std::string& str, const T& val) + { + m_values[str] = val; + } + + // using R-value(or universal ref depending) to move string and vector + template + void setValue(const std::string& str, T&& val) + { + m_values[str] = std::forward(val); + } + + const std::map& getValues() const { + return m_values; + } + + /** + * Retrieve the attribute value associated with the supplied name + * + * @param str Name of the attribute + * @param val Value of the attribute + * @return The getValue method returns true if the attribute was + * found in the representation. Otherwise it returns false. + */ + template + bool getValue(const std::string& str, T& val) const + { + auto x = m_values.find(str); + + if(x!= m_values.end()) + { + try + { + val = boost::get(x->second); + return true; + } + catch (boost::bad_get& e) + { + val = T(); + return false; + } + } + else + { + val = T(); + return false; + } + } + + /** + * Return the attribute value associated with the supplied name + * + * @param str Name of the attribute + * @return When the representation contains the attribute, the + * the associated value is returned. Otherwise, getValue + * returns the default contructed value for the type. + */ + template + T getValue(const std::string& str) const + { + T val = T(); + auto x = m_values.find(str); + if(x != m_values.end()) + { + try + { + val = boost::get(x->second); + } + catch (boost::bad_get& e) + { + return val; + } + } + return val; + } + + /** + * Retrieve the attributevalue structure associated with the supplied name + * + * @param str Name of the attribute + * @param attrValue Attribute Value structure + * @return The getAttributeValue method returns true if the attribute was + * found in the representation. Otherwise it returns false. + */ + bool getAttributeValue(const std::string& str, AttributeValue& attrValue) const + { + auto x = m_values.find(str); + + if (x != m_values.end()) + { + attrValue = x->second; + return true; + } + else + { + return false; + } + } + + std::string getValueToString(const std::string& key) const; + bool hasAttribute(const std::string& str) const; + + void setNULL(const std::string& str); + + bool isNULL(const std::string& str) const; + + private: + std::string m_host; + + // STL Container stuff + public: + class iterator; + class const_iterator; + // Shim class to allow iterating and indexing of the OCRepresentation + // object. + class AttributeItem + { + friend class OCRepresentation; + friend class iterator; + friend class const_iterator; + public: + const std::string& attrname() const; + AttributeType type() const; + AttributeType base_type() const; + size_t depth() const; + template + T getValue() const + { + try + { + return boost::get(m_values[m_attrName]); + } + catch (boost::bad_get& e) + { + T val = T(); + return val; + } + } + + std::string getValueToString() const; + + template + AttributeItem& operator=(T&& rhs) + { + m_values[m_attrName] = std::forward(rhs); + return *this; + } + + AttributeItem& operator=(std::nullptr_t /*rhs*/) + { + NullType t; + m_values[m_attrName] = t; + return *this; + } + + // Enable-if required to prevent conversions to alternate types. This prevents + // ambigious conversions in the case where conversions can include a number of + // types, such as the string constructor. +#if (defined(_MSC_VER) ) || (defined(__GNUC__) && (__GNUC__ <= 5)) + template::value || + std::is_same::value || + std::is_same::value || + std::is_same::value || + std::is_same::value || + std::is_same::value || + std::is_same>::value || + std::is_same>>::value || + std::is_same>>>::value || + std::is_same>::value || + std::is_same>>::value || + std::is_same>>>::value || + std::is_same>::value || + std::is_same>>::value || + std::is_same>>>::value || + std::is_same>::value || + std::is_same>>::value || + std::is_same>>>::value || + std::is_same>::value || + std::is_same>>::value || + std::is_same>>>::value || + std::is_same>::value || + std::is_same>>::value || + std::is_same>>>::value + , int>::type = 0// enable_if + > +#else + template::type + >::value + , int>::type = 0 + > +#endif + operator T() const + { + return this->getValue(); + } + + template::value + , int>::type = 0 + > + operator T() const + { + this->getValue(); + return nullptr; + } + + private: + AttributeItem(const std::string& name, + std::map& vals); + AttributeItem(const AttributeItem&) = default; + std::string m_attrName; + std::map& m_values; + }; + + // Iterator to allow iteration via STL containers/methods + class iterator + { + friend class OCRepresentation; + public: + typedef iterator self_type; + typedef AttributeItem value_type; + typedef value_type& reference; + typedef value_type* pointer; + typedef std::forward_iterator_tag iterator_category; + typedef int difference_type; + + iterator(const iterator&) = default; + ~iterator() = default; + + bool operator ==(const iterator&) const; + bool operator !=(const iterator&) const; + + iterator& operator++(); + iterator operator++(int); + + reference operator*(); + pointer operator->(); + private: + iterator(std::map::iterator&& itr, + std::map& vals) + : m_iterator(std::move(itr)), + m_item(m_iterator != vals.end() ? m_iterator->first:"", vals){} + std::map::iterator m_iterator; + AttributeItem m_item; + }; + + class const_iterator + { + friend class OCRepresentation; + public: + typedef iterator self_type; + typedef const AttributeItem value_type; + typedef value_type& const_reference; + typedef value_type* const_pointer; + typedef std::forward_iterator_tag iterator_category; + typedef int difference_type; + + const_iterator(const iterator& rhs) + :m_iterator(rhs.m_iterator), m_item(rhs.m_item){} + const_iterator(const const_iterator&) = default; + ~const_iterator() = default; + + bool operator ==(const const_iterator&) const; + bool operator !=(const const_iterator&) const; + + const_iterator& operator++(); + const_iterator operator++(int); + + const_reference operator*() const; + const_pointer operator->() const; + private: + const_iterator(std::map::const_iterator&& itr, + std::map& vals) + : m_iterator(std::move(itr)), + m_item(m_iterator != vals.end() ? m_iterator->first: "", vals){} + std::map::const_iterator m_iterator; + AttributeItem m_item; + }; + + iterator begin(); + const_iterator begin() const; + const_iterator cbegin() const; + iterator end(); + const_iterator end() const; + const_iterator cend() const; + size_t size() const; + bool empty() const; + + AttributeItem operator[](const std::string& key); + const AttributeItem operator[](const std::string& key) const; + private: + friend class OCResourceResponse; + friend class MessageContainer; + + template + void payload_array_helper(const OCRepPayloadValue* pl, size_t depth); + template + T payload_array_helper_copy(size_t index, const OCRepPayloadValue* pl); + void setPayload(const OCRepPayload* payload); + void setPayloadArray(const OCRepPayloadValue* pl); + void getPayloadArray(OCRepPayload* payload, + const OCRepresentation::AttributeItem& item) const; + // the root node has a slightly different JSON version + // based on the interface type configured in ResourceResponse. + // This allows ResourceResponse to set it, so that the save function + // doesn't serialize things that it isn't supposed to serialize. + void setInterfaceType(InterfaceType ift) + { + m_interfaceType = ift; + } + + // class used to wrap the 'prop' feature of the save/load + class Prop + { + public: + Prop(std::vector& resourceTypes, + std::vector& interfaces) + : m_types(resourceTypes), m_interfaces(interfaces) + {} + + /* Prop(const std::vector& resourceTypes, + const std::vector& interfaces) + :m_types(resourceTypes), + m_interfaces(interfaces) + {}*/ + private: + std::vector& m_types; + std::vector& m_interfaces; + }; + private: + std::string m_uri; + std::vector m_children; + mutable std::map m_values; + std::vector m_resourceTypes; + std::vector m_interfaces; + std::vector m_dataModelVersions; + + InterfaceType m_interfaceType; + }; + + std::ostream& operator <<(std::ostream& os, const OCRepresentation::AttributeItem& ai); +} // namespace OC + + +#endif // OC_REPRESENTATION_H_ diff --git a/inc/iotivity/OCResource.h b/inc/iotivity/OCResource.h new file mode 100644 index 0000000..2167ba6 --- /dev/null +++ b/inc/iotivity/OCResource.h @@ -0,0 +1,691 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH 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. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +/** + * @file + * + * This file contains the declaration of classes and its members related to + * Resource. + */ + +#ifndef OC_RESOURCE_H_ +#define OC_RESOURCE_H_ + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace OC +{ + class OCResource; + class OCResourceIdentifier; + std::ostream& operator <<(std::ostream& os, const OCResourceIdentifier& ri); + /** + * @brief OCResourceIdentifier represents the identity information for a server. This + * object combined with the OCResource's URI property uniquely identify an + * OCResource on or across networks. + * Equality operators are implemented. However, internal representation is subject + * to change and thus should not be accessed or depended on. + */ + class OCResourceIdentifier + { + friend class OCResource; + friend std::ostream& operator <<(std::ostream& os, const OCResourceIdentifier& ri); + + public: + OCResourceIdentifier() = delete; + + OCResourceIdentifier(const OCResourceIdentifier&) = default; + +#if defined(_MSC_VER) && (_MSC_VER < 1900) + OCResourceIdentifier(OCResourceIdentifier&& o): + m_resourceUri(std::move(o.m_resourceUri)), + m_representation(o.m_representation) + { + } +#else + OCResourceIdentifier(OCResourceIdentifier&&) = default; +#endif + + OCResourceIdentifier& operator=(const OCResourceIdentifier&) = delete; + + OCResourceIdentifier& operator=(OCResourceIdentifier&&) = delete; + + bool operator==(const OCResourceIdentifier &other) const; + + bool operator!=(const OCResourceIdentifier &other) const; + + bool operator<(const OCResourceIdentifier &other) const; + + bool operator>(const OCResourceIdentifier &other) const; + + bool operator<=(const OCResourceIdentifier &other) const; + + bool operator>=(const OCResourceIdentifier &other) const; + + private: + + OCResourceIdentifier(const std::string& wireServerIdentifier, + const std::string& resourceUri ); + + private: + std::string m_representation; + const std::string& m_resourceUri; + }; + + /** + * @brief OCResource represents an OC resource. A resource could be a light controller, + * temperature sensor, smoke detector, etc. A resource comes with a well-defined + * contract or interface onto which you can perform different operations, such as + * turning on the light, getting the current temperature or subscribing for event + * notifications from the smoke detector. A resource can be composed of one or + * more resources. + */ + class OCResource + { + friend class OCPlatform_impl; + friend class ListenOCContainer; + public: + typedef std::shared_ptr Ptr; + +#if defined(_MSC_VER) && (_MSC_VER < 1900) + OCResource(OCResource&& o): + m_clientWrapper(std::move(o.m_clientWrapper)), + m_uri(std::move(o.m_uri)), + m_resourceId(std::move(o.m_resourceId)), + m_devAddr(std::move(o.m_devAddr)), + m_useHostString(o.m_useHostString), + m_property(o.m_property), + m_isCollection(o.m_isCollection), + m_resourceTypes(std::move(o.m_resourceTypes)), + m_interfaces(std::move(o.m_interfaces)), + m_children(std::move(m_children)), + m_observeHandle(std::move(m_observeHandle)), + m_headerOptions(std::move(m_headerOptions)) + { + } +#else + OCResource(OCResource&&) = default; +#endif + // Explicitly delete the copy ctor since VS2013 would try to generate one, and + // the standard says that defaulting the move ctor should delete the copy ctor. + OCResource(const OCResource&) = delete; + + // We cannot support copy/move assigns since OCResourceIdentifier doesn't. + OCResource& operator=(OCResource&&) = delete; + OCResource& operator=(const OCResource&) = delete; + + /** + * Virtual destructor + */ + virtual ~OCResource(void); + + /** + * Function to get the attributes of a resource. + * @param queryParametersMap map which can have the query parameter name and value + * @param attributeHandler handles callback + * The callback function will be invoked with a map of attribute name and values. + * The callback function will also have the result from this Get operation + * This will have error codes + * @return Returns ::OC_STACK_OK on success, some other value upon failure. + * @note OCStackResult is defined in ocstack.h. + */ + OCStackResult get(const QueryParamsMap& queryParametersMap, GetCallback attributeHandler); + /** + * Function to get the attributes of a resource. + * @param queryParametersMap map which can have the query parameter name and value + * @param attributeHandler handles callback + * The callback function will be invoked with a map of attribute name and values. + * The callback function will also have the result from this Get operation + * This will have error codes + * @param QoS the quality of communication + * @return Returns ::OC_STACK_OK on success, some other value upon failure. + * @note OCStackResult is defined in ocstack.h. + */ + OCStackResult get(const QueryParamsMap& queryParametersMap, GetCallback attributeHandler, + QualityOfService QoS); + + /** + * Function to get the attributes of a resource. + * + * @param resourceType resourceType of the resource operate on + * @param resourceInterface interface type of the resource to operate on + * @param queryParametersMap map which can have the query parameter name and value + * @param attributeHandler handles callback + * The callback function will be invoked with a map of attribute name and values. + * The callback function will be invoked with a list of URIs if 'get' is invoked on a + * resource container (list will be empty if not a container) + * The callback function will also have the result from this Get operation. This will + * have error codes + * @return Returns ::OC_STACK_OK on success, some other value upon failure. + * @note OCStackResult is defined in ocstack.h. + * @par Example: + * Consider resource "a/home" (with link interface and resource type as home) contains links + * to "a/kitchen" and "a/room". + * -# get("home", Link_Interface, &onGet) + * @par + * Callback onGet will receive a) Empty attribute map because there are no attributes for + * a/home b) list with + * full URI of "a/kitchen" and "a/room" resources and their properties c) error code for GET + * operation + * @note A resource may contain single or multiple resource types. Also, a resource may + * contain single or multiple interfaces. + * Currently, single GET request is allowed to do operate on single resource type or resource + * interface. In future, a single GET + * can operate on multiple resource types and interfaces. + * @note A client can traverse a tree or graph by doing successive GETs on the returned + * resources at a node. + * + */ + OCStackResult get(const std::string& resourceType, const std::string& resourceInterface, + const QueryParamsMap& queryParametersMap, GetCallback attributeHandler); + /** + * Function to get the attributes of a resource. + * + * @param resourceType resourceType of the resource operate on + * @param resourceInterface interface type of the resource to operate on + * @param queryParametersMap map which can have the query parameter name and value + * @param attributeHandler handles callback + * The callback function will be invoked with a map of attribute name and values. + * The callback function will be invoked with a list of URIs if 'get' is invoked on a + * resource container (list will be empty if not a container) + * The callback function will also have the result from this Get operation. This will + * have error codes + * @param QoS the quality of communication + * @return Returns ::OC_STACK_OK on success, some other value upon failure. + * note OCStackResult is defined in ocstack.h. + * @par Example: + * Consider resource "a/home" (with link interface and resource type as home) contains links + * to "a/kitchen" and "a/room". + * -# get("home", Link_Interface, &onGet) + * @par + * Callback onGet will receive a) Empty attribute map because there are no attributes for + * a/home b) list with + * full URI of "a/kitchen" and "a/room" resources and their properties c) error code for GET + * operation + * @note A resource may contain single or multiple resource types. Also, a resource may + * contain single or multiple interfaces. + * Currently, single GET request is allowed to do operate on single resource type or resource + * interface. In future, a single GET + * can operate on multiple resource types and interfaces. + * @note A client can traverse a tree or graph by doing successive GETs on the returned + * resources at a node. + * + */ + OCStackResult get(const std::string& resourceType, const std::string& resourceInterface, + const QueryParamsMap& queryParametersMap, GetCallback attributeHandler, + QualityOfService QoS); + + /** + * Function to set the representation of a resource (via PUT) + * + * @param representation which can either have all the attribute names and values + (which will represent entire state of the resource) or a + * set of attribute names and values which needs to be modified + * The callback function will be invoked with a map of attribute name and values. + * The callback function will also have the result from this Put operation + * This will have error codes + * @param queryParametersMap map which can have the query parameter name and value + * @param attributeHandler attribute handler + * @return Returns ::OC_STACK_OK on success, some other value upon failure. + * @note OCStackResult is defined in ocstack.h. + * + */ + OCStackResult put(const OCRepresentation& representation, + const QueryParamsMap& queryParametersMap, PutCallback attributeHandler); + /** + * Function to set the representation of a resource (via PUT) + * + * @param representation which can either have all the attribute names and values + (which will represent entire state of the resource) or a + * set of attribute names and values which needs to be modified + * The callback function will be invoked with a map of attribute name and values. + * The callback function will also have the result from this Put operation + * This will have error codes + * @param queryParametersMap map which can have the query parameter name and value + * @param attributeHandler attribute handler + * @param QoS the quality of communication + * @return Returns ::OC_STACK_OK on success, some other value upon failure. + * @note OCStackResult is defined in ocstack.h. + * + */ + OCStackResult put(const OCRepresentation& representation, + const QueryParamsMap& queryParametersMap, PutCallback attributeHandler, + QualityOfService QoS); + + /** + * Function to set the attributes of a resource (via PUT) + * + * @param resourceType resource type of the resource to operate on + * @param resourceInterface interface type of the resource to operate on + * @param representation representation of the resource + * @param queryParametersMap Map which can have the query parameter name and value + * @param attributeHandler attribute handler + * The callback function will be invoked with a map of attribute name and values. + * The callback function will also have the result from this Put operation + * This will have error codes. + * The Representation parameter maps which can either have all the attribute names + * and values + * (which will represent entire state of the resource) or a + * set of attribute names and values which needs to be modified + * @return Returns ::OC_STACK_OK on success, some other value upon failure. + * @note OCStackResult is defined in ocstack.h. + * + */ + OCStackResult put(const std::string& resourceType, const std::string& resourceInterface, + const OCRepresentation& representation, const QueryParamsMap& queryParametersMap, + PutCallback attributeHandler); + /** + * Function to set the attributes of a resource (via PUT) + * @param resourceType resource type of the resource to operate on + * @param resourceInterface interface type of the resource to operate on + * @param representation representation of the resource + * @param queryParametersMap Map which can have the query parameter name and value + * @param attributeHandler attribute handler + * The callback function will be invoked with a map of attribute name and values. + * The callback function will also have the result from this Put operation + * This will have error codes. + * The Representation parameter maps which can either have all the attribute names + * and values + * (which will represent entire state of the resource) or a + * set of attribute names and values which needs to be modified + * @param QoS the quality of communication + * @return Returns ::OC_STACK_OK on success, some other value upon failure. + * @note OCStackResult is defined in ocstack.h. + * + */ + OCStackResult put(const std::string& resourceType, const std::string& resourceInterface, + const OCRepresentation& representation, const QueryParamsMap& queryParametersMap, + PutCallback attributeHandler, QualityOfService QoS); + + /** + * Function to post on a resource + * + * @param representation which can either have all the attribute names and values + * (which will represent entire state of the resource) or a + * set of attribute names and values which needs to be modified + * The callback function will be invoked with a map of attribute name and values. + * The callback function will also have the result from this Put operation + * This will have error codes + * @param queryParametersMap map which can have the query parameter name and value + * @param attributeHandler attribute handler + * @return Returns ::OC_STACK_OK on success, some other value upon failure. + * @note OCStackResult is defined in ocstack.h. + */ + OCStackResult post(const OCRepresentation& representation, + const QueryParamsMap& queryParametersMap, PostCallback attributeHandler); + /** + * Function to post on a resource + * + * @param representation which can either have all the attribute names and values + * (which will represent entire state of the resource) or a + * set of attribute names and values which needs to be modified + * The callback function will be invoked with a map of attribute name and values. + * The callback function will also have the result from this Put operation + * This will have error codes + * @param queryParametersMap map which can have the query parameter name and value + * @param attributeHandler attribute handler + * @param QoS the quality of communication + * @return Returns ::OC_STACK_OK on success, some other value upon failure. + * @note OCStackResult is defined in ocstack.h. + */ + OCStackResult post(const OCRepresentation& representation, + const QueryParamsMap& queryParametersMap, PostCallback attributeHandler, + QualityOfService QoS); + + /** + * Function to post on a resource + * + * @param resourceType resource type of the resource to operate on + * @param resourceInterface interface type of the resource to operate on + * @param representation representation of the resource + * @param queryParametersMap Map which can have the query parameter name and value + * @param attributeHandler attribute handler + * The callback function will be invoked with a map of attribute name and values. + * The callback function will also have the result from this Put operation + * This will have error codes. + * The Representation parameter maps which can either have all the attribute names + * and values + * (which will represent entire state of the resource) or a + * set of attribute names and values which needs to be modified + * @return Returns ::OC_STACK_OK on success, some other value upon failure. + * @note OCStackResult is defined in ocstack.h. + * + */ + OCStackResult post(const std::string& resourceType, const std::string& resourceInterface, + const OCRepresentation& representation, const QueryParamsMap& queryParametersMap, + PostCallback attributeHandler); + /** + * Function to post on a resource + * + * @param resourceType resource type of the resource to operate on + * @param resourceInterface interface type of the resource to operate on + * @param representation representation of the resource + * @param queryParametersMap Map which can have the query parameter name and value + * @param attributeHandler attribute handler + * The callback function will be invoked with a map of attribute name and values. + * The callback function will also have the result from this Put operation + * This will have error codes. + * The Representation parameter maps which can either have all the attribute names + * and values + * (which will represent entire state of the resource) or a + * set of attribute names and values which needs to be modified + * @param QoS the quality of communication + * @return Returns ::OC_STACK_OK on success, some other value upon failure. + * @note OCStackResult is defined in ocstack.h. + * + */ + OCStackResult post(const std::string& resourceType, const std::string& resourceInterface, + const OCRepresentation& representation, const QueryParamsMap& queryParametersMap, + PostCallback attributeHandler, QualityOfService QoS); + + /** + * Function to perform DELETE operation + * + * @param deleteHandler handles callback + * The callback function will have headerOptions and result from this Delete + * operation. This will have error codes + * @return Returns ::OC_STACK_OK on success, some other value upon failure. + * @note OCStackResult is defined in ocstack.h. + * + */ + OCStackResult deleteResource(DeleteCallback deleteHandler); + OCStackResult deleteResource(DeleteCallback deleteHandler, QualityOfService QoS); + + /** + * Function to set observation on the resource + * + * @param observeType allows the client to specify how it wants to observe. + * @param queryParametersMap map which can have the query parameter name and value + * @param observeHandler handles callback + * The callback function will be invoked with a map of attribute name and values. + * The callback function will also have the result from this observe operation + * This will have error codes + * @return Returns ::OC_STACK_OK on success, some other value upon failure. + * @note OCStackResult is defined in ocstack.h. + * + */ + OCStackResult observe(ObserveType observeType, const QueryParamsMap& queryParametersMap, + ObserveCallback observeHandler); + /** + * Function to set observation on the resource + * + * @param observeType allows the client to specify how it wants to observe. + * @param queryParametersMap map which can have the query parameter name and value + * @param observeHandler handles callback + * The callback function will be invoked with a map of attribute name and values. + * The callback function will also have the result from this observe operation + * This will have error codes + * @param qos the quality of communication + * @return Returns ::OC_STACK_OK on success, some other value upon failure. + * @note OCStackResult is defined in ocstack.h. + * + */ + OCStackResult observe(ObserveType observeType, const QueryParamsMap& queryParametersMap, + ObserveCallback observeHandler, QualityOfService qos); + + /** + * Function to cancel the observation on the resource + * + * @return Returns ::OC_STACK_OK on success, some other value upon failure. + * @note OCStackResult is defined in ocstack.h. + * + */ + OCStackResult cancelObserve(); + OCStackResult cancelObserve(QualityOfService qos); + + /** + * Function to set header information. + * @param headerOptions std::vector where header information(header optionID and optionData + * is passed + * + * @note Once the headers information is set, it will be applicable to GET, PUT and observe + * request. + * setHeaderOptions can be used multiple times if headers need to be modifed by the client. + * Latest headers will be used to send in the request.
+ * @note Initial support is only for two headers. If headerMap consists of more than two + * header options, they will be ignored.
+ * Use unsetHeaderOptions API to clear the header information. + */ + void setHeaderOptions(const HeaderOptions& headerOptions); + + /** + * Function to unset header options. + */ + void unsetHeaderOptions(); + + /** + * Function to get the host address of this resource + * @return std::string host address + * @note This might or might not be exposed in future due to security concerns + */ + std::string host() const; + + /** + * Function to get the URI for this resource + * @return std::string resource URI + */ + std::string uri() const; + + /** + * Function to get the connectivity type of this resource + * @return enum connectivity type (flags and adapter) + */ + OCConnectivityType connectivityType() const; + + /** + * Function to provide ability to check if this resource is observable or not + * @return bool true indicates resource is observable; false indicates resource is + * not observable. + */ + bool isObservable() const; + +#ifdef WITH_MQ + /** + * Function to provide ability to check if this resource is publisher or not + * @return bool true indicates resource is publisher; false indicates resource is + * not publisher. + */ + bool isPublish() const; +#endif + + /** + * Function to get the list of resource types + * @return vector of resource types + */ + std::vector getResourceTypes() const; + + /** + * Function to get the list of resource interfaces + * @return vector of resource interface + */ + std::vector getResourceInterfaces(void) const; + + // TODO-CA Revisit this since we are exposing two identifiers + /** + * Function to get a unique identifier for this + * resource across network interfaces. This will + * be guaranteed unique for every resource-per-server + * independent of how this was discovered. + * @return OCResourceIdentifier object, which can + * be used for all comparison and hashing. + */ + OCResourceIdentifier uniqueIdentifier() const; + + /** + * Function to get a string representation of the resource's server ID. + * This is unique per- server independent on how it was discovered. + * @note The format of the return value is subject to change and will + * likely change both in size and contents in the future. + */ + std::string sid() const; + +#ifdef WITH_MQ + /** + * Function to discovery Topics from MQ Broker. + * + * @param queryParametersMap map which can have the query parameter name and value + * @param attributeHandler handles callback + * @param qos the quality of communication + * + * @return Returns ::OC_STACK_OK on success, some other value upon failure. + * @note OCStackResult is defined in ocstack.h. + * + */ + OCStackResult discoveryMQTopics(const QueryParamsMap& queryParametersMap, + MQTopicCallback attributeHandler, + QualityOfService qos); + /** + * Function to create Topic into MQ Broker. + * SubTopic is also created through this method. + * + * @param rep representation of the topic + * @param topicUri new uri of the topic which want to create + * @param queryParametersMap map which can have the query parameter name and value + * @param attributeHandler handles callback + * @param qos the quality of communication + * + * @return Returns ::OC_STACK_OK on success, some other value upon failure. + * @note OCStackResult is defined in ocstack.h. + * + */ + OCStackResult createMQTopic(const OCRepresentation& rep, + const std::string& topicUri, + const QueryParamsMap& queryParametersMap, + MQTopicCallback attributeHandler, + QualityOfService qos); +#endif +#ifdef MQ_SUBSCRIBER + /** + * Function to subscribe Topic to MQ Broker. + * + * @param observeType allows the client to specify how it wants to observe. + * @param queryParametersMap map which can have the query parameter name and value + * @param observeHandler handles callback + * @param qos the quality of communication + * + * @return Returns ::OC_STACK_OK on success, some other value upon failure. + * @note OCStackResult is defined in ocstack.h. + * + */ + OCStackResult subscribeMQTopic(ObserveType observeType, + const QueryParamsMap& queryParametersMap, + ObserveCallback observeHandler, + QualityOfService qos); + + /** + * Function to unsubscribe Topic to MQ Broker. + * + * @param qos the quality of communication + * + * @return Returns ::OC_STACK_OK on success, some other value upon failure. + * @note OCStackResult is defined in ocstack.h. + * + */ + OCStackResult unsubscribeMQTopic(QualityOfService qos); + + /** + * Function to request publish to MQ publisher. + * Publisher can confirm the request message as key:"req_pub" and value:"true". + * + * @param queryParametersMap map which can have the query parameter name and value + * @param attributeHandler handles callback + * @param qos the quality of communication + * + * @return Returns ::OC_STACK_OK on success, some other value upon failure. + * @note OCStackResult is defined in ocstack.h. + * + */ + OCStackResult requestMQPublish(const QueryParamsMap& queryParametersMap, + PostCallback attributeHandler, + QualityOfService qos); +#endif +#ifdef MQ_PUBLISHER + /** + * Function to publish Topic information into MQ Broker. + * + * @param rep representation of the topic + * @param queryParametersMap map which can have the query parameter name and value + * @param attributeHandler handles callback + * @param qos the quality of communication + * + * @return Returns ::OC_STACK_OK on success, some other value upon failure. + * @note OCStackResult is defined in ocstack.h. + * + */ + OCStackResult publishMQTopic(const OCRepresentation& rep, + const QueryParamsMap& queryParametersMap, + PostCallback attributeHandler, + QualityOfService qos); +#endif + // overloaded operators allow for putting into a 'set' + // the uniqueidentifier allows for putting into a hash + bool operator==(const OCResource &other) const; + + bool operator!=(const OCResource &other) const; + + bool operator<(const OCResource &other) const; + + bool operator>(const OCResource &other) const; + + bool operator<=(const OCResource &other) const; + + bool operator>=(const OCResource &other) const; + + private: + void setHost(const std::string& host); + std::weak_ptr m_clientWrapper; + std::string m_uri; + OCResourceIdentifier m_resourceId; + OCDevAddr m_devAddr; + bool m_useHostString; + bool m_isCollection; + uint8_t m_property; + std::vector m_resourceTypes; + std::vector m_interfaces; + std::vector m_children; + OCDoHandle m_observeHandle; + HeaderOptions m_headerOptions; + + private: + OCResource(std::weak_ptr clientWrapper, + const OCDevAddr& devAddr, const std::string& uri, + const std::string& serverId, uint8_t property, + const std::vector& resourceTypes, + const std::vector& interfaces); + + OCResource(std::weak_ptr clientWrapper, + const std::string& host, const std::string& uri, + const std::string& serverId, + OCConnectivityType connectivityType, uint8_t property, + const std::vector& resourceTypes, + const std::vector& interfaces); + }; + +} // namespace OC + +#endif // OC_RESOURCE_H + diff --git a/inc/iotivity/OCResourceRequest.h b/inc/iotivity/OCResourceRequest.h new file mode 100644 index 0000000..8c7e1dc --- /dev/null +++ b/inc/iotivity/OCResourceRequest.h @@ -0,0 +1,268 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH 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. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +/** + * @file + * + * This file contains the declaration of classes and its members related to + * ResourceRequest. + */ + +#ifndef OC_RESOURCEREQUEST_H_ +#define OC_RESOURCEREQUEST_H_ + +#include "OCApi.h" +#include "OCRepresentation.h" + +void formResourceRequest(OCEntityHandlerFlag, + OCEntityHandlerRequest*, + std::shared_ptr); + + +namespace OC +{ + /** + * @brief OCResourceRequest provides APIs to extract details from a request URI + */ + class OCResourceRequest + { + public: + typedef std::shared_ptr Ptr; + + OCResourceRequest(): + m_requestType(""), + m_resourceUri(""), + m_queryParameters(QueryParamsMap()), + m_requestHandlerFlag(0), + m_messageID(0), + m_representation(OCRepresentation()), + m_headerOptions(HeaderOptions()), + m_requestHandle(0), + m_resourceHandle(nullptr) + { + m_observationInfo.action = ObserveAction::ObserveRegister; + m_observationInfo.obsId = 0; + m_observationInfo.connectivityType = OCConnectivityType::CT_DEFAULT; + m_observationInfo.address = ""; + m_observationInfo.port = 0; + } + +#if defined(_MSC_VER) && (_MSC_VER < 1900) + OCResourceRequest(OCResourceRequest&& o): + m_requestType(std::move(o.m_requestType)), + m_resourceUri(std::move(o.m_resourceUri)), + m_queryParameters(std::move(o.m_queryParameters)), + m_requestHandlerFlag(o.m_requestHandlerFlag), + m_representation(std::move(o.m_representation)), + m_observationInfo(std::move(o.m_observationInfo)), + m_headerOptions(std::move(o.m_headerOptions)), + m_requestHandle(std::move(o.m_requestHandle)), + m_resourceHandle(std::move(o.m_resourceHandle)) + { + } + OCResourceRequest& operator=(OCResourceRequest&& o) + { + m_requestType = std::move(o.m_requestType); + m_resourceUri = std::move(o.m_resourceUri); + m_queryParameters = std::move(o.m_queryParameters); + m_requestHandlerFlag = o.m_requestHandlerFlag; + m_representation = std::move(o.m_representation); + m_observationInfo = std::move(o.m_observationInfo); + m_headerOptions = std::move(o.m_headerOptions); + m_requestHandle = std::move(o.m_requestHandle); + m_resourceHandle = std::move(o.m_resourceHandle); + } +#else + OCResourceRequest(OCResourceRequest&&) = default; + OCResourceRequest& operator=(OCResourceRequest&&) = default; +#endif + + /** + * Virtual destructor + */ + virtual ~OCResourceRequest(void) + { + } + + /** + * Retrieves the type of request string for the entity handler function to operate + * @return std::string request type. This could be 'GET'/'PUT'/'POST'/'DELETE' + */ + std::string getRequestType() const {return m_requestType;} + + /** + * Retrieves the query parameters from the request + * @return std::string query parameters in the request + */ + const QueryParamsMap& getQueryParameters() const {return m_queryParameters;} + + /** + * Retrieves the request handler flag type. This can be either INIT flag or + * REQUEST flag or OBSERVE flag. + * NOTE: + * INIT indicates that the vendor's entity handler should go and perform + * initialization operations + * REQUEST indicates that it is a request of certain type (GET/PUT/POST/DELETE) + * and entity handler needs to perform corresponding operations + * OBSERVE indicates that the request is of type Observe and entity handler + * needs to perform corresponding operations + * @return int type of request flag + */ + int getRequestHandlerFlag() const {return m_requestHandlerFlag;} + + /** + * Provides the entire resource attribute representation + * @return OCRepresentation reference containing the name value pairs + * representing the resource's attributes + */ + const OCRepresentation& getResourceRepresentation() const {return m_representation;} + + /** + * @return ObservationInfo reference provides observation information + */ + const ObservationInfo& getObservationInfo() const {return m_observationInfo;} + + /** + * sets resource uri + * @param resourceUri specifies the resource uri + */ + void setResourceUri(const std::string resourceUri) + { + m_resourceUri = resourceUri; + } + + /** + * gets resource uri + * @return std::string resource uri + */ + std::string getResourceUri(void) + { + return m_resourceUri; + } + + /** + * This API retrieves headerOptions which was sent from a client + * + * @return std::map HeaderOptions with the header options + */ + const HeaderOptions& getHeaderOptions() const + { + return m_headerOptions; + } + + /** + * This API retrieves the request handle + * + * @return OCRequestHandle + */ + const OCRequestHandle& getRequestHandle() const + { + return m_requestHandle; + } + + /** + * This API retrieves the resource handle + * + * return OCResourceHandle + */ + const OCResourceHandle& getResourceHandle() const + { + return m_resourceHandle; + } + + /** + * This API retrieves the request message ID + * + * @return int16_t value of message ID + */ + int16_t getMessageID() const {return m_messageID;} + + private: + std::string m_requestType; + std::string m_resourceUri; + QueryParamsMap m_queryParameters; + int m_requestHandlerFlag; + int16_t m_messageID; + OCRepresentation m_representation; + ObservationInfo m_observationInfo; + HeaderOptions m_headerOptions; + OCRequestHandle m_requestHandle; + OCResourceHandle m_resourceHandle; + + + private: + friend void (::formResourceRequest)(OCEntityHandlerFlag, OCEntityHandlerRequest*, + std::shared_ptr); + void setRequestType(const std::string& requestType) + { + m_requestType = requestType; + } + + void setPayload(OCPayload* requestPayload); + + void setQueryParams(QueryParamsMap& queryParams) + { + m_queryParameters = queryParams; + } + + void setRequestHandlerFlag(int requestHandlerFlag) + { + m_requestHandlerFlag = requestHandlerFlag; + } + + void setMessageID(int16_t messageID) + { + m_messageID = messageID; + } + + void setObservationInfo(const ObservationInfo& observationInfo) + { + m_observationInfo = observationInfo; + } + + void setHeaderOptions(const HeaderOptions& headerOptions) + { + m_headerOptions = headerOptions; + } + + /** + * This API allows to set request handle + * @param requestHandle - OCRequestHandle type used to set the + * request handle + */ + void setRequestHandle(const OCRequestHandle& requestHandle) + { + m_requestHandle = requestHandle; + } + + /** + * This API allows to set the resource handle + * @param resourceHandle - OCResourceHandle type used to set the + * resource handle + */ + void setResourceHandle(const OCResourceHandle& resourceHandle) + { + m_resourceHandle = resourceHandle; + } + + }; + }// namespace OC + +#endif // OC_RESOURCEREQUEST_H_ diff --git a/inc/iotivity/OCResourceResponse.h b/inc/iotivity/OCResourceResponse.h new file mode 100644 index 0000000..754f1ac --- /dev/null +++ b/inc/iotivity/OCResourceResponse.h @@ -0,0 +1,303 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH 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. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +/** + * @file + * + * This file contains the declaration of classes and its members related to + * ResourceResponse. + */ + +#ifndef OC_RESOURCERESPONSE_H_ +#define OC_RESOURCERESPONSE_H_ + +#include "OCApi.h" +#include +#include +#include + +namespace OC +{ + class InProcServerWrapper; + + /** + * @brief OCResourceResponse provides APIs to set the response details + */ + class OCResourceResponse + { + public: + typedef std::shared_ptr Ptr; + + OCResourceResponse(): + m_newResourceUri{}, + m_errorCode{}, + m_headerOptions{}, + m_interface{}, + m_representation{}, + m_requestHandle{0}, + m_resourceHandle{nullptr}, + m_responseResult{} + { + } + +#if defined(_MSC_VER) && (_MSC_VER < 1900) + OCResourceResponse(OCResourceResponse&& o): + m_newResourceUri(std::move(o.m_newResourceUri)), + m_errorCode(o.m_errorCode), + m_headerOptions(std::move(o.m_headerOptions)), + m_interface(std::move(o.m_interface)), + m_representation(std::move(o.m_representation)), + m_requestHandle(std::move(o.m_requestHandle)), + m_resourceHandle(std::move(o.m_resourceHandle)), + m_responseResult(std::move(o.m_responseResult)) + { + } + OCResourceResponse& operator=(OCResourceResponse&& o) + { + m_newResourceUri = std::move(o.m_newResourceUri); + m_errorCode = o.m_errorCode; + m_headerOptions = std::move(o.m_headerOptions); + m_interface = std::move(o.m_interface); + m_representation = std::move(o.m_representation); + m_requestHandle = std::move(o.m_requestHandle); + m_resourceHandle = std::move(o.m_resourceHandle); + m_responseResult = std::move(o.m_responseResult); + } +#else + OCResourceResponse(OCResourceResponse&&) = default; + OCResourceResponse& operator=(OCResourceResponse&&) = default; +#endif + virtual ~OCResourceResponse(void) {} + + /** + * This API sets the error code for this response + * @param eCode error code to set + */ + void setErrorCode(const int eCode) { m_errorCode = eCode; } + + /** + * gets new resource uri + * @return std::string new resource uri + */ + std::string getNewResourceUri(void) + { + return m_newResourceUri; + } + + /** + * sets new resource uri + * @param newResourceUri specifies the resource uri of the resource created + */ + void setNewResourceUri(const std::string newResourceUri) + { + m_newResourceUri = newResourceUri; + } + + /** + * This API allows to set headerOptions in the response + * @param headerOptions HeaderOptions vector consisting of OCHeaderOption objects + */ + void setHeaderOptions(const HeaderOptions& headerOptions) + { + m_headerOptions = headerOptions; + } + + /** + * This API allows to set request handle + * + * @param requestHandle - OCRequestHandle type used to set the request handle + */ + void setRequestHandle(const OCRequestHandle& requestHandle) + { + m_requestHandle = requestHandle; + } + + /** + * This API allows to set the resource handle + * + * @param resourceHandle - OCResourceHandle type used to set the resource handle + */ + void setResourceHandle(const OCResourceHandle& resourceHandle) + { + m_resourceHandle = resourceHandle; + } + + /** + * This API allows to set the EntityHandler response result + * + * @param responseResult - OCEntityHandlerResult type to set the result value + */ + void setResponseResult(const OCEntityHandlerResult& responseResult) + { + m_responseResult = responseResult; + } + + /** + * API to set the entire resource attribute representation + * @param rep reference to the resource's representation + * @param interface specifies the interface + */ + void setResourceRepresentation(OCRepresentation& rep, std::string iface) { + m_interface = iface; + m_representation = rep; + } + + /** + * API to set the entire resource attribute representation + * @param rep rvalue reference to the resource's representation + * @param interface specifies the interface + */ + void setResourceRepresentation(OCRepresentation&& rep, std::string iface) { + setResourceRepresentation(rep, iface); + } + + /** + * API to set the entire resource attribute representation + * @param rep reference to the resource's representation + */ + void setResourceRepresentation(OCRepresentation& rep) { + // Call the default + m_interface = DEFAULT_INTERFACE; + m_representation = rep; + } + + /** + * API to set the entire resource attribute representation + * @param rep rvalue reference to the resource's representation + */ + void setResourceRepresentation(OCRepresentation&& rep) { + // Call the above function + setResourceRepresentation(rep); + } + private: + std::string m_newResourceUri; + int m_errorCode; + HeaderOptions m_headerOptions; + std::string m_interface; + OCRepresentation m_representation; + OCRequestHandle m_requestHandle; + OCResourceHandle m_resourceHandle; + OCEntityHandlerResult m_responseResult; + + private: + friend class InProcServerWrapper; + + OCRepPayload* getPayload() const + { + MessageContainer inf; + OCRepresentation first(m_representation); + + if(m_interface==LINK_INTERFACE) + { + first.setInterfaceType(InterfaceType::LinkParent); + } + else if(m_interface==BATCH_INTERFACE) + { + first.setInterfaceType(InterfaceType::BatchParent); + } + else + { + first.setInterfaceType(InterfaceType::DefaultParent); + } + + inf.addRepresentation(first); + + for(const OCRepresentation& rep : m_representation.getChildren()) + { + OCRepresentation cur(rep); + + if(m_interface==LINK_INTERFACE) + { + cur.setInterfaceType(InterfaceType::LinkChild); + } + else if(m_interface==BATCH_INTERFACE) + { + cur.setInterfaceType(InterfaceType::BatchChild); + } + else + { + cur.setInterfaceType(InterfaceType::DefaultChild); + } + + inf.addRepresentation(cur); + + } + + return inf.getPayload(); + } + public: + + /** + * Get error code + */ + int getErrorCode() const + { + return m_errorCode; + } + + /** + * Get the Response Representation + */ + const OCRepresentation& getResourceRepresentation() const + { + return m_representation; + } + /** + * This API allows to retrieve headerOptions from a response + */ + const HeaderOptions& getHeaderOptions() const + { + return m_headerOptions; + } + + /** + * This API retrieves the request handle + * + * @return OCRequestHandle value + */ + const OCRequestHandle& getRequestHandle() const + { + return m_requestHandle; + } + + /** + * This API retrieves the resource handle + * + * @return OCResourceHandle value + */ + const OCResourceHandle& getResourceHandle() const + { + return m_resourceHandle; + } + + /** + * This API retrieves the entity handle response result + * + * @return OCEntityHandler result value + */ + OCEntityHandlerResult getResponseResult() const + { + return m_responseResult; + } + }; + +} // namespace OC + +#endif // OC_RESOURCERESPONSE_H_ diff --git a/inc/iotivity/OCSerialization.h b/inc/iotivity/OCSerialization.h new file mode 100644 index 0000000..b7ba781 --- /dev/null +++ b/inc/iotivity/OCSerialization.h @@ -0,0 +1,164 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH 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. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include +#include "ocpayload.h" +#include "ocrandom.h" +#include "oic_string.h" + +namespace OC +{ + class ListenOCContainer + { + private: + static std::vector StringLLToVector(OCStringLL* ll) + { + std::vector strs; + while(ll) + { + strs.push_back(ll->value); + ll = ll->next; + } + return strs; + } + + public: + ListenOCContainer(std::weak_ptr cw, + OCDevAddr& devAddr, OCDiscoveryPayload* payload) + : m_clientWrapper(cw), m_devAddr(devAddr) + { + while (payload) + { + OCResourcePayload* res = payload->resources; + while (res) + { + if (res->secure) + { + m_devAddr.flags = + (OCTransportFlags)(OC_FLAG_SECURE | m_devAddr.flags); + } + + if (res->port != 0) + { + m_devAddr.port = res->port; + } + + if (payload->baseURI) + { + OCDevAddr rdPubAddr = m_devAddr; + + std::string baseURI = std::string(payload->baseURI); + size_t len = baseURI.length(); + int addressLen = baseURI.find_first_of(":"); + std::string ipaddress = baseURI.substr(0, addressLen); + int port = atoi(baseURI.substr(addressLen + 1, len).c_str()); + OICStrcpy(rdPubAddr.addr, addressLen + 1, ipaddress.c_str()); + rdPubAddr.port = port; + m_resources.push_back(std::shared_ptr( + new OC::OCResource(m_clientWrapper, rdPubAddr, + std::string(res->uri), + std::string(payload->sid), + res->bitmap, + StringLLToVector(res->types), + StringLLToVector(res->interfaces) + ))); + } + else + { + m_resources.push_back(std::shared_ptr( + new OC::OCResource(m_clientWrapper, m_devAddr, + std::string(res->uri), + std::string(payload->sid), + res->bitmap, + StringLLToVector(res->types), + StringLLToVector(res->interfaces) + ))); + +#ifdef TCP_ADAPTER + if (res->tcpPort != 0) + { + OCDevAddr tcpDevAddr = m_devAddr; + tcpDevAddr.port = res->tcpPort; + tcpDevAddr.adapter = OC_ADAPTER_TCP; + m_resources.push_back(std::shared_ptr( + new OC::OCResource(m_clientWrapper, tcpDevAddr, + std::string(res->uri), + std::string(payload->sid), + res->bitmap, + StringLLToVector(res->types), + StringLLToVector(res->interfaces) + ))); + } +#endif + } + res = res->next; + } + payload = payload->next; + } + } + +#ifdef WITH_MQ + ListenOCContainer(std::weak_ptr cw, + OCDevAddr& devAddr, OCRepPayload* payload) + : m_clientWrapper(cw), m_devAddr(devAddr) + { + if (payload) + { + char**topicList = nullptr; + size_t dimensions[MAX_REP_ARRAY_DEPTH] = {0}; + OCRepPayloadGetStringArray(payload, "topiclist", &topicList, dimensions); + + for(size_t idx = 0; idx < dimensions[0]; idx++) + { + m_resources.push_back(std::shared_ptr( + new OC::OCResource(m_clientWrapper, m_devAddr, + std::string(topicList[idx]), + "", + OC_OBSERVABLE, + {OC_RSRVD_RESOURCE_TYPE_MQ_TOPIC}, + {DEFAULT_INTERFACE}))); + } + } + } + + ListenOCContainer(std::weak_ptr cw, + OCDevAddr& devAddr, const std::string& topicUri) + : m_clientWrapper(cw), m_devAddr(devAddr) + { + m_resources.push_back(std::shared_ptr( + new OC::OCResource(m_clientWrapper, m_devAddr, + topicUri, + "", + OC_OBSERVABLE, + {OC_RSRVD_RESOURCE_TYPE_MQ_TOPIC}, + {DEFAULT_INTERFACE}))); + } +#endif + + const std::vector>& Resources() const + { + return m_resources; + } + private: + std::vector> m_resources; + std::weak_ptr m_clientWrapper; + OCDevAddr& m_devAddr; + }; +} diff --git a/inc/iotivity/OCUtilities.h b/inc/iotivity/OCUtilities.h new file mode 100644 index 0000000..85039d0 --- /dev/null +++ b/inc/iotivity/OCUtilities.h @@ -0,0 +1,148 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH 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. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef OC_UTILITIES_H_ +#define OC_UTILITIES_H_ + +#include +#include +#include +#include +#include + +#include +#include + +namespace OC { + namespace Utilities { + + typedef std::map QueryParamsKeyVal; + + /* + * @brief helper function that parses the query parameters component + * of a URI into a key-value map. This function expects the uri + * parameter to contain the query parameters component of a URI + * (everything after the '?', excluding anything anchors). + * + * Note that output will not perform URL decoding + */ + QueryParamsKeyVal getQueryParams(const std::string& uri); + } +} + +/* The C++11 standard unfortunately forgot to provide make_unique<>! However, if we're +using C++14 or later, we want to take the standard library's implementation: */ +namespace OC { +#if defined(__cplusplus) && __cplusplus < 201300 + + template + std::unique_ptr make_unique(XS&& ...xs) + { + return std::unique_ptr(new T(std::forward(xs)...)); + } + +#else + using std::make_unique; +#endif +} // namespace OC + +namespace OC { + + /* Examine an OCStackResult, and either forward its value or raise an exception: */ + OCStackResult result_guard(const OCStackResult r); + + /* Check for a nullptr, and throw an exception if we see one; otherwise, return the + result of the function call: */ + template + auto nil_guard(PtrT&& p, FnT&& fn, ParamTs&& ...params) -> OCStackResult + { + if(nullptr == p) + { + throw OCException(OC::Exception::NIL_GUARD_NULL, OC_STACK_INVALID_PARAM); + } + + // Note that the parameters are being passed by reference to std::bind. This is not an + // issue, as it is this function's parameters that are being passed by reference. So, + // unless the parameters are being passed by reference to here (or to checked_guard), + // they won't be modified. + return std::bind(fn, p, std::ref(params)...)(); + } + + /* Check for nullptr and forward the result of an OC function call on success; raise + an exception on failure or exceptional result: */ + template + auto checked_guard(PtrT&& p, FnT&& fn, ParamTs&& ...params) -> OCStackResult + { + return result_guard(nil_guard(p, fn, std::forward(params)...)); + } + +} // namespace OC + +namespace OC +{ + template + struct is_vector + { + BOOST_STATIC_CONSTEXPR bool value = false; + }; + + template + struct is_vector >::value + >::type + > + { + BOOST_STATIC_CONSTEXPR bool value = true; + }; + + // type trait to remove the first type from a parameter-packed list + template + struct remove_first; + + // specialization that does all the work + template